estrellio-worktree-integration 0.1.0__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.
- estrellio_worktree_integration-0.1.0.dist-info/METADATA +169 -0
- estrellio_worktree_integration-0.1.0.dist-info/RECORD +10 -0
- estrellio_worktree_integration-0.1.0.dist-info/WHEEL +5 -0
- estrellio_worktree_integration-0.1.0.dist-info/entry_points.txt +2 -0
- estrellio_worktree_integration-0.1.0.dist-info/licenses/LICENSE +21 -0
- estrellio_worktree_integration-0.1.0.dist-info/top_level.txt +1 -0
- worktree_integration/__init__.py +4 -0
- worktree_integration/__main__.py +3 -0
- worktree_integration/cli.py +49 -0
- worktree_integration/core.py +179 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: estrellio-worktree-integration
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cooperative Git worktree coordination for Linux and WSL
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# Worktree integration
|
|
12
|
+
|
|
13
|
+
## Requirements
|
|
14
|
+
|
|
15
|
+
Coordinate several Codex sessions using one local Git repository on Linux/WSL.
|
|
16
|
+
Development in task worktrees can proceed concurrently. Direct development on
|
|
17
|
+
`main` reserves the target worktree for the entire task, including commits and
|
|
18
|
+
validation. All participating sessions must use this protocol; ordinary Git
|
|
19
|
+
commands and manual edits do not acquire its lock automatically.
|
|
20
|
+
|
|
21
|
+
The target defaults to `main`. It must already exist and be checked out in a
|
|
22
|
+
worktree. `--target BRANCH` selects an explicitly agreed alternative; the tool
|
|
23
|
+
never creates or guesses a replacement target. Separate clones and Windows/WSL
|
|
24
|
+
mixed access to one repository are outside this protocol.
|
|
25
|
+
|
|
26
|
+
## Design
|
|
27
|
+
|
|
28
|
+
Implementation: `worktree_integration`.
|
|
29
|
+
|
|
30
|
+
Each repository stores its local coordination data in
|
|
31
|
+
`<git-common-dir>/worktree-integration/`. A nonblocking Linux process lock
|
|
32
|
+
serializes state changes and publication. A persistent owner record reserves the
|
|
33
|
+
main worktree across multiple commands. Linked worktrees share both; unrelated
|
|
34
|
+
repositories do not. The reservation is repository-wide even when a different
|
|
35
|
+
target branch is selected. Owner IDs are coordination identifiers, not secrets.
|
|
36
|
+
|
|
37
|
+
`prepare` fixes the source HEAD and target commit, creates a detached temporary
|
|
38
|
+
worktree under the coordination directory, and performs a normal merge there.
|
|
39
|
+
Fast-forwards are allowed; divergent histories produce a merge commit. Conflicts
|
|
40
|
+
and other merge failures remain in that worktree for inspection. Existing Git
|
|
41
|
+
merge hooks run during preparation. Submodules and build dependencies needed for
|
|
42
|
+
validation must be initialized in the candidate using the target project's SOP.
|
|
43
|
+
|
|
44
|
+
`publish` accepts the full candidate commit ID that the caller has validated.
|
|
45
|
+
It does not run tests or independently certify the caller's validation. Under the
|
|
46
|
+
process lock it checks ownership, clean worktrees, unfinished Git operations,
|
|
47
|
+
the candidate's inclusion of its source and base, and the current target commit.
|
|
48
|
+
It only fast-forwards the target to that exact candidate. If the target changed,
|
|
49
|
+
prepare and validate again. A candidate edited after validation must be revalidated.
|
|
50
|
+
|
|
51
|
+
Publication disables Git hooks and recursive submodule updates: checks belong in
|
|
52
|
+
the candidate, and publication must not introduce hook edits or recursively modify
|
|
53
|
+
other repositories. If gitlink changes leave checked-out target submodules at old
|
|
54
|
+
commits, `status` reports the resulting dirty state. Acquire a main reservation
|
|
55
|
+
and follow the project's submodule update/validation SOP before releasing it;
|
|
56
|
+
subsequent publication remains blocked until clean. Submodule coordination is per
|
|
57
|
+
Git repository, not an atomic transaction across a parent and its submodules.
|
|
58
|
+
|
|
59
|
+
No automatic stash, reset, push, worktree deletion, or commit-history audit is
|
|
60
|
+
performed. Ignored files that would be overwritten also block publication.
|
|
61
|
+
Completed candidates are retained for inspection and recovery.
|
|
62
|
+
|
|
63
|
+
## SOP
|
|
64
|
+
|
|
65
|
+
Use the installed command from any repository. All global options precede the subcommand. Successful commands write one JSON
|
|
66
|
+
object to stdout; errors are logged and return exit code 1. Busy commands fail
|
|
67
|
+
promptly: retain your work, wait briefly, and retry. No background queue is used.
|
|
68
|
+
|
|
69
|
+
### Installation
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
python -m pip install estrellio-worktree-integration
|
|
73
|
+
worktree-integration --help
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Python >=3.10 and Git are required. Coordination runs on Linux/WSL only.
|
|
77
|
+
The package does not require AutoScripts or personal configuration.
|
|
78
|
+
`python -m worktree_integration` is equivalent to the console command.
|
|
79
|
+
Python callers use `from worktree_integration import Coordinator, IntegrationError`.
|
|
80
|
+
|
|
81
|
+
### Direct development on main
|
|
82
|
+
|
|
83
|
+
Before modifying the target worktree:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
worktree-integration --repo /path/to/repo begin-main --label 'Task description'
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Save the returned `id`. Complete the task, run its validation, and commit only
|
|
90
|
+
its changes, then release the reservation:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
worktree-integration --repo /path/to/repo end-main --owner OWNER_ID
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
An owner reservation persists until explicitly released; committing does not
|
|
97
|
+
release it. A read-only task does not need a reservation. `end-main` does not
|
|
98
|
+
clean the worktree. Existing user changes remain protected by publication checks.
|
|
99
|
+
|
|
100
|
+
### Integrate a task worktree
|
|
101
|
+
|
|
102
|
+
Commit and validate the completed task in its original worktree, then prepare:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
worktree-integration --repo /path/to/task-worktree prepare
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The JSON result contains `id`, `base`, `source`, `worktree`, and preparation
|
|
109
|
+
`status`. A `needs-attention` result requires inspecting `message` and the candidate
|
|
110
|
+
worktree; it is not a successful merge. Resolve and commit conflicts there, then
|
|
111
|
+
run the repository's appropriate validation on the final candidate result. Read
|
|
112
|
+
its full commit ID with `git -C CANDIDATE_PATH rev-parse HEAD` and publish:
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
worktree-integration --repo /path/to/task-worktree publish --candidate CANDIDATE_ID --verified-commit FULL_COMMIT_ID
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
If main is occupied, retry after release. If main changed, run `prepare` again and
|
|
119
|
+
validate the new result. The original task may have a detached HEAD. Do not modify
|
|
120
|
+
the original task while publishing a previously fixed source commit.
|
|
121
|
+
|
|
122
|
+
### Inspect and recover
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
worktree-integration --repo /path/to/repo status
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
This reports the actual target HEAD, persistent owner, current blockers, and
|
|
129
|
+
candidate records. Candidate statuses are historical observations: if a process
|
|
130
|
+
was interrupted, inspect Git's actual state as well as the record. An interrupted
|
|
131
|
+
publication may show `publishing` even though the fast-forward completed; retrying
|
|
132
|
+
`publish` with the same validated commit reconciles that state if the target is
|
|
133
|
+
still at that commit and clean. Never reset main to retry an older candidate.
|
|
134
|
+
|
|
135
|
+
Process termination releases the operating-system lock, but not a task reservation.
|
|
136
|
+
Do not expire reservations by timestamp or PID. Confirm the previous task has
|
|
137
|
+
ended, inspect and preserve its work, then explicitly release its recorded owner
|
|
138
|
+
ID with `end-main`. If Git left a lock file or unfinished operation, inspect that
|
|
139
|
+
operation separately; the coordinator does not delete Git locks or abort operations.
|
|
140
|
+
|
|
141
|
+
Do not delete the coordinator's process-lock file: it is reused by all sessions.
|
|
142
|
+
To discard an unused candidate, first ensure no session is using it. Manually
|
|
143
|
+
remove only that candidate worktree with ordinary `git worktree remove` (without
|
|
144
|
+
`--force`); retain its state record for recovery. Never remove the original task
|
|
145
|
+
worktree as part of integration.
|
|
146
|
+
|
|
147
|
+
The commands write Git metadata and may need the execution environment's normal
|
|
148
|
+
permission escalation. A busy/permission error must not be bypassed with a raw merge.
|
|
149
|
+
|
|
150
|
+
## Testing
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
python -m pytest -q tests
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Tests use temporary Git repositories and independent Linux processes. They cover
|
|
157
|
+
concurrent claims and publication, stale candidates, detached HEAD, conflict
|
|
158
|
+
resolution, dirty and unfinished worktrees, ignored-file preservation, validation
|
|
159
|
+
commit identity, interrupted publication, owner persistence after process death,
|
|
160
|
+
independent repositories, and the CLI JSON contract. No application build is
|
|
161
|
+
performed by the coordinator tests.
|
|
162
|
+
|
|
163
|
+
## Provenance and release
|
|
164
|
+
|
|
165
|
+
Extracted from AutoScripts commit `1f22d7afb1c8fc1924005fe4b13ee42e3ebe8f86`.
|
|
166
|
+
The existing state directory, lock inode and JSON records remain compatible.
|
|
167
|
+
Source repository is private; the MIT-licensed Python wheel is publicly readable.
|
|
168
|
+
Version tags trigger publication only after Linux/Windows installed-wheel checks.
|
|
169
|
+
Windows checks certify import/help and rejection, not coordination support.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
estrellio_worktree_integration-0.1.0.dist-info/licenses/LICENSE,sha256=yAt48nv6oAYMWjETk8lC71NkGtpIBX7Op_svNv43RDQ,1062
|
|
2
|
+
worktree_integration/__init__.py,sha256=ZC9jY6F-4ulrNsFKvX3GSfE_Z_WZ_T-4UJXTKzg1-D4,154
|
|
3
|
+
worktree_integration/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
4
|
+
worktree_integration/cli.py,sha256=NdzbI6Yep_Z5xscovuyOe6wORDcFpRD4G89h6fjZpwA,2028
|
|
5
|
+
worktree_integration/core.py,sha256=7QNU2vCY3Dc0GWvlq9sMTvnkmy6G3fHH8XcCQS6dlSw,8129
|
|
6
|
+
estrellio_worktree_integration-0.1.0.dist-info/METADATA,sha256=IuBfQpgWQ9OE37J3f7Mapy7kNwQCxnwTpJ4iRfQG3WA,7902
|
|
7
|
+
estrellio_worktree_integration-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
estrellio_worktree_integration-0.1.0.dist-info/entry_points.txt,sha256=EnPQWbRMZQp10vTkygex2i15_YgZyF76cKxHV5mqch4,71
|
|
9
|
+
estrellio_worktree_integration-0.1.0.dist-info/top_level.txt,sha256=IWUjiVH16TJdMnfhMkDdBrhKiX8HsjDBdr45oryvN7Y,21
|
|
10
|
+
estrellio_worktree_integration-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 shade
|
|
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
|
+
worktree_integration
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Coordinate local Git worktrees on Linux/WSL; stdout contains JSON results."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
from .core import Coordinator, IntegrationError
|
|
10
|
+
|
|
11
|
+
def main(argv: Sequence[str] | None = None, *, logger: logging.Logger | None = None) -> int:
|
|
12
|
+
if logger is None:
|
|
13
|
+
logger = logging.getLogger("worktree_integration")
|
|
14
|
+
if not logger.handlers:
|
|
15
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
16
|
+
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
|
|
17
|
+
logger.addHandler(handler)
|
|
18
|
+
logger.setLevel(logging.INFO)
|
|
19
|
+
logger.propagate = False
|
|
20
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
21
|
+
parser.add_argument('--repo', type=Path, default=Path.cwd())
|
|
22
|
+
parser.add_argument('--target', default='main')
|
|
23
|
+
sub = parser.add_subparsers(dest='action', required=True)
|
|
24
|
+
sub.add_parser('begin-main').add_argument('--label', required=True)
|
|
25
|
+
sub.add_parser('end-main').add_argument('--owner', required=True)
|
|
26
|
+
sub.add_parser('prepare')
|
|
27
|
+
publish = sub.add_parser('publish')
|
|
28
|
+
publish.add_argument('--candidate', required=True)
|
|
29
|
+
publish.add_argument('--verified-commit', required=True)
|
|
30
|
+
sub.add_parser('status')
|
|
31
|
+
args = parser.parse_args(argv)
|
|
32
|
+
try:
|
|
33
|
+
coordinator = Coordinator(args.repo, args.target)
|
|
34
|
+
if args.action == 'begin-main':
|
|
35
|
+
result = coordinator.begin(args.label)
|
|
36
|
+
elif args.action == 'end-main':
|
|
37
|
+
result = coordinator.end(args.owner)
|
|
38
|
+
elif args.action == 'prepare':
|
|
39
|
+
result = coordinator.prepare()
|
|
40
|
+
elif args.action == 'publish':
|
|
41
|
+
result = coordinator.publish(args.candidate, args.verified_commit)
|
|
42
|
+
else:
|
|
43
|
+
result = coordinator.status()
|
|
44
|
+
print(json.dumps(result, indent=2))
|
|
45
|
+
return 0
|
|
46
|
+
except (IntegrationError, OSError, ValueError) as exc:
|
|
47
|
+
logger.error('%s', exc)
|
|
48
|
+
return 1
|
|
49
|
+
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Coordinate local worktree integration and direct development on a target branch.
|
|
2
|
+
|
|
3
|
+
Stdout is a JSON result contract. This cooperative protocol supports Linux/WSL.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Sequence
|
|
16
|
+
import uuid
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class IntegrationError(RuntimeError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def git(repo: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:
|
|
25
|
+
result = subprocess.run(
|
|
26
|
+
['git', '-C', str(repo), *args], text=True, capture_output=True,
|
|
27
|
+
env={**os.environ, 'GIT_TERMINAL_PROMPT': '0', 'GIT_MERGE_AUTOEDIT': 'no'},
|
|
28
|
+
)
|
|
29
|
+
if check and result.returncode:
|
|
30
|
+
raise IntegrationError(result.stderr.strip() or result.stdout.strip())
|
|
31
|
+
return result
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Coordinator:
|
|
35
|
+
def __init__(self, repo: Path, target: str = 'main'):
|
|
36
|
+
if not sys.platform.startswith('linux'):
|
|
37
|
+
raise IntegrationError('Only Linux/WSL is supported.')
|
|
38
|
+
self.repo = repo.resolve()
|
|
39
|
+
git(self.repo, 'check-ref-format', f'refs/heads/{target}')
|
|
40
|
+
self.target = target
|
|
41
|
+
self.ref = f'refs/heads/{target}'
|
|
42
|
+
common = git(self.repo, 'rev-parse', '--path-format=absolute', '--git-common-dir').stdout.strip()
|
|
43
|
+
self.root = Path(common) / 'worktree-integration'
|
|
44
|
+
|
|
45
|
+
@contextmanager
|
|
46
|
+
def locked(self):
|
|
47
|
+
import fcntl
|
|
48
|
+
self.root.mkdir(exist_ok=True)
|
|
49
|
+
with (self.root / 'lock').open('a') as handle:
|
|
50
|
+
try:
|
|
51
|
+
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
52
|
+
except BlockingIOError as exc:
|
|
53
|
+
raise IntegrationError('Coordinator busy; retry later.') from exc
|
|
54
|
+
yield
|
|
55
|
+
|
|
56
|
+
def read(self, path: Path) -> dict:
|
|
57
|
+
return json.loads(path.read_text()) if path.exists() else {}
|
|
58
|
+
|
|
59
|
+
def write(self, path: Path, value: dict):
|
|
60
|
+
temporary = path.with_name(path.name + '.tmp')
|
|
61
|
+
with temporary.open('w') as handle:
|
|
62
|
+
json.dump(value, handle, indent=2)
|
|
63
|
+
handle.write('\n')
|
|
64
|
+
handle.flush()
|
|
65
|
+
os.fsync(handle.fileno())
|
|
66
|
+
temporary.replace(path)
|
|
67
|
+
|
|
68
|
+
def head(self) -> str:
|
|
69
|
+
return git(self.repo, 'rev-parse', '--verify', self.ref).stdout.strip()
|
|
70
|
+
|
|
71
|
+
def target_worktree(self) -> Path:
|
|
72
|
+
path = None
|
|
73
|
+
for field in git(self.repo, 'worktree', 'list', '--porcelain', '-z').stdout.split('\0'):
|
|
74
|
+
if field.startswith('worktree '):
|
|
75
|
+
path = Path(field[len('worktree '):])
|
|
76
|
+
elif field == f'branch {self.ref}' and path is not None:
|
|
77
|
+
return path
|
|
78
|
+
raise IntegrationError(f'{self.target} must be checked out in a worktree.')
|
|
79
|
+
|
|
80
|
+
def require_clean(self, path: Path):
|
|
81
|
+
for name in ('MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply', 'sequencer'):
|
|
82
|
+
location = git(path, 'rev-parse', '--path-format=absolute', '--git-path', name).stdout.strip()
|
|
83
|
+
if Path(location).exists():
|
|
84
|
+
raise IntegrationError(f'Unfinished Git operation in {path}: {name}')
|
|
85
|
+
if git(path, 'status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none').stdout:
|
|
86
|
+
raise IntegrationError(f'Worktree has uncommitted changes: {path}')
|
|
87
|
+
|
|
88
|
+
def begin(self, label: str) -> dict:
|
|
89
|
+
with self.locked():
|
|
90
|
+
path = self.target_worktree()
|
|
91
|
+
owner_path = self.root / 'owner.json'
|
|
92
|
+
owner = self.read(owner_path)
|
|
93
|
+
if owner:
|
|
94
|
+
raise IntegrationError(f'Target occupied by {owner["id"]}: {owner["label"]}')
|
|
95
|
+
owner = {'id': uuid.uuid4().hex, 'label': label, 'target': self.target, 'worktree': str(path)}
|
|
96
|
+
self.write(owner_path, owner)
|
|
97
|
+
return owner
|
|
98
|
+
|
|
99
|
+
def end(self, owner_id: str) -> dict:
|
|
100
|
+
with self.locked():
|
|
101
|
+
path = self.root / 'owner.json'
|
|
102
|
+
owner = self.read(path)
|
|
103
|
+
if not owner or owner['id'] != owner_id:
|
|
104
|
+
raise IntegrationError('Owner ID does not match; inspect status before recovery.')
|
|
105
|
+
self.write(path, {})
|
|
106
|
+
return {'released': owner_id}
|
|
107
|
+
|
|
108
|
+
def prepare(self) -> dict:
|
|
109
|
+
with self.locked():
|
|
110
|
+
self.require_clean(self.repo)
|
|
111
|
+
base = self.head()
|
|
112
|
+
source = git(self.repo, 'rev-parse', 'HEAD').stdout.strip()
|
|
113
|
+
candidate_id = uuid.uuid4().hex
|
|
114
|
+
folder = self.root / 'candidates' / candidate_id
|
|
115
|
+
folder.mkdir(parents=True)
|
|
116
|
+
tree = folder / 'tree'
|
|
117
|
+
state = {'id': candidate_id, 'target': self.target, 'base': base, 'source': source,
|
|
118
|
+
'worktree': str(tree), 'status': 'preparing'}
|
|
119
|
+
state_path = folder / 'state.json'
|
|
120
|
+
self.write(state_path, state)
|
|
121
|
+
git(self.repo, 'worktree', 'add', '--detach', str(tree), base)
|
|
122
|
+
result = git(tree, 'merge', '--ff', '--no-edit', '--no-autostash', source, check=False)
|
|
123
|
+
state['status'] = 'ready' if result.returncode == 0 else 'needs-attention'
|
|
124
|
+
state['message'] = result.stderr.strip() or result.stdout.strip()
|
|
125
|
+
state['candidate'] = git(tree, 'rev-parse', 'HEAD').stdout.strip()
|
|
126
|
+
self.write(state_path, state)
|
|
127
|
+
return state
|
|
128
|
+
|
|
129
|
+
def candidate_path(self, candidate_id: str) -> Path:
|
|
130
|
+
if len(candidate_id) != 32 or any(c not in '0123456789abcdef' for c in candidate_id):
|
|
131
|
+
raise IntegrationError('Invalid candidate ID.')
|
|
132
|
+
return self.root / 'candidates' / candidate_id / 'state.json'
|
|
133
|
+
|
|
134
|
+
def publish(self, candidate_id: str, verified_commit: str) -> dict:
|
|
135
|
+
with self.locked():
|
|
136
|
+
state_path = self.candidate_path(candidate_id)
|
|
137
|
+
state = self.read(state_path)
|
|
138
|
+
if not state or state['target'] != self.target:
|
|
139
|
+
raise IntegrationError('Candidate missing or target does not match.')
|
|
140
|
+
owner = self.read(self.root / 'owner.json')
|
|
141
|
+
if owner:
|
|
142
|
+
raise IntegrationError(f'Target occupied by {owner["id"]}: {owner["label"]}')
|
|
143
|
+
tree = Path(state['worktree'])
|
|
144
|
+
self.require_clean(tree)
|
|
145
|
+
candidate = git(tree, 'rev-parse', 'HEAD').stdout.strip()
|
|
146
|
+
if candidate != verified_commit:
|
|
147
|
+
raise IntegrationError('Specify the exact candidate HEAD that passed validation.')
|
|
148
|
+
for ancestor in (state['base'], state['source']):
|
|
149
|
+
if git(tree, 'merge-base', '--is-ancestor', ancestor, candidate, check=False).returncode:
|
|
150
|
+
raise IntegrationError('Candidate does not contain its base and source commits.')
|
|
151
|
+
target_tree = self.target_worktree()
|
|
152
|
+
self.require_clean(target_tree)
|
|
153
|
+
current = self.head()
|
|
154
|
+
if current == candidate:
|
|
155
|
+
state['status'] = 'published'
|
|
156
|
+
self.write(state_path, state)
|
|
157
|
+
return state
|
|
158
|
+
if current != state['base']:
|
|
159
|
+
raise IntegrationError('Target changed; prepare and validate a new candidate.')
|
|
160
|
+
state.update(status='publishing', candidate=candidate)
|
|
161
|
+
self.write(state_path, state)
|
|
162
|
+
git(target_tree, '-c', 'core.hooksPath=/dev/null', '-c', 'submodule.recurse=false',
|
|
163
|
+
'merge', '--ff-only', '--no-edit', '--no-autostash', '--no-overwrite-ignore', candidate)
|
|
164
|
+
state['status'] = 'published'
|
|
165
|
+
self.write(state_path, state)
|
|
166
|
+
return state
|
|
167
|
+
|
|
168
|
+
def status(self) -> dict:
|
|
169
|
+
with self.locked():
|
|
170
|
+
owner = self.read(self.root / 'owner.json')
|
|
171
|
+
blockers = [f'Target occupied by {owner["id"]}: {owner["label"]}'] if owner else []
|
|
172
|
+
try:
|
|
173
|
+
self.require_clean(self.target_worktree())
|
|
174
|
+
except IntegrationError as exc:
|
|
175
|
+
blockers.append(str(exc))
|
|
176
|
+
return {'target': self.target, 'head': self.head(),
|
|
177
|
+
'owner': owner, 'blockers': blockers,
|
|
178
|
+
'candidates': [self.read(p) for p in sorted(self.root.glob('candidates/*/state.json'))]}
|
|
179
|
+
|