Skip to content

Commit 4b9529c

Browse files
authored
sync(feat): Retain dirty checkouts for recovery (#563)
why: Uncommitted changes in Git, Mercurial, and Subversion checkouts could be overwritten or lost without recoverable snapshots or explicit dirty-tree policy. what: - Add SyncTarget, SyncPolicy, RecoveryToken, SyncConflict, and extended SyncResult contracts with default dirty="abort" - Implement mode-0700 sibling RecoveryStore and format-31 Subversion working-copy sealing - Preserve, inspect, recover offline, and release local changes across GitSync, HgSync, and SvnSync - Add HgRemote and non-destructive .hg/hgrc [paths] management
2 parents 83da79f + 3a04d81 commit 4b9529c

24 files changed

Lines changed: 6576 additions & 959 deletions

‎CHANGES‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,24 @@ _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+
#### Sync aborts on dirty checkouts by default (#563)
31+
32+
{meth}`~libvcs.sync.git.GitSync.update_repo`,
33+
{meth}`~libvcs.sync.hg.HgSync.update_repo`, and
34+
{meth}`~libvcs.sync.svn.SvnSync.update_repo` now default to
35+
`SyncPolicy(drift="follow", dirty="abort")` and record a `"dirty"` error instead
36+
of updating over uncommitted changes. Pass `SyncPolicy(dirty="preserve")` to
37+
retain recoverable changes or `SyncPolicy(dirty="discard")` to remove ordinary
38+
local modifications explicitly.
39+
40+
```python
41+
# Before
42+
result = repo.update_repo()
43+
44+
# After
45+
result = repo.update_repo(policy=SyncPolicy(dirty="preserve"))
46+
```
47+
3048
#### Sync constructors take typed backend options (#562)
3149

3250
Backend-specific sync constructor arguments move into frozen
@@ -55,6 +73,88 @@ repo = GitSync(
5573

5674
### What's new
5775

76+
#### Subversion retains complete working copies for recovery (#563)
77+
78+
Explicit preservation in {meth}`~libvcs.sync.svn.SvnSync.update_repo` uses
79+
native update or switch and retains a complete working copy, including
80+
schedules, binary properties, unknown files, and ignored files.
81+
Missing paths stay absent only when their complete native and physical scope
82+
is unchanged. Conflicts and failed inspection retain their recovery token.
83+
{meth}`~libvcs.sync.svn.SvnSync.recover_changes` creates independent copies
84+
offline; {meth}`~libvcs.sync.svn.SvnSync.list_recoveries` reports interrupted
85+
operations, and {meth}`~libvcs.sync.svn.SvnSync.release_changes` releases
86+
verified copies. Recovery and release work after the original checkout is
87+
deleted or replaced.
88+
89+
SVN targets accept `rev`; the configured repository URL controls switching.
90+
Branch, tag, commit, and remote selectors are rejected. Preservation requires
91+
POSIX and SVN working-copy format 31. It rejects externals, nested repositories,
92+
and linked administrative storage. Callers must stop external editors and native
93+
writers.
94+
95+
#### Mercurial remotes keep fetch and push separate (#563)
96+
97+
`create_project(vcs="hg", remotes=...)` forwards configured Mercurial paths
98+
through the same factory used by configuration consumers.
99+
100+
{class}`~libvcs.sync.hg.HgRemote` and `HgSync(remotes=...)` expose native
101+
`[paths]` aliases with separate fetch and push URLs. `SyncTarget(remote=...)`
102+
chooses where to pull without changing unrelated push destinations. Configured
103+
aliases update atomically during following syncs; keep, warn, and dirty-abort
104+
preflight leave native configuration unchanged. Comments and includes survive
105+
updates, and equivalent relative or environment-expanded paths do not rewrite
106+
the file. See {doc}`sync/hg`.
107+
108+
#### Shared checkout targets and recovery outcomes (#563)
109+
110+
{class}`~libvcs.sync.base.SyncTarget` selects one branch, tag, commit, or
111+
revision. {class}`~libvcs.sync.base.SyncPolicy` keeps configured-target drift
112+
separate from local-change handling and defaults to `dirty="abort"`.
113+
{class}`~libvcs.sync.base.SyncResult` reports update and preservation outcomes,
114+
conflicts, and retained recovery tokens independently.
115+
116+
#### Mercurial retains shelves for independent recovery (#563)
117+
118+
Explicit `SyncPolicy(dirty="preserve")` in
119+
{meth}`~libvcs.sync.hg.HgSync.update_repo` retains native shelves in private
120+
storage, including added, removed, modified, and unknown files. Missing files
121+
retain their unscheduled state; upstream changes to a missing path report a
122+
conflict. Native unshelve conflicts keep their recovery token and caller-owned
123+
backups. {meth}`~libvcs.sync.hg.HgSync.recover_changes` restores the original
124+
branch, bookmark, and native status in a separate checkout using retained local
125+
history, without remote access. {meth}`~libvcs.sync.hg.HgSync.list_recoveries`
126+
exposes interrupted saves and damaged records;
127+
{meth}`~libvcs.sync.hg.HgSync.release_changes` removes only verified owned
128+
shelf artifacts.
129+
130+
#### Mercurial clone applies transport and revision selection (#563)
131+
132+
{class}`~libvcs.sync.hg.HgSync` strips the `hg+` adapter prefix before invoking
133+
Mercurial and applies the constructor's `rev` when checking out a new clone.
134+
An explicit `update_repo(target=...)` overrides that revision. A new checkout
135+
starts at its configured target before keep or warn policy applies.
136+
137+
#### Git retains dirty changes for independent recovery (#563)
138+
139+
Explicit `SyncPolicy(dirty="preserve")` in
140+
{meth}`~libvcs.sync.git.GitSync.update_repo` retains staged, unstaged, and
141+
untracked changes in an owned stash and applies them with the index after a
142+
fast-forward update. Conflicts and failed updates retain a recovery token.
143+
{meth}`~libvcs.sync.git.GitSync.list_recoveries` finds interrupted saves;
144+
{meth}`~libvcs.sync.git.GitSync.recover_changes` creates a separate
145+
original-base checkout from local Git objects;
146+
{meth}`~libvcs.sync.git.GitSync.release_changes` removes owned material.
147+
Recovery requires those local objects and never fetches from the remote.
148+
Malformed recovery records remain visible as errors carrying their token.
149+
Ignored target collisions, divergent commits, active native operations,
150+
dirty submodule scopes, and nested repositories fail before capture.
151+
Clean recursive submodule updates reject ignored-file collisions in initialized
152+
children before any checkout advances. Target resolution refreshes every
153+
configured remote; clone and fetch honor command-scoped TLS configuration.
154+
155+
New Git checkouts follow the configured target before keep or warn policy
156+
applies. Those policies continue to leave existing checkouts unchanged.
157+
58158
#### Git command configuration precedes subcommands (#562)
59159

60160
{meth}`~libvcs.cmd.git.Git.run` places global flags before the subcommand and

‎MIGRATION‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,42 @@ _Notes on the upcoming release will be added here_
2424

2525
<!-- Maintainers, insert migration notes for the next release here -->
2626

27+
### Sync results and dirty checkout policy
28+
29+
`update_repo()` creates or updates a checkout and returns `SyncResult`.
30+
Check `result.ok` and its ordered `errors` before proceeding. `obtain()` only
31+
creates the initial checkout.
32+
33+
The default is now `SyncPolicy(drift="follow", dirty="abort")`. Automation
34+
that updates dirty checkouts must choose `dirty="preserve"` to retain
35+
recoverable changes or explicitly choose `dirty="discard"` to remove them.
36+
The library does not prompt for discard. Preservation may report conflicts;
37+
it never falls back to discard.
38+
39+
Pass `target=SyncTarget(...)` and `policy=SyncPolicy(...)` to `update_repo()`.
40+
A method target replaces the constructor's `rev` default. Existing Git/Hg
41+
keep/warn operations do not fetch or change attachment; new checkouts first
42+
establish their configured target. SVN keep/warn requires a numeric revision
43+
for local comparison.
44+
45+
Retain `result.recovery` on both successful and failed updates. Tokens stay
46+
available until `release_changes()`; `list_recoveries()` discovers them and
47+
`recover_changes()` writes a separate new checkout. See the executing
48+
{ref}`recovery example <sync-recovery>` and backend limits before deleting
49+
source repositories or recovery storage.
50+
51+
### Mercurial remotes and selected pull sources
52+
53+
Use `HgSync(remotes={"upstream": HgRemote("upstream", fetch_url, push_url)})`
54+
to declare native Mercurial paths. A string value sets both destinations to
55+
that URL. Pass `SyncTarget(branch="default", remote="upstream")` to choose
56+
the pull source independently of the push URL.
57+
58+
Following updates apply configured paths. On existing checkouts, keep/warn
59+
policies and dirty-abort preflight leave `.hg/hgrc` unchanged. The library owns a final marked `[paths]`
60+
block; comments and includes outside it remain intact. Leave that block last
61+
when editing native configuration manually.
62+
2763
### Sync backends use typed options
2864

2965
Backend-specific constructor arguments move into frozen option objects. Import

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ dependencies = ["libvcs>=0.45,<0.46"]
6868
`GitSync`, `HgSync`, and `SvnSync` give the same two calls regardless of the
6969
underlying VCS: `obtain()` clones if the path does not exist yet, and
7070
`update_repo()` does that or fetches and updates an existing checkout — call
71-
it either way and let libvcs decide.
71+
it either way and let libvcs decide. By default (`SyncPolicy(dirty="abort")`),
72+
`update_repo()` refuses to overwrite uncommitted local changes; pass
73+
`SyncPolicy(dirty="preserve")` to retain recoverable changes across an update.
7274

7375
[**Learn more about Synchronization**](https://libvcs.git-pull.com/sync/)
7476

‎docs/sync/git.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,23 @@ If gitlinks exist, obtain raises `ValueError` before initializing them and
3838
leaves the parent clone at the destination. Existing checkout updates do not
3939
change their configured filter.
4040

41+
## Update and recovery behavior
42+
43+
Following a branch requires fast-forward ancestry and retains ahead local
44+
commits. Select a tag or commit explicitly when you want a detached checkout.
45+
Use the shared {ref}`policy guide <sync-policies>` and executing
46+
{ref}`recovery example <sync-recovery>` to handle results and retained tokens.
47+
48+
Preservation uses indexed stash application to retain staged and unstaged
49+
changes separately. An index conflict remains a conflict; restoration does
50+
not retry without the index. Ordinary ignored output is not dirt, but updates
51+
protect ignored files that collide with the target.
52+
53+
Offline recovery needs the retained local common object database. Missing
54+
objects in a partial clone cause recovery to fail without fetching. Keep that
55+
database until you release its tokens. Preservation rejects submodule scopes
56+
and independent nested repositories; clean recursive updates remain available.
57+
4158
```{eval-rst}
4259
.. automodule:: libvcs.sync.git
4360
:members:

‎docs/sync/hg.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,53 @@ settings. The default verifies TLS certificates.
2020
True
2121
```
2222

23+
## Remotes and checkout policy
24+
25+
Name native fetch and push destinations separately:
26+
27+
```python
28+
>>> from libvcs import HgRemote, HgSync, SyncPolicy, SyncTarget
29+
>>> repo = HgSync(
30+
... url="https://example.com/project",
31+
... path=tmp_path / "project",
32+
... remotes={"upstream": HgRemote(
33+
... "upstream", "https://example.com/project", "ssh://example.com/publish"
34+
... )},
35+
... )
36+
>>> target = SyncTarget(branch="default", remote="upstream")
37+
>>> policy = SyncPolicy(dirty="preserve")
38+
```
39+
40+
Pass `target` and `policy` to `update_repo()`. The remote selects the pull
41+
source; its push URL stays separate. The shared {ref}`recovery example <sync-recovery>`
42+
executes an update and checks its result against a disposable repository.
43+
A synthesized `default` alias retains
44+
an existing push destination. An explicitly configured alias supplies both
45+
destinations, with push defaulting to its fetch URL when omitted.
46+
47+
`remotes()` reads effective aliases, including native `%include` files.
48+
`set_remotes(overwrite=True)` writes configured aliases atomically. The method
49+
preserves comments and included files and owns a final `[paths]` block in
50+
`.hg/hgrc`; keep that block last when editing the file manually. Without
51+
`overwrite=True`, existing aliases remain unchanged.
52+
53+
Existing checkouts apply configured remotes after keep/warn and dirty-abort
54+
preflight. New checkouts start at the configured target before drift policy
55+
applies. A method-level target overrides the constructor's revision.
56+
Preservation retains an owned shelf and supplemental native state. Recovery
57+
creates a separate checkout from retained local history; the configured remote
58+
is never contacted during recovery.
59+
60+
## Preservation limits
61+
62+
Named branches, bookmarks, tags, and changesets resolve locally. Native
63+
unshelve conflicts retain both the conflict state and recovery token. Keep
64+
the source history until releasing its tokens: deleting that history prevents
65+
offline recovery. Preservation rejects subrepositories, nested repositories,
66+
shared-store layouts, and unfinished native operations. See the shared
67+
{ref}`token lifecycle <sync-recovery>` for discovery, separate recovery, and
68+
explicit release.
69+
2370
```{eval-rst}
2471
.. automodule:: libvcs.sync.hg
2572
:members:

‎docs/sync/index.md‎

Lines changed: 106 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,25 @@
22

33
# Sync - `libvcs.sync`
44

5-
Keep a local checkout in sync with its remote: {meth}`~libvcs.sync.git.GitSync.obtain`
6-
and its Mercurial and Subversion counterparts clone the repository when it
5+
Keep a local checkout in sync with its remote: {meth}`~libvcs.sync.git.GitSync.update_repo`
6+
and its Mercurial and Subversion counterparts create the checkout when it
77
doesn't exist yet and update it when it does, through
88
{class}`~libvcs.sync.git.GitSync`, {class}`~libvcs.sync.hg.HgSync`, and
99
{class}`~libvcs.sync.svn.SvnSync` — built on top of {mod}`libvcs.cmd`.
10+
Use `obtain()` only to create the initial checkout.
11+
12+
`update_repo()` returns a {class}`~libvcs.sync.base.SyncResult`. Check its
13+
`ok` flag before proceeding; failed results retain ordered errors with the
14+
operation that failed. These examples use disposable repositories from
15+
libvcs's {doc}`pytest fixtures </api/pytest-plugin>`.
16+
17+
```python
18+
>>> result = example_git_repo.update_repo()
19+
>>> result.ok
20+
True
21+
>>> [(error.step, error.message) for error in result.errors]
22+
[]
23+
```
1024

1125
Compare to:
1226
[`fabtools.require.git`](https://fabtools.readthedocs.io/en/0.19.0/api/require/git.html),
@@ -41,6 +55,96 @@ active bookmark when present, otherwise its named branch. Subversion reports
4155
the checkout URL and root base revision; `mixed` and `switched` identify
4256
working copies whose children cannot be described by the root alone.
4357

58+
(sync-policies)=
59+
60+
## Choose an update policy
61+
62+
The default `SyncPolicy(drift="follow", dirty="abort")` follows the selected
63+
target and aborts on detected local changes. Pass `target=SyncTarget(...)`
64+
and `policy=SyncPolicy(...)` to `update_repo()` to choose another behavior.
65+
A method target replaces the constructor's `rev` default.
66+
67+
| Policy | Behavior |
68+
| --- | --- |
69+
| `drift="follow"` | Update to the selected target using native VCS rules. |
70+
| `drift="keep"` | Leave an existing checkout at its current position. |
71+
| `drift="warn"` | Keep its position and report a resolved target mismatch. |
72+
| `dirty="abort"` | Refuse updates while ordinary local changes are present. |
73+
| `dirty="preserve"` | Retain recoverable changes, update, then restore them; conflicts remain visible. |
74+
| `dirty="discard"` | Explicitly discard supported ordinary local changes. |
75+
76+
The library does not prompt for discard. Preservation never falls back to
77+
discard. Existing Git and Hg keep/warn operations inspect local targets
78+
without fetching or changing attachment; different names at the same revision
79+
do not count as drift. New checkouts establish the configured target first.
80+
SVN keep/warn needs a numeric revision for local comparison: remote `HEAD`
81+
cannot be resolved without contacting the server.
82+
83+
(sync-recovery)=
84+
85+
## Preserve and recover local changes
86+
87+
Preservation returns a token when it captures changes. Keep that token even
88+
when `result.ok` is false: `update_state`, `preservation_state`, `conflicts`,
89+
and `errors` describe separate update and restoration outcomes.
90+
91+
This example selects an earlier Git commit while retaining an untracked note,
92+
then recovers the original checkout into a separate directory:
93+
94+
```python
95+
>>> from libvcs import SyncPolicy, SyncTarget
96+
>>> repo = example_git_repo
97+
>>> target = SyncTarget(commit=repo.get_revision())
98+
>>> _ = repo.run(["commit", "--allow-empty", "-m", "local work"])
99+
>>> original_revision = repo.get_revision()
100+
>>> _ = (repo.path / "notes.txt").write_text("keep this note\n")
101+
>>> result = repo.update_repo(target=target, policy=SyncPolicy(dirty="preserve"))
102+
>>> result.ok, result.update_state, result.preservation_state
103+
(True, 'completed', 'restored')
104+
>>> result.conflicts, result.errors
105+
((), [])
106+
>>> token = result.recovery
107+
>>> assert token is not None
108+
>>> repo.get_revision() == target.commit
109+
True
110+
>>> (repo.path / "notes.txt").read_text()
111+
'keep this note\n'
112+
>>> token in [record.recovery for record in repo.list_recoveries()]
113+
True
114+
>>> destination = tmp_path / "recovered"
115+
>>> recovered = repo.recover_changes(token, destination=destination)
116+
>>> recovered.ok, recovered.preservation_state
117+
(True, 'restored')
118+
>>> from libvcs import GitSync
119+
>>> copy = GitSync(url=repo.url, path=destination)
120+
>>> copy.get_revision() == original_revision
121+
True
122+
>>> (destination / "notes.txt").read_text()
123+
'keep this note\n'
124+
>>> repo.release_changes(token)
125+
>>> repo.list_recoveries()
126+
()
127+
```
128+
129+
Release only after verifying the retained changes. Tokens remain after a
130+
successful restoration, conflict, failed update, or separate recovery;
131+
recovery is repeatable until explicit release. `recovery` is `None` when no
132+
capture was needed. Discovery can return damaged or incomplete records with
133+
errors, so a token alone does not certify usable recovery material.
134+
135+
`recover_changes()` writes a new checkout; it does not overwrite the source
136+
or resume an interrupted update. Its destination must not exist, must have
137+
an existing parent, and must not overlap the source or recovery storage.
138+
Interrupted records block automatic updates; listing them does not resume
139+
work. Prevent external editors and VCS writers during these operations: the
140+
POSIX ownership lock coordinates libvcs operations only.
141+
142+
Recovery uses local material. Its dependencies and admitted repository layouts
143+
differ for {doc}`Git <git>`, {doc}`Mercurial <hg>`, and {doc}`Subversion <svn>`.
144+
Process-death tests cover persisted operation boundaries and an active Git
145+
checkout; they do not establish power-loss durability or arbitrary native
146+
command interruption guarantees.
147+
44148
## Modules
45149

46150
::::{grid} 1 1 2 2

‎docs/sync/svn.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,24 @@ representation.
2525
False
2626
```
2727

28+
## Targets and recovery
29+
30+
`SyncTarget(rev=...)` accepts a numeric revision or `HEAD`. The configured
31+
repository URL determines whether synchronization updates or switches the
32+
working copy. Local `resolve_target()` cannot resolve remote `HEAD`; use a
33+
numeric revision for keep/warn comparison without server contact.
34+
35+
Preservation seals a complete physical working copy, including `.svn`,
36+
schedules, properties, unknown and ignored files, and working-tree symlinks.
37+
Recovery creates a separate checkout offline, even after the original source
38+
is deleted or replaced. See the shared {ref}`policy guide <sync-policies>`
39+
and {ref}`token lifecycle <sync-recovery>` for result handling and release.
40+
41+
Preservation admits POSIX format-31 working-copy roots. It rejects externals,
42+
nested working copies, busy or unsupported database schemas, and
43+
administrative symlinks. Missing paths are removed again only after verified
44+
safe native completion; upstream changes remain visible as conflicts.
45+
2846
```{eval-rst}
2947
.. automodule:: libvcs.sync.svn
3048
:members:

0 commit comments

Comments
 (0)