Skip to content

Commit 6d0168e

Browse files
committed
sync(fix,docs): Isolate worker sys.path and share recovery formatting
1 parent a4ef84c commit 6d0168e

10 files changed

Lines changed: 248 additions & 77 deletions

File tree

‎docs/cli/status.md‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,13 @@ Output format:
120120
"workspace_root": "~/study/ai/",
121121
"exists": false,
122122
"is_git": false,
123+
"vcs": null,
124+
"position": null,
125+
"target_position": null,
126+
"configured_target": false,
127+
"policy": null,
128+
"drifted": null,
129+
"errors": [],
123130
"clean": null,
124131
"branch": null,
125132
"ahead": null,
@@ -132,6 +139,27 @@ Output format:
132139
"workspace_root": "~/code/",
133140
"exists": true,
134141
"is_git": true,
142+
"vcs": "git",
143+
"position": {
144+
"revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b",
145+
"ref_name": "main",
146+
"ref_kind": "branch",
147+
"follows": true,
148+
"mixed": false,
149+
"switched": false
150+
},
151+
"target_position": {
152+
"revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b",
153+
"ref_name": "main",
154+
"ref_kind": "branch",
155+
"follows": true,
156+
"mixed": false,
157+
"switched": false
158+
},
159+
"configured_target": false,
160+
"policy": {"drift": "follow", "dirty": "abort"},
161+
"drifted": false,
162+
"errors": [],
135163
"clean": true,
136164
"branch": null,
137165
"ahead": null,
@@ -155,8 +183,14 @@ Each status entry includes:
155183
- `path`: Full filesystem path
156184
- `workspace_root`: Configuration section this repo belongs to
157185
- `exists`: Whether the directory exists
158-
- `is_git`: Whether it's a Git repository
159-
- `clean`: Git working tree status (`null` if not a git repo or missing)
186+
- `is_git`: Whether the checkout is a Git repository
187+
- `vcs`: Detected checkout backend (`"git"`, `"hg"`, `"svn"`, or `null`)
188+
- `position`, `target_position`: Current and resolved checkout position objects (`null` when missing or unavailable)
189+
- `configured_target`: Whether `working_copy` is explicitly configured
190+
- `policy`: Effective `drift` and `dirty` policy (`null` when missing)
191+
- `drifted`: Whether `position` differs from `target_position` (`null` when unknown)
192+
- `errors`: List of `{"step", "message"}` status or target-resolution diagnostics
193+
- `clean`: Working tree cleanliness (`null` if missing or unavailable)
160194
- `branch`: Current branch (populated only with `--detailed`, otherwise `null`)
161195
- `ahead`, `behind`: Divergence counts relative to the upstream branch
162196
(populated only with `--detailed`, otherwise `null`)

‎docs/cli/sync.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,9 @@ Each event emitted during the run includes:
250250
- `detail`: Short explanation of the action, when available
251251
- `branch`, `ahead`, `behind`, `dirty`: Working-tree state for existing
252252
checkouts
253+
- `update_state`, `preservation_state`, `recovery`, `conflicts`, `errors`,
254+
`retained_recoveries`: Native synchronization and recovery fields on live
255+
`reason: "sync"` events
253256
254257
Use `--json` without `--dry-run` to capture actual sync executions—successful
255258
and failed repositories are emitted with their final state.

