devstuff 2.13.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,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)
@@ -25,139 +25,188 @@ set -euo pipefail
25
25
 
26
26
  """
27
27
 
28
+ _TYPES = ["npm", "uvx", "apt", "git", "script", "bash"]
29
+
30
+ # Catalog fields collected per type — filters out answers left over from a type
31
+ # the user backed out of and changed.
32
+ _TYPE_FIELDS = {
33
+ "npm": ["npm_name", "check_cmd"],
34
+ "uvx": ["pip_name", "check_cmd", "uv_executables_from", "uv_with", "uv_python"],
35
+ "apt": ["apt_packages", "check_cmd"],
36
+ "git": ["git_url", "git_install_cmd", "git_remove_cmd", "check_cmd"],
37
+ "script": ["script_url", "check_cmd"],
38
+ "bash": ["check_cmd", "install_script", "remove_script"],
39
+ }
40
+ _COMMON_FIELDS = ["help_cmd", "docs_url"]
41
+
28
42
 
29
43
  @click.command("add")
30
44
  def add_cmd() -> None:
31
45
  """Add a custom package via guided wizard."""
32
46
  ui.section("Add Custom Package")
33
47
 
34
- install_type = ui.select(
35
- "Package type:",
36
- ["npm", "uvx", "apt", "git", "script", "bash"],
37
- )
38
- if not install_type:
48
+ answers = ui.Wizard("Add package").run(_steps())
49
+ if answers is None:
39
50
  ui.warn("Aborted.")
40
51
  return
41
52
 
42
- key = _prompt_key()
43
- if not key:
44
- return
45
-
46
- name = ui.text_input("Display name:", default=key, required=True)
47
- description = ui.text_input("Short description:", required=False)
48
-
53
+ install_type = answers["type"]
49
54
  kwargs: dict = dict(
50
- key=key,
51
- name=name,
52
- description=description,
55
+ key=answers["key"],
56
+ name=answers["name"],
57
+ description=answers.get("description", ""),
53
58
  category="custom",
54
59
  install_type=install_type,
55
60
  )
56
-
57
- if install_type == "npm":
58
- kwargs["npm_name"] = ui.text_input("npm package name:", default=key, required=True)
59
- kwargs["check_cmd"] = ui.text_input("Command to check if installed:", default=key)
60
-
61
- elif install_type == "uvx":
62
- kwargs["pip_name"] = ui.text_input("PyPI package name:", default=key, required=True)
63
- kwargs["check_cmd"] = ui.text_input("Command to check if installed:", default=key)
64
- # All optional. Empty answers must not write empty keys into the user catalog.
65
- exes = ui.text_input(
66
- "Also expose executables from (space-separated packages, blank for none):"
67
- )
68
- if exes:
69
- kwargs["uv_executables_from"] = exes.split()
70
- extra = ui.text_input(
71
- "Extra packages to install alongside it (space-separated, blank for none):"
72
- )
73
- if extra:
74
- kwargs["uv_with"] = extra.split()
75
- py = ui.text_input("Pin to a Python version (e.g. 3.12, blank for uv's default):")
76
- if py:
77
- kwargs["uv_python"] = py
78
-
79
- elif install_type == "apt":
80
- kwargs["apt_packages"] = ui.text_input(
81
- "apt package(s) (space-separated):", default=key, required=True
82
- )
83
- kwargs["check_cmd"] = ui.text_input("Command to check if installed:", default=key)
84
-
85
- elif install_type == "git":
86
- kwargs["git_url"] = ui.text_input("Git repository URL:", required=True)
87
- kwargs["git_install_cmd"] = ui.text_input(
88
- "Post-clone install command (optional, run inside repo):", required=False
89
- )
90
- kwargs["git_remove_cmd"] = ui.text_input(
91
- "Pre-delete remove command (optional):", required=False
92
- )
93
- kwargs["check_cmd"] = ui.text_input("Command to check if installed:", required=False)
94
-
95
- elif install_type == "script":
96
- kwargs["script_url"] = ui.text_input("Install script URL (curl | sh):", required=True)
97
- kwargs["check_cmd"] = ui.text_input("Command to check if installed:", required=False)
98
-
99
- elif install_type == "bash":
100
- kwargs["check_cmd"] = ui.text_input(
101
- "Command to verify installation (e.g. bat, aws):", required=False
102
- )
103
- install_script = _edit_script("install", name, required=True)
104
- if install_script is None:
105
- ui.warn("No install script provided — aborted.")
106
- return
107
- kwargs["install_script"] = install_script
108
-
109
- remove_script = _edit_script("remove", name, required=False)
110
- remove_script = _validate_remove_script(
111
- remove_script or "",
112
- install_script,
113
- kwargs.get("check_cmd", ""),
114
- name,
115
- )
116
- if remove_script:
117
- kwargs["remove_script"] = remove_script
118
-
119
- kwargs["help_cmd"] = ui.text_input(
120
- "Help command (optional, e.g. tool --help):", required=False
121
- )
122
- kwargs["docs_url"] = ui.text_input(
123
- "Documentation URL (optional):", required=False
124
- )
125
-
126
- ui.console.print()
127
- ui.heading("Summary")
128
- for k, v in kwargs.items():
129
- if v:
130
- display = _truncate_script(v) if k.endswith("_script") else v
131
- ui.console.print(f" [{ui.PURPLE}]{k:<18}[/] {display}")
132
- ui.console.print()
133
-
134
- if not ui.confirm("Save this package?"):
135
- ui.warn("Aborted — package not saved.")
136
- return
61
+ for field in _TYPE_FIELDS.get(install_type, []) + _COMMON_FIELDS:
62
+ if answers.get(field):
63
+ kwargs[field] = answers[field]
137
64
 
138
65
  tool = GenericTool(**kwargs)
139
66
  tool.save()
140
-
141
- from dev_setup import registry
142
67
  registry.register(tool)
143
68
 
144
- ui.success(f"Package '{key}' added. Install with: devstuff install {key}")
69
+ ui.success(f"Package '{tool.key}' added. Install with: devstuff install {tool.key}")
70
+
71
+
72
+ def _steps() -> list[ui.Step]:
73
+ def is_type(*types: str):
74
+ return lambda a: a.get("type") in types
75
+
76
+ def text(key: str, label: str, prompt: str, *, required: bool = False,
77
+ default=None, when=None, split: bool = False) -> ui.Step:
78
+ def ask(a: dict):
79
+ dflt = a.get(key) or (default(a) if default else "")
80
+ if isinstance(dflt, list):
81
+ dflt = " ".join(dflt)
82
+ val = ui.text_input_back(prompt, default=dflt, required=required)
83
+ if val is ui.BACK:
84
+ return ui.BACK
85
+ return val.split() if split and val else val
86
+
87
+ return ui.Step(key, label, ask, when=when)
88
+
89
+ return [
90
+ ui.Step(
91
+ "type", "package type",
92
+ lambda a: ui.select_back("Package type:", _TYPES, default=a.get("type")),
93
+ ),
94
+ ui.Step("key", "package key", _ask_key),
95
+ text(
96
+ "name", "display name", "Display name:", required=True,
97
+ default=lambda a: a.get("key", ""),
98
+ ),
99
+ text("description", "description", "Short description:"),
100
+ # npm
101
+ text(
102
+ "npm_name", "npm package", "npm package name:", required=True,
103
+ default=lambda a: a.get("key", ""), when=is_type("npm"),
104
+ ),
105
+ # uvx
106
+ text(
107
+ "pip_name", "PyPI package", "PyPI package name:", required=True,
108
+ default=lambda a: a.get("key", ""), when=is_type("uvx"),
109
+ ),
110
+ text(
111
+ "uv_executables_from", "executables from",
112
+ "Also expose executables from (space-separated packages, blank for none):",
113
+ when=is_type("uvx"), split=True,
114
+ ),
115
+ text(
116
+ "uv_with", "extra packages",
117
+ "Extra packages to install alongside it (space-separated, blank for none):",
118
+ when=is_type("uvx"), split=True,
119
+ ),
120
+ text(
121
+ "uv_python", "python pin",
122
+ "Pin to a Python version (e.g. 3.12, blank for uv's default):",
123
+ when=is_type("uvx"),
124
+ ),
125
+ # apt
126
+ text(
127
+ "apt_packages", "apt packages", "apt package(s) (space-separated):",
128
+ required=True, default=lambda a: a.get("key", ""), when=is_type("apt"),
129
+ ),
130
+ # git
131
+ text("git_url", "repo URL", "Git repository URL:", required=True, when=is_type("git")),
132
+ text(
133
+ "git_install_cmd", "install command",
134
+ "Post-clone install command (optional, run inside repo):",
135
+ when=is_type("git"),
136
+ ),
137
+ text(
138
+ "git_remove_cmd", "remove command",
139
+ "Pre-delete remove command (optional):", when=is_type("git"),
140
+ ),
141
+ # script
142
+ text(
143
+ "script_url", "script URL", "Install script URL (curl | sh):",
144
+ required=True, when=is_type("script"),
145
+ ),
146
+ # every type collects check_cmd — required nowhere, defaulted to the key
147
+ # for the types where the binary name almost always matches
148
+ text(
149
+ "check_cmd", "check command", "Command to check if installed:",
150
+ default=lambda a: a.get("key", "") if a.get("type") in ("npm", "uvx", "apt") else "",
151
+ ),
152
+ # bash
153
+ ui.Step(
154
+ "install_script", "install script", _ask_install_script,
155
+ when=is_type("bash"), show=_show_script,
156
+ ),
157
+ ui.Step(
158
+ "remove_script", "remove script", _ask_remove_script,
159
+ when=is_type("bash"), show=_show_script,
160
+ ),
161
+ text("help_cmd", "help command", "Help command (optional, e.g. tool --help):"),
162
+ text("docs_url", "docs URL", "Documentation URL (optional):"),
163
+ ]
145
164
 
146
165
 
147
- def _prompt_key() -> str:
166
+ def _ask_key(answers: dict):
148
167
  while True:
149
- key = ui.text_input("Package key (lowercase, hyphens ok):", required=True)
168
+ key = ui.text_input_back(
169
+ "Package key (lowercase, hyphens ok):",
170
+ default=answers.get("key", ""),
171
+ required=True,
172
+ )
173
+ if key is ui.BACK:
174
+ return ui.BACK
150
175
  if not _VALID_KEY.match(key):
151
176
  ui.error("Key must be lowercase letters, digits, hyphens, or underscores.")
152
177
  continue
153
178
  if registry.exists(key):
154
179
  ui.error(f"A package with key '{key}' already exists.")
155
- if not ui.confirm("Use a different key?"):
156
- return ""
157
180
  continue
158
181
  return key
159
182
 
160
183
 
184
+ def _ask_install_script(answers: dict):
185
+ script = _edit_script("install", answers.get("name", ""), required=True,
186
+ prefill=answers.get("install_script", ""))
187
+ if script is None:
188
+ ui.warn("No install script provided.")
189
+ return ui.BACK
190
+ return script
191
+
192
+
193
+ def _ask_remove_script(answers: dict):
194
+ script = _edit_script(
195
+ "remove", answers.get("name", ""), required=False,
196
+ prefill=answers.get("remove_script", ""),
197
+ )
198
+ return _validate_remove_script(
199
+ script or "",
200
+ answers.get("install_script", ""),
201
+ answers.get("check_cmd", ""),
202
+ answers.get("name", ""),
203
+ )
204
+
205
+
206
+ def _show_script(script) -> str:
207
+ return _truncate_script(str(script))
208
+
209
+
161
210
  def _edit_script(
162
211
  action: str,
163
212
  package_name: str,
@@ -5,31 +5,56 @@ from concurrent.futures import ThreadPoolExecutor
5
5
 
6
6
  import click
7
7
  import questionary
8
+ from rich.markup import escape
8
9
 
9
10
  from dev_setup import registry, ui
10
11
  from dev_setup.base import Tool
12
+ from dev_setup.commands._plan import plan_for, plan_summary
11
13
 
12
14
 
13
15
  @click.command("install")
16
+ @click.option("-y", "--yes", is_flag=True, help="Skip plan previews and confirmations.")
14
17
  @click.argument("packages", nargs=-1)
15
- def install_cmd(packages: tuple[str, ...]) -> None:
18
+ def install_cmd(packages: tuple[str, ...], yes: bool) -> None:
16
19
  """Install packages. Interactive picker when called with no arguments."""
17
20
  if not packages:
18
- _install_interactive()
19
- else:
20
- failed = False
21
- for key in packages:
22
- if not registry.exists(key):
23
- ui.error(f"Unknown package: '{key}'")
24
- failed = True
25
- continue
26
- if not _install_one(registry.get(key)): # type: ignore[arg-type]
27
- failed = True
28
- if failed:
21
+ _install_interactive(yes=yes)
22
+ return
23
+
24
+ tools: list[Tool] = []
25
+ for key in packages:
26
+ tool = registry.get(key)
27
+ if tool is None:
28
+ ui.error(f"Unknown package: '{key}'")
29
29
  sys.exit(1)
30
+ tools.append(tool)
30
31
 
32
+ # Report already-installed tools up front so the plan only covers real work.
33
+ results: list[tuple[str, str, str]] = []
34
+ to_install: list[Tool] = []
35
+ for t in tools:
36
+ if t.is_installed():
37
+ version = t.get_version()
38
+ ui.success(f"{t.name} is already installed: {version}")
39
+ results.append(
40
+ (t.key, "skip", f"already installed{': ' + version if version else ''}")
41
+ )
42
+ else:
43
+ to_install.append(t)
44
+
45
+ if not to_install:
46
+ _report(results)
47
+ return
31
48
 
32
- def install_by_key(key: str) -> bool:
49
+ if not yes and not _confirm_plans(to_install):
50
+ ui.warn("Aborted.")
51
+ return
52
+
53
+ results += _install_all(to_install, yes=yes, confirmed=True)
54
+ _report(results)
55
+
56
+
57
+ def install_by_key(key: str, *, yes: bool = False) -> bool:
33
58
  """Install one tool by catalog key, reporting through the normal install output.
