Repository navigation
Ledger merge driver #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
892cd62
rebase: match incoming records across renumbering
NovusEdge 53bf12d
Add docket merge-driver, a git merge driver for the ledger
NovusEdge b273624
Use the merge driver for this repository's ledger and document it
NovusEdge e62b890
init: register the ledger merge driver; brief when a clone lacks it
NovusEdge 6d25960
init: register only merge.docket.driver, report a failed registration…
NovusEdge e527f89
merge-driver: always leave conflict markers and append without rewrit…
NovusEdge 71286e0
docs: merge driver remap limits, ancestor rule, unregistered clones
NovusEdge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,7 @@ | ||
| # Both stores are append-only JSONL, so a union merge is the right resolution: | ||
| # it keeps every line from both sides. Duplicate ids that union produces are | ||
| # renumbered afterwards by `docket rebase` and `docket feature remap`. | ||
| # The ledger merges through `docket merge-driver`, which appends the other | ||
| # side's new records under fresh ids. Each clone registers the driver with | ||
| # `docket init`; without it git reports an ordinary conflict. | ||
| # features.jsonl stays on union until it has a driver of its own: duplicate | ||
| # feature ids after a union need renumbering by hand. | ||
| .docket/*.jsonl merge=union | ||
| .docket/ledger.jsonl merge=docket |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| """A git merge driver for the ledger. | ||
|
|
||
| Git hands a merge driver three temp files and keeps whatever the second one | ||
| holds. On a non-zero exit it marks the path unmerged but still takes that | ||
| file as the worktree version, so a failure must leave conflict markers in it: | ||
| an untouched OURS would look like a clean ledger, and staging it would drop | ||
| every incoming record. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import subprocess | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| from docket import ledger, rebase | ||
|
|
||
|
|
||
| def _conflict(base: Path, ours: Path, theirs: Path) -> None: | ||
| try: | ||
| original = ours.read_bytes() | ||
| incoming = theirs.read_bytes() | ||
| except OSError: | ||
| return | ||
| status = None | ||
| try: | ||
| status = subprocess.run( | ||
| [ | ||
| "git", | ||
| "merge-file", | ||
| "-L", | ||
| "ours", | ||
| "-L", | ||
| "base", | ||
| "-L", | ||
| "theirs", | ||
| str(ours), | ||
| str(base), | ||
| str(theirs), | ||
| ], | ||
| capture_output=True, | ||
| timeout=30, | ||
| ).returncode | ||
| except (OSError, subprocess.SubprocessError): | ||
| print("docket: git merge-file could not run; wrote whole-file markers", file=sys.stderr) | ||
| # merge-file exits with the conflict count (1..127); 0 means it merged the | ||
| # text cleanly, which the driver's own refusal overrides, and anything else | ||
| # is a failure that may have left OURS untouched. | ||
| if status is not None and 0 < status < 128: | ||
| return | ||
| block = b"<<<<<<< ours\n" + _terminated(original) + b"=======\n" | ||
| block += _terminated(incoming) + b">>>>>>> theirs\n" | ||
| try: | ||
| ours.write_bytes(block) | ||
| except OSError as exc: | ||
| print(f"docket: cannot write conflict markers: {exc}", file=sys.stderr) | ||
|
|
||
|
|
||
| def _terminated(data: bytes) -> bytes: | ||
| return data if not data or data.endswith(b"\n") else data + b"\n" | ||
|
|
||
|
|
||
| def run(base: Path, ours: Path, theirs: Path) -> int: | ||
| """Merge THEIRS into OURS in place. 0 when merged, 1 when left in conflict.""" | ||
|
|
||
| try: | ||
| # lock=False: the default lock creates <file>.lock next to git's temp | ||
| # files at the repository root, where nothing ignores it. | ||
| old, mine, incoming = (ledger.read(p, lock=False) for p in (base, ours, theirs)) | ||
| tail, moved = rebase.merge(old, mine, incoming) | ||
| ledger.validate_entries(mine + tail) | ||
| except (ledger.LedgerError, rebase.RebaseError, OSError) as exc: | ||
| print(f"docket: cannot merge the ledger: {exc}", file=sys.stderr) | ||
| _conflict(base, ours, theirs) | ||
| return 1 | ||
| if tail: | ||
| lines = "".join( | ||
| json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n" for r in tail | ||
| ) | ||
| with ours.open("rb") as handle: | ||
| handle.seek(0, 2) | ||
| needs_newline = False | ||
| if handle.tell(): | ||
| handle.seek(-1, 2) | ||
| needs_newline = handle.read(1) != b"\n" | ||
| with ours.open("a", encoding="utf-8", newline="") as handle: | ||
| handle.write(("\n" if needs_newline else "") + lines) | ||
| for old_id, new_id in moved.items(): | ||
| if old_id != new_id: | ||
| print(f"docket: {old_id} -> {new_id}", file=sys.stderr) | ||
| return 0 | ||
|
|
||
|
|
||
| __all__ = ["run"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Wire the ledger merge driver into a clone. | ||
|
|
||
| The attribute line is committed, but git reads a driver's command only from | ||
| git config, never from the repository, so every clone needs `docket init`. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import shlex | ||
| import shutil | ||
| import subprocess | ||
| from pathlib import Path | ||
|
|
||
| ATTRIBUTE = ".docket/ledger.jsonl merge=docket" | ||
| # docket on PATH, never an absolute path: the plugin cache path changes with | ||
| # every release, and a config naming a deleted version fails every merge. | ||
| DRIVER = "docket merge-driver %O %A %B" | ||
|
|
||
|
|
||
| def _git(root: Path, *args: str) -> subprocess.CompletedProcess[str] | None: | ||
| try: | ||
| return subprocess.run( | ||
| ["git", "-C", str(root), *args], capture_output=True, text=True, timeout=5 | ||
| ) | ||
| except (OSError, subprocess.SubprocessError): | ||
| return None | ||
|
|
||
|
|
||
| def _in_repository(root: Path) -> bool: | ||
| result = _git(root, "rev-parse", "--git-dir") | ||
| return result is not None and result.returncode == 0 | ||
|
|
||
|
|
||
| def _has_attribute(root: Path) -> bool: | ||
| path = root / ".gitattributes" | ||
| if not path.is_file(): | ||
| return False | ||
| return ATTRIBUTE in (line.strip() for line in path.read_text(encoding="utf-8").splitlines()) | ||
|
|
||
|
|
||
| def setup(root: Path) -> list[str]: | ||
| """Add the attribute line and register the driver; return what to tell the user.""" | ||
|
|
||
| if not _in_repository(root): | ||
| return [] | ||
| messages: list[str] = [] | ||
| path = root / ".gitattributes" | ||
| try: | ||
| if not _has_attribute(root): | ||
| text = path.read_text(encoding="utf-8") if path.is_file() else "" | ||
| if text and not text.endswith("\n"): | ||
| text += "\n" | ||
| # Appended, not substituted: a later matching line overrides an earlier | ||
| # one, so a .docket/*.jsonl union line keeps covering features.jsonl. | ||
| path.write_text(text + ATTRIBUTE + "\n", encoding="utf-8") | ||
| messages.append(f"docket: added the ledger merge driver to {path}; commit it") | ||
| except (UnicodeError, OSError) as exc: | ||
| messages.append(f"docket: could not update {path}: {exc}") | ||
| if shutil.which("docket") is None: | ||
| messages.append( | ||
| "docket: merge driver not registered: docket is not on PATH, so git could not run it. " | ||
| "Put docket on PATH and run docket init again." | ||
| ) | ||
| return messages | ||
| # Only the driver key: git aborts every merge ("lacks command line") when | ||
| # merge.docket.name exists without merge.docket.driver, and needs no name. | ||
| result = _git(root, "config", "--local", "merge.docket.driver", DRIVER) | ||
| if result is not None and result.returncode == 0: | ||
| messages.append("docket: registered the ledger merge driver in this clone's git config") | ||
| else: | ||
| reason = result.stderr.strip() if result is not None else "git could not run" | ||
| messages.append( | ||
| f"docket: merge driver not registered: git config failed ({reason}); nothing was changed" | ||
| ) | ||
| return messages | ||
|
|
||
|
|
||
| def notice(root: Path) -> str | None: | ||
| """One briefing line when the repository asks for the driver and this clone lacks it.""" | ||
|
|
||
| try: | ||
| if not _has_attribute(root) or not _in_repository(root): | ||
| return None | ||
| result = _git(root, "config", "--get", "merge.docket.driver") | ||
| command = result.stdout.strip() if result is not None and result.returncode == 0 else "" | ||
| words = shlex.split(command) if command else [] | ||
| if words and shutil.which(words[0]): | ||
| return None | ||
| except (OSError, ValueError): | ||
| return None | ||
| return "# merge driver not set up in this clone; run docket init" | ||
|
|
||
|
|
||
| __all__ = ["ATTRIBUTE", "DRIVER", "notice", "setup"] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: NovusEdge/docket
Length of output: 10878
🏁 Script executed:
Repository: NovusEdge/docket
Length of output: 42070
🏁 Script executed:
Repository: NovusEdge/docket
Length of output: 43467
🏁 Script executed:
Repository: NovusEdge/docket
Length of output: 19642
Keep merge-and-write failures inside the conflict fallback.
The validators convert malformed records to
LedgerError, and the allocator paths do not establish the claimed rawValueError,KeyError, orTypeErrorcases. However, a schema-valid record can contain an escaped lone surrogate.json.dumps(..., ensure_ascii=False)preserves it, and the UTF-8 append can raiseUnicodeEncodeError. The append is outside thetry, so_conflictdoes not run. Git retains OURS, and staging it can drop incoming records.Move the append block inside the
tryand catchExceptionfor the complete merge-and-write operation.🛡️ Suggested fix
try: # lock=False: the default lock creates <file>.lock next to git's temp # files at the repository root, where nothing ignores it. old, mine, incoming = (ledger.read(p, lock=False) for p in (base, ours, theirs)) tail, moved = rebase.merge(old, mine, incoming) ledger.validate_entries(mine + tail) - except (ledger.LedgerError, rebase.RebaseError, OSError) as exc: + if tail: + lines = "".join( + json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n" for r in tail + ) + with ours.open("rb") as handle: + handle.seek(0, 2) + needs_newline = False + if handle.tell(): + handle.seek(-1, 2) + needs_newline = handle.read(1) != b"\n" + with ours.open("a", encoding="utf-8", newline="") as handle: + handle.write(("\n" if needs_newline else "") + lines) + except Exception as exc: print(f"docket: cannot merge the ledger: {exc}", file=sys.stderr) _conflict(base, ours, theirs) return 1 - if tail: - lines = "".join( - json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n" for r in tail - ) - with ours.open("rb") as handle: - handle.seek(0, 2) - needs_newline = False - if handle.tell(): - handle.seek(-1, 2) - needs_newline = handle.read(1) != b"\n" - with ours.open("a", encoding="utf-8", newline="") as handle: - handle.write(("\n" if needs_newline else "") + lines)🧰 Tools
🪛 ast-grep (0.45.3)
[info] 78-78: use jsonify instead of json.dumps for JSON output
Context: json.dumps(r, ensure_ascii=False, separators=(",", ":"))
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
🤖 Prompt for AI Agents