scriptvault 0.0.1__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,8 @@
1
+ """ScriptVault: store and run project commands in a hidden vault directory."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("scriptvault")
7
+ except PackageNotFoundError:
8
+ __version__ = "0.0.0"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
scriptvault/cli.py ADDED
@@ -0,0 +1,475 @@
1
+ """Command-line interface for ScriptVault."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import shlex
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from . import __version__, templates
13
+ from .run import run_target
14
+ from .term import GREEN, MAGENTA, Palette
15
+ from .vault import (
16
+ NAME_RE,
17
+ Orchestration,
18
+ Script,
19
+ VaultError,
20
+ VaultNotFound,
21
+ find_root,
22
+ hidden_dir_name,
23
+ load_vault,
24
+ )
25
+
26
+ COMMANDS = ("add", "completion", "edit", "help", "init", "list", "run")
27
+ BUILTIN_COMMANDS = set(COMMANDS) | {"__names"}
28
+ RESERVED_NAMES = BUILTIN_COMMANDS | {"config", "env"}
29
+
30
+
31
+ class CLIError(Exception):
32
+ """A user-facing error: the message is printed and the code is returned."""
33
+
34
+ def __init__(self, message: str, code: int = 1):
35
+ super().__init__(message)
36
+ self.code = code
37
+
38
+
39
+ def _toml_str(value: str) -> str:
40
+ """Escape a string for use inside a TOML basic string literal."""
41
+ return json.dumps(value)[1:-1]
42
+
43
+
44
+ def cmd_init(args: argparse.Namespace) -> int:
45
+ """Initialize a vault in a project directory."""
46
+ path = Path(args.path)
47
+ if not path.is_dir():
48
+ raise CLIError(f"'{path}' is not a directory")
49
+ root = path.resolve()
50
+
51
+ hidden = root / hidden_dir_name()
52
+ if hidden.exists() and not hidden.is_dir():
53
+ raise CLIError(f"'{hidden}' exists and is not a directory")
54
+ vault_toml = hidden / "vault.toml"
55
+ if vault_toml.is_file():
56
+ raise CLIError(f"a vault already exists at '{vault_toml}'")
57
+
58
+ name = args.name or root.name
59
+ if not name:
60
+ raise CLIError("cannot derive a vault name from path; pass --name")
61
+
62
+ (hidden / "scripts").mkdir(parents=True, exist_ok=True)
63
+ vault_toml.write_text(
64
+ templates.VAULT_TOML.format(name=_toml_str(name)), encoding="utf-8"
65
+ )
66
+
67
+ env_path = hidden / ".env"
68
+ if not env_path.exists():
69
+ env_path.write_text(templates.GLOBAL_ENV, encoding="utf-8")
70
+
71
+ print(f"initialized vault {name!r} at {hidden}")
72
+ return 0
73
+
74
+
75
+ def _target_json(target: Script | Orchestration) -> dict:
76
+ if isinstance(target, Orchestration):
77
+ return {
78
+ "name": target.name,
79
+ "kind": "orchestration",
80
+ "description": target.description,
81
+ "steps": [step.describe() for step in target.steps],
82
+ }
83
+ entry: dict = {
84
+ "name": target.name,
85
+ "kind": "script",
86
+ "source": target.kind,
87
+ "description": target.description,
88
+ }
89
+ if target.path is not None:
90
+ entry["path"] = str(target.path)
91
+ else:
92
+ entry["cmd"] = target.cmd
93
+ return entry
94
+
95
+
96
+ def _load_vault(path: str | None = None):
97
+ """Find and load the vault, translating errors into CLIError."""
98
+ try:
99
+ root = find_root(Path(path) if path is not None else None)
100
+ vault = load_vault(root)
101
+ except VaultNotFound as exc:
102
+ raise CLIError(str(exc)) from exc
103
+ except VaultError as exc:
104
+ raise CLIError(str(exc)) from exc
105
+ return vault
106
+
107
+
108
+ def cmd_list(args: argparse.Namespace) -> int:
109
+ """List scripts and orchestrations in the vault."""
110
+ vault = _load_vault(args.path)
111
+
112
+ if args.json:
113
+ json.dump(
114
+ [_target_json(target) for target in vault.targets.values()],
115
+ sys.stdout,
116
+ indent=2,
117
+ )
118
+ sys.stdout.write("\n")
119
+ return 0
120
+
121
+ rows = [
122
+ (
123
+ name,
124
+ "orchestration" if isinstance(target, Orchestration) else "script",
125
+ target.description,
126
+ )
127
+ for name, target in vault.targets.items()
128
+ ]
129
+ if not rows:
130
+ print("no scripts or orchestrations defined")
131
+ return 0
132
+
133
+ header = ("NAME", "KIND", "DESCRIPTION")
134
+ widths = [
135
+ max(len(header[i]), *(len(row[i]) for row in rows)) for i in range(3)
136
+ ]
137
+ palette = Palette(sys.stdout)
138
+ for is_header, row in enumerate((header, *rows)):
139
+ parts = []
140
+ for i, cell in enumerate(row):
141
+ plain = cell if i == len(row) - 1 else cell.ljust(widths[i])
142
+ if palette.enabled and is_header == 0:
143
+ parts.append(palette.paint(plain, bold=True))
144
+ elif palette.enabled and i == 0:
145
+ parts.append(palette.paint(plain, bold=True))
146
+ elif palette.enabled and i == 1:
147
+ fg = MAGENTA if cell == "orchestration" else GREEN
148
+ parts.append(palette.paint(plain, fg=fg))
149
+ else:
150
+ parts.append(plain)
151
+ print(" ".join(parts))
152
+ return 0
153
+
154
+
155
+ def cmd_run(args: argparse.Namespace) -> int:
156
+ """Run a script or orchestration from the vault."""
157
+ vault = _load_vault(None)
158
+ if vault.get(args.name) is None:
159
+ available = ", ".join(vault.targets) or "none"
160
+ raise CLIError(
161
+ f"unknown target {args.name!r} (available: {available})", 127
162
+ )
163
+ run_args = list(args.args or [])
164
+ if run_args and run_args[0] == "--":
165
+ run_args = run_args[1:]
166
+ try:
167
+ return run_target(vault, args.name, run_args)
168
+ except OSError as exc:
169
+ detail = exc.strerror or str(exc)
170
+ raise CLIError(f"failed to run {args.name!r}: {detail}")
171
+
172
+
173
+ def cmd_add(args: argparse.Namespace) -> int:
174
+ """Create a new file script in the vault."""
175
+ name = args.name
176
+ if not NAME_RE.match(name):
177
+ raise CLIError(f"invalid name {name!r}: must match {NAME_RE.pattern}")
178
+ if name in RESERVED_NAMES:
179
+ raise CLIError(f"'{name}' is a reserved name")
180
+ vault = _load_vault(None)
181
+ if vault.get(name) is not None:
182
+ raise CLIError(f"target {name!r} already exists")
183
+
184
+ if args.from_stdin:
185
+ if sys.stdin.isatty():
186
+ raise CLIError("--in requires the script to be piped on stdin")
187
+ body = sys.stdin.read()
188
+ else:
189
+ body = templates.SCRIPT_TEMPLATE.format(name=name)
190
+ if not body.endswith("\n"):
191
+ body += "\n"
192
+
193
+ vault.scripts_dir.mkdir(parents=True, exist_ok=True)
194
+ path = vault.scripts_dir / f"{name}.sh"
195
+ if path.exists():
196
+ raise CLIError(f"'{path}' already exists")
197
+ path.write_text(body, encoding="utf-8")
198
+ path.chmod(0o755)
199
+ print(path)
200
+ return 0
201
+
202
+
203
+ _LINE_EDITORS = {"vi", "vim", "nvim"}
204
+
205
+
206
+ def _editor_argv(path: Path, line: int | None = None) -> list[str]:
207
+ """Build the argv for the user's editor, optionally seeking a line."""
208
+ editor = os.environ.get("EDITOR") or os.environ.get("VISUAL") or "vi"
209
+ argv = shlex.split(editor)
210
+ if not argv:
211
+ raise CLIError("editor is empty")
212
+ if line is not None and os.path.basename(argv[0]) in _LINE_EDITORS:
213
+ argv.append(f"+{line}")
214
+ argv.append(str(path))
215
+ return argv
216
+
217
+
218
+ def _run_editor(argv: list[str]) -> int:
219
+ """Run the user's editor and translate startup failures into CLI errors."""
220
+ try:
221
+ proc = subprocess.run(argv)
222
+ except FileNotFoundError:
223
+ raise CLIError(f"editor command not found: {argv[0]}", 127)
224
+ except OSError as exc:
225
+ detail = exc.strerror or str(exc)
226
+ raise CLIError(f"failed to start editor: {detail}")
227
+ if proc.returncode:
228
+ raise CLIError(f"editor exited with code {proc.returncode}", proc.returncode)
229
+ return 0
230
+
231
+
232
+ def _toml_line(vault, name: str) -> int | None:
233
+ """1-based line number of the [scripts.NAME] / [orchestrate.NAME] header."""
234
+ lines = vault.vault_toml.read_text(encoding="utf-8").splitlines()
235
+ exact = {f"[scripts.{name}]", f"[orchestrate.{name}]"}
236
+ for i, line in enumerate(lines, 1):
237
+ part = line.split("#", 1)[0].strip()
238
+ if "".join(part.split()) in exact:
239
+ return i
240
+ return None
241
+
242
+
243
+ def _interactive() -> bool:
244
+ try:
245
+ return sys.stdin.isatty() and sys.stdout.isatty()
246
+ except (AttributeError, ValueError):
247
+ return False
248
+
249
+
250
+ def _select_target(vault) -> str:
251
+ """Interactively pick a target (or 'config'/'env') to edit."""
252
+ choices = list(vault.targets)
253
+ for pseudo in ("config", "env"):
254
+ if pseudo not in choices:
255
+ choices.append(pseudo)
256
+ fzf = shutil.which("fzf")
257
+ if fzf and _interactive():
258
+ try:
259
+ proc = subprocess.run(
260
+ [fzf],
261
+ input="\n".join(choices) + "\n",
262
+ capture_output=True,
263
+ text=True,
264
+ )
265
+ except OSError:
266
+ proc = None
267
+ if proc is not None:
268
+ if proc.returncode != 0:
269
+ raise CLIError("nothing selected")
270
+ choice = proc.stdout.strip()
271
+ if choice in choices:
272
+ return choice
273
+ raise CLIError(f"unknown selection {choice!r}")
274
+ print("edit which target?")
275
+ for i, name in enumerate(choices, 1):
276
+ print(f" {i}. {name}")
277
+ try:
278
+ raw = input("> ").strip()
279
+ except EOFError:
280
+ raise CLIError("nothing selected")
281
+ if not raw.isdigit() or not 1 <= int(raw) <= len(choices):
282
+ raise CLIError(f"nothing selected (choose 1-{len(choices)})")
283
+ return choices[int(raw) - 1]
284
+
285
+
286
+ def cmd_edit(args: argparse.Namespace) -> int:
287
+ """Edit a script, its env, or the vault configuration in $EDITOR."""
288
+ vault = _load_vault(None)
289
+ name = args.name
290
+ kind = args.kind
291
+ if name is None:
292
+ name = _select_target(vault)
293
+ if name in ("config", "env"):
294
+ if kind is not None:
295
+ raise CLIError(f"{name!r} does not take a kind argument")
296
+ if name == "config":
297
+ return _run_editor(_editor_argv(vault.vault_toml))
298
+ return _run_editor(_editor_argv(vault.global_env))
299
+ target = vault.get(name)
300
+ if target is None:
301
+ available = ", ".join(vault.targets) or "none"
302
+ raise CLIError(
303
+ f"unknown target {name!r} (available: {available})", 127
304
+ )
305
+ if kind == "env":
306
+ if not isinstance(target, Script):
307
+ raise CLIError(f"'{name}' is an orchestration and has no env file")
308
+ path = target.env_file(vault)
309
+ if not path.exists():
310
+ path.parent.mkdir(parents=True, exist_ok=True)
311
+ path.write_text(
312
+ templates.SCRIPT_ENV.format(name=name), encoding="utf-8"
313
+ )
314
+ return _run_editor(_editor_argv(path))
315
+ if kind == "config":
316
+ if isinstance(target, Orchestration) or target.path is None:
317
+ line = _toml_line(vault, name)
318
+ else:
319
+ line = None
320
+ return _run_editor(_editor_argv(vault.vault_toml, line))
321
+ if isinstance(target, Script) and target.path is not None:
322
+ return _run_editor(_editor_argv(target.path))
323
+ line = _toml_line(vault, name)
324
+ return _run_editor(_editor_argv(vault.vault_toml, line))
325
+
326
+
327
+ def _render_completion(template: str) -> str:
328
+ return template.replace("__COMMANDS__", " ".join(COMMANDS))
329
+
330
+
331
+ _COMPLETIONS = {
332
+ "bash": _render_completion(templates.COMPLETION_BASH),
333
+ "zsh": _render_completion(templates.COMPLETION_ZSH),
334
+ "fish": _render_completion(templates.COMPLETION_FISH),
335
+ }
336
+
337
+
338
+ def cmd_completion(args: argparse.Namespace) -> int:
339
+ """Print a completion script for the given shell."""
340
+ print(_COMPLETIONS[args.shell], end="")
341
+ return 0
342
+
343
+
344
+ def cmd_names(_args: argparse.Namespace | None = None) -> int:
345
+ """Print target names, one per line (used by shell completions)."""
346
+ vault = _load_vault(None)
347
+ for name in vault.targets:
348
+ print(name)
349
+ return 0
350
+
351
+
352
+ def build_parser() -> argparse.ArgumentParser:
353
+ parser = argparse.ArgumentParser(
354
+ prog="sv",
355
+ description="Store and run project commands in a hidden vault directory.",
356
+ )
357
+ parser.add_argument(
358
+ "--version", action="version", version=f"sv {__version__}"
359
+ )
360
+ sub = parser.add_subparsers(dest="command", required=True, title="commands")
361
+
362
+ init = sub.add_parser("init", help="initialize a vault in a project directory")
363
+ init.add_argument(
364
+ "path",
365
+ nargs="?",
366
+ default=".",
367
+ metavar="PATH",
368
+ help="project directory (default: current directory)",
369
+ )
370
+ init.add_argument(
371
+ "--name",
372
+ metavar="NAME",
373
+ help="vault name (default: the directory name)",
374
+ )
375
+ init.set_defaults(func=cmd_init)
376
+
377
+ lst = sub.add_parser(
378
+ "list", help="list scripts and orchestrations in the vault"
379
+ )
380
+ lst.add_argument(
381
+ "path",
382
+ nargs="?",
383
+ default=".",
384
+ metavar="PATH",
385
+ help="directory to search for a vault from (default: current directory)",
386
+ )
387
+ lst.add_argument(
388
+ "--json", action="store_true", help="output as a JSON array"
389
+ )
390
+ lst.set_defaults(func=cmd_list)
391
+
392
+ run = sub.add_parser("run", help="run a script or orchestration")
393
+ run.add_argument(
394
+ "name", metavar="NAME", help="script or orchestration to run"
395
+ )
396
+ run.add_argument(
397
+ "args",
398
+ nargs=argparse.REMAINDER,
399
+ metavar="ARG",
400
+ help="arguments to pass to the script, optionally after --",
401
+ )
402
+ run.set_defaults(func=cmd_run)
403
+
404
+ add = sub.add_parser(
405
+ "add", help="create a new file script in the vault"
406
+ )
407
+ add.add_argument(
408
+ "name", metavar="NAME", help="name of the script to create"
409
+ )
410
+ add.add_argument(
411
+ "--in",
412
+ dest="from_stdin",
413
+ action="store_true",
414
+ help="read the script body from stdin instead of the template",
415
+ )
416
+ add.set_defaults(func=cmd_add)
417
+
418
+ edit = sub.add_parser(
419
+ "edit", help="edit a script, its env, or the vault configuration"
420
+ )
421
+ edit.add_argument(
422
+ "name",
423
+ nargs="?",
424
+ metavar="NAME",
425
+ help="target to edit (default: choose interactively)",
426
+ )
427
+ edit.add_argument(
428
+ "kind",
429
+ nargs="?",
430
+ choices=("env", "config"),
431
+ help="edit the target's env file or its vault configuration",
432
+ )
433
+ edit.set_defaults(func=cmd_edit)
434
+
435
+ completion = sub.add_parser(
436
+ "completion", help="print a completion script for a shell"
437
+ )
438
+ completion.add_argument(
439
+ "shell",
440
+ choices=sorted(_COMPLETIONS),
441
+ help="shell to print completions for",
442
+ )
443
+ completion.set_defaults(func=cmd_completion)
444
+
445
+ return parser
446
+
447
+
448
+ def _run_command(func, args) -> int:
449
+ try:
450
+ return func(args)
451
+ except CLIError as exc:
452
+ print(f"sv: {exc}", file=sys.stderr)
453
+ return exc.code
454
+
455
+
456
+ def main(argv: list[str] | None = None) -> int:
457
+ argv = list(sys.argv[1:] if argv is None else argv)
458
+ if argv and argv[0] == "__names":
459
+ return _run_command(cmd_names, None)
460
+ if argv and argv[0] == "help":
461
+ build_parser().print_help()
462
+ return 0
463
+ if (
464
+ argv
465
+ and not argv[0].startswith("-")
466
+ and argv[0] not in BUILTIN_COMMANDS
467
+ ):
468
+ argv = ["run", *argv]
469
+ parser = build_parser()
470
+ args = parser.parse_args(argv)
471
+ return _run_command(args.func, args)
472
+
473
+
474
+ if __name__ == "__main__":
475
+ sys.exit(main())
scriptvault/envfile.py ADDED
@@ -0,0 +1,35 @@
1
+ """Parse dotenv-style files (KEY=VALUE lines, comments, optional quotes)."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+
6
+ _KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
7
+
8
+
9
+ def _parse_value(raw: str) -> str:
10
+ value = raw.strip()
11
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
12
+ return value[1:-1]
13
+ for i, ch in enumerate(value):
14
+ if ch == "#" and (i == 0 or value[i - 1] in " \t"):
15
+ return value[:i].rstrip()
16
+ return value
17
+
18
+
19
+ def parse_env_file(path: Path) -> dict[str, str]:
20
+ """Parse a dotenv-style file into a dict of string values."""
21
+ values: dict[str, str] = {}
22
+ for line in path.read_text(encoding="utf-8").splitlines():
23
+ line = line.strip()
24
+ if not line or line.startswith("#"):
25
+ continue
26
+ if line.startswith("export "):
27
+ line = line[len("export "):].lstrip()
28
+ if "=" not in line:
29
+ continue
30
+ key, _, value = line.partition("=")
31
+ key = key.strip()
32
+ if not _KEY_RE.match(key):
33
+ continue
34
+ values[key] = _parse_value(value)
35
+ return values