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.
scriptvault/vault.py ADDED
@@ -0,0 +1,326 @@
1
+ """Vault discovery, loading, and validation."""
2
+
3
+ import os
4
+ import re
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from .envfile import parse_env_file
10
+
11
+ NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
12
+
13
+ DEFAULT_HIDDEN_DIR = ".sv"
14
+ ENV_HIDDEN_DIR_VAR = "SV_HIDDEN_DIR"
15
+
16
+
17
+ class ScriptVaultError(Exception):
18
+ """Base error for ScriptVault."""
19
+
20
+
21
+ class VaultNotFound(ScriptVaultError):
22
+ """No vault was found at or above the current directory."""
23
+
24
+
25
+ class VaultError(ScriptVaultError):
26
+ """The vault exists but its configuration is invalid."""
27
+
28
+
29
+ def hidden_dir_name() -> str:
30
+ return os.environ.get(ENV_HIDDEN_DIR_VAR, DEFAULT_HIDDEN_DIR)
31
+
32
+
33
+ def find_root(start: Path | None = None) -> Path:
34
+ """Walk up from `start` (default: cwd) looking for a vault."""
35
+ current = (start or Path.cwd()).resolve()
36
+ hidden = hidden_dir_name()
37
+ for candidate in [current, *current.parents]:
38
+ if (candidate / hidden / "vault.toml").is_file():
39
+ return candidate
40
+ raise VaultNotFound(
41
+ f"no vault found; run 'sv init' in a project directory"
42
+ )
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Script:
47
+ name: str
48
+ cmd: str = ""
49
+ path: Path | None = None
50
+ description: str = ""
51
+
52
+ @property
53
+ def kind(self) -> str:
54
+ return "file" if self.path is not None else "inline"
55
+
56
+ def env_file(self, vault: "Vault") -> Path:
57
+ return vault.scripts_dir / f"{self.name}.env"
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Step:
62
+ run_name: str | None = None
63
+ run_args: list[str] = field(default_factory=list)
64
+ parallel: list[str] | None = None
65
+ sh: str | None = None
66
+
67
+ @property
68
+ def kind(self) -> str:
69
+ if self.run_name is not None:
70
+ return "run"
71
+ if self.parallel is not None:
72
+ return "parallel"
73
+ return "sh"
74
+
75
+ def describe(self) -> str:
76
+ if self.run_name is not None:
77
+ base = f"run {self.run_name}"
78
+ if self.run_args:
79
+ base += " " + " ".join(repr(a) for a in self.run_args)
80
+ return base
81
+ if self.parallel is not None:
82
+ return f"parallel {list(self.parallel)}"
83
+ return f"sh {self.sh!r}"
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Orchestration:
88
+ name: str
89
+ steps: list[Step]
90
+ description: str = ""
91
+
92
+ @property
93
+ def kind(self) -> str:
94
+ return "orchestration"
95
+
96
+
97
+ Target = Script | Orchestration
98
+
99
+
100
+ class Vault:
101
+ def __init__(self, root: Path):
102
+ self.root = root
103
+ self.hidden_dir = root / hidden_dir_name()
104
+ self.name = ""
105
+ self.shell = "/bin/sh"
106
+ self.scripts: dict[str, Script] = {}
107
+ self.orchestrations: dict[str, Orchestration] = {}
108
+
109
+ @property
110
+ def vault_toml(self) -> Path:
111
+ return self.hidden_dir / "vault.toml"
112
+
113
+ @property
114
+ def global_env(self) -> Path:
115
+ return self.hidden_dir / ".env"
116
+
117
+ @property
118
+ def scripts_dir(self) -> Path:
119
+ return self.hidden_dir / "scripts"
120
+
121
+ @property
122
+ def targets(self) -> dict[str, Target]:
123
+ merged: dict[str, Target] = {**self.scripts, **self.orchestrations}
124
+ return dict(sorted(merged.items()))
125
+
126
+ def get(self, name: str) -> Target | None:
127
+ if name in self.scripts:
128
+ return self.scripts[name]
129
+ if name in self.orchestrations:
130
+ return self.orchestrations[name]
131
+ return None
132
+
133
+
134
+ def _validate_name(name: str) -> None:
135
+ if not NAME_RE.match(name):
136
+ raise VaultError(
137
+ f"invalid name {name!r}: must match {NAME_RE.pattern}"
138
+ )
139
+
140
+
141
+ def _require_str(mapping: dict, key: str, context: str) -> str:
142
+ value = mapping.get(key)
143
+ if not isinstance(value, str) or not value:
144
+ raise VaultError(f"{context}: {key!r} must be a non-empty string")
145
+ return value
146
+
147
+
148
+ def _parse_steps(raw_steps: object, known_names: set[str], where: str) -> list[Step]:
149
+ if not isinstance(raw_steps, list) or not raw_steps:
150
+ raise VaultError(f"{where}: 'steps' must be a non-empty list")
151
+ steps: list[Step] = []
152
+ for i, raw in enumerate(raw_steps):
153
+ if not isinstance(raw, dict):
154
+ raise VaultError(f"{where}.steps[{i}]: step must be a table")
155
+ kinds = [k for k in ("run", "parallel", "sh") if k in raw]
156
+ if len(kinds) != 1:
157
+ raise VaultError(
158
+ f"{where}.steps[{i}]: step must have exactly one of "
159
+ "'run', 'parallel', 'sh'"
160
+ )
161
+ extra = set(raw) - {kinds[0], "args"}
162
+ if extra:
163
+ raise VaultError(
164
+ f"{where}.steps[{i}]: unknown key(s) {sorted(extra)}"
165
+ )
166
+ kind = kinds[0]
167
+ run_name: str | None = None
168
+ run_args: list[str] = []
169
+ parallel: list[str] | None = None
170
+ sh: str | None = None
171
+ if kind == "run":
172
+ target = raw["run"]
173
+ if not isinstance(target, str) or not target:
174
+ raise VaultError(f"{where}.steps[{i}]: 'run' must be a non-empty string")
175
+ _validate_name(target)
176
+ if target not in known_names:
177
+ raise VaultError(
178
+ f"{where}.steps[{i}]: unknown script or orchestration {target!r}"
179
+ )
180
+ run_name = target
181
+ args = raw.get("args", [])
182
+ if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
183
+ raise VaultError(f"{where}.steps[{i}]: 'args' must be a list of strings")
184
+ run_args = list(args)
185
+ elif kind == "parallel":
186
+ names = raw["parallel"]
187
+ if not isinstance(names, list) or not names or not all(
188
+ isinstance(n, str) for n in names
189
+ ):
190
+ raise VaultError(f"{where}.steps[{i}]: 'parallel' must be a non-empty list of names")
191
+ for n in names:
192
+ _validate_name(n)
193
+ if n not in known_names:
194
+ raise VaultError(f"{where}.steps[{i}]: unknown script or orchestration {n!r}")
195
+ parallel = list(names)
196
+ else:
197
+ sh = _require_str(raw, "sh", f"{where}.steps[{i}]")
198
+ if "args" in raw and kind != "run":
199
+ raise VaultError(f"{where}.steps[{i}]: 'args' is only valid with 'run'")
200
+ steps.append(
201
+ Step(
202
+ run_name=run_name,
203
+ run_args=run_args,
204
+ parallel=parallel,
205
+ sh=sh,
206
+ )
207
+ )
208
+ return steps
209
+
210
+
211
+ def load_vault(root: Path) -> Vault:
212
+ """Load and validate a vault rooted at `root`."""
213
+ vault = Vault(root)
214
+ toml_path = vault.vault_toml
215
+ if not toml_path.is_file():
216
+ raise VaultNotFound(
217
+ f"no vault found; run 'sv init' in a project directory"
218
+ )
219
+ try:
220
+ data = tomllib.loads(toml_path.read_text(encoding="utf-8"))
221
+ except tomllib.TOMLDecodeError as exc:
222
+ raise VaultError(f"invalid TOML in {toml_path}: {exc}") from exc
223
+
224
+ table = data.get("vault", {})
225
+ if not isinstance(table, dict):
226
+ raise VaultError("'vault' table must be a table")
227
+ if not isinstance(table.get("name"), str) or not table["name"]:
228
+ raise VaultError("'vault.name' must be a non-empty string")
229
+ vault.name = table["name"]
230
+ shell = table.get("shell", "/bin/sh")
231
+ if not isinstance(shell, str) or not shell:
232
+ raise VaultError("'vault.shell' must be a non-empty string")
233
+ vault.shell = shell
234
+
235
+ inline: dict[str, Script] = {}
236
+ scripts_section = data.get("scripts", {})
237
+ if not isinstance(scripts_section, dict):
238
+ raise VaultError("'scripts' must be a table of tables")
239
+ for name, table in scripts_section.items():
240
+ _validate_name(name)
241
+ if not isinstance(table, dict):
242
+ raise VaultError(f"[scripts.{name}] must be a table")
243
+ cmd = _require_str(table, "cmd", f"[scripts.{name}]")
244
+ description = table.get("description", "")
245
+ if not isinstance(description, str):
246
+ raise VaultError(f"[scripts.{name}]: 'description' must be a string")
247
+ inline[name] = Script(name=name, cmd=cmd, description=description)
248
+
249
+ # File scripts override same-name inline scripts.
250
+ vault.scripts = dict(inline)
251
+ if vault.scripts_dir.is_dir():
252
+ for path in sorted(vault.scripts_dir.glob("*.sh")):
253
+ if path.name.startswith("."):
254
+ continue
255
+ name = path.stem
256
+ if not NAME_RE.match(name):
257
+ continue
258
+ description = ""
259
+ if name in inline:
260
+ description = inline[name].description
261
+ vault.scripts[name] = Script(name=name, path=path, description=description)
262
+
263
+ # Steps may reference both scripts and orchestrations, in any order of
264
+ # definition; cycles are rejected afterwards, before anything runs.
265
+ known_names = set(vault.scripts)
266
+ orchestrations: dict[str, Orchestration] = {}
267
+ orch_section = data.get("orchestrate", {})
268
+ if not isinstance(orch_section, dict):
269
+ raise VaultError("'orchestrate' must be a table of tables")
270
+ for name, table in orch_section.items():
271
+ _validate_name(name)
272
+ if not isinstance(table, dict):
273
+ raise VaultError(f"[orchestrate.{name}] must be a table")
274
+ if name in vault.scripts:
275
+ raise VaultError(f"name {name!r} is both a script and an orchestration")
276
+ known_names |= set(orch_section)
277
+ for name, table in orch_section.items():
278
+ description = table.get("description", "")
279
+ if not isinstance(description, str):
280
+ raise VaultError(f"[orchestrate.{name}]: 'description' must be a string")
281
+ steps = _parse_steps(
282
+ table.get("steps"),
283
+ known_names=known_names,
284
+ where=f"[orchestrate.{name}]",
285
+ )
286
+ orchestrations[name] = Orchestration(
287
+ name=name, steps=steps, description=description
288
+ )
289
+ _check_orchestration_cycles(orchestrations)
290
+ vault.orchestrations = orchestrations
291
+ return vault
292
+
293
+
294
+ def _check_orchestration_cycles(orchestrations: dict[str, Orchestration]) -> None:
295
+ """Raise VaultError if orchestrations reference each other in a loop."""
296
+
297
+ def dependencies(name: str) -> list[str]:
298
+ deps: list[str] = []
299
+ for step in orchestrations[name].steps:
300
+ if step.run_name is not None and step.run_name in orchestrations:
301
+ deps.append(step.run_name)
302
+ if step.parallel is not None:
303
+ deps.extend(n for n in step.parallel if n in orchestrations)
304
+ return deps
305
+
306
+ WHITE, GRAY, BLACK = 0, 1, 2
307
+ color = {name: WHITE for name in orchestrations}
308
+ stack: list[str] = []
309
+
310
+ def dfs(name: str) -> None:
311
+ color[name] = GRAY
312
+ stack.append(name)
313
+ for dep in dependencies(name):
314
+ if color[dep] == GRAY:
315
+ cycle = stack[stack.index(dep):] + [dep]
316
+ raise VaultError(
317
+ "orchestration loop detected: " + " -> ".join(cycle)
318
+ )
319
+ if color[dep] == WHITE:
320
+ dfs(dep)
321
+ stack.pop()
322
+ color[name] = BLACK
323
+
324
+ for name in orchestrations:
325
+ if color[name] == WHITE:
326
+ dfs(name)
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: scriptvault
3
+ Version: 0.0.1
4
+ Summary: Store and run project commands in a hidden vault directory
5
+ Author: Majwt
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Majwt/ScriptVault
8
+ Project-URL: Repository, https://github.com/Majwt/ScriptVault
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # ScriptVault (`sv`)
22
+
23
+ Store and run project commands in a hidden vault directory.
24
+
25
+ `sv` keeps scripts, orchestrations, and environment files under a hidden `.sv/` directory so projects do not need a pile of top-level Makefile targets, shell scripts, or ad-hoc commands.
26
+
27
+ ## Install
28
+
29
+ Requires Python 3.11+.
30
+
31
+ From PyPI:
32
+
33
+ ```sh
34
+ pipx install scriptvault
35
+ ```
36
+
37
+ From a checkout:
38
+
39
+ ```sh
40
+ pipx install --editable .
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ Initialize a vault in a project directory:
46
+
47
+ ```sh
48
+ sv init
49
+ ```
50
+
51
+ Create a script:
52
+
53
+ ```sh
54
+ sv add hello
55
+ ```
56
+
57
+ Run it:
58
+
59
+ ```sh
60
+ sv hello
61
+ # or
62
+ sv run hello
63
+ ```
64
+
65
+ List targets:
66
+
67
+ ```sh
68
+ sv list
69
+ ```
70
+
71
+ ## Vault layout
72
+
73
+ ```text
74
+ .sv/
75
+ vault.toml
76
+ .env
77
+ scripts/
78
+ hello.sh
79
+ hello.env
80
+ ```
81
+
82
+ - `vault.toml` defines inline scripts and orchestrations.
83
+ - `.env` is the global dotenv file.
84
+ - `scripts/*.sh` are executable file scripts.
85
+ - `scripts/NAME.env` is the per-script dotenv file.
86
+
87
+ ## Scripts
88
+
89
+ ### File scripts
90
+
91
+ A file at `.sv/scripts/hello.sh` becomes `sv hello`.
92
+
93
+ ```sh
94
+ #!/bin/sh
95
+ echo "Hello from $SV_NAME"
96
+ ```
97
+
98
+ ### Inline scripts
99
+
100
+ Define a command in `vault.toml`:
101
+
102
+ ```toml
103
+ [scripts.hello]
104
+ cmd = "echo hello"
105
+ ```
106
+
107
+ ### Creating scripts
108
+
109
+ ```sh
110
+ sv add hello
111
+ sv add hello --in < script.sh
112
+ ```
113
+
114
+ ## Running targets
115
+
116
+ ```sh
117
+ sv hello
118
+ sv run hello arg1 arg2
119
+ sv run hello -- --special-arg
120
+ ```
121
+
122
+ Arguments after the target are passed to the script. Use `--` to pass a leading dash safely.
123
+
124
+ ## Orchestrations
125
+
126
+ An orchestration is a named sequence of steps in `vault.toml`.
127
+
128
+ ```toml
129
+ [orchestrate.ci]
130
+ steps = [
131
+ { sh = "echo build" },
132
+ { run = "hello" },
133
+ { parallel = ["test", "lint"] },
134
+ ]
135
+ ```
136
+
137
+ Run it like any other target:
138
+
139
+ ```sh
140
+ sv ci
141
+ ```
142
+
143
+ Orchestrations can call scripts and other orchestrations. `sv` detects cycles and reports them.
144
+
145
+ ## Environment
146
+
147
+ Environment files are dotenv-style `KEY=VALUE` files.
148
+
149
+ Precedence, from lowest to highest:
150
+
151
+ 1. `.sv/.env`
152
+ 2. `.sv/scripts/NAME.env`
153
+ 3. The real environment
154
+ 4. Injected `SV_*` variables
155
+
156
+ Injected variables:
157
+
158
+ - `SV_ROOT`: project root
159
+ - `SV_DIR`: `.sv` directory
160
+ - `SV_CWD`: current working directory at invocation
161
+ - `SV_NAME`: target name, when running a named script
162
+
163
+ ## Editing
164
+
165
+ Open the interactive target picker:
166
+
167
+ ```sh
168
+ sv edit
169
+ ```
170
+
171
+ `sv edit` uses `fzf` when available and stdin/stdout are a TTY; otherwise it falls back to a numbered prompt.
172
+
173
+ Edit a specific target:
174
+
175
+ ```sh
176
+ sv edit hello
177
+ ```
178
+
179
+ Edit a script's environment:
180
+
181
+ ```sh
182
+ sv edit hello env
183
+ ```
184
+
185
+ Edit a target's configuration in `vault.toml`:
186
+
187
+ ```sh
188
+ sv edit hello config
189
+ ```
190
+
191
+ Edit the global vault config or global env:
192
+
193
+ ```sh
194
+ sv edit config
195
+ sv edit env
196
+ ```
197
+
198
+ ## Shell completion
199
+
200
+ Print a completion script for your shell:
201
+
202
+ ```sh
203
+ sv completion bash
204
+ sv completion zsh
205
+ sv completion fish
206
+ ```
207
+
208
+ Examples:
209
+
210
+ ```sh
211
+ # bash
212
+ eval "$(sv completion bash)"
213
+ ```
214
+
215
+ ```sh
216
+ # zsh
217
+ eval "$(sv completion zsh)"
218
+ ```
219
+
220
+ ```sh
221
+ # fish
222
+ sv completion fish | source
223
+ ```
224
+
225
+ ## Help
226
+
227
+ ```sh
228
+ sv help
229
+ sv --version
230
+ ```
@@ -0,0 +1,14 @@
1
+ scriptvault/__init__.py,sha256=cvc4SyC264koM1Fyc-nehkJZJxJdleTksfYcBGjKIWc,243
2
+ scriptvault/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
3
+ scriptvault/cli.py,sha256=yHJS2yz_NBjrsCz47UhUaU6YMbO7Ab_eQCYUC8OBboM,14788
4
+ scriptvault/envfile.py,sha256=ILbhOkMSNt9BqDzAPuQXm-jGWlhg_TmuEBrXgxG7veA,1110
5
+ scriptvault/run.py,sha256=96OSixbNAtk3FLdqF6hp3XvW0J9yOPA2E0k1ncR8neA,10925
6
+ scriptvault/templates.py,sha256=y7un-ba2CBsUuPd29MHrjdYaTDvJNnC3XipmTXCB_4Y,2399
7
+ scriptvault/term.py,sha256=S3JCGMu6Ur0HNS7L7NgL3IZPzrp4BXUTwBMHKKnvU4w,1040
8
+ scriptvault/vault.py,sha256=aB1x1Ah-HXQr_4kkA_OIwb0Oj8r8gRpkTZn3hUGj-u0,11152
9
+ scriptvault-0.0.1.dist-info/licenses/LICENSE,sha256=A-kmRJyoliFYuI9imK76Avfn_8q9HOpXvKeZQG72nWk,1061
10
+ scriptvault-0.0.1.dist-info/METADATA,sha256=NQ8HYABzlphTBXHG4AZPE-U_FbEFiil3TSj5QBDPUjY,3607
11
+ scriptvault-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ scriptvault-0.0.1.dist-info/entry_points.txt,sha256=bSQhmgtUVX_8ZVTHZ-vyrbraguw-wxgZ1BNRY-uZRyU,44
13
+ scriptvault-0.0.1.dist-info/top_level.txt,sha256=m86GdWmqPmeR7aqkOf8Tl1ka3zj7RZhXe4cixflaO94,12
14
+ scriptvault-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sv = scriptvault.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Majwt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ scriptvault