scriptvault 0.4.0__tar.gz → 0.5.0__tar.gz

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.
Files changed (28) hide show
  1. {scriptvault-0.4.0/src/scriptvault.egg-info → scriptvault-0.5.0}/PKG-INFO +12 -4
  2. {scriptvault-0.4.0 → scriptvault-0.5.0}/README.md +11 -3
  3. {scriptvault-0.4.0 → scriptvault-0.5.0}/pyproject.toml +1 -1
  4. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/__init__.py +2 -2
  5. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/cli.py +2 -2
  6. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/run.py +93 -30
  7. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/templates.py +13 -5
  8. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/vault.py +3 -2
  9. {scriptvault-0.4.0 → scriptvault-0.5.0/src/scriptvault.egg-info}/PKG-INFO +12 -4
  10. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_add.py +25 -2
  11. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_edit.py +13 -0
  12. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_list.py +1 -0
  13. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_run.py +251 -1
  14. {scriptvault-0.4.0 → scriptvault-0.5.0}/LICENSE +0 -0
  15. {scriptvault-0.4.0 → scriptvault-0.5.0}/setup.cfg +0 -0
  16. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/__main__.py +0 -0
  17. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/envfile.py +0 -0
  18. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault/term.py +0 -0
  19. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault.egg-info/SOURCES.txt +0 -0
  20. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault.egg-info/dependency_links.txt +0 -0
  21. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault.egg-info/entry_points.txt +0 -0
  22. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault.egg-info/requires.txt +0 -0
  23. {scriptvault-0.4.0 → scriptvault-0.5.0}/src/scriptvault.egg-info/top_level.txt +0 -0
  24. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_completion.py +0 -0
  25. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_guide.py +0 -0
  26. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_hooks.py +0 -0
  27. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_init.py +0 -0
  28. {scriptvault-0.4.0 → scriptvault-0.5.0}/tests/test_real.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scriptvault
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Store and run project commands in a hidden vault directory
5
5
  Author: Majwt
6
6
  License-Expression: MIT
@@ -161,6 +161,13 @@ set, `description` takes precedence. Descriptions are shown beside names in
161
161
  Listings use colors on supported terminals. Piped output, JSON, `TERM=dumb`,
162
162
  and environments with `NO_COLOR` set remain plain.
163
163
 
164
+ On macOS/Linux, captured orchestration and parallel output uses a
165
+ pseudo-terminal (PTY) when the output terminal supports color, so child
166
+ commands retain their automatic colors. Stdin and signal handling remain
167
+ unchanged. Redirected output, `NO_COLOR`, `TERM=dumb`, Windows and unavailable
168
+ PTYs use normal pipes instead. Explicit force-color settings in child commands
169
+ still apply.
170
+
164
171
  ### Inline scripts
165
172
 
166
173
  Define a command in `vault.toml`:
@@ -188,8 +195,9 @@ sv list --all
188
195
 
189
196
  Local scripts live in `.sv/local/scripts/`. `sv init` and `sv add --local`
190
197
  ensure `.sv/.gitignore` ignores `/local/`, preserving existing ignore rules.
191
- Local scripts are hidden from `sv list` by default but remain callable by
192
- name, including from orchestration steps. Local and shared names must not
198
+ Local scripts appear in `sv list` by default; use `hidden = true` to hide
199
+ them. `.sv/local/scripts/NAME.env` supplies per-script environment variables.
200
+ Local and shared names must not
193
201
  conflict. Gitignore rules do not untrack files already committed.
194
202
 
195
203
  Shared helpers can also be hidden:
@@ -274,7 +282,7 @@ Environment files are dotenv-style `KEY=VALUE` files.
274
282
  Precedence, from lowest to highest:
275
283
 
276
284
  1. `.sv/.env`
277
- 2. `.sv/scripts/NAME.env`
285
+ 2. `.sv/scripts/NAME.env`, or `.sv/local/scripts/NAME.env` for local scripts
278
286
  3. The real environment
279
287
  4. Injected `SV_*` variables
280
288
 
@@ -140,6 +140,13 @@ set, `description` takes precedence. Descriptions are shown beside names in
140
140
  Listings use colors on supported terminals. Piped output, JSON, `TERM=dumb`,
141
141
  and environments with `NO_COLOR` set remain plain.
142
142
 
143
+ On macOS/Linux, captured orchestration and parallel output uses a
144
+ pseudo-terminal (PTY) when the output terminal supports color, so child
145
+ commands retain their automatic colors. Stdin and signal handling remain
146
+ unchanged. Redirected output, `NO_COLOR`, `TERM=dumb`, Windows and unavailable
147
+ PTYs use normal pipes instead. Explicit force-color settings in child commands
148
+ still apply.
149
+
143
150
  ### Inline scripts
144
151
 
