git-dirty-triage 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.
- git_dirty_triage/__init__.py +47 -0
- git_dirty_triage/__main__.py +3 -0
- git_dirty_triage/classify.py +167 -0
- git_dirty_triage/cli.py +109 -0
- git_dirty_triage/commit.py +75 -0
- git_dirty_triage/gitio.py +218 -0
- git_dirty_triage/report.py +130 -0
- git_dirty_triage-0.1.0.dist-info/METADATA +249 -0
- git_dirty_triage-0.1.0.dist-info/RECORD +13 -0
- git_dirty_triage-0.1.0.dist-info/WHEEL +5 -0
- git_dirty_triage-0.1.0.dist-info/entry_points.txt +2 -0
- git_dirty_triage-0.1.0.dist-info/licenses/LICENSE +21 -0
- git_dirty_triage-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""In a lagging shared checkout, tell which modified files are really unpublished.
|
|
2
|
+
|
|
3
|
+
from git_dirty_triage import classify, summarize
|
|
4
|
+
|
|
5
|
+
top, rows = classify("/path/to/checkout", "origin/main")
|
|
6
|
+
print(summarize(rows))
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .classify import (
|
|
10
|
+
DECISION_CLASSES,
|
|
11
|
+
PUBLISHED_CLASSES,
|
|
12
|
+
UNPUBLISHED_CLASSES,
|
|
13
|
+
classify,
|
|
14
|
+
classify_ahead,
|
|
15
|
+
counts_by_bucket,
|
|
16
|
+
summarize,
|
|
17
|
+
)
|
|
18
|
+
from .commit import build_commit, commit_unpublished, unpublished_rows
|
|
19
|
+
from .gitio import git, is_text, out, pathspecs_for, resolve_ref, short_path, toplevel, under
|
|
20
|
+
from .report import format_report, json_report, summary_line
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"__version__",
|
|
26
|
+
"PUBLISHED_CLASSES",
|
|
27
|
+
"UNPUBLISHED_CLASSES",
|
|
28
|
+
"DECISION_CLASSES",
|
|
29
|
+
"classify",
|
|
30
|
+
"classify_ahead",
|
|
31
|
+
"summarize",
|
|
32
|
+
"counts_by_bucket",
|
|
33
|
+
"unpublished_rows",
|
|
34
|
+
"build_commit",
|
|
35
|
+
"commit_unpublished",
|
|
36
|
+
"format_report",
|
|
37
|
+
"json_report",
|
|
38
|
+
"summary_line",
|
|
39
|
+
"git",
|
|
40
|
+
"out",
|
|
41
|
+
"toplevel",
|
|
42
|
+
"is_text",
|
|
43
|
+
"resolve_ref",
|
|
44
|
+
"pathspecs_for",
|
|
45
|
+
"short_path",
|
|
46
|
+
"under",
|
|
47
|
+
]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Classify each modified path against the remote tip.
|
|
2
|
+
|
|
3
|
+
Classes, checked in this order:
|
|
4
|
+
|
|
5
|
+
identical working bytes equal the remote file: already published
|
|
6
|
+
stale working bytes equal an earlier published version of the path: already published
|
|
7
|
+
contained every non-blank working line already exists in the remote file: nothing unique
|
|
8
|
+
new not on the remote at all: unpublished
|
|
9
|
+
differs_clean has unique lines and a three-way merge (base = local HEAD) is clean: unpublished
|
|
10
|
+
differs_conflict has unique lines and the merge conflicts: needs a decision, never committed
|
|
11
|
+
differs_binary binary file that differs: unpublished whole only if the remote file is unchanged since HEAD
|
|
12
|
+
deleted removed in the working tree: reported only
|
|
13
|
+
untracked_dir untracked directory with --untracked normal: one row, never expanded or committed
|
|
14
|
+
skipped not a plain file (symlink, path with a newline): reported only
|
|
15
|
+
|
|
16
|
+
A clean merge that equals the remote bytes is `contained`: the path only lags.
|
|
17
|
+
|
|
18
|
+
Files are hashed in one batch and compared with one ls-tree per side; only a path that really
|
|
19
|
+
differs spawns more git calls (`log` + `cat-file --batch-check` for earlier versions, then
|
|
20
|
+
`cat-file blob` and `merge-file`).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import time
|
|
27
|
+
|
|
28
|
+
from .gitio import (
|
|
29
|
+
count_files,
|
|
30
|
+
dirty_paths,
|
|
31
|
+
hash_files,
|
|
32
|
+
is_text,
|
|
33
|
+
merge_base,
|
|
34
|
+
out,
|
|
35
|
+
published_versions,
|
|
36
|
+
show_blob,
|
|
37
|
+
three_way,
|
|
38
|
+
tree_map,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
PUBLISHED_CLASSES = ("identical", "stale", "contained")
|
|
42
|
+
UNPUBLISHED_CLASSES = ("new", "differs_clean", "differs_binary")
|
|
43
|
+
DECISION_CLASSES = ("differs_conflict",)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def judge(top, ref, row, wblob, oblob, base_blob):
|
|
47
|
+
"""Set row["class"] (and merged/reason) for one file that exists in the working tree."""
|
|
48
|
+
full = os.path.join(os.fsencode(top), row["path"])
|
|
49
|
+
if oblob and wblob == oblob:
|
|
50
|
+
row["class"] = "identical"
|
|
51
|
+
elif oblob is None:
|
|
52
|
+
row["class"] = "new" # bytes are read when a commit is built
|
|
53
|
+
elif wblob in published_versions(top, ref, row["path"]):
|
|
54
|
+
row["class"] = "stale"
|
|
55
|
+
else:
|
|
56
|
+
working, theirs = open(full, "rb").read(), show_blob(top, oblob)
|
|
57
|
+
if not (is_text(working) and is_text(theirs)):
|
|
58
|
+
if base_blob == oblob:
|
|
59
|
+
row["class"] = "differs_binary"
|
|
60
|
+
row["merged"] = working
|
|
61
|
+
else:
|
|
62
|
+
row["class"] = "differs_conflict"
|
|
63
|
+
row["reason"] = "binary changed on both sides"
|
|
64
|
+
return
|
|
65
|
+
theirs_lines = set(theirs.decode("utf-8").splitlines())
|
|
66
|
+
unique = [ln for ln in working.decode("utf-8").splitlines() if ln.strip() and ln not in theirs_lines]
|
|
67
|
+
if not unique:
|
|
68
|
+
row["class"] = "contained"
|
|
69
|
+
return
|
|
70
|
+
merged, clean = three_way(show_blob(top, base_blob) if base_blob else b"", working, theirs)
|
|
71
|
+
if clean and merged == theirs:
|
|
72
|
+
row["class"] = "contained"
|
|
73
|
+
row["reason"] = "merge equals the remote"
|
|
74
|
+
else:
|
|
75
|
+
row["class"] = "differs_clean" if clean else "differs_conflict"
|
|
76
|
+
row["merged"] = merged if clean else None
|
|
77
|
+
row["reason"] = f"{len(unique)} unique line(s)"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def working_rows(top, found):
|
|
81
|
+
"""Row per (state, path); also returns the rows that are plain files and still need judging."""
|
|
82
|
+
rows, todo = [], []
|
|
83
|
+
for state, path in found:
|
|
84
|
+
full = os.path.join(os.fsencode(top), path)
|
|
85
|
+
row = {"path": path, "state": state, "age_min": None, "class": None, "merged": None,
|
|
86
|
+
"reason": "", "untracked": state[:1] == "?", "files": None}
|
|
87
|
+
rows.append(row)
|
|
88
|
+
if state.strip() == "D" or state[1:] == "D" or not os.path.lexists(full):
|
|
89
|
+
row["class"] = "deleted"
|
|
90
|
+
elif row["untracked"] and path.endswith(b"/") and os.path.isdir(full):
|
|
91
|
+
# git status -unormal: one row for the whole untracked directory, never hashed
|
|
92
|
+
row["class"] = "untracked_dir"
|
|
93
|
+
row["files"] = count_files(full)
|
|
94
|
+
row["reason"] = f"{row['files']} file(s)"
|
|
95
|
+
elif not os.path.isfile(full) or os.path.islink(full) or b"\n" in path:
|
|
96
|
+
row["class"] = "skipped"
|
|
97
|
+
row["reason"] = "not a regular file"
|
|
98
|
+
else:
|
|
99
|
+
row["age_min"] = int((time.time() - os.stat(full).st_mtime) / 60)
|
|
100
|
+
todo.append(row)
|
|
101
|
+
return rows, todo
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def classify(repo, ref, pathspecs=(), untracked="normal"):
|
|
105
|
+
"""(checkout root, rows) for the dirty paths, optionally limited by pathspecs.
|
|
106
|
+
|
|
107
|
+
`untracked` is passed to git status: "normal" (one row per untracked directory), "all"
|
|
108
|
+
(every file) or "no" (none).
|
|
109
|
+
"""
|
|
110
|
+
top = out(repo, "rev-parse", "--show-toplevel").decode().strip()
|
|
111
|
+
rows, todo = working_rows(top, dirty_paths(top, pathspecs, untracked))
|
|
112
|
+
wblobs = hash_files(top, [r["path"] for r in todo])
|
|
113
|
+
remote, head = tree_map(top, ref, pathspecs), tree_map(top, "HEAD", pathspecs)
|
|
114
|
+
for row, wblob in zip(todo, wblobs):
|
|
115
|
+
judge(top, ref, row, wblob, remote.get(row["path"]), head.get(row["path"]))
|
|
116
|
+
return top, rows
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def classify_ahead(repo, ref, pathspecs=()):
|
|
120
|
+
"""Rows for the files that local-only commits touched, judged by the current bytes against ref.
|
|
121
|
+
|
|
122
|
+
A dirty-path scan cannot see a committed file whose working copy is clean. The base of the
|
|
123
|
+
three-way merge is the merge-base blob, a path the remote deleted is never brought back, and
|
|
124
|
+
a version the remote once held counts as `stale`.
|
|
125
|
+
"""
|
|
126
|
+
top = out(repo, "rev-parse", "--show-toplevel").decode().strip()
|
|
127
|
+
base_rev = merge_base(top, "HEAD", ref)
|
|
128
|
+
paths = set()
|
|
129
|
+
for line in out(top, "cherry", ref, "HEAD").decode().splitlines():
|
|
130
|
+
if line.startswith("+"):
|
|
131
|
+
raw = out(top, "diff-tree", "-r", "--no-commit-id", "--name-only", "-z", "--no-renames", line.split()[1])
|
|
132
|
+
paths.update(p for p in raw.split(b"\0") if p)
|
|
133
|
+
if pathspecs:
|
|
134
|
+
roots = [s.encode("utf-8", "surrogateescape").rstrip(b"/") for s in pathspecs]
|
|
135
|
+
paths = {p for p in paths if any(p == r or p.startswith(r + b"/") for r in roots)}
|
|
136
|
+
rows, todo = working_rows(top, [("A", p) for p in sorted(paths)])
|
|
137
|
+
wblobs = hash_files(top, [r["path"] for r in todo])
|
|
138
|
+
remote, base = tree_map(top, ref, pathspecs), tree_map(top, base_rev, pathspecs)
|
|
139
|
+
for row, wblob in zip(todo, wblobs):
|
|
140
|
+
path, oblob, bblob = row["path"], remote.get(row["path"]), base.get(row["path"])
|
|
141
|
+
if oblob is None and bblob is not None:
|
|
142
|
+
# the remote deleted it: never bring it back; an edit made here needs a decision
|
|
143
|
+
row["class"] = "skipped" if wblob == bblob else "differs_conflict"
|
|
144
|
+
row["reason"] = "deleted on the remote" if wblob == bblob else "edited here, deleted on the remote"
|
|
145
|
+
elif oblob is None and wblob in published_versions(top, ref, path):
|
|
146
|
+
row["class"] = "stale" # published once, deleted since
|
|
147
|
+
else:
|
|
148
|
+
judge(top, ref, row, wblob, oblob, bblob)
|
|
149
|
+
return top, rows
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def summarize(rows):
|
|
153
|
+
"""{class: count}."""
|
|
154
|
+
counts = {}
|
|
155
|
+
for r in rows:
|
|
156
|
+
counts[r["class"]] = counts.get(r["class"], 0) + 1
|
|
157
|
+
return counts
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def counts_by_bucket(rows):
|
|
161
|
+
"""(published, unpublished, needs a decision) counts over a row list."""
|
|
162
|
+
counts = summarize(rows)
|
|
163
|
+
return (
|
|
164
|
+
sum(counts.get(c, 0) for c in PUBLISHED_CLASSES),
|
|
165
|
+
sum(counts.get(c, 0) for c in UNPUBLISHED_CLASSES),
|
|
166
|
+
sum(counts.get(c, 0) for c in DECISION_CLASSES),
|
|
167
|
+
)
|
git_dirty_triage/cli.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Command line: git-dirty-triage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .classify import UNPUBLISHED_CLASSES, classify, classify_ahead
|
|
13
|
+
from .commit import commit_unpublished
|
|
14
|
+
from .gitio import git, out, pathspecs_for, resolve_ref, toplevel, under
|
|
15
|
+
from .report import format_report, json_report
|
|
16
|
+
|
|
17
|
+
DESCRIPTION = (
|
|
18
|
+
"In a checkout that lags behind its remote, show which modified files are already published "
|
|
19
|
+
"and which carry something new."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_parser():
|
|
24
|
+
p = argparse.ArgumentParser(prog="git-dirty-triage", description=DESCRIPTION)
|
|
25
|
+
p.add_argument("--repo", default=".", help="checkout to inspect (default: the current directory)")
|
|
26
|
+
p.add_argument("--remote", default="origin", help="remote to compare with (default: origin)")
|
|
27
|
+
p.add_argument("--branch", default=None,
|
|
28
|
+
help="remote branch (default: the remote's default branch, then main, then master)")
|
|
29
|
+
p.add_argument("--prefix", action="append", default=[], metavar="PATH",
|
|
30
|
+
help="limit the listing and the report to this repo-relative path (repeatable)")
|
|
31
|
+
p.add_argument("--ahead", action="store_true",
|
|
32
|
+
help="judge the files that local-only commits touched instead of the dirty paths")
|
|
33
|
+
p.add_argument("-u", "--untracked", choices=("no", "normal", "all"), default="normal",
|
|
34
|
+
help="untracked paths: 'normal' lists an untracked directory as one row (default), "
|
|
35
|
+
"'all' lists every untracked file, 'no' skips them")
|
|
36
|
+
mode = p.add_mutually_exclusive_group()
|
|
37
|
+
mode.add_argument("--print-unpublished", action="store_true",
|
|
38
|
+
help="print only the unpublished paths, one per line, for piping to git add")
|
|
39
|
+
mode.add_argument("--commit-unpublished", action="store_true",
|
|
40
|
+
help="commit the unpublished clean paths on top of the remote tip; nothing is pushed")
|
|
41
|
+
p.add_argument("-m", "--message", help="commit message for --commit-unpublished")
|
|
42
|
+
p.add_argument("--no-fetch", action="store_true", help="compare with the last fetched remote ref")
|
|
43
|
+
p.add_argument("--json", action="store_true", help="print one JSON object")
|
|
44
|
+
p.add_argument("--version", action="version", version=f"git-dirty-triage {__version__}")
|
|
45
|
+
return p
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def main(argv=None):
|
|
49
|
+
parser = build_parser()
|
|
50
|
+
a = parser.parse_args(argv)
|
|
51
|
+
if a.commit_unpublished and not a.message:
|
|
52
|
+
parser.error("--commit-unpublished needs -m/--message")
|
|
53
|
+
for prefix in a.prefix:
|
|
54
|
+
if os.path.isabs(prefix) or ".." in prefix.split("/"):
|
|
55
|
+
parser.error(f"--prefix must be a repo-relative path: {prefix}")
|
|
56
|
+
try:
|
|
57
|
+
top = toplevel(a.repo)
|
|
58
|
+
ref = resolve_ref(top, a.remote, a.branch)
|
|
59
|
+
branch = ref.split("/", 1)[1]
|
|
60
|
+
fetched = None if a.no_fetch else git(top, "fetch", a.remote, branch)
|
|
61
|
+
if git(top, "rev-parse", "--verify", "--quiet", ref + "^{commit}").returncode:
|
|
62
|
+
detail = fetched.stderr.decode("utf-8", "replace").strip()[:200] if fetched is not None else ""
|
|
63
|
+
raise RuntimeError(f"{ref} does not exist; pass --branch or fetch {a.remote} first"
|
|
64
|
+
+ (f" ({detail})" if detail else ""))
|
|
65
|
+
if fetched is not None and fetched.returncode:
|
|
66
|
+
print(f"warning: git fetch {a.remote} {branch} failed; comparing with the last fetched {ref}",
|
|
67
|
+
file=sys.stderr)
|
|
68
|
+
prefixes = [os.fsencode(x) for x in a.prefix]
|
|
69
|
+
specs = pathspecs_for(top, prefixes)
|
|
70
|
+
rows = (classify_ahead(top, ref, specs) if a.ahead else classify(top, ref, specs, a.untracked))[1]
|
|
71
|
+
if prefixes:
|
|
72
|
+
rows = [r for r in rows if any(under(r["path"], x) for x in prefixes)]
|
|
73
|
+
behind = int(out(top, "rev-list", "--count", f"HEAD..{ref}").decode().strip())
|
|
74
|
+
except (RuntimeError, subprocess.SubprocessError) as error:
|
|
75
|
+
print(f"error: {error}", file=sys.stderr)
|
|
76
|
+
return 2
|
|
77
|
+
|
|
78
|
+
if a.print_unpublished:
|
|
79
|
+
for path in sorted(r["path"] for r in rows if r["class"] in UNPUBLISHED_CLASSES):
|
|
80
|
+
print(path.decode("utf-8", "surrogateescape"))
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
if a.commit_unpublished:
|
|
84
|
+
try:
|
|
85
|
+
receipt = commit_unpublished(top, ref, rows, a.message, prefixes, a.remote)
|
|
86
|
+
except (RuntimeError, OSError, subprocess.SubprocessError) as error:
|
|
87
|
+
print(f"error: {error}", file=sys.stderr)
|
|
88
|
+
return 2
|
|
89
|
+
if a.json:
|
|
90
|
+
print(json.dumps(receipt, ensure_ascii=False))
|
|
91
|
+
return 0
|
|
92
|
+
if receipt["status"] == "nothing_to_commit":
|
|
93
|
+
print("nothing to commit: no unpublished path needs a commit")
|
|
94
|
+
else:
|
|
95
|
+
print(f"committed {receipt['files']} path(s) as {receipt['commit']} on top of {ref}")
|
|
96
|
+
print(f" ref: {receipt['ref']}")
|
|
97
|
+
print(" push: not pushed")
|
|
98
|
+
print(f" next: {receipt['push']}")
|
|
99
|
+
return 0
|
|
100
|
+
|
|
101
|
+
if a.json:
|
|
102
|
+
print(json.dumps(json_report(rows, behind, ref, a.ahead, top), ensure_ascii=False))
|
|
103
|
+
else:
|
|
104
|
+
print(format_report(rows, behind, ref, a.ahead))
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
sys.exit(main())
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Build one commit from the unpublished paths on top of the remote tip.
|
|
2
|
+
|
|
3
|
+
The commit is created on a temporary index (GIT_INDEX_FILE) from the remote tip's tree, so the
|
|
4
|
+
checkout's index, HEAD and working tree are not touched. Nothing is pushed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import tempfile
|
|
11
|
+
|
|
12
|
+
from .classify import UNPUBLISHED_CLASSES
|
|
13
|
+
from .gitio import git, out, under
|
|
14
|
+
|
|
15
|
+
LOCAL_REF_PREFIX = "refs/git-dirty-triage/"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def unpublished_rows(rows, prefixes=()):
|
|
19
|
+
"""Rows a commit should carry: new, cleanly merged edits and whole-file binary replacements."""
|
|
20
|
+
picked = [r for r in rows if r["class"] in UNPUBLISHED_CLASSES]
|
|
21
|
+
if prefixes:
|
|
22
|
+
picked = [r for r in picked if any(under(r["path"], p) for p in prefixes)]
|
|
23
|
+
return sorted(picked, key=lambda r: r["path"])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_commit(top, parent, rows, message):
|
|
27
|
+
"""(commit, tree, files) for `rows` on top of `parent`; each row carries merged bytes or None."""
|
|
28
|
+
parent = out(top, "rev-parse", "--verify", parent + "^{commit}").decode().strip()
|
|
29
|
+
with tempfile.TemporaryDirectory(prefix="git-dirty-triage-") as d:
|
|
30
|
+
env = {"GIT_INDEX_FILE": os.path.join(d, "index")}
|
|
31
|
+
out(top, "read-tree", parent, env=env)
|
|
32
|
+
entries = bytearray()
|
|
33
|
+
for r in rows:
|
|
34
|
+
full = os.path.join(os.fsencode(top), r["path"])
|
|
35
|
+
data = r["merged"]
|
|
36
|
+
if data is None: # a new file: read the working bytes for this commit only
|
|
37
|
+
with open(full, "rb") as fh:
|
|
38
|
+
data = fh.read()
|
|
39
|
+
blob = out(top, "hash-object", "-w", "--stdin", inp=data).decode().strip()
|
|
40
|
+
mode = b"100755" if os.access(full, os.X_OK) else b"100644"
|
|
41
|
+
entries += mode + b" " + blob.encode() + b"\t" + r["path"] + b"\0"
|
|
42
|
+
out(top, "update-index", "-z", "--add", "--index-info", inp=bytes(entries), env=env)
|
|
43
|
+
tree = out(top, "write-tree", env=env).decode().strip()
|
|
44
|
+
r = git(top, "commit-tree", tree, "-p", parent, "-m", message)
|
|
45
|
+
if r.returncode:
|
|
46
|
+
raise RuntimeError(
|
|
47
|
+
"git commit-tree failed: " + r.stderr.decode("utf-8", "replace").strip()[:300]
|
|
48
|
+
+ " (set user.name and user.email in this repository)"
|
|
49
|
+
)
|
|
50
|
+
return r.stdout.decode().strip(), tree, len(rows)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def commit_unpublished(top, ref, rows, message, prefixes=(), remote="origin"):
|
|
54
|
+
"""Commit the unpublished clean paths on top of `ref` and point a private ref at the commit.
|
|
55
|
+
|
|
56
|
+
Returns a JSON-ready receipt. The commit is not pushed and no branch is moved.
|
|
57
|
+
"""
|
|
58
|
+
picked = unpublished_rows(rows, prefixes)
|
|
59
|
+
branch = ref.split("/", 1)[1]
|
|
60
|
+
if not picked:
|
|
61
|
+
return {"status": "nothing_to_commit", "ref": ref, "files": 0}
|
|
62
|
+
commit, tree, files = build_commit(top, ref, picked, message)
|
|
63
|
+
local_ref = LOCAL_REF_PREFIX + branch
|
|
64
|
+
out(top, "update-ref", local_ref, commit)
|
|
65
|
+
return {
|
|
66
|
+
"status": "committed",
|
|
67
|
+
"commit": commit,
|
|
68
|
+
"tree": tree,
|
|
69
|
+
"parent": out(top, "rev-parse", ref + "^{commit}").decode().strip(),
|
|
70
|
+
"ref": local_ref,
|
|
71
|
+
"files": files,
|
|
72
|
+
"paths": [r["path"].decode("utf-8", "surrogateescape") for r in picked],
|
|
73
|
+
"pushed": False,
|
|
74
|
+
"push": f"git push {remote} {commit}:refs/heads/{branch}",
|
|
75
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Thin wrappers over the git plumbing this tool needs.
|
|
2
|
+
|
|
3
|
+
Every call here is read-only. The committer builds its objects with the same wrappers, on a
|
|
4
|
+
temporary index, so the checkout's own index and HEAD are never touched.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def git(repo, *args, inp=None, env=None, check=False):
|
|
15
|
+
"""Run git inside `repo` with literal pathspecs; return the CompletedProcess."""
|
|
16
|
+
e = dict(os.environ)
|
|
17
|
+
if env:
|
|
18
|
+
e.update(env)
|
|
19
|
+
r = subprocess.run(
|
|
20
|
+
["git", "-C", repo, "--literal-pathspecs", *args],
|
|
21
|
+
capture_output=True,
|
|
22
|
+
input=inp,
|
|
23
|
+
env=e,
|
|
24
|
+
)
|
|
25
|
+
if check and r.returncode:
|
|
26
|
+
raise RuntimeError(f"git {' '.join(args[:3])} failed: {r.stderr.decode('utf-8', 'replace')[:300]}")
|
|
27
|
+
return r
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def out(repo, *args, inp=None, env=None):
|
|
31
|
+
return git(repo, *args, inp=inp, env=env, check=True).stdout
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def toplevel(repo):
|
|
35
|
+
"""Absolute path of the working-tree root; raises with a readable message outside a checkout."""
|
|
36
|
+
r = git(repo, "rev-parse", "--show-toplevel")
|
|
37
|
+
if r.returncode:
|
|
38
|
+
raise RuntimeError(f"{repo} is not a git checkout: {r.stderr.decode('utf-8', 'replace').strip()[:200]}")
|
|
39
|
+
return r.stdout.decode().strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def dirty_paths(repo, pathspecs=(), untracked="normal"):
|
|
43
|
+
"""[(two-letter status, path bytes)] under `pathspecs`.
|
|
44
|
+
|
|
45
|
+
`untracked` follows git status: "normal" lists an untracked directory as one trailing-slash
|
|
46
|
+
entry, "all" lists every file inside it, "no" skips untracked paths.
|
|
47
|
+
"""
|
|
48
|
+
cmd = ["status", "--porcelain=v1", "-z", f"--untracked-files={untracked}"]
|
|
49
|
+
if pathspecs:
|
|
50
|
+
cmd += ["--", *pathspecs]
|
|
51
|
+
records = out(repo, *cmd).split(b"\0")
|
|
52
|
+
found, i = [], 0
|
|
53
|
+
while i < len(records):
|
|
54
|
+
rec = records[i]
|
|
55
|
+
if rec:
|
|
56
|
+
state, path = rec[:2].decode(), rec[3:]
|
|
57
|
+
found.append((state, path))
|
|
58
|
+
if state[:1] in "RC":
|
|
59
|
+
i += 1 # a rename or copy record carries the source path in the next field
|
|
60
|
+
i += 1
|
|
61
|
+
return found
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def tree_map(repo, rev, pathspecs=()):
|
|
65
|
+
"""{path bytes: blob id} for every file at `rev`, optionally under `pathspecs`."""
|
|
66
|
+
cmd = ["ls-tree", "-r", "-z", rev]
|
|
67
|
+
if pathspecs:
|
|
68
|
+
cmd += ["--", *pathspecs]
|
|
69
|
+
blobs = {}
|
|
70
|
+
for rec in out(repo, *cmd).split(b"\0"):
|
|
71
|
+
if rec:
|
|
72
|
+
meta, path = rec.split(b"\t", 1)
|
|
73
|
+
blobs[path] = meta.split()[2].decode()
|
|
74
|
+
return blobs
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def hash_files(repo, paths):
|
|
78
|
+
"""Blob id of each working file, in order: one hash-object call per 5,000 paths."""
|
|
79
|
+
if not paths:
|
|
80
|
+
return []
|
|
81
|
+
ids = []
|
|
82
|
+
for i in range(0, len(paths), 5000):
|
|
83
|
+
chunk = paths[i:i + 5000]
|
|
84
|
+
ids += out(repo, "hash-object", "--stdin-paths", inp=b"\n".join(chunk) + b"\n").decode().split()
|
|
85
|
+
return ids
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def show_blob(repo, blob):
|
|
89
|
+
return out(repo, "cat-file", "blob", blob)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def published_versions(repo, ref, path, limit=300):
|
|
93
|
+
"""Blob ids this path has had on `ref` (most recent `limit` commits that touched it)."""
|
|
94
|
+
p = path.decode("utf-8", "surrogateescape")
|
|
95
|
+
commits = out(repo, "log", f"-n{limit}", "--format=%H", ref, "--", p).decode().split()
|
|
96
|
+
if not commits:
|
|
97
|
+
return set()
|
|
98
|
+
query = "".join(f"{c}:{p}\n" for c in commits).encode("utf-8", "surrogateescape")
|
|
99
|
+
res = out(repo, "cat-file", "--batch-check", inp=query).decode("utf-8", "replace").splitlines()
|
|
100
|
+
return {line.split()[0] for line in res if len(line.split()) >= 3 and line.split()[1] == "blob"}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def merge_base(repo, a, b):
|
|
104
|
+
return out(repo, "merge-base", a, b).decode().strip()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def is_text(data):
|
|
108
|
+
if b"\0" in data:
|
|
109
|
+
return False
|
|
110
|
+
try:
|
|
111
|
+
data.decode("utf-8")
|
|
112
|
+
return True
|
|
113
|
+
except UnicodeDecodeError:
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def three_way(base, ours, theirs):
|
|
118
|
+
"""(merged bytes, clean?) through git merge-file with a temporary directory."""
|
|
119
|
+
with tempfile.TemporaryDirectory(prefix="git-dirty-triage-") as d:
|
|
120
|
+
paths = []
|
|
121
|
+
for name, data in (("ours", ours), ("base", base), ("theirs", theirs)):
|
|
122
|
+
p = os.path.join(d, name)
|
|
123
|
+
with open(p, "wb") as fh:
|
|
124
|
+
fh.write(data)
|
|
125
|
+
paths.append(p)
|
|
126
|
+
r = subprocess.run(["git", "merge-file", "-p", *paths], capture_output=True)
|
|
127
|
+
return r.stdout, r.returncode == 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def under(path, prefix):
|
|
131
|
+
"""True when a repo-relative path is the prefix itself or sits below it."""
|
|
132
|
+
p = prefix.rstrip(b"/")
|
|
133
|
+
return path == p or path.startswith(p + b"/")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def pathspecs_for(top, prefixes):
|
|
137
|
+
"""Pathspecs that cannot leave out a path a prefix selects.
|
|
138
|
+
|
|
139
|
+
An existing path is used as it is; otherwise its parent directory; [] (the whole checkout)
|
|
140
|
+
when a prefix has no parent directory to start from.
|
|
141
|
+
"""
|
|
142
|
+
specs = []
|
|
143
|
+
for prefix in prefixes:
|
|
144
|
+
p = prefix.decode("utf-8", "surrogateescape")
|
|
145
|
+
if os.path.exists(os.path.join(top, p)):
|
|
146
|
+
specs.append(p.rstrip("/") or ".")
|
|
147
|
+
elif os.path.dirname(p):
|
|
148
|
+
specs.append(os.path.dirname(p))
|
|
149
|
+
else:
|
|
150
|
+
return []
|
|
151
|
+
return specs
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def count_files(root):
|
|
155
|
+
"""Number of non-directory entries under `root`; symlinks to directories are not followed."""
|
|
156
|
+
total = 0
|
|
157
|
+
for _dirpath, _dirnames, filenames in os.walk(root):
|
|
158
|
+
total += len(filenames)
|
|
159
|
+
return total
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def short_path(path, n=90):
|
|
163
|
+
"""Path for one terminal line, shortened from the left when long and with control characters escaped."""
|
|
164
|
+
s = path.decode("utf-8", "surrogateescape")
|
|
165
|
+
s = s.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
|
|
166
|
+
return s if len(s) <= n else "..." + s[-(n - 3):]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def remote_branches(top, remote):
|
|
170
|
+
prefix = f"refs/remotes/{remote}/"
|
|
171
|
+
listing = git(top, "for-each-ref", "--format=%(refname)", prefix)
|
|
172
|
+
return {
|
|
173
|
+
line[len(prefix):]
|
|
174
|
+
for line in listing.stdout.decode("utf-8", "replace").splitlines()
|
|
175
|
+
if line.startswith(prefix) and line != prefix + "HEAD"
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def remote_default_branch(top, remote):
|
|
180
|
+
"""The branch the remote's HEAD points at, read without fetching."""
|
|
181
|
+
r = git(top, "ls-remote", "--symref", remote, "HEAD")
|
|
182
|
+
if r.returncode:
|
|
183
|
+
return None
|
|
184
|
+
for line in r.stdout.decode("utf-8", "replace").splitlines():
|
|
185
|
+
if line.startswith("ref: ") and line.endswith("\tHEAD"):
|
|
186
|
+
target = line[5:].split("\t")[0].strip()
|
|
187
|
+
if target.startswith("refs/heads/"):
|
|
188
|
+
return target[len("refs/heads/"):]
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def resolve_ref(top, remote, branch):
|
|
193
|
+
"""remote/branch to compare with: the flag, the remote's default, main, master, or the current branch."""
|
|
194
|
+
if branch:
|
|
195
|
+
return f"{remote}/{branch}"
|
|
196
|
+
configured = out(top, "remote").decode().split()
|
|
197
|
+
if remote not in configured:
|
|
198
|
+
raise RuntimeError(
|
|
199
|
+
f"no remote named '{remote}' (configured: {', '.join(configured) or 'none'}); pass --remote"
|
|
200
|
+
)
|
|
201
|
+
names = remote_branches(top, remote)
|
|
202
|
+
head = git(top, "symbolic-ref", "--quiet", f"refs/remotes/{remote}/HEAD")
|
|
203
|
+
if head.returncode == 0:
|
|
204
|
+
target = head.stdout.decode().strip()
|
|
205
|
+
candidate = target[len(f"refs/remotes/{remote}/"):] if target.startswith(f"refs/remotes/{remote}/") else ""
|
|
206
|
+
if candidate in names:
|
|
207
|
+
return f"{remote}/{candidate}"
|
|
208
|
+
for name in ("main", "master"):
|
|
209
|
+
if name in names:
|
|
210
|
+
return f"{remote}/{name}"
|
|
211
|
+
current = git(top, "symbolic-ref", "--short", "--quiet", "HEAD")
|
|
212
|
+
if current.returncode == 0 and current.stdout.decode().strip() in names:
|
|
213
|
+
return f"{remote}/{current.stdout.decode().strip()}"
|
|
214
|
+
default = remote_default_branch(top, remote)
|
|
215
|
+
if default:
|
|
216
|
+
return f"{remote}/{default}"
|
|
217
|
+
known = ", ".join(sorted(names)) if names else "none fetched"
|
|
218
|
+
raise RuntimeError(f"no branch found on remote '{remote}' ({known}); pass --branch")
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Terminal and JSON reports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .classify import PUBLISHED_CLASSES, counts_by_bucket, summarize
|
|
6
|
+
from .gitio import short_path
|
|
7
|
+
|
|
8
|
+
LABELS = [
|
|
9
|
+
("identical", "same bytes as the remote"),
|
|
10
|
+
("stale", "an earlier published version of the remote file"),
|
|
11
|
+
("contained", "the remote already holds every line"),
|
|
12
|
+
("new", "not on the remote"),
|
|
13
|
+
("differs_clean", "unpublished edit, merges cleanly"),
|
|
14
|
+
("differs_conflict", "needs a decision, conflicting lines"),
|
|
15
|
+
("differs_binary", "unpublished binary change"),
|
|
16
|
+
("deleted", "deleted in the working tree"),
|
|
17
|
+
("untracked_dir", "untracked directory, not expanded"),
|
|
18
|
+
("skipped", "skipped"),
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
NOT_PUBLISHED = (
|
|
22
|
+
"new",
|
|
23
|
+
"differs_clean",
|
|
24
|
+
"differs_conflict",
|
|
25
|
+
"differs_binary",
|
|
26
|
+
"deleted",
|
|
27
|
+
"untracked_dir",
|
|
28
|
+
"skipped",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _decision_word(count):
|
|
33
|
+
return "needs" if count == 1 else "need"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def summary_line(rows, ahead=False):
|
|
37
|
+
"""One line: tracked changes in full detail, untracked entries as a count, separated by '·'."""
|
|
38
|
+
if ahead:
|
|
39
|
+
published, unpublished, decide = counts_by_bucket(rows)
|
|
40
|
+
subject = f"{len(rows)} path{'' if len(rows) == 1 else 's'} touched by local-only commits"
|
|
41
|
+
line = (
|
|
42
|
+
f"{subject}: {published} already published, {unpublished} unpublished, "
|
|
43
|
+
f"{decide} {_decision_word(decide)} a decision"
|
|
44
|
+
)
|
|
45
|
+
counts = summarize(rows)
|
|
46
|
+
if counts.get("deleted"):
|
|
47
|
+
line += f", {counts['deleted']} deleted"
|
|
48
|
+
if counts.get("skipped"):
|
|
49
|
+
line += f", {counts['skipped']} skipped"
|
|
50
|
+
return line
|
|
51
|
+
if not rows:
|
|
52
|
+
return "0 dirty paths"
|
|
53
|
+
tracked = [r for r in rows if not r["untracked"]]
|
|
54
|
+
untracked = [r for r in rows if r["untracked"]]
|
|
55
|
+
parts = []
|
|
56
|
+
if tracked:
|
|
57
|
+
published, unpublished, decide = counts_by_bucket(tracked)
|
|
58
|
+
part = (
|
|
59
|
+
f"{len(tracked)} changed tracked file{'' if len(tracked) == 1 else 's'}: "
|
|
60
|
+
f"{published} already published, {unpublished} unpublished, "
|
|
61
|
+
f"{decide} {_decision_word(decide)} a decision"
|
|
62
|
+
)
|
|
63
|
+
counts = summarize(tracked)
|
|
64
|
+
if counts.get("deleted"):
|
|
65
|
+
part += f", {counts['deleted']} deleted"
|
|
66
|
+
if counts.get("skipped"):
|
|
67
|
+
part += f", {counts['skipped']} skipped"
|
|
68
|
+
parts.append(part)
|
|
69
|
+
if untracked:
|
|
70
|
+
part = f"{len(untracked)} untracked entr{'y' if len(untracked) == 1 else 'ies'}"
|
|
71
|
+
already = sum(1 for r in untracked if r["class"] in PUBLISHED_CLASSES)
|
|
72
|
+
if already:
|
|
73
|
+
part += f" ({already} already on the remote)"
|
|
74
|
+
parts.append(part)
|
|
75
|
+
return " · ".join(parts)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def format_report(rows, behind, ref, ahead=False):
|
|
79
|
+
lines = [f"checkout is {behind} commit{'' if behind == 1 else 's'} behind {ref}", summary_line(rows, ahead)]
|
|
80
|
+
counts = summarize(rows)
|
|
81
|
+
for key, label in LABELS:
|
|
82
|
+
if counts.get(key):
|
|
83
|
+
lines.append(f" {counts[key]:>5} {key:<17} {label}")
|
|
84
|
+
for r in rows:
|
|
85
|
+
if r["class"] in NOT_PUBLISHED:
|
|
86
|
+
age = f"{r['age_min']:>4} min ago" if r["age_min"] is not None else " " * 11
|
|
87
|
+
reason = f" {r['reason']}" if r["reason"] else ""
|
|
88
|
+
lines.append(f" {r['class']:<17} {age} {short_path(r['path'])}{reason}")
|
|
89
|
+
return "\n".join(lines)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def json_report(rows, behind, ref, ahead=False, repo=None):
|
|
93
|
+
counts = summarize(rows)
|
|
94
|
+
tracked = [r for r in rows if not r["untracked"]]
|
|
95
|
+
untracked = [r for r in rows if r["untracked"]]
|
|
96
|
+
published, unpublished, decide = counts_by_bucket(tracked)
|
|
97
|
+
tracked_counts = summarize(tracked)
|
|
98
|
+
return {
|
|
99
|
+
"repo": repo,
|
|
100
|
+
"ref": ref,
|
|
101
|
+
"behind": behind,
|
|
102
|
+
"mode": "ahead" if ahead else "worktree",
|
|
103
|
+
"counts": counts,
|
|
104
|
+
"summary": {
|
|
105
|
+
"paths": len(rows),
|
|
106
|
+
"tracked": {
|
|
107
|
+
"paths": len(tracked),
|
|
108
|
+
"published": published,
|
|
109
|
+
"unpublished": unpublished,
|
|
110
|
+
"decide": decide,
|
|
111
|
+
"deleted": tracked_counts.get("deleted", 0),
|
|
112
|
+
"skipped": tracked_counts.get("skipped", 0),
|
|
113
|
+
},
|
|
114
|
+
"untracked": {
|
|
115
|
+
"entries": len(untracked),
|
|
116
|
+
"published": sum(1 for r in untracked if r["class"] in PUBLISHED_CLASSES),
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
"paths": [
|
|
120
|
+
{
|
|
121
|
+
"path": r["path"].decode("utf-8", "surrogateescape"),
|
|
122
|
+
"class": r["class"],
|
|
123
|
+
"age_min": r["age_min"],
|
|
124
|
+
"reason": r["reason"],
|
|
125
|
+
"untracked": r["untracked"],
|
|
126
|
+
"files": r["files"],
|
|
127
|
+
}
|
|
128
|
+
for r in rows
|
|
129
|
+
],
|
|
130
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: git-dirty-triage
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tell which modified files in a lagging or shared Git checkout are really unpublished, and commit only those on top of the remote tip without pushing.
|
|
5
|
+
Author: El Fenomeno
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/elfenomenokim/git-dirty-triage
|
|
8
|
+
Project-URL: Repository, https://github.com/elfenomenokim/git-dirty-triage
|
|
9
|
+
Project-URL: Issues, https://github.com/elfenomenokim/git-dirty-triage/issues
|
|
10
|
+
Keywords: git,dirty,checkout,monorepo,multi-agent,agents,three-way-merge,cli
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
18
|
+
Classifier: Topic :: Utilities
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# git-dirty-triage
|
|
25
|
+
|
|
26
|
+
[한국어](https://github.com/elfenomenokim/git-dirty-triage/blob/main/README.ko.md)
|
|
27
|
+
|
|
28
|
+
Tell which modified files in a lagging checkout are really unpublished.
|
|
29
|
+
|
|
30
|
+
```console
|
|
31
|
+
$ git-dirty-triage
|
|
32
|
+
checkout is 7 commits behind origin/main
|
|
33
|
+
5 changed tracked files: 3 already published, 1 unpublished, 1 needs a decision · 3 untracked entries (1 already on the remote)
|
|
34
|
+
2 identical same bytes as the remote
|
|
35
|
+
1 stale an earlier published version of the remote file
|
|
36
|
+
1 contained the remote already holds every line
|
|
37
|
+
1 new not on the remote
|
|
38
|
+
1 differs_clean unpublished edit, merges cleanly
|
|
39
|
+
1 differs_conflict needs a decision, conflicting lines
|
|
40
|
+
1 untracked_dir untracked directory, not expanded
|
|
41
|
+
differs_conflict 0 min ago conflict.txt 1 unique line(s)
|
|
42
|
+
differs_clean 0 min ago merge.txt 1 unique line(s)
|
|
43
|
+
untracked_dir build/ 3 file(s)
|
|
44
|
+
new 0 min ago new.txt
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Why
|
|
48
|
+
|
|
49
|
+
Several agents or sessions share one checkout. When one of them publishes, it builds a commit on top of the remote tip and pushes; it does not fast-forward the shared checkout, because other sessions are editing files there at that moment. The branch lags on purpose, and `git status` keeps listing work that is already on the remote.
|
|
50
|
+
|
|
51
|
+
That listing is not harmless. A later "commit everything and push" builds on the stale local HEAD, collides with the remote's newer version of the same file, and the conflict is not in anyone's edit — it is in the publication.
|
|
52
|
+
|
|
53
|
+
`git status` cannot tell you which modified files carry something new: it compares the working tree with the local index, never with the remote. This tool compares every modified path with the remote tip and answers the real question per path.
|
|
54
|
+
|
|
55
|
+
- The bytes equal the remote file: the work is published; nothing to do.
|
|
56
|
+
- The bytes equal an earlier published version: also published.
|
|
57
|
+
- Every line already exists in the remote file: nothing unique.
|
|
58
|
+
- The bytes are not on the remote: unpublished.
|
|
59
|
+
|
|
60
|
+
Untracked trees make that list worse. A build output directory is thousands of files nobody edited, and expanding it buries the handful of real changes. By default git lists an untracked directory as one `build/` row, and this tool keeps it that way: one row, no hashing, never committed. Untracked files themselves are still classified, so a file the remote already has counts as published.
|
|
61
|
+
|
|
62
|
+
Without `--commit-unpublished` the command only reads. That option writes a commit object and a private ref; it still never moves your branch, index or working tree.
|
|
63
|
+
|
|
64
|
+
## Install
|
|
65
|
+
|
|
66
|
+
```console
|
|
67
|
+
$ pipx install git-dirty-triage # recommended: isolated, on PATH
|
|
68
|
+
$ uvx git-dirty-triage --help # or run without installing
|
|
69
|
+
$ pip install git-dirty-triage # inside a project
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Python 3.9 or newer, git 2.x, and no Python dependencies. The installed command is named `git-dirty-triage`, so git also runs it as `git dirty-triage`.
|
|
73
|
+
|
|
74
|
+
## Usage
|
|
75
|
+
|
|
76
|
+
### Classify the dirty paths
|
|
77
|
+
|
|
78
|
+
```console
|
|
79
|
+
$ git-dirty-triage
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
It fetches the branch first, then compares. The first line says how far the checkout lags. The second is the count that matters, in two parts separated by `·`: tracked changes in full detail, then untracked entries. The lines below list only the paths that are not already published. `git status` order is kept; a long path is shortened from the left.
|
|
83
|
+
|
|
84
|
+
The per-class counts under the summary cover every row, untracked files included. The summary line splits tracked changes from untracked entries, so the two views differ when an untracked file is already on the remote.
|
|
85
|
+
|
|
86
|
+
### Untracked paths
|
|
87
|
+
|
|
88
|
+
`-u/--untracked` follows git status:
|
|
89
|
+
|
|
90
|
+
| Value | An untracked directory | An untracked file |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `normal` (default) | one row, `build/`, with a file count | its own row, classified |
|
|
93
|
+
| `all` | expanded: every file gets a row and is classified | its own row, classified |
|
|
94
|
+
| `no` | not listed | not listed |
|
|
95
|
+
|
|
96
|
+
```console
|
|
97
|
+
$ git-dirty-triage --prefix build
|
|
98
|
+
checkout is 7 commits behind origin/main
|
|
99
|
+
1 untracked entry
|
|
100
|
+
1 untracked_dir untracked directory, not expanded
|
|
101
|
+
untracked_dir build/ 3 file(s)
|
|
102
|
+
|
|
103
|
+
$ git-dirty-triage --prefix build --untracked all
|
|
104
|
+
checkout is 7 commits behind origin/main
|
|
105
|
+
3 untracked entries
|
|
106
|
+
3 new not on the remote
|
|
107
|
+
new 0 min ago build/a.log
|
|
108
|
+
new 0 min ago build/cache/b.log
|
|
109
|
+
new 0 min ago build/cache/c.log
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The file count comes from a directory walk; nothing inside an untracked directory is hashed or compared with the remote. `untracked_dir` rows are never printed by `--print-unpublished` and never committed. Use `--untracked all` when you want those files.
|
|
113
|
+
|
|
114
|
+
### Print only the unpublished paths
|
|
115
|
+
|
|
116
|
+
```console
|
|
117
|
+
$ git-dirty-triage --print-unpublished
|
|
118
|
+
merge.txt
|
|
119
|
+
new.txt
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
One path per line, ready to pipe. Untracked directories are not printed; untracked files are. Filenames that contain a newline are reported as `skipped` and never printed, so a line is always one path:
|
|
123
|
+
|
|
124
|
+
```console
|
|
125
|
+
$ git-dirty-triage --print-unpublished | while IFS= read -r p; do git add -- "$p"; done
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Commit the unpublished paths on top of the remote tip, without pushing
|
|
129
|
+
|
|
130
|
+
```console
|
|
131
|
+
$ git-dirty-triage --commit-unpublished -m "local work"
|
|
132
|
+
committed 2 path(s) as 08627b9a8f3ccfca858b1c32dd5bc5ac2135915e on top of origin/main
|
|
133
|
+
ref: refs/git-dirty-triage/main
|
|
134
|
+
push: not pushed
|
|
135
|
+
next: git push origin 08627b9a8f3ccfca858b1c32dd5bc5ac2135915e:refs/heads/main
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The commit is built on a temporary index from the remote tip's tree: the parent is `origin/main`, not your HEAD. Edited text uses the three-way merge of your bytes and the remote's, so neither side loses a line; new and binary files are taken whole. Your branch, index and working tree are untouched, and nothing is pushed.
|
|
139
|
+
|
|
140
|
+
The commit is kept reachable as `refs/git-dirty-triage/<branch>`. Push it when you have looked at it. Until the remote actually has those bytes, a rerun still reports the paths as unpublished on the remote — that is the question the tool answers.
|
|
141
|
+
|
|
142
|
+
Conflicting paths are never committed. Resolve them where they are edited; a line-union merge of a changelog or a ledger is not a resolution.
|
|
143
|
+
|
|
144
|
+
### Files touched by local-only commits
|
|
145
|
+
|
|
146
|
+
`--ahead` answers the other blind spot: a file that was committed locally, never reached the remote, and has a clean working copy. The dirty scan cannot see it.
|
|
147
|
+
|
|
148
|
+
```console
|
|
149
|
+
$ git-dirty-triage --ahead
|
|
150
|
+
checkout is 7 commits behind origin/main
|
|
151
|
+
1 path touched by local-only commits: 0 already published, 1 unpublished, 0 need a decision
|
|
152
|
+
1 new not on the remote
|
|
153
|
+
new 0 min ago notes.txt
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The three-way base is the merge-base blob instead of `HEAD`. A path the remote deleted is not brought back, and a version the remote once held counts as `stale`. `--ahead` reads commit contents, so `--untracked` does not apply.
|
|
157
|
+
|
|
158
|
+
### One directory or file
|
|
159
|
+
|
|
160
|
+
```console
|
|
161
|
+
$ git-dirty-triage --prefix src --prefix README.md
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`--prefix` limits the listing itself, not only the report, so a unit costs what its own paths cost. Prefixes are repo-relative.
|
|
165
|
+
|
|
166
|
+
### Machine-readable output
|
|
167
|
+
|
|
168
|
+
```console
|
|
169
|
+
$ git-dirty-triage --json
|
|
170
|
+
{"repo": "/tmp/demo/shared", "ref": "origin/main", "behind": 7, "mode": "worktree",
|
|
171
|
+
"counts": {"identical": 2, "stale": 1, "contained": 1, "new": 1, "differs_clean": 1,
|
|
172
|
+
"differs_conflict": 1, "untracked_dir": 1},
|
|
173
|
+
"summary": {"paths": 8,
|
|
174
|
+
"tracked": {"paths": 5, "published": 3, "unpublished": 1, "decide": 1, "deleted": 0, "skipped": 0},
|
|
175
|
+
"untracked": {"entries": 3, "published": 1}},
|
|
176
|
+
"paths": [{"path": "conflict.txt", "class": "differs_conflict", "age_min": 0,
|
|
177
|
+
"reason": "1 unique line(s)", "untracked": false, "files": null}, …]}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
(Shown wrapped and shortened; the command prints one line.)
|
|
181
|
+
|
|
182
|
+
Every row carries `untracked` and `files`; `files` is the count on an `untracked_dir` row and `null` elsewhere.
|
|
183
|
+
|
|
184
|
+
`--commit-unpublished --json` prints a receipt instead: `status`, `commit`, `parent`, `ref`, `files`, `paths`, `pushed` and the `push` command, or `{"status": "nothing_to_commit"}`.
|
|
185
|
+
|
|
186
|
+
### Exit status
|
|
187
|
+
|
|
188
|
+
`0` means the report was printed, even when it reports unpublished or conflicting paths — the report is data. `2` means a usage or git error. With `--commit-unpublished`, `0` also covers `nothing to commit`.
|
|
189
|
+
|
|
190
|
+
## How it decides
|
|
191
|
+
|
|
192
|
+
| Class | Working bytes against the remote tip | Unpublished? |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `identical` | same blob as remote | no |
|
|
195
|
+
| `stale` | equal to an earlier published version of the path | no |
|
|
196
|
+
| `contained` | every non-blank line already exists in the remote file | no |
|
|
197
|
+
| `new` | the remote has no file at this path | yes |
|
|
198
|
+
| `differs_clean` | unique lines, and a three-way merge with `HEAD` as base is clean | yes |
|
|
199
|
+
| `differs_conflict` | unique lines, and the same merge conflicts | no — a decision |
|
|
200
|
+
| `differs_binary` | binary, and the remote blob is unchanged since `HEAD` | yes, whole file |
|
|
201
|
+
| `deleted` | removed in the working tree | reported only |
|
|
202
|
+
| `untracked_dir` | untracked directory under `--untracked normal` | one row; never hashed, printed or committed |
|
|
203
|
+
| `skipped` | not a plain file (symlink, path with a newline) | reported only |
|
|
204
|
+
|
|
205
|
+
A clean merge whose result equals the remote bytes is `contained`: the path only lags.
|
|
206
|
+
|
|
207
|
+
The cost is one batched `hash-object` pass and one `ls-tree` per side. Per-path history is read only for a path that really differs. A 38,925-path checkout was classified in 107 seconds on an Apple-silicon Mac (Python 3.12, warm cache).
|
|
208
|
+
|
|
209
|
+
## A real example
|
|
210
|
+
|
|
211
|
+
The output at the top of this page comes from `examples/make-demo.sh`, which builds a throwaway remote and two clones in a temp directory: `peer` publishes seven commits, `shared` lags and edits the same five files plus one new file, one untracked copy of a published file and an untracked `build/` tree.
|
|
212
|
+
|
|
213
|
+
```console
|
|
214
|
+
$ bash examples/make-demo.sh
|
|
215
|
+
demo repo: /tmp/git-dirty-triage-demo/shared
|
|
216
|
+
$ cd /tmp/git-dirty-triage-demo/shared && git-dirty-triage
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## When you do not need it
|
|
220
|
+
|
|
221
|
+
- **Each agent has its own clone or worktree.** Every checkout then tracks the remote, and `git status` is already the truth.
|
|
222
|
+
- **The checkout is up to date with the remote.** Same reason.
|
|
223
|
+
- **A single writer, no concurrent publication.** Nothing is published behind your back.
|
|
224
|
+
- **You want to know whether two branches will merge.** Use `git merge-tree` or `git range-diff`; this tool judges one working tree against one remote branch.
|
|
225
|
+
|
|
226
|
+
You need it when a checkout is deliberately behind and still has edits — the state a shared multi-agent checkout ends up in.
|
|
227
|
+
|
|
228
|
+
## Limits
|
|
229
|
+
|
|
230
|
+
- **The answer describes the last fetch.** The command fetches by default and prints a warning when the fetch fails, then compares with what is already fetched. `--no-fetch` skips the fetch without a notice.
|
|
231
|
+
- **Files, not trees.** Directories are not classified; a rename appears as a delete plus a new file. Deleted and skipped paths are reported and never committed.
|
|
232
|
+
- **"Unpublished" is not "wanted".** A cleanly merging edit is unpublished by definition; deciding whether it belongs in a commit is yours.
|
|
233
|
+
- **Binary files are all-or-nothing**, and only when the remote copy has not changed since HEAD; otherwise the path needs a decision.
|
|
234
|
+
- **A committed edit is not your working file.** For `differs_clean` the commit holds the three-way merge, which can differ from the bytes on disk. Your working tree is left as it was.
|
|
235
|
+
- **Untracked directories stay opaque by default.** Their file count comes from a directory walk; nothing inside is hashed or compared with the remote. `--untracked all` expands them, which is expensive on a large build tree and is the only way to see, print or commit their files.
|
|
236
|
+
- **`--ahead` needs a merge-base.** A depth-1 shallow clone has none.
|
|
237
|
+
- **Empty repositories are not supported**; there is no remote tip to compare with.
|
|
238
|
+
- **Tested on macOS (Apple silicon, Python 3.12).** The code uses only the standard library and `git`; Linux and Windows are untested — reports welcome.
|
|
239
|
+
- **Very large dirty sets** cost one `cat-file` and one `log` per genuinely differing file; only the identical and new paths are cheap.
|
|
240
|
+
|
|
241
|
+
There is no configuration file and no environment variable. Every default is a flag: `--repo`, `--remote`, `--branch`, `--untracked`.
|
|
242
|
+
|
|
243
|
+
## Agents
|
|
244
|
+
|
|
245
|
+
If you are an AI agent asked to publish work from a shared checkout, read [AGENTS.md](https://github.com/elfenomenokim/git-dirty-triage/blob/main/AGENTS.md). The Claude Code skill lives in [`skill/git-dirty-triage/SKILL.md`](https://github.com/elfenomenokim/git-dirty-triage/blob/main/skill/git-dirty-triage/SKILL.md); install it by copying that folder to `~/.claude/skills/git-dirty-triage/`.
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
MIT — see [LICENSE](https://github.com/elfenomenokim/git-dirty-triage/blob/main/LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
git_dirty_triage/__init__.py,sha256=4TGJaYiZujjFScMl2D4IHWZ5Q7fY-fekBHXMx2AsBmM,1090
|
|
2
|
+
git_dirty_triage/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
git_dirty_triage/classify.py,sha256=uSTAbeOnzf8234WV4xlumXXtR4Ok7VhjokbWfKHYr1E,7536
|
|
4
|
+
git_dirty_triage/cli.py,sha256=6QeH8CNtJxjBfKONs15LcmrH1vRw551P9ngpANmlGsA,5227
|
|
5
|
+
git_dirty_triage/commit.py,sha256=qsLTpeK76j1MTga2caN-OPW_naJuG-hAtZ5NCUfIvZ4,3250
|
|
6
|
+
git_dirty_triage/gitio.py,sha256=FNFNOG4lbvciKm3xIBmWMEZopeJDa3vitl4bYXErkCI,7923
|
|
7
|
+
git_dirty_triage/report.py,sha256=t2tHOL-yyp9gqCqzWJ6_42MC9HOHanCN_6sIutPlZ90,4726
|
|
8
|
+
git_dirty_triage-0.1.0.dist-info/licenses/LICENSE,sha256=doJZh0OcqN6KH1mad-WIcL9Eovit4M2O3THyZB9_7gE,1068
|
|
9
|
+
git_dirty_triage-0.1.0.dist-info/METADATA,sha256=u85cAFZtZkAV97v8YUwrums5SaBlEKMxM9D1lwtgNbk,14042
|
|
10
|
+
git_dirty_triage-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
git_dirty_triage-0.1.0.dist-info/entry_points.txt,sha256=HQkaX6wbrZPceAQVr4N0SjreESukmQPWDliXViKPgBQ,63
|
|
12
|
+
git_dirty_triage-0.1.0.dist-info/top_level.txt,sha256=dvpv4A78MbG_MC-6Hkts2S_tYsJQwAuLzoFowctX_6M,17
|
|
13
|
+
git_dirty_triage-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 El Fenomeno
|
|
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
|
+
git_dirty_triage
|