34
59
 
35
60
  For callers outside the command layer — a configurator that offers to install a
@@ -40,19 +65,61 @@ def install_by_key(key: str) -> bool:
40
65
  if tool is None:
41
66
  ui.error(f"Unknown package: '{key}'")
42
67
  return False
43
- return _install_one(tool)
68
+ status, _detail = _install_one(tool, yes=yes)
69
+ # "skip" covers both already-installed (success for the caller's purpose)
70
+ # and declined-plan — the installed probe distinguishes them.
71
+ return status == "ok" or tool.is_installed()
72
+
73
+
74
+ def _install_all(
75
+ tools: list[Tool], *, yes: bool, confirmed: bool = False
76
+ ) -> list[tuple[str, str, str]]:
77
+ """Install each tool in order, tracking a summary row per tool."""
78
+ results: list[tuple[str, str, str]] = []
79
+ for i, tool in enumerate(tools, 1):
80
+ pos = f"{i}/{len(tools)}" if len(tools) > 1 else ""
81
+ status, detail = _install_one(tool, yes=yes, position=pos, confirmed=confirmed)
82
+ results.append((tool.key, status, detail))
83
+ return results
84
+
85
+
86
+ def _install_one(
87
+ tool: Tool, *, yes: bool = False, position: str = "", confirmed: bool = False
88
+ ) -> tuple[str, str]:
89
+ """Install one tool. Returns (status, detail): status is "ok" | "skip" | "fail"."""
90
+ ui.section(tool.name, note=position)
44
91
 