145
152
  Define a command in `vault.toml`:
@@ -167,8 +174,9 @@ sv list --all
167
174
 
168
175
  Local scripts live in `.sv/local/scripts/`. `sv init` and `sv add --local`
169
176
  ensure `.sv/.gitignore` ignores `/local/`, preserving existing ignore rules.
170
- Local scripts are hidden from `sv list` by default but remain callable by
171
- name, including from orchestration steps. Local and shared names must not
177
+ Local scripts appear in `sv list` by default; use `hidden = true` to hide
178
+ them. `.sv/local/scripts/NAME.env` supplies per-script environment variables.
179
+ Local and shared names must not
172
180
  conflict. Gitignore rules do not untrack files already committed.
173
181
 
174
182
  Shared helpers can also be hidden:
@@ -253,7 +261,7 @@ Environment files are dotenv-style `KEY=VALUE` files.
253
261
  Precedence, from lowest to highest:
254
262
 
255
263
  1. `.sv/.env`
256
- 2. `.sv/scripts/NAME.env`
264
+ 2. `.sv/scripts/NAME.env`, or `.sv/local/scripts/NAME.env` for local scripts
257
265
  3. The real environment
258
266
  4. Injected `SV_*` variables
259
267
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scriptvault"
7
- version = "0.4.0"
7
+ version = "0.5.0"
8
8
  description = "Store and run project commands in a hidden vault directory"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -3,6 +3,6 @@
3
3
  from importlib.metadata import PackageNotFoundError
4
4
 
5
5
  try:
6
- __version__ = "0.4.0"
6
+ __version__ = "0.5.0"
7
7
  except PackageNotFoundError:
8
- __version__ = "0.4.0"
8
+ __version__ = "0.5.0"
@@ -925,7 +925,7 @@ def build_parser() -> argparse.ArgumentParser:
925
925
  lst.add_argument(
926
926
  "--json", action="store_true", help="output as a JSON object with include info"
927
927
  )
928
- lst.add_argument("--all", action="store_true", help="include hidden and local targets")
928
+ lst.add_argument("--all", action="store_true", help="include hidden targets")
929
929
  lst.add_argument(
930
930
  "--nested", action="store_true",
931
931
  help="show all nested vault scripts (default: only root scripts)"
@@ -985,7 +985,7 @@ def build_parser() -> argparse.ArgumentParser:
985
985
  help="read the script body from stdin instead of the template",
986
986
  )
987
987
  add.set_defaults(func=cmd_add)
988
- add.add_argument("--local", action="store_true", help="create a gitignored, hidden local script")
988
+ add.add_argument("--local", action="store_true", help="create a gitignored local script")
989
989
 