‎docs/internals/api/index.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ If you need an internal API stabilized please [file an issue](https://github.com
1010

1111
```{toctree}
1212
config_reader
13+
sync
14+
sync_process
1315
worktree_sync
1416
private_path
1517
```

‎docs/internals/api/sync.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Sync helpers
2+
3+
:::{warning}
4+
Be careful with these! Internal APIs are **not** covered by version policies. They can break or be removed between minor versions!
5+
6+
If you need an internal API stabilized please [file an issue](https://github.com/vcs-python/vcspull/issues).
7+
:::
8+
9+
{mod}`vcspull._internal.sync` translates validated checkout configuration into
10+
typed libvcs backend instances, target selectors, sync policies, and structured
11+
recovery payloads.
12+
13+
```{eval-rst}
14+
.. automodule:: vcspull._internal.sync
15+
:members:
16+
:show-inheritance:
17+
:undoc-members:
18+
```

‎docs/internals/api/sync_process.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Sync process supervision
2+
3+
:::{warning}
4+
Be careful with these! Internal APIs are **not** covered by version policies. They can break or be removed between minor versions!
5+
6+
If you need an internal API stabilized please [file an issue](https://github.com/vcs-python/vcspull/issues).
7+
:::
8+
9+
{mod}`vcspull._internal.sync_process` supervises per-repository CLI mutations in
10+
owned POSIX process groups and inspects retained recovery records after timeouts
11+
or interrupts.
12+
13+
```{eval-rst}
14+
.. automodule:: vcspull._internal.sync_process
15+
:members:
16+
:show-inheritance:
17+
:undoc-members:
18+
```

‎src/vcspull/_internal/sync.py‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,45 @@
22

33
from __future__ import annotations
44

5+
import collections.abc
56
import dataclasses
67
import datetime
78
import typing as t
8-
from collections.abc import Callable, Mapping
99

10-
from libvcs import BaseSync, SyncPolicy, SyncResult, SyncTarget
10+
from libvcs import BaseSync, RecoveryToken, SyncPolicy, SyncResult, SyncTarget
1111
from libvcs._internal.shortcuts import create_project
1212
from libvcs._internal.types import VCSLiteral
1313
from libvcs.sync.git import GitOptions, GitRemote
1414
from libvcs.sync.hg import HgOptions
1515
from libvcs.sync.svn import SvnOptions
1616

17+
from vcspull import exc
18+
from vcspull._internal.private_path import PrivatePath
1719
from vcspull.validator import validate_working_copy
1820

1921

20-
@dataclasses.dataclass(frozen=True)
22+
@dataclasses.dataclass(frozen=True, slots=True)
2123
class SyncExecution:
22-
"""Keep the backend instance and its complete synchronization result."""
24+
"""Keep the backend instance and its complete synchronization result.
25+
26+
Attributes
27+
----------
28+
project : BaseSync
29+
Constructed libvcs synchronization backend for the repository.
30+
result : SyncResult
31+
Completed synchronization outcome, including recovery metadata.
32+
"""
2333

2434
project: BaseSync
2535
result: SyncResult
2636

2737

2838
def create_sync_project(
29-
repo: Mapping[str, t.Any],
39+
repo: collections.abc.Mapping[str, t.Any],
3040
*,
3141
vcs: VCSLiteral,
32-
progress_callback: Callable[[str, datetime.datetime], None] | None = None,
42+
progress_callback: collections.abc.Callable[[str, datetime.datetime], None]
43+
| None = None,
3344
) -> BaseSync:
3445
"""Construct a typed backend without accessing or changing its checkout."""
3546
options_type = {"git": GitOptions, "hg": HgOptions, "svn": SvnOptions}[vcs]
@@ -52,7 +63,7 @@ def create_sync_project(
5263

5364

5465
def checkout_settings(
55-
config: Mapping[str, t.Any] | None, *, worktree: bool = False
66+
config: collections.abc.Mapping[str, t.Any] | None, *, worktree: bool = False
5667
) -> tuple[SyncTarget | None, SyncPolicy]:
5768
"""Translate a validated checkout without collapsing its selector kind.
5869
@@ -91,3 +102,52 @@ def sync_result_data(result: SyncResult) -> dict[str, t.Any]:
91102
{"step": error.step, "message": error.message} for error in result.errors
92103
],
93104
}
105+
106+
107+
def format_recovery_lines(
108+
primary: SyncResult | None,
109+
retained: collections.abc.Sequence[SyncResult] = (),
110+
) -> list[str]:
111+
"""Render deduplicated recovery, conflict, and inspection lines.
112+
113+
>>> token = RecoveryToken("tok-1", "git", "/tmp/store/tok-1")
114+
>>> res = SyncResult(
115+
... recovery=token,
116+
... update_state="completed",
117+
... preservation_state="restored",
118+
... )
119+
>>> format_recovery_lines(res)
120+
['Update: completed; local changes: restored', 'Recovery retained (git): tok-1 ...']
121+
"""
122+
lines: list[str] = []
123+
if primary is not None:
124+
lines.extend(
125+
f"Recovery inspection: {error.message}"
126+
for error in primary.errors
127+
if error.step == "recovery-inspection"
128+
)
129+
seen: set[RecoveryToken] = set()
130+
for result in (primary, *retained):
131+
if result is None or result.recovery is None or result.recovery in seen:
132+
continue
133+
token = result.recovery
134+
seen.add(token)
135+
lines.append(
136+
f"Update: {result.update_state}; local changes: {result.preservation_state}"
137+
)
138+
lines.extend(
139+
f"Conflict: {conflict.path} ({conflict.reason})"
140+
for conflict in result.conflicts
141+
)
142+
lines.append(
143+
f"Recovery retained ({token.backend}): {token.id} "
144+
f"at {PrivatePath(token.location)}"
145+
)
146+
return lines
147+
148+
149+
def require_discard_authorization(policy: SyncPolicy, *, allow_discard: bool) -> None:
150+
"""Require explicit invocation consent before constructing a discard backend."""
151+
if policy.dirty == "discard" and not allow_discard:
152+
message = "dirty: discard requires --yes before synchronization"
153+
raise exc.VCSPullException(message)

‎src/vcspull/_internal/sync_process.py‎

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
import codecs
6+
import collections.abc
67
import contextlib
78
import dataclasses
89
import datetime
@@ -16,7 +17,6 @@
1617
import sys
1718
import time
1819
import typing as t
19-
from collections.abc import Callable, Mapping
2020

2121
from libvcs import RecoveryToken, SyncConflict, SyncResult
2222
from libvcs.sync.git import GitRemote
@@ -25,9 +25,25 @@
2525
from vcspull._internal.sync import sync_result_data
2626

2727

28-
@dataclasses.dataclass
28+
@dataclasses.dataclass(slots=True)
2929
class SyncOutcome:
30-
"""Keep completed results separate from forced termination and inspection."""
30+
"""Keep completed results separate from forced termination and inspection.
31+
32+
Attributes
33+
----------
34+
status : {"synced", "failed", "timed_out"}
35+
Terminal watchdog classification for the worker run.
36+
captured_output : str | None
37+
Buffered worker stdout/stderr when running in machine-readable mode.
38+
error : BaseException | None
39+
Synthesized failure exception when ``status == "failed"``.
40+
duration : float
41+
Elapsed wall-clock seconds spent in the worker run.
42+
result : SyncResult | None
43+
Deserialized synchronization result from the worker, if reported.
44+
retained_recoveries : tuple[SyncResult, ...]
45+
Retained recovery records discovered by post-failure inspection.
46+
"""
3147

3248
status: t.Literal["synced", "failed", "timed_out"]
3349
captured_output: str | None = None
@@ -45,7 +61,7 @@ def __init__(self, outcome: SyncOutcome) -> None:
4561
super().__init__()
4662

4763

48-
@dataclasses.dataclass
64+
@dataclasses.dataclass(slots=True)
4965
class _Exchange:
5066
terminal: dict[str, t.Any] | None
5167
output: str
@@ -85,7 +101,11 @@ def _worker_command(control_fd: int) -> list[str]:
85101
sys.executable,
86102
"-u",
87103
"-c",
88-
"from vcspull._internal.sync_process import _main; _main()",
104+
(
105+
"import sys; sys.path.insert(0, sys.argv.pop(1)); "
106+
"from vcspull._internal.sync_process import _main; _main()"
107+
),
108+
str(pathlib.Path(__file__).resolve().parents[2]),
89109
str(control_fd),
90110
]
91111

@@ -122,7 +142,7 @@ def _exchange(
122142
request: dict[str, t.Any],
123143
*,
124144
timeout: float,
125-
progress_callback: Callable[[str, datetime.datetime], None],
145+
progress_callback: collections.abc.Callable[[str, datetime.datetime], None],
126146
is_human: bool,
127147
) -> _Exchange:
128148
payload = memoryview(json.dumps(request, default=_json_default).encode())
@@ -135,17 +155,6 @@ def _exchange(
135155
interrupted = False
136156
protocol_error: str | None = None
137157
deadline = time.monotonic() + timeout
138-
environment = {
139-
**os.environ,
140-
"PYTHONPATH": os.pathsep.join(
141-
part
142-
for part in (
143-
str(pathlib.Path(__file__).resolve().parents[2]),
144-
os.environ.get("PYTHONPATH", ""),
145-
)
146-
if part
147-
),
148-
}
149158
try:
150159
process = subprocess.Popen(
151160
_worker_command(write_fd),
@@ -154,7 +163,6 @@ def _exchange(
154163
stderr=subprocess.PIPE,
155164
start_new_session=True,
156165
pass_fds=(write_fd,),
157-
env=environment,
158166
)
159167
except BaseException:
160168
os.close(read_fd)
@@ -301,9 +309,9 @@ def accept(frame: dict[str, t.Any]) -> None:
301309

302310

303311
def run_sync_process(
304-
repo: Mapping[str, t.Any],
312+
repo: collections.abc.Mapping[str, t.Any],
305313
*,
306-
progress_callback: Callable[[str, datetime.datetime], None],
314+
progress_callback: collections.abc.Callable[[str, datetime.datetime], None],
307315
timeout: float,
308316
is_human: bool,
309317
yes: bool = False,

‎src/vcspull/cli/status.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@
1111
import re
1212
import subprocess
1313
import sys
14+
import time
1415
import typing as t
15-
from dataclasses import dataclass
16-
from time import perf_counter
1716

1817
from libvcs import exc as vcs_exc
1918
from libvcs._internal.types import VCSLiteral
@@ -34,7 +33,7 @@
3433
ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m")
3534

3635

37-
@dataclass
36+
@dataclasses.dataclass
3837
class StatusCheckConfig:
3938
"""Configuration options for status checking.
4039
@@ -455,15 +454,15 @@ def status_repos(
455454
progress_enabled,
456455
)
457456

458-
start_time = perf_counter()
457+
start_time = time.perf_counter()
459458
status_results = asyncio.run(
460459
_check_repos_status_async(
461460
found_repos,
462461
config=check_config,
463462
progress=progress_printer if progress_enabled else None,
464463
),
465464
)
466-
duration_ms = int((perf_counter() - start_time) * 1000)
465+
duration_ms = int((time.perf_counter() - start_time) * 1000)
467466

468467
if progress_enabled:
469468
progress_printer.finish()

0 commit comments

Comments
 (0)