Skip to content

Commit a4d6fd1

Browse files
authored
cmd,sync(fix): Harden command options and pipes (#559)
why: Untimed subprocess calls could deadlock on full pipes or leak children on callback errors, Git remote listing dropped promisor URLs, and Mercurial and Subversion placed global flags after operands. what: - Drain stdout and stderr concurrently without a timeout and reap children on callback failure in run() - Preserve filtered fetch URLs in GitRemoteManager.ls() and keep fetch and push URLs separate in GitSync.set_remote() - Surface git clone failures in GitSync.obtain() - Place Hg.run() and Svn.run() global options before targets and fix --trust-server-cert and --quiet handling - Install Git, Mercurial, and Subversion in CI with --reruns 0
2 parents 633b709 + c3f60ca commit a4d6fd1

13 files changed

Lines changed: 283 additions & 58 deletions

File tree

‎.github/workflows/tests.yml‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ on:
1414
jobs:
1515
build:
1616
runs-on: ubuntu-latest
17+
env:
18+
UV_PYTHON: ${{ matrix.python-version }}
1719
strategy:
1820
matrix:
1921
python-version: ['3.11', '3.15']
@@ -27,8 +29,17 @@ jobs:
2729
- name: Set up Python ${{ matrix.python-version }}
2830
run: uv python install ${{ matrix.python-version }}
2931

32+
- name: Install native VCS tools
33+
run: |
34+
sudo apt-get update
35+
sudo apt-get install --yes --no-install-recommends git mercurial subversion
36+
git --version
37+
hg --version
38+
svn --version --quiet
39+
svnadmin --version --quiet
40+
3041
- name: Install dependencies
31-
run: uv sync --all-extras --dev
42+
run: uv sync --frozen --all-extras --dev
3243

3344
- name: Lint with ruff check
3445
run: uv run ruff check .
@@ -43,9 +54,10 @@ jobs:
4354
run: |
4455
python -V
4556
uv run python -V
57+
uv run python -c 'import os, sys; assert ".".join(map(str, sys.version_info[:2])) == os.environ["UV_PYTHON"]'
4658
4759
- name: Test with pytest
48-
run: uv run py.test --cov=./ --cov-append --cov-report=xml
60+
run: uv run py.test --no-showlocals --reruns 0 -ra -n 2 --dist worksteal --cov=./ --cov-append --cov-report=xml
4961
env:
5062
COV_CORE_SOURCE: .
5163
COV_CORE_CONFIG: .coveragerc

‎CHANGES‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,36 @@ _Notes on the upcoming release will go here._
2727
Python 3.10 reached end-of-life in October 2026. libvcs now requires Python
2828
3.11 or newer.
2929

30+
### Fixes
31+
32+
#### Drain command output while the process runs (#559)
33+
34+
Commands with large stdout or stderr output complete without filling an
35+
unread pipe. Both streams drain concurrently with or without a timeout,
36+
and progress callbacks retain command diagnostics for failure reporting.
37+
Progress callback exceptions and interrupts terminate and reap the direct
38+
subprocess before propagating.
39+
40+
#### Keep partial-clone remotes usable (#559)
41+
42+
{meth}`~libvcs.cmd.git.GitRemoteManager.ls` retains fetch URLs annotated with a
43+
partial-clone filter. A failed {meth}`~libvcs.sync.git.GitSync.obtain` reports
44+
the clone command and Git's original message before attempting submodule or
45+
remote setup.
46+
47+
#### Keep fetch and push destinations separate (#559)
48+
49+
{class}`~libvcs.sync.git.GitSync` configures a remote's push URL via
50+
{meth}`~libvcs.sync.git.GitSync.set_remote` without replacing its fetch URL or
51+
requiring `overwrite=True`.
52+
53+
#### Place Subversion and Mercurial global options before command targets (#559)
54+
55+
{meth}`~libvcs.cmd.svn.Svn.run` and {meth}`~libvcs.cmd.hg.Hg.run` place global
56+
options before subcommand operands so an explicit `--` separator does not turn
57+
global flags into filenames, and `Svn.run()` forwards `--trust-server-cert` and
58+
`--quiet` accurately.
59+
3060
## libvcs 0.46.0 (2026-08-30)
3161

3262
libvcs 0.46.0 hardens the command wrappers against argument injection: `Git.pull()`, a `GitSync` revision, and `Svn.checkout()` now reject a value a VCS binary would parse as an option in the positions an end-of-options `--` cannot guard, closing paths that could otherwise run a command or truncate a file. It also gives progress-callback timestamps an aware UTC value, documents what every field holds in the API reference, and moves the lint and CI toolchain to current majors.

‎src/libvcs/_internal/run.py‎

Lines changed: 24 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,6 @@ def progress_cb(output, timestamp):
267267
)
268268

269269
all_output: str = ""
270-
code = None
271-
line = None
272270
if log_in_real_time and callback is None:
273271

274272
def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
@@ -277,34 +275,22 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
277275

278276
callback = progress_cb
279277