45
-
46
- def _install_one(tool: Tool) -> bool:
47
- ui.section(tool.name)
48
92
  if tool.is_installed():
49
- ui.success(f"{tool.name} is already installed: {tool.get_version()}")
50
- return True
93
+ version = tool.get_version()
94
+ ui.success(f"{tool.name} is already installed: {version}")
95
+ return "skip", f"already installed{': ' + version if version else ''}"
96
+
51
97
  missing = registry.missing_requires(tool)
52
98
  if missing:
53
- ui.error(f"Cannot install {tool.name} — missing required tools: {', '.join(missing)}")
54
- ui.dim(f"Install first: devstuff install {' '.join(missing)}")
55
- return False
99
+ unresolvable = [k for k in missing if not registry.exists(k)]
100
+ if unresolvable:
101
+ ui.error(
102
+ f"Cannot install {tool.name} — unknown required tools: "
103
+ f"{', '.join(unresolvable)}"
104
+ )
105
+ return "fail", "unknown requires"
106
+ if yes or ui.confirm(
107
+ f"{tool.name} requires {', '.join(missing)} — install them first?",
108
+ default=True,
109
+ ):
110
+ for dep_key in missing:
111
+ dep = registry.get(dep_key)
112
+ status, detail = _install_one(dep, yes=yes) if dep else ("fail", "")
113
+ if status == "fail":
114
+ return "fail", f"required tool {dep_key} failed"
115
+ else:
116
+ ui.error(f"Cannot install {tool.name} — missing: {', '.join(missing)}")
117
+ return "fail", "declined required tools"
118
+
119
+ if not confirmed and not yes and not _confirm_plan(tool):
120
+ ui.dim("Skipped.")
121
+ return "skip", "skipped"
122
+
56
123
  try:
