devstuff 2.12.0__py3-none-any.whl → 2.14.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.
@@ -0,0 +1,156 @@
1
+ """Carrying out an apply plan (docs/specs/profile-apply, FR-6–11, FR-19, NFR-5).
2
+
3
+ `perform` does one step; `execute` runs a whole plan under the failure policy. Together they are
4
+ the non-interactive core. `devstuff install` wraps `tool.install()` in a section header, an
5
+ "already installed" short-circuit and, at the end, an offer to run the tool's setup wizard; none
6
+ of that belongs in an unattended run, so this does only the work and reports how it went.
7
+
8
+ It deliberately does not share code with `install_cmd._install_one`: what they would share is one
9
+ `try`/`except`, and `install_cmd` is a file with no parity tests to refactor against.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from enum import StrEnum
17
+
18
+ from dev_setup import generic
19
+ from dev_setup.apply_plan import Action, Outcome, Plan, Step, blocked_by
20
+ from dev_setup.base import Tool
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Result:
25
+ """How one step ended. `ok` means the installer returned — not that the machine now matches.
26
+
27
+ Whether it matches is decided afterwards, by re-measuring (spec SD-3); an installer that
28
+ exits 0 having installed nothing is a known hazard of this catalog.
29
+ """
30
+
31
+ ok: bool
32
+ version: str | None = None # what the tool reports afterwards, when it reports anything
33
+ error: str = ""
34
+
35
+
36
+ def perform(tool: Tool, step: Step) -> Result:
37
+ """Do what `step` says to `tool`. Never raises for a failed install; always forgets probes.
38
+
39
+ `KeyboardInterrupt` is not caught: an interrupted run must stop, not record a failed step
40
+ and carry on (FR-19). Probes are forgotten on every path out, because an installer that
41
+ failed or was interrupted may still have changed the machine.
42
+ """
43
+ try:
44
+ if step.action is Action.INSTALL:
45
+ return Result(True, tool.install())
46
+ if not step.version:
47
+ return Result(False, error=f"a '{step.action}' step has no version to pin to")
48
+ # One call, not install-then-update: `update(version=…)` is the installer's own command
49
+ # with a version in it, and works on a tool that is not installed (spec F-3, SD-1).
50
+ return Result(True, tool.update(version=step.version)) # type: ignore[attr-defined]
51
+ except Exception as exc:
52
+ return Result(False, error=str(exc) or type(exc).__name__)
53
+ finally:
54
+ generic.forget_probes()
55
+
56
+
57
+ class Status(StrEnum):
58
+ """How one planned step ended. Values are the `--json` spellings."""
59
+
60
+ DONE = "done"
61
+ FAILED = "failed"
62
+ SKIPPED = "skipped" # not attempted: something it needs failed or was skipped
63
+ INTERRUPTED = "interrupted" # Ctrl-C arrived while it was the current step
64
+ NOT_RUN = "not run" # never reached, because the run was interrupted first
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class StepResult:
69
+ key: str
70
+ status: Status
71
+ version: str | None = None
72
+ detail: str = "" # the installer's error, or why the step was skipped
73
+
74
+ def to_json(self) -> dict[str, str | None]:
75
+ return {
76
+ "key": self.key,
77
+ "status": self.status.value,
78
+ "version": self.version,
79
+ "detail": self.detail,
80
+ }
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class RunResult:
85
+ results: tuple[StepResult, ...]
86
+ interrupted: bool = False
87
+
88
+ @property
89
+ def ok(self) -> bool:
90
+ """Every planned step ran and returned. Not "the machine matches": that is re-measured."""
91
+ return not self.interrupted and all(r.status is Status.DONE for r in self.results)
92
+
93
+ def to_json(self) -> dict[str, object]:
94
+ return {"interrupted": self.interrupted, "steps": [r.to_json() for r in self.results]}
95
+
96
+
97
+ def execute(
98
+ plan: Plan,
99
+ lookup: Callable[[str], Tool | None],
100
+ *,
101
+ run: Callable[[Tool, Step], Result] = perform,
102
+ on_start: Callable[[Step], None] | None = None,
103
+ on_done: Callable[[StepResult], None] | None = None,
104
+ ) -> RunResult:
105
+ """Run the plan's steps serially, in order, and say how each one ended.
106
+
107
+ **A failure never stops the run** (FR-9, SD-4). Anything whose requires include a failed or
108
+ skipped step is skipped with the reason, without being attempted; everything else carries on.
109
+
110
+ **Ctrl-C ends the run cleanly** (FR-19): the step that was current is `interrupted`, the rest
111
+ are `not run`, and what finished stays `done`. It returns normally so the caller can still
112
+ print the summary — the exit status, not an exception, is what says it did not complete.
113
+
114
+ `lookup` maps a key to its tool (`registry.get`); `run` is `perform`, injectable so every path
115
+ here can be exercised without installing anything. `on_start`/`on_done` are for progress
116
+ output; `on_start` is not called for a step that is skipped without being attempted.
117
+ """
118
+ results: list[StepResult] = []
119
+ bad: dict[str, Outcome] = {}
120
+ current: Step | None = None
121
+
122
+ def record(result: StepResult) -> None:
123
+ results.append(result)
124
+ if result.status is Status.FAILED:
125
+ bad[result.key] = Outcome.FAILED
126
+ elif result.status is Status.SKIPPED:
127
+ bad[result.key] = Outcome.SKIPPED
128
+ if on_done:
129
+ on_done(result)
130
+
131
+ try:
132
+ for step in plan.steps:
133
+ reason = blocked_by(step, bad)
134
+ if reason:
135
+ record(StepResult(step.key, Status.SKIPPED, None, reason))
136
+ continue
137
+ current = step
138
+ if on_start:
139
+ on_start(step)
140
+ tool = lookup(step.key)
141
+ if tool is None:
142
+ outcome = Result(False, error="not in this machine's catalog")
143
+ else:
144
+ outcome = run(tool, step)
145
+ current = None # the step is over: an interrupt from here on is "between steps"
146
+ if outcome.ok:
147
+ record(StepResult(step.key, Status.DONE, outcome.version))
148
+ else:
149
+ record(StepResult(step.key, Status.FAILED, None, outcome.error))
150
+ except KeyboardInterrupt:
151
+ if current is not None:
152
+ results.append(StepResult(current.key, Status.INTERRUPTED))
153
+ seen = {r.key for r in results}
154
+ results += [StepResult(st.key, Status.NOT_RUN) for st in plan.steps if st.key not in seen]
155
+ return RunResult(tuple(results), interrupted=True)
156
+ return RunResult(tuple(results))
@@ -0,0 +1,218 @@
1
+ """Turning a diff into an install plan (docs/specs/profile-apply, FR-2, FR-3, FR-9, FR-22).
2
+
3
+ Pure: rows in, `Plan` out — no subprocess, no registry, no terminal. The one thing it needs from
4
+ the outside, which dependencies a tool is still missing, arrives as a function, so the ordering
5
+ rules can be tested exhaustively without installing anything.
6
+
7
+ The plan is derived from `profile.compare`'s rows rather than from a second comparison (SD-2): two
8
+ definitions of "missing" or "drift" would let `diff` say a machine matches while `apply` changes it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Mapping, Sequence
14
+ from dataclasses import dataclass
15
+ from enum import StrEnum
16
+
17
+ from dev_setup.profile import DiffRow, DiffState, MachineTool
18
+
19
+
20
+ class Action(StrEnum):
21
+ """Values are the `--json` spellings and the words the plan table shows."""
22
+
23
+ INSTALL = "install"
24
+ # One `update(version=…)` call, not install-then-update: measured to work on a tool that is
25
+ # not installed, and it never installs a "latest" that was not asked for (spec F-3, SD-1).
26
+ INSTALL_PINNED = "install pinned"
27
+ UPDATE_TO_PIN = "update to pin"
28
+
29
+
30
+ class Outcome(StrEnum):
31
+ """How an earlier step ended, for deciding whether a later one can run (FR-9)."""
32
+
33
+ FAILED = "failed"
34
+ SKIPPED = "skipped"
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Step:
39
+ key: str
40
+ action: Action
41
+ version: str | None # the pin, for the two pinned actions
42
+ installed: str | None # what is installed now, for `update to pin`
43
+ type: str
44
+ # Asked for by the profile, as opposed to pulled in because something else needs it.
45
+ requested: bool
46
+ # The requested tools this one is here for. Empty when nothing else needs it.
47
+ needed_by: tuple[str, ...]
48
+ # Every not-yet-installed tool in this one's requires closure, deepest first. All of them are
49
+ # planned earlier; a run uses this to skip the step when one of them failed (`blocked_by`).
50
+ needs: tuple[str, ...]
51
+
52
+ def to_json(self) -> dict[str, object]:
53
+ return {
54
+ "key": self.key,
55
+ "action": self.action.value,
56
+ "version": self.version,
57
+ "installed": self.installed,
58
+ "type": self.type,
59
+ "requested": self.requested,
60
+ "needed_by": list(self.needed_by),
61
+ "needs": list(self.needs),
62
+ }
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Skip:
67
+ """A profile entry `apply` will not act on, and why. Never silently dropped (FR-2)."""
68
+
69
+ key: str
70
+ state: DiffState
71
+ reason: str
72
+
73
+ def to_json(self) -> dict[str, str]:
74
+ return {"key": self.key, "state": self.state.value, "reason": self.reason}
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Plan:
79
+ steps: tuple[Step, ...]
80
+ skipped: tuple[Skip, ...]
81
+ ok: tuple[str, ...] # entries that already match — no work, but part of the picture
82
+
83
+ @property
84
+ def nothing_to_do(self) -> bool:
85
+ return not self.steps
86
+
87
+ def to_json(self) -> dict[str, object]:
88
+ return {
89
+ "steps": [s.to_json() for s in self.steps],
90
+ "skipped": [s.to_json() for s in self.skipped],
91
+ "ok": list(self.ok),
92
+ }
93
+
94
+
95
+ def blocked_by(step: Step, bad: Mapping[str, Outcome]) -> str | None:
96
+ """Why `step` must not run, given how earlier steps ended; None when nothing it needs went wrong.
97
+
98
+ The first offender in plan order is named, so the reason points at the root of the chain.
99
+ """
100
+ for need in step.needs:
101
+ outcome = bad.get(need)
102
+ if outcome is Outcome.FAILED:
103
+ return f"needs {need}, which failed"
104
+ if outcome is Outcome.SKIPPED:
105
+ return f"needs {need}, which was skipped"
106
+ return None
107
+
108
+
109
+ def _skip_reason(row: DiffRow) -> str:
110
+ return row.note or f"{row.state.value}: couldn't act on this entry"
111
+
112
+
113
+ def build_plan(
114
+ rows: Sequence[DiffRow],
115
+ machine: Mapping[str, MachineTool],
116
+ closure: Callable[[str], Sequence[str]],
117
+ *,
118
+ missing_only: bool = False,
119
+ ) -> Plan:
120
+ """The steps to make the machine match, in an order where every tool follows what it needs.
121
+
122
+ `closure(key)` is the tool's transitive requires that are *not installed*, deepest first —
123
+ `registry.missing_requires` in production. It is asked only about tools about to be installed.
124
+ `missing_only` leaves a drifted tool where it is.
125
+ """
126
+ ok: list[str] = []
127
+ skipped: dict[str, Skip] = {}
128
+ wanted: dict[str, tuple[Action, str | None, str | None, str]] = {} # key -> step ingredients
129
+
130
+ for row in rows:
131
+ state = row.state
132
+ if state is DiffState.OK:
133
+ ok.append(row.key)
134
+ elif state is DiffState.EXTRA:
135
+ pass # apply never removes (non-goal), and an extra is not a problem to report
136
+ elif state is DiffState.MISSING:
137
+ if row.pinned is None:
138
+ wanted[row.key] = (Action.INSTALL, None, None, row.type or "")
139
+ elif machine[row.key].pinnable:
140
+ wanted[row.key] = (Action.INSTALL_PINNED, row.pinned, None, row.type or "")
141
+ else:
142
+ # The profile asked for a version this install type cannot give. Installing
143
+ # "latest" instead is the silent substitution this command exists to avoid.
144
+ skipped[row.key] = Skip(
145
+ row.key, state,
146
+ f"pinned to {row.pinned}, but a {row.type} install can't be pinned — "
147
+ "remove the version from the profile to install the latest",
148
+ )
149
+ elif state is DiffState.DRIFT:
150
+ if missing_only:
151
+ skipped[row.key] = Skip(
152
+ row.key, state,
153
+ f"installed at {row.installed}, profile pins {row.pinned} — "
154
+ "left alone (--missing-only)",
155
+ )
156
+ else:
157
+ wanted[row.key] = (Action.UPDATE_TO_PIN, row.pinned, row.installed, row.type or "")
158
+ else: # unverifiable, unpinnable, unknown-key: the comparison could not be made
159
+ skipped[row.key] = Skip(row.key, state, _skip_reason(row))
160
+
161
+ # Dependencies. A tool that needs something this plan cannot provide is skipped, not tried.
162
+ needs: dict[str, tuple[str, ...]] = {}
163
+ for key in sorted(wanted):
164
+ action = wanted[key][0]
165
+ if action is Action.UPDATE_TO_PIN:
166
+ continue # already installed; its dependencies are not this command's business
167
+ chain = tuple(closure(key))
168
+ blocker = _blocker(chain, machine, skipped)
169
+ if blocker is not None:
170
+ del wanted[key]
171
+ skipped[key] = Skip(key, DiffState.MISSING, blocker)
172
+ else:
173
+ needs[key] = chain
174
+
175
+ # Emission order: each requested tool (by key, so the plan is deterministic) preceded by
176
+ # whatever it needs that is not already out. Each closure is deepest-first, so a tool's own
177
+ # dependencies are always out before it is — keeping first occurrences preserves that.
178
+ order: list[str] = []
179
+ for key in sorted(wanted):
180
+ for dep in needs.get(key, ()):
181
+ if dep not in order:
182
+ order.append(dep)
183
+ if key not in order:
184
+ order.append(key)
185
+
186
+ needed_by: dict[str, set[str]] = {}
187
+ for key, chain in needs.items():
188
+ for dep in chain:
189
+ needed_by.setdefault(dep, set()).add(key)
190
+
191
+ steps: list[Step] = []
192
+ for key in order:
193
+ if key in wanted:
194
+ action, version, installed, type_ = wanted[key]
195
+ requested = True
196
+ else: # pulled in only because something needs it: installed unpinned, as the catalog says
197
+ action, version, installed, type_ = Action.INSTALL, None, None, machine[key].install_type
198
+ requested = False
199
+ steps.append(
200
+ Step(
201
+ key, action, version, installed, type_, requested,
202
+ tuple(sorted(needed_by.get(key, ()))),
203
+ needs.get(key, ()) if requested else tuple(closure(key)),
204
+ )
205
+ )
206
+
207
+ return Plan(tuple(steps), tuple(skipped[k] for k in sorted(skipped)), tuple(sorted(ok)))
208
+
209
+
210
+ def _blocker(
211
+ chain: Sequence[str], machine: Mapping[str, MachineTool], skipped: Mapping[str, Skip]
212
+ ) -> str | None:
213
+ for dep in chain:
214
+ if dep not in machine:
215
+ return f"needs {dep}, which is not in this machine's catalog"
216
+ if dep in skipped:
217
+ return f"needs {dep}, which was skipped: {skipped[dep].reason}"
218
+ return None
@@ -0,0 +1,10 @@
1
+ # @ai-agents — Coding agents for the terminal. The npm-based ones pull in nvm automatically.
2
+ # Apply with: devstuff profile apply @ai-agents
3
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
4
+ version: 1
5
+ tools:
6
+ claude-code: {}
7
+ codex: {}
8
+ devin: {}
9
+ hey-dave: {}
10
+ pi: {}
@@ -0,0 +1,10 @@
1
+ # @ai-local — Running models on this machine, and checking what it can run.
2
+ # Note: lmstudio asks for sudo when libatomic1 is missing.
3
+ # Apply with: devstuff profile apply @ai-local
4
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
5
+ version: 1
6
+ tools:
7
+ llamactl: {}
8
+ llm-checker: {}
9
+ lmstudio: {}
10
+ ollama: {}
@@ -0,0 +1,12 @@
1
+ # @devops — Containers, configuration management and cloud access.
2
+ # Note: docker asks for sudo (and a re-login before your user can use it without sudo).
3
+ # Apply with: devstuff profile apply @devops
4
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
5
+ version: 1
6
+ tools:
7
+ ansible: {}
8
+ ansible-vault: {}
9
+ aws: {}
10
+ docker: {}
11
+ mkcert: {}
12
+ saml2aws: {}
@@ -0,0 +1,14 @@
1
+ # @essentials — A fresh machine's everyday set: git helpers, a nicer shell prompt, and the small tools you reach for daily.
2
+ # Note: nerd-font supplies the icons starship draws; installing it does not switch your terminal to that font.
3
+ # Apply with: devstuff profile apply @essentials
4
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
5
+ version: 1
6
+ tools:
7
+ bat: {}
8
+ gh: {}
9
+ git-lfs: {}
10
+ htop: {}
11
+ lazygit: {}
12
+ nerd-font: {}
13
+ starship: {}
14
+ yq: {}
@@ -0,0 +1,11 @@
1
+ # @languages — Language toolchains. The heaviest bundle: java comes from apt, php from a PPA, and ruby builds from source.
2
+ # Note: java, php and ruby all ask for sudo (apt packages, the PHP PPA, ruby build dependencies).
3
+ # Apply with: devstuff profile apply @languages
4
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
5
+ version: 1
6
+ tools:
7
+ go: {}
8
+ java: {}
9
+ php: {}
10
+ python: {}
11
+ ruby: {}
@@ -0,0 +1,10 @@
1
+ # @python — Python the way devstuff does it: uv owns the interpreter, plus the usual quality tooling.
2
+ # Apply with: devstuff profile apply @python
3
+ # Names no versions, so it installs the latest of each; extra tools it needs are added for you.
4
+ version: 1
5
+ tools:
6
+ commitizen: {}
7
+ ipython: {}
8
+ pre-commit: {}
9
+ python: {}
10
+ uv: {}
dev_setup/bundles.py ADDED
@@ -0,0 +1,62 @@
1
+ """Profiles that ship with devstuff, named with a leading `@` (docs/specs/profile-apply, FR-20, FR-21).
2
+
3
+ `devstuff profile apply @devops` is `apply` on a file that lives in the package. A bundle is an
4
+ ordinary profile — same format, same strict loader — so there is exactly one thing to document
5
+ and to validate (SD-9), and any bundle can be copied out and edited.
6
+
7
+ The name is never turned into a path. Lookup lists the bundle directory and matches the name
8
+ against what it finds, so `@../x` or `@/etc/passwd` has nothing to traverse: it is simply not in
9
+ the list.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from importlib import resources
16
+ from importlib.resources.abc import Traversable
17
+ from pathlib import Path
18
+
19
+ from dev_setup import profile
20
+ from dev_setup.profile import Profile, ProfileError
21
+
22
+ _SUFFIX = ".yaml"
23
+ _NAME = re.compile(r"[a-z][a-z0-9-]*")
24
+
25
+
26
+ def _root() -> Traversable:
27
+ return resources.files("dev_setup") / "bundles"
28
+
29
+
30
+ def _files() -> dict[str, Traversable]:
31
+ """Bundle name -> its file. Anything in the directory that is not a well-named YAML file is
32
+ not a bundle: the data tests insist the directory holds nothing else."""
33
+ found: dict[str, Traversable] = {}
34
+ for entry in _root().iterdir():
35
+ stem = entry.name.removesuffix(_SUFFIX)
36
+ if entry.is_file() and entry.name.endswith(_SUFFIX) and _NAME.fullmatch(stem):
37
+ found[stem] = entry
38
+ return found
39
+
40
+
41
+ def names() -> list[str]:
42
+ return sorted(_files())
43
+
44
+
45
+ def is_bundle(arg: str) -> bool:
46
+ """`@name` is a bundle; anything else is a file. A file that really starts with `@` is `./@x`."""
47
+ return arg.startswith("@")
48
+
49
+
50
+ def resolve(arg: str) -> Profile:
51
+ """Load the bundle `arg` (`@name`). An unknown name lists the ones that exist (FR-21)."""
52
+ files = _files()
53
+ entry = files.get(arg[1:]) if is_bundle(arg) else None
54
+ if entry is None:
55
+ available = ", ".join(f"@{n}" for n in sorted(files)) or "(none)"
56
+ raise ProfileError(f"no bundle named {arg!r}. Bundles: {available}")
57
+ return profile.loads(entry.read_text(encoding="utf-8"), source=arg)
58
+
59
+
60
+ def load_arg(arg: str) -> Profile:
61
+ """The one way a command turns its PROFILE argument into a profile."""
62
+ return resolve(arg) if is_bundle(arg) else profile.load(Path(arg))
@@ -0,0 +1,26 @@
1
+ """Shared plan-preview helpers for install/remove/update commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dev_setup.base import Tool
6
+
7
+
8
+ def plan_for(tool: Tool, action: str, version: str | None = None) -> list:
9
+ """The tool's resolved plan items, or a generic note for non-GenericTool entries."""
10
+ planner = getattr(tool, "plan_items", None)
11
+ if planner is None:
12
+ return [("note", "", f"{action} {tool.key}")]
13
+ return planner(action, version)
14
+
15
+
16
+ def plan_summary(tool: Tool, action: str, version: str | None = None) -> str:
17
+ """One-line digest of a tool's plan for the batch preview table."""
18
+ parts = []
19
+ for kind, _label, detail in plan_for(tool, action, version):
20
+ if kind == "cmd":
21
+ parts.append(detail)
22
+ elif kind == "script":
23
+ parts.append("runs a script")
24
+ else:
25
+ parts.append(detail)
26
+ return "; ".join(parts)