devstuff 2.10.0__py3-none-any.whl → 2.12.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dev_setup/cli.py CHANGED
@@ -33,6 +33,8 @@ def _register_commands() -> None:
33
33
  from dev_setup.commands.install_cmd import install_cmd
34
34
  from dev_setup.commands.links_cmd import links_cmd
35
35
  from dev_setup.commands.list_cmd import list_cmd
36
+ from dev_setup.commands.outdated_cmd import outdated_cmd
37
+ from dev_setup.commands.profile_cmd import profile_cmd
36
38
  from dev_setup.commands.remove_cmd import remove_cmd
37
39
  from dev_setup.commands.run_cmd import run_cmd
38
40
  from dev_setup.commands.skills_cmd import skills_cmd
@@ -44,6 +46,8 @@ def _register_commands() -> None:
44
46
  cli.add_command(remove_cmd, "uninstall")
45
47
  cli.add_command(doctor_cmd, "doctor")
46
48
  cli.add_command(update_cmd, "update")
49
+ cli.add_command(outdated_cmd, "outdated")
50
+ cli.add_command(profile_cmd, "profile")
47
51
  cli.add_command(configure_cmd, "configure")
48
52
  cli.add_command(configure_cmd, "config")
49
53
  cli.add_command(add_cmd, "add")
@@ -25,6 +25,8 @@ def print_help() -> None:
25
25
  ("install", "[package ...]", "Install packages (interactive if no args)"),
26
26
  ("remove", "<package ...>", "Uninstall installed packages"),
27
27
  ("update", "[package ...] [--version]", "Update packages (interactive if no args)"),
28
+ ("outdated", "[package ...] [--json]", "Show which installed packages have updates"),
29
+ ("profile", "<snapshot|diff> [...]", "Save this machine's tools, or compare to a file"),
28
30
  ("configure", "[tool] [--list] [--path]", "Set up a tool with a guided wizard"),
29
31
  ("add", "", "Add a custom package (guided wizard)"),