57
124
  version = tool.install()
58
125
  msg = f"{tool.name} installed"
@@ -60,16 +127,39 @@ def _install_one(tool: Tool) -> bool:
60
127
  msg += f": {version}"
61
128
  ui.success(msg)
62
129
  except Exception as exc:
63
- ui.error(f"Failed to install {tool.name}: {exc}")
64
- return False
130
+ ui.error(f"Failed to install {tool.name}: {escape(str(exc))}")
131
+ return "fail", str(exc).splitlines()[-1][:120]
65
132
 
66
133
  # A freshly installed tool with a setup wizard is the moment to mention it.
67
134
  from dev_setup.commands.configure_cmd import offer_after_install
68
135
  offer_after_install(tool.key)
69
- return True
136
+ return "ok", version or "installed"
137
+
138
+
139
+ def _confirm_plan(tool: Tool) -> bool:
140
+ """Single-tool plan preview + confirm. Returns True to proceed."""
141
+ ui.plan_panel(f"Install {tool.name}", plan_for(tool, "install"))
142
+ return ui.confirm(f"Install {tool.name}?", default=True)
70
143
 
71
144
 
72
- def _install_interactive() -> None:
145
+ def _confirm_plans(tools: list[Tool]) -> bool:
146
+ """Batch plan preview — one row per tool, one confirm for the run."""
147
+ if len(tools) == 1:
148
+ return _confirm_plan(tools[0])
149
+ rows = [(t.key, plan_summary(t, "install")) for t in tools]
150
+ ui.batch_plan_panel(rows, "Install")
151
+ return ui.confirm(f"Install {len(tools)} packages?", default=True)
152
+
153
+
154
+ def _report(results: list[tuple[str, str, str]]) -> None:
155
+ """Print the summary table and exit non-zero if anything failed."""
156
+ if len(results) > 1:
157
+ ui.summary(results, title="Install")
158
+ if any(s == "fail" for _, s, _ in results):
159
+ sys.exit(1)
160
+
161
+
162
+ def _install_interactive(*, yes: bool) -> None:
73
163
  ui.print_banner()