990
990
  edit = sub.add_parser(
991
991
  "edit", help="edit a script, its env, or the vault configuration"
@@ -1,6 +1,9 @@
1
1
  """Execution engine for scripts and orchestrations."""
2
2
 
3
3
  import os
4
+ import errno
5
+ import io
6
+ import shutil
4
7
  import signal
5
8
  import subprocess
6
9
  import sys
@@ -241,7 +244,8 @@ def build_env(
241
244
  env.update(parse_env_file(env_path))
242
245
 
243
246
  if name is not None:
244
- script_env = ctx.scripts_dir / f"{name}.env"
247
+ script = ctx.scripts.get(name)
248
+ script_env = script.env_file(ctx) if script is not None else ctx.scripts_dir / f"{name}.env"
245
249
  if script_env.is_file():
246
250
  env.update(parse_env_file(script_env))
247
251
 
@@ -265,19 +269,88 @@ def _script_argv(vault: Vault, script: Script, args: list[str]) -> list[str]:
265
269
  return [vault.shell, "-c", script.cmd, script.name, *args]
266
270
 
267
271
 
272
+ class _PtyReader(io.RawIOBase):
273
+ def __init__(self, descriptor):
274
+ self._descriptor = descriptor
275
+
276
+ def readable(self):
277
+ return True
278
+
279
+ def readinto(self, buffer):
280
+ try:
281
+ data = os.read(self._descriptor, len(buffer))
282
+ except OSError as exc:
283
+ if exc.errno != errno.EIO:
284
+ raise
285
+ data = b""
286
+ buffer[:len(data)] = data
287
+ return len(data)
288
+
289
+ def close(self):
290
+ if not self.closed:
291
+ try:
292
+ os.close(self._descriptor)
293
+ finally:
294
+ super().close()
295
+
296
+
297
+ def _spawn_captured(argv, env, cwd, out, progress):
298
+ terminal = progress._out if progress is not None else out
299
+ use_pty = (
300
+ os.name == "posix"
301
+ and Palette(terminal).enabled
302
+ and "NO_COLOR" not in env
303
+ and env.get("TERM") != "dumb"
304
+ )
305
+ master = slave = None
306
+ if use_pty:
307
+ import termios
308
+
309
+ try:
310
+ master, slave = os.openpty()
311
+ attributes = termios.tcgetattr(slave)
312
+ attributes[1] &= ~termios.OPOST
313
+ termios.tcsetattr(slave, termios.TCSANOW, attributes)
314
+ try:
315
+ size = os.get_terminal_size(terminal.fileno())
316
+ except (AttributeError, OSError, ValueError):
317
+ size = shutil.get_terminal_size()
318
+ termios.tcsetwinsize(slave, (size.lines, size.columns))
319
+ except (OSError, termios.error):
320
+ if master is not None:
321
+ os.close(master)
322
+ if slave is not None:
323
+ os.close(slave)
324
+ master = slave = None
325
+ try:
326
+ proc = subprocess.Popen(
327
+ argv,
328
+ cwd=str(cwd),
329
+ env=env,
330
+ stdout=slave if slave is not None else subprocess.PIPE,
331
+ stderr=subprocess.STDOUT,
332
+ text=True,
333
+ encoding="utf-8",
334
+ errors="replace",
335
+ )
336
+ except BaseException:
337
+ if master is not None:
338
+ os.close(master)
339
+ raise
340
+ finally:
341
+ if slave is not None:
342
+ os.close(slave)
343
+ if master is not None:
344
+ proc.stdout = io.TextIOWrapper(
345
+ io.BufferedReader(_PtyReader(master)), encoding="utf-8", errors="replace", newline=""
346
+ )
347
+ return proc
348
+
349
+
268
350
  def _run_child(argv: list[str], env: dict[str, str], cwd, out, progress):
269
351
  if out is None:
270
352
  out = sys.stdout
271
- proc = subprocess.Popen(
272
- argv,
273
- cwd=str(cwd),
274
- env=env,
275
- stdout=subprocess.PIPE,
276
- stderr=subprocess.STDOUT,
277
- text=True,
278
- encoding="utf-8",
279
- errors="replace",
280
- )
353
+ proc = _spawn_captured(argv, env, cwd, out, progress)
281
354
  _GUARD.add(proc)
282
355
  try:
283
356
  stdout = proc.stdout
@@ -452,22 +525,13 @@ def run_parallel(
452
525
  if global_flags is not None:
453
526
  argv = global_flags + argv
454
527
  cwd = target_vault.root if target_vault else vault.root
455
- proc = subprocess.Popen(
456
- argv,
457
- cwd=str(cwd),
458
- env=env,
459
- stdout=subprocess.PIPE,
460
- stderr=subprocess.STDOUT,
461
- text=True,
462
- encoding="utf-8",
463
- errors="replace",
464
- )
528
+ proc = _spawn_captured(argv, env, cwd, out, progress)
465
529
  procs.append(proc)
466
530
  _GUARD.add(proc)
467
531
  stream = proc.stdout
468
532
  else:
469
533
  rfd, wfd = os.pipe()
470
- stream = os.fdopen(rfd, "r", encoding="utf-8", errors="replace")
534
+ stream = os.fdopen(rfd, "r", encoding="utf-8", errors="replace", newline="")
471
535
  job_out = os.fdopen(wfd, "w", encoding="utf-8", errors="replace")
472
536
  codes = []
473
537
 
@@ -502,16 +566,15 @@ def run_parallel(
502
566
  except KeyboardInterrupt:
503
567
  for proc in procs:
504
568
  _kill_and_reap(proc)
569
+ raise
570
+ finally:
505
571
  for proc in procs:
506
572
  _GUARD.discard(proc)
507
- raise
508
- for proc in procs:
509
- _GUARD.discard(proc)
510
- try:
511
- if proc.stdout is not None:
512
- proc.stdout.close()
513
- except Exception:
514
- pass
573
+ try:
574
+ if proc.stdout is not None:
575
+ proc.stdout.close()
576
+ except Exception:
577
+ pass
515
578
 
516
579
  codes = [proc.returncode for proc in procs]
517
580
  for _, job_codes in jobs:
@@ -53,7 +53,8 @@ checkout instead.
53
53
  .sv/GUIDE.md this file
54
54
  .sv/scripts/NAME file script, run as `sv NAME`
55
55
  .sv/scripts/NAME.env environment for that one script
56
- .sv/local/scripts/NAME gitignored local script, hidden by default
56
+ .sv/local/scripts/NAME gitignored local script, listed by default
57
+ .sv/local/scripts/NAME.env environment for that local script
57
58
  .sv/.gitignore ignores /local/
58
59
  .sv/lib/NAME.sh source-only helper, not a runnable target
59
60
  ```
@@ -101,6 +102,13 @@ set, `description` takes precedence. Descriptions are shown beside names in
101
102
  Listings use colors on supported terminals. Piped output, JSON, `TERM=dumb`,
102
103
  and environments with `NO_COLOR` set remain plain.
103
104
 
105
+ On macOS/Linux, captured orchestration and parallel output uses a
106
+ pseudo-terminal (PTY) when the output terminal supports color, so child
107
+ commands retain their automatic colors. Stdin and signal handling remain
108
+ unchanged. Redirected output, `NO_COLOR`, `TERM=dumb`, Windows and unavailable
109
+ PTYs use normal pipes instead. Explicit force-color settings in child commands
110
+ still apply.
111
+
104
112
  ## Running
105
113
 
106
114
  ```sh
@@ -110,7 +118,7 @@ sv run build --release # arguments go to the script
110
118
  sv run build -- --flag # `--` when an argument could look like an sv flag
111
119
 
112
120
  sv list # show visible targets
113
- sv list --all # include hidden and local targets
121
+ sv list --all # include hidden targets
114
122
  sv guide # refresh .sv/GUIDE.md when sv is newer than it
115
123
  sv add deploy # create .sv/scripts/deploy.sh
116
124
  sv add personal --local # create .sv/local/scripts/personal.sh
@@ -125,8 +133,8 @@ sv help
125
133
 
126
134
  `sv add NAME --local` creates an executable script in `.sv/local/scripts/`
127
135
  and ensures `.sv/.gitignore` ignores `/local/`. Existing ignore rules are
128
- preserved. Local scripts are hidden from listings by default, but `sv NAME`
129
- and orchestration steps can still call them. Local and shared names must not
136
+ preserved. Local scripts are listed by default; use `hidden = true` to hide
137
+ them. Their adjacent `.env` files are loaded automatically. Local and shared names must not
130
138
  conflict. Gitignore rules do not untrack files already committed.
131
139
 
132
140
  Shared helpers can be hidden with metadata:
@@ -230,7 +238,7 @@ Sources are applied in this order, so later ones win:
230
238
  1. `.sv/.env` - vault-wide defaults
231
239
  2. `.env` of every included vault (in include order), then `.env` in the
232
240
  project root
233
- 3. `.sv/scripts/NAME.env` - one file per script
241
+ 3. `.sv/scripts/NAME.env`, or `.sv/local/scripts/NAME.env` for local scripts
234
242
  4. the real environment (your shell)
235
243
  5. injected `SV_*` variables:
236
244
  - `SV_TOP_ROOT` - outermost vault's root directory in the execution chain
@@ -145,7 +145,8 @@ class Script:
145
145
  return "file" if self.path is not None else "inline"
146
146
 
147
147
  def env_file(self, vault: "Vault") -> Path:
148
- return vault.scripts_dir / f"{self.name}.env"
148
+ scripts_dir = self.path.parent if self.path is not None else vault.scripts_dir
149
+ return scripts_dir / f"{self.name}.env"
149
150
 
150
151
  def environment_paths(self, vault: "Vault") -> list[Path]:
151
152
  """Return environment file paths for this script based on its environment setting."""
@@ -516,7 +517,7 @@ def load_vault(root: Path) -> Vault:
516
517
  path=path,
517
518
  description=metadata.description if metadata else "",
518
519
  environment=metadata.environment if metadata else "",
519
- hidden=local or (metadata.hidden if metadata else False),
520
+ hidden=metadata.hidden if metadata else False,
520
521
  )
521
522
 
522
523
  for name, script in vault.scripts.items():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scriptvault
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Store and run project commands in a hidden vault directory
5
5
  Author: Majwt
6
6
  License-Expression: MIT
@@ -161,6 +161,13 @@ set, `description` takes precedence. Descriptions are shown beside names in
161
161
  Listings use colors on supported terminals. Piped output, JSON, `TERM=dumb`,
162
162
  and environments with `NO_COLOR` set remain plain.
163
163
 
164
+ On macOS/Linux, captured orchestration and parallel output uses a
165
+ pseudo-terminal (PTY) when the output terminal supports color, so child
166
+ commands retain their automatic colors. Stdin and signal handling remain
167
+ unchanged. Redirected output, `NO_COLOR`, `TERM=dumb`, Windows and unavailable
168
+ PTYs use normal pipes instead. Explicit force-color settings in child commands
169
+ still apply.
170
+
164
171
  ### Inline scripts
165
172
 
166
173
  Define a command in `vault.toml`:
@@ -188,8 +195,9 @@ sv list --all
188
195
 
189
196
  Local scripts live in `.sv/local/scripts/`. `sv init` and `sv add --local`
190
197
  ensure `.sv/.gitignore` ignores `/local/`, preserving existing ignore rules.
191
- Local scripts are hidden from `sv list` by default but remain callable by
192
- name, including from orchestration steps. Local and shared names must not
198
+ Local scripts appear in `sv list` by default; use `hidden = true` to hide
199
+ them. `.sv/local/scripts/NAME.env` supplies per-script environment variables.
200
+ Local and shared names must not
193
201
  conflict. Gitignore rules do not untrack files already committed.
194
202
 
195
203
  Shared helpers can also be hidden:
@@ -274,7 +282,7 @@ Environment files are dotenv-style `KEY=VALUE` files.
274
282
  Precedence, from lowest to highest:
275
283
 
276
284
  1. `.sv/.env`
277
- 2. `.sv/scripts/NAME.env`
285
+ 2. `.sv/scripts/NAME.env`, or `.sv/local/scripts/NAME.env` for local scripts
278
286
  3. The real environment
279
287
  4. Injected `SV_*` variables
280
288
 
@@ -49,7 +49,7 @@ def test_add_script_is_listed_and_runnable(project, capsys, monkeypatch):
49
49
  assert result.stdout == 'Hello from hello\n'
50
50
 
51
51
 
52
- def test_add_local_script_is_ignored_hidden_and_runnable(project, capsys, monkeypatch):
52
+ def test_add_local_script_is_ignored_listed_and_runnable(project, capsys, monkeypatch):
53
53
  init(project, monkeypatch)
54
54
  ignore = project / ".sv" / ".gitignore"
55
55
  ignore.write_text("keep-this-rule\n", encoding="utf-8")
@@ -61,7 +61,7 @@ def test_add_local_script_is_ignored_hidden_and_runnable(project, capsys, monkey
61
61
  assert ignore.read_text(encoding="utf-8") == "keep-this-rule\n/local/\n"
62
62
 
63
63
  assert main(["list"]) == 0
64
- assert "personal" not in capsys.readouterr().out
64
+ assert "personal" in capsys.readouterr().out
65
65
  assert main(["list", "--all"]) == 0
66
66
  assert "personal" in capsys.readouterr().out
67
67
  result = subprocess.run(
@@ -88,6 +88,29 @@ def test_add_local_from_stdin_and_ignore_rule_is_not_duplicated(project, monkeyp
88
88
  assert (project / ".sv" / ".gitignore").read_text().splitlines().count("/local/") == 1
89
89
 
90
90
 
91
+ @pytest.mark.parametrize("hidden_dir", [".sv", ".scripts"])
92
+ @pytest.mark.parametrize("shell_override", [False, True])
93
+ def test_local_script_loads_adjacent_env(project, monkeypatch, hidden_dir, shell_override):
94
+ monkeypatch.setenv("SV_HIDDEN_DIR", hidden_dir)
95
+ init(project, monkeypatch)
96
+ monkeypatch.setattr(sys, "stdin", io.StringIO('#!/bin/sh\nprintf "%s\\n" "$PUSHBOX"\n'))
97
+ assert main(["add", "move-to-pushbox", "--local", "--in"]) == 0
98
+ local = project / hidden_dir / "local" / "scripts"
99
+ (local / "move-to-pushbox.env").write_text('PUSHBOX="local path with spaces"\n', encoding="utf-8")
100
+ (project / hidden_dir / "scripts" / "move-to-pushbox.env").write_text("PUSHBOX=wrong-shared-path\n", encoding="utf-8")
101
+ (project / hidden_dir / ".env").write_text("PUSHBOX=global-default\n", encoding="utf-8")
102
+ if shell_override:
103
+ monkeypatch.setenv("PUSHBOX", "shell-override")
104
+ else:
105
+ monkeypatch.delenv("PUSHBOX", raising=False)
106
+ result = subprocess.run(
107
+ [sys.executable, "-m", "scriptvault", "move-to-pushbox"], cwd=project,
108
+ capture_output=True, text=True, env={**os.environ, "PYTHONPATH": SRC},
109
+ )
110
+ assert result.returncode == 0, result.stderr
111
+ assert result.stdout == ("shell-override\n" if shell_override else "local path with spaces\n")
112
+
113
+
91
114
  def test_add_local_rejects_shared_name_and_loader_rejects_collision(project, capsys, monkeypatch):
92
115
  init(project, monkeypatch)
93
116
  assert main(["add", "shared"]) == 0
@@ -244,6 +244,19 @@ def test_edit_env_for_file_script(project, monkeypatch):
244
244
  assert path.exists()
245
245
 
246
246
 
247
+ def test_edit_env_for_local_script(project, monkeypatch):
248
+ make_vault(project)
249
+ editor, log = make_editor(project)
250
+ monkeypatch.setenv("EDITOR", str(editor))
251
+ monkeypatch.chdir(project)
252
+ assert main(["add", "personal", "--local"]) == 0
253
+ assert main(["edit", "personal", "env"]) == 0
254
+ path = project / ".sv" / "local" / "scripts" / "personal.env"
255
+ assert logged(log) == [str(path)]
256
+ assert path.exists()
257
+ assert not (project / ".sv" / "scripts" / "personal.env").exists()
258
+
259
+
247
260
  def test_edit_env_preserves_existing_file(project, monkeypatch):
248
261
  make_vault(project)
249
262
  path = project / ".sv" / "scripts" / "hello.env"
@@ -172,6 +172,7 @@ def test_hidden_included_targets_are_filtered(project, monkeypatch, capsys, opti
172
172
  nested_toml.write_text(
173
173
  nested_toml.read_text(encoding="utf-8")
174
174
  + '\n[scripts.helper]\ncmd = "exit 0"\nhidden = true\n'
175
+ + '\n[scripts.personal]\nhidden = true\n'
175
176
  + '\n[orchestrate.internal]\nhidden = true\nsteps = [{ run = "helper" }]\n',
176
177
  encoding="utf-8",
177
178
  )
@@ -2,6 +2,7 @@
2
2
 
3
3
  import os
4
4
  import io
5
+ import select
5
6
  import signal
6
7
  import subprocess
7
8
  import sys
@@ -11,7 +12,7 @@ from pathlib import Path
11
12
  import pytest
12
13
 
13
14
  from scriptvault.cli import main
14
- from scriptvault.run import _StepProgress, build_env
15
+ from scriptvault.run import _StepProgress, _run_child, build_env
15
16
  from scriptvault.vault import Vault
16
17
 
17
18
  SRC = str(Path(__file__).resolve().parents[1] / "src")
@@ -350,6 +351,232 @@ class _TtyStringIO(io.StringIO):
350
351
  return True
351
352
 
352
353
 
354
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
355
+ @pytest.mark.parametrize("tty,term,no_color,expected", [
356
+ (True, "xterm-256color", False, True),
357
+ (False, "xterm-256color", False, False),
358
+ (True, "dumb", False, False),
359
+ (True, "xterm-256color", True, False),
360
+ ])
361
+ def test_captured_child_detects_supported_terminal(project, monkeypatch, tty, term, no_color, expected):
362
+ monkeypatch.setenv("TERM", "xterm-256color")
363
+ monkeypatch.delenv("NO_COLOR", raising=False)
364
+ env = {**os.environ, "TERM": term}
365
+ if no_color:
366
+ env["NO_COLOR"] = ""
367
+ out = _TtyStringIO() if tty else io.StringIO()
368
+ command = (
369
+ "import os; "
370
+ "print(f'stdout={os.isatty(1)} stderr={os.isatty(2)}'); "
371
+ "os.write(1, b'\\x1b[32mcolor\\x1b[0m\\rprogress\\n' if os.isatty(1) else b'plain\\n')"
372
+ )
373
+ assert _run_child([sys.executable, "-c", command], env, project, out, None) == 0
374
+ output = out.getvalue()
375
+ assert f"stdout={expected} stderr={expected}" in output
376
+ if expected:
377
+ assert "\033[32mcolor\033[0m\rprogress\n" in output
378
+ assert "\r\n" not in output
379
+ else:
380
+ assert "\033[" not in output
381
+
382
+
383
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
384
+ def test_pty_child_preserves_exit_code_and_decodes_invalid_bytes(project, monkeypatch):
385
+ monkeypatch.setenv("TERM", "xterm-256color")
386
+ monkeypatch.delenv("NO_COLOR", raising=False)
387
+ out = _TtyStringIO()
388
+ command = "import os, sys; os.write(1, b'\\xff'); sys.exit(7)"
389
+ assert _run_child([sys.executable, "-c", command], dict(os.environ), project, out, None) == 7
390
+ assert out.getvalue() == "\ufffd\n"
391
+
392
+
393
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
394
+ @pytest.mark.parametrize("mode", ["sequential", "parallel", "nested-parallel", "shell"])
395
+ @pytest.mark.parametrize("tty", [False, True])
396
+ def test_orchestrated_children_keep_terminal_colors(project, monkeypatch, mode, tty):
397
+ steps = {
398
+ "sequential": '[{ run = "color" }]',
399
+ "parallel": '[{ parallel = ["color"] }]',
400
+ "nested-parallel": '[{ parallel = ["child"] }]',
401
+ "shell": '[{ sh = ".sv/scripts/color.sh" }]',
402
+ }
403
+ make_orch_vault(project, f"""
404
+ [orchestrate.child]
405
+ steps = [{{ run = "color" }}]
406
+
407
+ [orchestrate.check]
408
+ steps = {steps[mode]}
409
+ """)
410
+ script = project / ".sv" / "scripts" / "color.sh"
411
+ script.write_text(
412
+ f"#!{sys.executable}\n"
413
+ "import os, sys\n"
414
+ "print(f'child-tty={os.isatty(1)} stderr-tty={os.isatty(2)}')\n"
415
+ "sys.stdout.write('\\033[32mchild-color\\033[0m\\rprogress\\n' if os.isatty(1) else 'child-plain\\n')\n",
416
+ encoding="utf-8",
417
+ )
418
+ script.chmod(0o755)
419
+ monkeypatch.chdir(project)
420
+ monkeypatch.setenv("TERM", "xterm-256color")
421
+ monkeypatch.delenv("NO_COLOR", raising=False)
422
+ out = _TtyStringIO() if tty else io.StringIO()
423
+ monkeypatch.setattr(sys, "stdout", out)
424
+
425
+ assert main(["check"]) == 0
426
+ output = out.getvalue()
427
+ assert f"child-tty={tty} stderr-tty={tty}" in output
428
+ if tty:
429
+ assert "\033[32mchild-color\033[0m\r" in output
430
+ assert "\r\n" not in output
431
+ else:
432
+ assert "\033[" not in output
433
+ assert "child-plain" in output
434
+
435
+
436
+ @pytest.mark.skipif(os.name != "posix", reason="PTY allocation is supported on POSIX")
437
+ def test_captured_child_falls_back_when_pty_unavailable(project, monkeypatch):
438
+ monkeypatch.setenv("TERM", "xterm-256color")
439
+ monkeypatch.delenv("NO_COLOR", raising=False)
440
+
441
+ def unavailable():
442
+ raise OSError("no PTYs available")
443
+
444
+ monkeypatch.setattr(os, "openpty", unavailable)
445
+ out = _TtyStringIO()
446
+ command = "import os; print(os.isatty(1))"
447
+ assert _run_child([sys.executable, "-c", command], dict(os.environ), project, out, None) == 0
448
+ assert out.getvalue() == "False\n"
449
+
450
+
451
+ @pytest.mark.skipif(os.name != "posix", reason="PTY setup is supported on POSIX")
452
+ @pytest.mark.parametrize("failure", ["setup", "spawn"])
453
+ def test_pty_descriptors_close_on_setup_and_spawn_failures(project, monkeypatch, failure):
454
+ import termios
455
+
456
+ monkeypatch.setenv("TERM", "xterm-256color")
457
+ monkeypatch.delenv("NO_COLOR", raising=False)
458
+ descriptors = []
459
+ openpty = os.openpty
460
+
461
+ def tracked_openpty():
462
+ pair = openpty()
463
+ descriptors.extend(pair)
464
+ return pair
465
+
466
+ monkeypatch.setattr(os, "openpty", tracked_openpty)
467
+ out = _TtyStringIO()
468
+ if failure == "setup":
469
+ def fail_setup(*args):
470
+ raise termios.error(22, "terminal setup failed")
471
+
472
+ monkeypatch.setattr(termios, "tcsetwinsize", fail_setup)
473
+ assert _run_child([sys.executable, "-c", "print('fallback')"], dict(os.environ), project, out, None) == 0
474
+ assert out.getvalue() == "fallback\n"
475
+ else:
476
+ def fail_spawn(*args, **kwargs):
477
+ raise FileNotFoundError("missing executable")
478
+
479
+ monkeypatch.setattr(subprocess, "Popen", fail_spawn)
480
+ with pytest.raises(FileNotFoundError):
481
+ _run_child(["missing-executable"], dict(os.environ), project, out, None)
482
+ assert len(descriptors) == 2
483
+ for descriptor in descriptors:
484
+ with pytest.raises(OSError):
485
+ os.fstat(descriptor)
486
+
487
+
488
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
489
+ def test_pty_child_is_reaped_and_closed_on_interrupt(project, monkeypatch):
490
+ import scriptvault.run as runner
491
+
492
+ monkeypatch.setenv("TERM", "xterm-256color")
493
+ monkeypatch.delenv("NO_COLOR", raising=False)
494
+ children = []
495
+ spawn = runner._spawn_captured
496
+
497
+ def tracked_spawn(*args):
498
+ proc = spawn(*args)
499
+ children.append(proc)
500
+ return proc
501
+
502
+ def interrupt(text):
503
+ raise KeyboardInterrupt
504
+
505
+ monkeypatch.setattr(runner, "_spawn_captured", tracked_spawn)
506
+ out = _TtyStringIO()
507
+ monkeypatch.setattr(out, "write", interrupt)
508
+ command = "import signal; print('ready', flush=True); signal.pause()"
509
+ with pytest.raises(KeyboardInterrupt):
510
+ _run_child([sys.executable, "-c", command], dict(os.environ), project, out, None)
511
+ assert len(children) == 1
512
+ assert children[0].returncode is not None
513
+ assert children[0].stdout.closed
514
+ assert children[0] not in runner._GUARD._children
515
+
516
+
517
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
518
+ def test_parallel_pty_stream_closes_on_interrupt(project, monkeypatch):
519
+ import scriptvault.run as runner
520
+
521
+ monkeypatch.setenv("TERM", "xterm-256color")
522
+ monkeypatch.delenv("NO_COLOR", raising=False)
523
+ children = []
524
+ spawn = runner._spawn_captured
525
+
526
+ def tracked_spawn(*args):
527
+ proc = spawn(*args)
528
+ children.append(proc)
529
+ return proc
530
+
531
+ def interrupted_wait(proc):
532
+ raise KeyboardInterrupt
533
+
534
+ monkeypatch.setattr(runner, "_spawn_captured", tracked_spawn)
535
+ monkeypatch.setattr(runner, "_wait_child", interrupted_wait)
536
+ script = project / "waiting.py"
537
+ script.write_text(f"#!{sys.executable}\nimport signal\nsignal.pause()\n", encoding="utf-8")
538
+ script.chmod(0o755)
539
+ vault = Vault(project)
540
+ vault.scripts["waiting"] = runner.Script(name="waiting", path=script)
541
+ with pytest.raises(KeyboardInterrupt):
542
+ runner.run_parallel(vault, ["waiting"], out=_TtyStringIO())
543
+ assert len(children) == 1
544
+ assert children[0].returncode is not None
545
+ assert children[0].stdout.closed
546
+ assert children[0] not in runner._GUARD._children
547
+
548
+
549
+ @pytest.mark.skipif(os.name != "posix", reason="PTY output is supported on POSIX")
550
+ def test_cli_preserves_child_color_in_real_terminal(project, monkeypatch):
551
+ make_orch_vault(project, """
552
+ [scripts.color]
553
+ cmd = 'if [ -t 1 ]; then printf "\\033[32mterminal-color\\033[0m\\n"; else echo non-terminal; fi'
554
+
555
+ [orchestrate.check]
556
+ steps = [{ run = "color" }]
557
+ """)
558
+ monkeypatch.delenv("NO_COLOR", raising=False)
559
+ env = {**os.environ, "PYTHONPATH": SRC, "TERM": "xterm-256color", "SV_ACTIVE_VAULT": str(project)}
560
+ master, slave = os.openpty()
561
+ try:
562
+ result = subprocess.run(
563
+ [sys.executable, "-m", "scriptvault", "check"], cwd=project, env=env,
564
+ stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, timeout=10,
565
+ )
566
+ output = bytearray()
567
+ while select.select([master], [], [], 0)[0]:
568
+ chunk = os.read(master, 4096)
569
+ if not chunk:
570
+ break
571
+ output.extend(chunk)
572
+ finally:
573
+ os.close(slave)
574
+ os.close(master)
575
+ assert result.returncode == 0, output.decode("utf-8", errors="replace")
576
+ assert b"\033[32mterminal-color\033[0m" in output
577
+ assert b"non-terminal" not in output
578
+
579
+
353
580
  def test_step_progress_tty_finishes_header_line(monkeypatch):
354
581
  monkeypatch.setenv("NO_COLOR", "1")
355
582
  out = _TtyStringIO()
@@ -543,6 +770,29 @@ def test_run_nested_script_loads_root_vault_env(project):
543
770
  assert result.stdout == "root-env nested-hello\n"
544
771
 
545
772
 
773
+ @pytest.mark.parametrize("mode", ["direct", "sequential", "parallel"])
774
+ def test_nested_local_script_loads_adjacent_env(project, monkeypatch, mode):
775
+ monkeypatch.delenv("LOCAL_VALUE", raising=False)
776
+ root, proj = make_nested_root(project)
777
+ local = proj / ".sv" / "local" / "scripts"
778
+ local.mkdir(parents=True)
779
+ (local / "personal.sh").write_text('#!/bin/sh\necho "$LOCAL_VALUE"\n', encoding="utf-8")
780
+ (local / "personal.env").write_text("LOCAL_VALUE=from-adjacent-env\n", encoding="utf-8")
781
+ if mode == "direct":
782
+ argv = ["run", "proj:personal"]
783
+ else:
784
+ steps = '[{ run = "proj:personal" }]' if mode == "sequential" else '[{ parallel = ["proj:personal"] }]'
785
+ toml = root / ".sv" / "vault.toml"
786
+ toml.write_text(
787
+ toml.read_text(encoding="utf-8") + f'\n[orchestrate.localenv]\nsteps = {steps}\n',
788
+ encoding="utf-8",
789
+ )
790
+ argv = ["localenv"]
791
+ result = sv(*argv, cwd=root)
792
+ assert result.returncode == 0, result.stderr
793
+ assert "from-adjacent-env" in result.stdout
794
+
795
+
546
796
  def test_run_root_owned_target_keeps_root_context(project):
547
797
  root, proj = make_nested_root(project)
548
798
  rhidden = root / ".sv"
File without changes
File without changes