30
32
  ("delete", "<key>", "Remove a custom package from the registry"),
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from contextlib import nullcontext
6
+
7
+ import click
8
+ from rich.markup import escape
9
+
10
+ from dev_setup import registry, ui, verbose
11
+ from dev_setup.base import Tool
12
+ from dev_setup.updates import Row, State, collect_candidates, make_row, sort_rows, summarize
13
+
14
+ # One glyph + wording per state. `unknown` and `unsupported` deliberately share nothing
15
+ # with `current`: "could not check" must never read as "up to date" (spec FR-7).
16
+ _STATUS: dict[State, tuple[str, str]] = {
17
+ State.OUTDATED: (ui.AMBER, "⬆ outdated"),
18
+ State.CURRENT: (ui.GREEN, "✔ current"),
19
+ State.UNKNOWN: (ui.GRAY, "? unknown"),
20
+ State.UNSUPPORTED: (ui.GRAY, "– can't check"),
21
+ State.NOT_INSTALLED: (ui.GRAY, "○ not installed"),
22
+ }
23
+
24
+ # Order of the closing summary line; the wording is each state's own name.
25
+ _SUMMARY_ORDER = (
26
+ State.OUTDATED, State.CURRENT, State.UNKNOWN, State.UNSUPPORTED, State.NOT_INSTALLED,
27
+ )
28
+
29
+ _FOOTER_NAMES = 12
30
+
31
+
32
+ @click.command("outdated")
33
+ @click.option(
34
+ "--updates-only", is_flag=True,
35
+ help="Show only tools with an update available (the summary still counts everything).",
36
+ )
37
+ @click.option(
38
+ "--all", "show_all", is_flag=True,
39
+ help="List the tools that can't be checked (bash/script installers) instead of one footer line.",
40
+ )
41
+ @click.option(
42
+ "--json", "as_json", is_flag=True,
43
+ help="Write a JSON array to stdout and nothing else. Includes every state.",
44
+ )
45
+ @click.argument("packages", nargs=-1)
46
+ def outdated_cmd(packages: tuple[str, ...], updates_only: bool, show_all: bool, as_json: bool) -> None:
47
+ """Show which installed packages have a newer version available.
48
+
49
+ Read-only: nothing is installed, updated or written. Each package is reported as
50
+ outdated, current, unknown (a check exists but couldn't answer), or unsupported
51
+ (script/bash installers have no way to check). Unknown and unsupported are never
52
+ reported as current. Use `devstuff update` to act on the result.
53
+
54
+ The exit status says whether the lookup ran, not what it found: 0 even when
55
+ updates are available.
56
+ """
57
+ named: list[Tool] | None = None
58
+ if packages:
59
+ named = []
60
+ for key in packages:
61
+ tool = registry.get(key)
62
+ if tool is None:
63
+ click.echo(f"Unknown package: '{key}'", err=True)
64
+ sys.exit(1)
65
+ named.append(tool)
66
+
67
+ interactive = sys.stdout.isatty() and not as_json
68
+ if interactive:
69
+ ui.print_banner()
70
+ progress = (
71
+ verbose.step("Checking installed packages for updates...") if interactive else nullcontext()
72
+ )
73
+ with progress:
74
+ candidates = collect_candidates(named)
75
+
76
+ result = [make_row(tool, status) for tool, status in candidates]
77
+ if named is not None:
78
+ found = {tool.key for tool, _ in candidates}
79
+ result += [make_row(t, None, installed=False) for t in named if t.key not in found]
80
+
81
+ result = sort_rows(result)
82
+ shown = [r for r in result if r.state is State.OUTDATED] if updates_only else result
83
+
84
+ if as_json:
85
+ click.echo(json.dumps([r.to_json() for r in shown], indent=2))
86
+ return
87
+
88
+ _render(shown, result, updates_only=updates_only, show_all=show_all)
89
+
90
+
91
+ def _render(shown: list[Row], everything: list[Row], *, updates_only: bool, show_all: bool) -> None:
92
+ if not everything:
93
+ ui.info("No installed packages to check.")
94
+ return
95
+
96
+ collapsed = [] if show_all else [r for r in shown if r.state is State.UNSUPPORTED]
97
+ rows = [r for r in shown if r not in collapsed]
98
+
99
+ if rows:
100
+ tbl = ui.table()
101
+ tbl.add_column("Package", style="bold", no_wrap=True)
102
+ tbl.add_column("Type", style=ui.CYAN, no_wrap=True)
103
+ tbl.add_column("Installed", style=ui.GRAY, no_wrap=True)
104
+ tbl.add_column("Latest", style=ui.GRAY, no_wrap=True)
105
+ tbl.add_column("Status")
106
+ for r in rows:
107
+ tbl.add_row(r.key, r.type, r.installed or "", r.latest or "", _status_cell(r))
108
+ ui.console.print(tbl)
109
+ elif updates_only:
110
+ ui.info("No updates available.")
111
+
112
+ if collapsed:
113
+ _footer(collapsed)
114
+
115
+ ui.dim(_summary(everything))
116
+
117
+
118
+ def _status_cell(r: Row) -> str:
119
+ color, label = _STATUS[r.state]
120
+ cell = f"[{color}]{label}[/]"
121
+ if r.note:
122
+ # Escaped: a note is free text from a checker, and Rich would read "[docs]" as markup.
123
+ cell += f"\n[{ui.GRAY}]{escape(r.note)}[/]"
124
+ return cell
125
+
126
+
127
+ def _footer(unsupported: list[Row]) -> None:
128
+ kinds = ", ".join(sorted({r.type for r in unsupported}))
129
+ names = [r.key for r in unsupported]
130
+ listed = ", ".join(names[:_FOOTER_NAMES])
131
+ if len(names) > _FOOTER_NAMES:
132
+ listed += f", +{len(names) - _FOOTER_NAMES} more (--all lists them)"
133
+ noun = "tool" if len(names) == 1 else "tools"
134
+ ui.dim(f"{len(names)} {noun} can't be checked ({kinds} installers): {listed}")
135
+
136
+
137
+ def _summary(rows: list[Row]) -> str:
138
+ counts = summarize(rows)
139
+ return " · ".join(
140
+ f"{counts[s]} {s.value.replace('-', ' ')}" for s in _SUMMARY_ORDER if counts[s]
141
+ )
@@ -0,0 +1,199 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from contextlib import nullcontext
6
+ from pathlib import Path
7
+
8
+ import click
9
+ from rich.markup import escape
10
+
11
+ from dev_setup import profile, snapshot, ui, verbose
12
+ from dev_setup.profile import DiffRow, DiffState
13
+
14
+ _CUSTOM_NAMES_SHOWN = 6
15
+
16
+
17
+ def _warn(message: str) -> None:
18
+ # stderr only: with no -o, stdout is the profile itself and must parse (spec FR-14, NFR-1).
19
+ click.echo(message, err=True)
20
+
21
+
22
+ @click.group("profile")
23
+ def profile_cmd() -> None:
24
+ """Describe a machine's tools as a portable file, and compare a machine against one.
25
+
26
+ A profile is a small YAML file naming catalog tools (and, optionally, versions). It holds
27
+ keys only — never install scripts — so a profile from elsewhere cannot run anything the
28
+ catalog doesn't already define.
29
+ """
30
+
31
+
32
+ @profile_cmd.command("snapshot")
33
+ @click.option(
34
+ "-o", "--output", "output", type=click.Path(path_type=Path), default=None,
35
+ help="Write to this file instead of stdout.",
36
+ )
37
+ @click.option(
38
+ "--versions", is_flag=True,
39
+ help="Also record each tool's installed version, for the types that can be pinned "
40
+ "(npm, pip/uvx, single-package apt). Off by default: a pinned profile goes stale "
41
+ "the day a tool updates.",
42
+ )
43
+ @click.option("--force", is_flag=True, help="Overwrite the -o file if it already exists.")
44
+ def snapshot_cmd(output: Path | None, versions: bool, force: bool) -> None:
45
+ """Write a profile of the tools installed on this machine.
46
+
47
+ Read-only, and local: it asks the machine, never the network, so it works offline. The
48
+ output is deterministic (sorted, no timestamp, no hostname), so a profile kept in git shows
49
+ only real changes.
50
+
51
+ With no -o, stdout is exactly the YAML — notes and warnings go to stderr.
52
+ """
53
+ if output is not None and output.exists() and not force:
54
+ _warn(f"error: {output} already exists; use --force to overwrite it")
55
+ sys.exit(2)
56
+
57
+ snap = snapshot.take(versions=versions)
58
+
59
+ for key in snap.unreadable:
60
+ _warn(
61
+ f"warning: {key}: couldn't read its installed version, so it is written without "
62
+ f"one — {snap.why[key]}"
63
+ )
64
+ if snap.custom:
65
+ shown = ", ".join(snap.custom[:_CUSTOM_NAMES_SHOWN])
66
+ if len(snap.custom) > _CUSTOM_NAMES_SHOWN:
67
+ shown += f", +{len(snap.custom) - _CUSTOM_NAMES_SHOWN} more"
68
+ _warn(
69
+ f"note: {len(snap.custom)} of these tools are defined or overridden in your user "
70
+ f"catalog ({shown}); a machine without them won't know these keys — move them with "
71
+ "`devstuff catalog export` / `devstuff catalog import`"
72
+ )
73
+
74
+ text = profile.dumps(snap.profile)
75
+ if output is None:
76
+ click.echo(text, nl=False)
77
+ return
78
+
79
+ try:
80
+ output.write_text(text, encoding="utf-8")
81
+ except OSError as exc:
82
+ _warn(f"error: cannot write {output}: {exc.strerror or exc}")
83
+ sys.exit(2)
84
+ n = len(snap.profile.tools)
85
+ _warn(f"Wrote {n} tool{'' if n == 1 else 's'} to {output}")
86
+
87
+
88
+ # -- diff ---------------------------------------------------------------------------------------
89
+
90
+ # One glyph + wording per state. The three "could not compare" states share nothing with `ok`:
91
+ # they must never read as a match (spec FR-17).
92
+ _LABEL: dict[DiffState, tuple[str, str]] = {
93
+ DiffState.OK: (ui.GREEN, "✔ ok"),
94
+ DiffState.MISSING: (ui.RED, "✘ missing"),
95
+ DiffState.DRIFT: (ui.AMBER, "≠ drift"),
96
+ DiffState.UNVERIFIABLE: (ui.GRAY, "? unverifiable"),
97
+ DiffState.UNPINNABLE: (ui.GRAY, "– unpinnable"),
98
+ DiffState.UNKNOWN_KEY: (ui.GRAY, "? unknown-key"),
99
+ DiffState.EXTRA: (ui.CYAN, "+ extra"),
100
+ }
101
+
102
+ _EXTRA_NAMES_SHOWN = 12
103
+
104
+
105
+ @profile_cmd.command("diff")
106
+ @click.argument("profile_file", metavar="PROFILE", type=click.Path(path_type=Path))
107
+ @click.option(
108
+ "--all", "show_all", is_flag=True,
109
+ help="Also list the tools that match, and the tools not in the profile, as rows.",
110
+ )
111
+ @click.option(
112
+ "--json", "as_json", is_flag=True,
113
+ help="Write a JSON array to stdout and nothing else. Always includes every state.",
114
+ )
115
+ @click.option(
116
+ "--exit-code", "exit_code", is_flag=True,
117
+ help="Exit 1 if the machine differs from the profile (default: 0 whenever the comparison ran).",
118
+ )
119
+ @click.option(
120
+ "--ignore-extras", is_flag=True,
121
+ help="For --exit-code: don't count installed tools that aren't in the profile as a difference.",
122
+ )
123
+ def diff_cmd(
124
+ profile_file: Path, show_all: bool, as_json: bool, exit_code: bool, ignore_extras: bool
125
+ ) -> None:
126
+ """Compare this machine to a profile.
127
+
128
+ Read-only. Each key is reported as ok, missing, drift (installed at a different version
129
+ than the profile pins), unverifiable (pinned, but the installed version can't be read),
130
+ unpinnable (pinned, but that install type can't honour a pin), unknown-key (not in this
131
+ machine's catalog) or extra (installed but not in the profile). The last three that mean
132
+ "couldn't compare" are never reported as ok.
133
+
134
+ Exit status: 0 whenever the comparison ran. With --exit-code, 1 if the machine differs. A
135
+ profile that can't be read or isn't valid is always 2, so 1 only ever means "differs".
136
+ """
137
+ try:
138
+ wanted = profile.load(profile_file)
139
+ except profile.ProfileError as exc:
140
+ click.echo(f"error: {exc}", err=True)
141
+ sys.exit(2)
142
+
143
+ interactive = sys.stdout.isatty() and not as_json
144
+ if interactive:
145
+ ui.print_banner()
146
+ progress = (
147
+ verbose.step(f"Comparing this machine to {profile_file.name}...")
148
+ if interactive else nullcontext()
149
+ )
150
+ with progress:
151
+ rows = profile.sort_diff_rows(profile.compare(wanted, snapshot.machine_facts(wanted)))
152
+
153
+ if as_json:
154
+ click.echo(json.dumps([r.to_json() for r in rows], indent=2))
155
+ else:
156
+ _render(rows, show_all=show_all)
157
+
158
+ if exit_code and profile.differs(rows, ignore_extras=ignore_extras):
159
+ sys.exit(1)
160
+
161
+
162
+ def _status_cell(row: DiffRow) -> str:
163
+ color, label = _LABEL[row.state]
164
+ cell = f"[{color}]{label}[/]"
165
+ if row.note:
166
+ # Escaped: a note is free text, and Rich would read "[docs]" as markup.
167
+ cell += f"\n[{ui.GRAY}]{escape(row.note)}[/]"
168
+ return cell
169
+
170
+
171
+ def _render(rows: list[DiffRow], *, show_all: bool) -> None:
172
+ extras = [r for r in rows if r.state is DiffState.EXTRA]
173
+ shown = rows if show_all else [r for r in rows if r.state not in (DiffState.OK, DiffState.EXTRA)]
174
+
175
+ if shown:
176
+ tbl = ui.table()
177
+ tbl.add_column("Package", style="bold", no_wrap=True)
178
+ tbl.add_column("Type", style=ui.CYAN, no_wrap=True)
179
+ tbl.add_column("Profile", style=ui.GRAY, no_wrap=True)
180
+ tbl.add_column("Installed", style=ui.GRAY, no_wrap=True)
181
+ tbl.add_column("Status")
182
+ for r in shown:
183
+ tbl.add_row(r.key, r.type or "", r.pinned or "", r.installed or "", _status_cell(r))
184
+ ui.console.print(tbl)
185
+ elif not extras:
186
+ ui.info("This machine matches the profile.")
187
+ else:
188
+ ui.info("Everything the profile asks for is here.")
189
+
190
+ if extras and not show_all:
191
+ names = [r.key for r in extras]
192
+ listed = ", ".join(names[:_EXTRA_NAMES_SHOWN])
193
+ if len(names) > _EXTRA_NAMES_SHOWN:
194
+ listed += f", +{len(names) - _EXTRA_NAMES_SHOWN} more"
195
+ noun = "tool isn't" if len(names) == 1 else "tools aren't"
196
+ ui.dim(f"{len(names)} installed {noun} in the profile: {listed} (--all lists them)")
197
+
198
+ counts = profile.summarize_diff(rows)
199
+ ui.dim(" · ".join(f"{counts[s]} {s.value}" for s in profile.DIFF_ORDER if counts[s]))
@@ -1,14 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import sys
4
- from concurrent.futures import ThreadPoolExecutor
5
4
 