74
164
  tools = registry.all_tools()
75
165
 
@@ -100,15 +190,22 @@ def _install_interactive() -> None:
100
190
  if len(desc) > desc_width:
101
191
  desc = desc[: desc_width - 1] + "…"
102
192
  if is_inst:
103
- disabled = True
193
+ disabled = "installed"
104
194
  elif missing:
105
195
  disabled = f"requires {', '.join(missing)}"
106
196
  else:
107
197
  disabled = None
108
- title = [
109
- ("class:check", "● " if is_inst else " "),
110
- ("class:text", f"{t.key:<{key_width}}{desc}"),
111
- ]
198
+ # A token-list title is emitted verbatim — questionary never applies
199
+ # `highlighted`/`selected` to it — so only disabled rows (skipped by
200
+ # arrow keys, never pointed) may carry styled tokens.
201
+ title: str | list[tuple[str, str]] = (
202
+ [
203
+ ("class:check", "● " if is_inst else " "),
204
+ ("class:text", f"{t.key:<{key_width}}{desc}"),
205
+ ]
206
+ if disabled
207
+ else f" {t.key:<{key_width}}{desc}"
208
+ )
112
209
  choices.append(questionary.Choice(
113
210
  title=title,
114
211
  value=t.key,
@@ -126,17 +223,10 @@ def _install_interactive() -> None:
126
223
  ui.info("No packages selected.")
127
224
  return
128
225
 
129
- to_install = selected
130
-
131
- if not ui.confirm(f"Install {len(to_install)} package(s)?"):
226
+ tools_to_install = [t for k in selected if (t := registry.get(k)) is not None]
227
+ if not yes and not _confirm_plans(tools_to_install):
132
228
  ui.warn("Aborted.")
133
229
  return
134
230
 
135
- failed = False
136
- for key in to_install:
137
- tool = registry.get(key)
138
- if tool and not _install_one(tool):
139
- failed = True
140
-
141
- if failed:
142
- sys.exit(1)
231
+ results = _install_all(tools_to_install, yes=yes, confirmed=True)
232
+ _report(results)