280-
# Note: When git detects that stderr is not a TTY (e.g., when piped),
281-
# it outputs progress with newlines instead of carriage returns.
282-
# This causes each progress update to appear on a new line.
283-
# To get proper single-line progress updates, git would need to be
284-
# connected to a pseudo-TTY, which would require significant changes
285-
# to how subprocess execution is handled.
286-
287-
timeout_stdout: bytes | None = None
288-
timeout_stderr: bytes | None = None
289-
if timeout is None:
290-
while code is None:
291-
code = proc.poll()
292-
293-
if callback and callable(callback) and proc.stderr is not None:
294-
line = console_to_str(proc.stderr.read(128))
295-
if line:
296-
callback(
297-
output=line,
298-
timestamp=datetime.datetime.now(tz=datetime.UTC),
299-
)
300-
else:
278+
try:
301279
code, timeout_stdout, timeout_stderr = _wait_with_deadline(
302280
proc,
303-
deadline=time.monotonic() + timeout,
281+
deadline=time.monotonic() + timeout if timeout is not None else None,
304282
timeout=timeout,
305283
callback=callback,
306284
cmd=_stringify_command(normalized_args),
307285
)
286+
except BaseException:
287+
try:
288+
_terminate_process(proc, _stringify_command(normalized_args))
289+
finally:
290+
for stream in (proc.stdin, proc.stdout, proc.stderr):
291+
if stream is not None:
292+
stream.close()
293+
raise
308294
if callback and callable(callback):
309295
callback(output="\r", timestamp=datetime.datetime.now(tz=datetime.UTC))
310296

@@ -348,12 +334,12 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
348334
def _wait_with_deadline(
349335
proc: subprocess.Popen[bytes],
350336
*,
351-
deadline: float,
352-
timeout: float,
337+
deadline: float | None,
338+
timeout: float | None,
353339
callback: ProgressCallbackProtocol | None,
354340
cmd: str | list[str],
355341
) -> tuple[int, bytes | None, bytes | None]:
356-
"""Wait for ``proc`` to exit, enforcing a wall-clock deadline.
342+
"""Drain child pipes while waiting, enforcing an optional wall-clock deadline.
357343
358344
Drains both ``stdout`` and ``stderr`` concurrently so a child that fills
359345
either kernel pipe buffer (~64 KiB on Linux) cannot deadlock waiting for
@@ -427,8 +413,8 @@ def _wait_with_deadline(
427413
)
428414
break
429415

430-
remaining = deadline - time.monotonic()
431-
if remaining <= 0:
416+
remaining = deadline - time.monotonic() if deadline is not None else None
417+
if remaining is not None and remaining <= 0:
432418
# ``vcs_exit_code`` deliberately omitted here: ``proc.returncode``
433419
# is still ``None`` because the child has not been signalled yet,
434420
# and CLAUDE.md treats ``vcs_exit_code`` as a scalar ``int``.
@@ -452,12 +438,16 @@ def _wait_with_deadline(
452438
timeout=timeout,
453439
)
454440

455-
wait = min(_TIMEOUT_POLL_INTERVAL_SECONDS, remaining)
441+
wait = (
442+
min(_TIMEOUT_POLL_INTERVAL_SECONDS, remaining)
443+
if remaining is not None
444+
else _TIMEOUT_POLL_INTERVAL_SECONDS
445+
)
456446
if not registered:
457-
# No streams to select on (e.g. ``os.set_blocking`` failed on
458-
# Windows pipes). Yield the CPU explicitly instead of busy-
459-
# looping until the deadline or process exit.
460-
time.sleep(wait)
447+
try:
448+
proc.wait(timeout=remaining)
449+
except subprocess.TimeoutExpired:
450+
continue
461451
continue
462452

463453
events = sel.select(timeout=wait)