6
5
  import click
7
6
  import questionary
8
7
 
9
8
  from dev_setup import registry, ui
10
9
  from dev_setup.base import Tool
11
- from dev_setup.generic import UpdateStatus
10
+ from dev_setup.updates import collect_candidates
12
11
 
13
12
 
14
13
  @click.command("update")
@@ -74,28 +73,11 @@ def _update_one(tool: Tool, version: str | None) -> bool:
74
73
  return False
75
74
 
76
75
 
77
- def _collect_update_candidates() -> list[tuple[Tool, UpdateStatus]]:
78
- """Return (tool, UpdateStatus) for every installed tool, probed concurrently.
79
-
80
- Pure data-gathering, kept free of any UI/prompt code so it can be exercised
81
- directly without a terminal.
82
- """
83
- tools = registry.all_tools()
84
- with ThreadPoolExecutor(max_workers=8) as pool:
85
- installed_flags = list(pool.map(lambda t: t.is_installed(), tools))
86
- installed = [t for t, flag in zip(tools, installed_flags, strict=True) if flag]
87
- if not installed:
88
- return []
89
- with ThreadPoolExecutor(max_workers=8) as pool:
90
- statuses = list(pool.map(lambda t: t.check_for_update(), installed)) # type: ignore[attr-defined]
91
- return list(zip(installed, statuses, strict=True))
92
-
93
-
94
76
  def _update_interactive() -> None:
95
77
  ui.print_banner()
96
78
 
97
79
  with ui.spinner("Checking installed packages for available updates..."):
98
- candidates = _collect_update_candidates()
80
+ candidates = collect_candidates()
99
81
 
100
82
  if not candidates:
101
83
  ui.info("No installed packages to update.")