‎src/libvcs/_internal/subprocess.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ def run(
430430
universal_newlines: bool = ...,
431431
*,
432432
capture_output: bool = ...,
433+
timeout: float | None = ...,
433434
check: bool = ...,
434435
encoding: str | None = ...,
435436
errors: str | None = ...,
@@ -443,6 +444,7 @@ def run(
443444
universal_newlines: bool = ...,
444445
*,
445446
capture_output: bool = ...,
447+
timeout: float | None = ...,
446448
check: bool = ...,
447449
encoding: str,
448450
errors: str | None = ...,
@@ -456,6 +458,7 @@ def run(
456458
universal_newlines: bool = ...,
457459
*,
458460
capture_output: bool = ...,
461+
timeout: float | None = ...,
459462
check: bool = ...,
460463
encoding: str | None = ...,
461464
errors: str,
@@ -470,6 +473,7 @@ def run(
470473
universal_newlines: t.Literal[True],
471474
# where the *real* keyword only args start
472475
capture_output: bool = ...,
476+
timeout: float | None = ...,
473477
check: bool = ...,
474478
encoding: str | None = ...,
475479
errors: str | None = ...,
@@ -483,6 +487,7 @@ def run(
483487
universal_newlines: t.Literal[False] = ...,
484488
*,
485489
capture_output: bool = ...,
490+
timeout: float | None = ...,
486491
check: bool = ...,
487492
encoding: None = ...,
488493
errors: None = ...,

‎src/libvcs/cmd/git.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4423,6 +4423,7 @@ def ls(self) -> QueryList[GitRemoteCmd]:
44234423
(?P<url>.+?) # URL: any characters (non-greedy) - supports spaces
44244424
\s+ # One or more whitespace characters
44254425
\((?P<cmd_type>fetch|push)\) # 'fetch' or 'push' in parentheses
4426+
(?:[ \t]+\[[^\]\r\n]*\])? # Partial-clone filter annotation
44264427
$ # End of line
44274428
""",
44284429
re.VERBOSE | re.MULTILINE,
@@ -6869,10 +6870,16 @@ def add(
68696870
68706871
Examples
68716872
--------
6872-
>>> GitWorktreeManager(path=example_git_repo.path).add(
6873-
... path='/tmp/test-worktree-add', commit_ish='HEAD'
6873+
>>> worktree_path = tmp_path / "linked"
6874+
>>> _ = GitWorktreeManager(path=example_git_repo.path).add(
6875+
... path=worktree_path, commit_ish="HEAD", detach=True,
6876+
... check_returncode=True,
68746877
... )
6875-
"Preparing worktree (detached HEAD ...)..."
6878+
>>> (worktree_path / ".git").is_file()
6879+
True
6880+
>>> revision = Git(path=worktree_path).rev_parse(args="HEAD").strip()
6881+
>>> revision == example_git_repo.get_revision()
6882+
True
68766883
"""
68776884
local_flags: list[str] = []
68786885

‎src/libvcs/cmd/hg.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def run(
164164
>>> hg.run(['help'])
165165
"Mercurial Distributed SCM..."
166166
"""
167-
cli_args: list[StrOrBytesPath] = ["hg", *_normalize_command_args(args)]
167+
cli_args: list[StrOrBytesPath] = ["hg"]
168168

169169
if "cwd" not in kwargs:
170170
kwargs["cwd"] = self.path
@@ -196,6 +196,8 @@ def run(
196196
if _help is True:
197197
cli_args.append("--help")
198198

199+
cli_args.extend(_normalize_command_args(args))
200+
199201
if self.progress_callback is not None:
200202
kwargs["callback"] = self.progress_callback
201203

‎src/libvcs/cmd/svn.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,13 @@ def run(
139139
>>> svn.run(['help'])
140140
"usage: svn <subcommand> [options] [args]..."
141141
"""
142-
cli_args: list[StrOrBytesPath] = ["svn", *_normalize_command_args(args)]
142+
cli_args: list[StrOrBytesPath] = ["svn"]
143143

144144
if "cwd" not in kwargs:
145145
kwargs["cwd"] = self.path
146146

147+
if quiet is True:
148+
cli_args.append("--quiet")
147149
if no_auth_cache is True:
148150
cli_args.append("--no-auth-cache")
149151
if non_interactive is True:
@@ -153,12 +155,14 @@ def run(
153155
if password is not None:
154156
cli_args.extend(["--password", password])
155157
if trust_server_cert is True:
156-
cli_args.append("--trust-server_cert")
158+
cli_args.append("--trust-server-cert")
157159
if config_dir is not None:
158160
cli_args.extend(["--config-dir", os.fspath(config_dir)])
159161
if config_option is not None:
160162
cli_args.extend(["--config-option", os.fspath(config_option)])
161163

164+
cli_args.extend(_normalize_command_args(args))
165+
162166
if self.progress_callback is not None:
163167
kwargs["callback"] = self.progress_callback
164168

‎src/libvcs/sync/git.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,7 @@ def obtain(self, *args: t.Any, **kwargs: t.Any) -> None:
428428
depth=clone_depth,
429429
config={"http.sslVerify": False} if self.tls_verify else None,
430430
log_in_real_time=True,
431+
check_returncode=True,
431432
)
432433

433434
self.log.info("Initializing submodules.")
@@ -799,16 +800,19 @@ def set_remote(
799800
Parameters
800801
----------
801802
name : str
802-
defines the remote name.
803-
803+
Remote name.
804804
url : str
805-
defines the remote URL
805+
Remote URL.
806+
push : bool, default: False
807+
Configure ``remote.<name>.pushurl`` instead of the fetch URL.
808+
overwrite : bool, default: False
809+
Update the fetch URL when ``name`` already exists.
806810
"""
807811
url = self.chomp_protocol(url)
808812
remote_cmd = self.cmd.remotes.get(remote_name=name, default=None)
809813

810-
if remote_cmd is not None and overwrite:
811-
remote_cmd.set_url(url=url, check_returncode=True)
814+
if remote_cmd is not None and (overwrite or push):
815+
remote_cmd.set_url(url=url, push=push, check_returncode=True)
812816
else:
813817
self.cmd.remotes.add(name=name, url=url, check_returncode=True)
814818

0 commit comments

Comments
 (0)