gitstory-cli 0.2.2__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.
gitstory/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """gitstory — "why is this code like this" narrative assembler."""
2
+
3
+ __version__ = "0.2.2"
gitstory/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Entry point: python -m gitstory."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
gitstory/cli.py ADDED
@@ -0,0 +1,196 @@
1
+ """gitstory CLI — "why is this code like this" in one command.
2
+
3
+ Usage:
4
+ gitstory <file> <line-range> | <file>:<line-range> | <file> -L START,END
5
+ [--json] [--full] [--no-gh] [--blame-only] [--no-ignore-revs]
6
+
7
+ Exit codes: 0 narrative produced, 2 error (not a repo, file not
8
+ tracked, bad range, range outside the file, git failure).
9
+
10
+ gitstory never writes to the repo and never calls an LLM. The only
11
+ network use is optional read-only `gh pr view` / `gh issue view` /
12
+ `gh api repos/.../commits/<sha>/pulls`
13
+ enrichment, disabled with --no-gh and skipped entirely when gh or a
14
+ GitHub remote is absent.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import ast
21
+ import json
22
+ import re
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ from . import __version__, gitops
27
+ from . import evidence as ev
28
+ from . import narrative as nar
29
+
30
+
31
+ def _fail(message: str) -> int:
32
+ # messages can echo user-typed paths and git's stderr: same filter as the text output
33
+ print(f"gitstory: error: {_printable(message)}", file=sys.stderr)
34
+ return 2
35
+
36
+
37
+ def build_parser() -> argparse.ArgumentParser:
38
+ parser = argparse.ArgumentParser(
39
+ prog="gitstory",
40
+ description="Why is this code like this? Blame + commit messages "
41
+ "+ linked PRs/issues, assembled into a short narrative.",
42
+ epilog="Examples:\n"
43
+ " gitstory src/app.py 42-58 why are lines 42-58 like this?\n"
44
+ " gitstory src/app.py:42 one line\n"
45
+ " gitstory auth.py::Auth.login a Python function or class\n"
46
+ " gitstory src/app.py 42 --json structured evidence\n"
47
+ "Exit codes: 0 narrative produced, 2 error.",
48
+ formatter_class=argparse.RawDescriptionHelpFormatter,
49
+ )
50
+ parser.add_argument("--version", action="version", version=__version__)
51
+ parser.add_argument(
52
+ "file", help="file inside a git repository; 'file:42' or 'file:42-58' also accepted"
53
+ )
54
+ parser.add_argument("range", nargs="?", help="line range: '42' or '42-58'")
55
+ parser.add_argument(
56
+ "-L", dest="dash_l", metavar="START,END", help="line range, git style: '-L 40,58'"
57
+ )
58
+ parser.add_argument(
59
+ "--json", action="store_true", help="structured evidence instead of narrative text"
60
+ )
61
+ parser.add_argument(
62
+ "--full", action="store_true", help="append the raw evidence dump (text mode)"
63
+ )
64
+ parser.add_argument("--no-gh", action="store_true", help="skip gh PR/issue enrichment entirely")
65
+ parser.add_argument(
66
+ "--blame-only",
67
+ action="store_true",
68
+ help="skip git log -L history (faster on long histories; narrative uses blame only)",
69
+ )
70
+ parser.add_argument(
71
+ "--no-ignore-revs",
72
+ action="store_true",
73
+ help="don't skip revisions listed in .git-blame-ignore-revs / blame.ignoreRevsFile",
74
+ )
75
+ return parser
76
+
77
+
78
+ def _repo_for_file(file_arg: str) -> Path:
79
+ """Repo root for a file argument. The repo is found from the
80
+ FILE's location, not the caller's cwd: `gitstory /other/repo/
81
+ src.py 10` from anywhere must use /other/repo, not fail with
82
+ "file is outside this repository" because the cwd is elsewhere.
83
+ A relative path resolves from the cwd as usual; a nonexistent
84
+ path resolves from its parent, so typos still error cleanly
85
+ downstream ("not tracked" / "not a git repository")."""
86
+ candidate = Path(file_arg)
87
+ if not candidate.is_absolute():
88
+ candidate = Path.cwd() / candidate
89
+ try:
90
+ resolved = candidate.resolve()
91
+ except OSError:
92
+ resolved = candidate
93
+ anchor = resolved if resolved.is_dir() else resolved.parent
94
+ return gitops.find_repo_root(anchor)
95
+
96
+
97
+ def split_target(target: str) -> tuple[str, str | None]:
98
+ """'path:42' / 'path:40-58' -> (path, range). Splits only on the LAST
99
+ colon followed by digits, so a Windows drive letter (C:\\...) stays."""
100
+ m = re.fullmatch(r"(.+):(\d+(?:-\d+)?)", target)
101
+ return (m.group(1), m.group(2)) if m else (target, None)
102
+
103
+
104
+ def resolve_symbol(path: str, symbol: str) -> tuple[int, int]:
105
+ """'func' or 'Class.method' -> (first, last) line in the WORKING-TREE
106
+ file, decorators included. Python only. Raises ValueError."""
107
+ if not path.endswith(".py"):
108
+ raise ValueError(f"symbol targets work on Python files only: {path}")
109
+ try:
110
+ tree = ast.parse(Path(path).read_bytes(), filename=path)
111
+ except OSError as exc:
112
+ raise ValueError(f"cannot read {path}: {exc}") from exc
113
+ except SyntaxError as exc:
114
+ raise ValueError(f"cannot parse {path}: {exc.msg}") from exc
115
+ node: ast.AST = tree
116
+ for part in symbol.split("."):
117
+ node = next(
118
+ (
119
+ n
120
+ for n in getattr(node, "body", [])
121
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
122
+ and n.name == part
123
+ ),
124
+ None,
125
+ )
126
+ if node is None:
127
+ raise ValueError(f"no function or class {symbol!r} in {path}")
128
+ first = min([node.lineno] + [d.lineno for d in node.decorator_list])
129
+ return first, node.end_lineno
130
+
131
+
132
+ def _printable(text: str) -> str:
133
+ """Drop control characters (ESC, BEL, backspace, C1) but keep
134
+ newline and tab, so repo-controlled text cannot drive the
135
+ reader's terminal."""
136
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
137
+ return "".join(ch for ch in text if ch in "\n\t" or not (ord(ch) < 32 or 127 <= ord(ch) <= 159))
138
+
139
+
140
+ def main(argv: list[str] | None = None) -> int:
141
+ parser = build_parser()
142
+ args = parser.parse_args(argv)
143
+ symbol = None
144
+ if "::" in args.file:
145
+ args.file, symbol = args.file.rsplit("::", 1)
146
+ colon_range = None
147
+ else:
148
+ args.file, colon_range = split_target(args.file)
149
+ dash_l = args.dash_l.replace(",", "-") if args.dash_l else None
150
+ given = [r for r in (colon_range, args.range, dash_l) if r]
151
+ if symbol is not None:
152
+ if given:
153
+ return _fail("give a symbol or a line range, not both")
154
+ try:
155
+ start, end = resolve_symbol(args.file, symbol)
156
+ except ValueError as exc:
157
+ return _fail(str(exc))
158
+ else:
159
+ if len(given) != 1:
160
+ return _fail(
161
+ "give exactly one line range: 'file 42-58', "
162
+ "'file:42-58', 'file -L 42,58' or 'file.py::name'"
163
+ )
164
+ try:
165
+ start, end = ev.parse_range(given[0])
166
+ except ev.RangeError as exc:
167
+ return _fail(str(exc))
168
+ try:
169
+ repo = _repo_for_file(args.file)
170
+ relpath = gitops.resolve_repo_file(repo, args.file)
171
+ data = nar.assemble(
172
+ repo,
173
+ relpath,
174
+ start,
175
+ end,
176
+ gh_enabled=not args.no_gh,
177
+ blame_only=args.blame_only,
178
+ ignore_revs=not args.no_ignore_revs,
179
+ )
180
+ except gitops.GitError as exc:
181
+ return _fail(str(exc))
182
+ if symbol is not None:
183
+ data["target"] = symbol
184
+ if args.json:
185
+ print(json.dumps(data, indent=2))
186
+ else:
187
+ if symbol is not None:
188
+ print(
189
+ f"target: {symbol} -> lines {start}-{end} (resolved by ast from the working tree)"
190
+ )
191
+ print(_printable(nar.render_text(data, full=args.full)), end="")
192
+ return 0
193
+
194
+
195
+ if __name__ == "__main__":
196
+ sys.exit(main())
gitstory/evidence.py ADDED
@@ -0,0 +1,330 @@
1
+ """Evidence parsing: blame, -L history, PR references, AI trailers.
2
+
3
+ Nothing here invents anything. Every function turns git output into
4
+ structured data; the narrative layer decides what to print, and the
5
+ honesty contract lives there: EVIDENCE is quoted or cited, INFERENCE
6
+ is labeled, and absence prints as "unknown from history".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from .gitops import ZERO_HASH, split_message
14
+
15
+ # ---------------------------------------------------------------- ranges
16
+
17
+
18
+ class RangeError(ValueError):
19
+ """Bad line-range argument."""
20
+
21
+
22
+ def parse_range(text: str) -> tuple[int, int]:
23
+ """Parse '42' or '42-58' into (start, end). Raises RangeError."""
24
+ m = re.fullmatch(r"(\d+)(?:-(\d+))?", text.strip())
25
+ if not m:
26
+ raise RangeError(f"bad line range: {text!r} (expected '42' or '42-58')")
27
+ start = int(m.group(1))
28
+ end = int(m.group(2)) if m.group(2) else start
29
+ if start < 1 or end < start:
30
+ raise RangeError(f"bad line range: {text!r} (lines start at 1, end >= start)")
31
+ return start, end
32
+
33
+
34
+ # ---------------------------------------------------------------- blame
35
+
36
+
37
+ def parse_blame_porcelain(raw: str) -> list[dict]:
38
+ """Parse git blame --porcelain into one entry per line.
39
+
40
+ Porcelain grouping (the detail that matters): consecutive lines
41
+ from one commit form a group. Only the FIRST line of a group gets
42
+ the full header (hash, orig, final, num_lines) plus attributes;
43
+ each following line in the group gets a SHORT header (hash, orig,
44
+ final) and a content line only, inheriting the group's attributes.
45
+ A naive one-block-per-line parser silently merges grouped lines
46
+ (line 11's content overwriting line 10's) — this parser does not.
47
+
48
+ Each entry: line (final line number), hash, author, date (raw
49
+ author-time + tz), summary, content, previous (dict with hash +
50
+ filename, for moved lines), uncommitted (bool).
51
+ """
52
+ entries: list[dict] = []
53
+ current: dict | None = None
54
+ group: dict | None = None
55
+ for line in raw.splitlines():
56
+ full = re.match(r"^([0-9a-f]{40}) (\d+) (\d+) (\d+)$", line)
57
+ if full:
58
+ if current is not None:
59
+ entries.append(current)
60
+ current = {
61
+ "hash": full.group(1),
62
+ "orig_line": int(full.group(2)),
63
+ "line": int(full.group(3)),
64
+ "num_lines": int(full.group(4)),
65
+ "author": "",
66
+ "author_time": "",
67
+ "summary": "",
68
+ "content": "",
69
+ "previous": None,
70
+ "uncommitted": full.group(1) == ZERO_HASH,
71
+ }
72
+ group = current
73
+ continue
74
+ short = re.match(r"^([0-9a-f]{40}) (\d+) (\d+)$", line)
75
+ if short and group is not None:
76
+ if current is not None:
77
+ entries.append(current)
78
+ current = {
79
+ "hash": short.group(1),
80
+ "orig_line": int(short.group(2)),
81
+ "line": int(short.group(3)),
82
+ "num_lines": 1,
83
+ "author": group["author"],
84
+ "author_time": group["author_time"],
85
+ "summary": group["summary"],
86
+ "content": "",
87
+ "previous": group["previous"],
88
+ "uncommitted": short.group(1) == ZERO_HASH,
89
+ }
90
+ continue
91
+ if current is None:
92
+ continue
93
+ if line.startswith("\t"):
94
+ current["content"] = line[1:]
95
+ elif line.startswith("author "):
96
+ current["author"] = line[len("author ") :]
97
+ elif line.startswith("author-time "):
98
+ current["author_time"] = line[len("author-time ") :]
99
+ elif line.startswith("author-tz "):
100
+ current["author_time"] += " " + line[len("author-tz ") :]
101
+ elif line.startswith("summary "):
102
+ current["summary"] = line[len("summary ") :]
103
+ elif line.startswith("previous "):
104
+ parts = line[len("previous ") :].split(" ", 1)
105
+ current["previous"] = {
106
+ "hash": parts[0],
107
+ "filename": parts[1] if len(parts) > 1 else "",
108
+ }
109
+ if current is not None:
110
+ entries.append(current)
111
+ return entries
112
+
113
+
114
+ # ---------------------------------------------------------------- -L history
115
+
116
+
117
+ def parse_line_history(raw: str) -> list[dict]:
118
+ """Parse git log -L output into records, newest first.
119
+
120
+ Real layout per record: a header starting at a line beginning
121
+ with "COMMIT\\x1f" (fields separated by \\x1f, body may span
122
+ lines, header terminated by \\x1e), then the range-scoped diff,
123
+ up to the next COMMIT line. A diff line never starts with
124
+ "COMMIT\\x1f" (diff lines carry a space/+/-/@/d prefix), so the
125
+ record boundary is unambiguous.
126
+
127
+ Hardening (v0.2.0): the old parser required exactly one blank
128
+ line between the header terminator and the diff, so a record
129
+ with an empty diff (or a missing blank line) silently vanished
130
+ from history — a dropped record is a dropped piece of the story.
131
+ This parser splits on header positions instead: the diff is
132
+ whatever lies between one header's end and the next header's
133
+ start, leading/trailing blank lines stripped. An empty diff
134
+ yields a record with diff "", never a dropped record.
135
+
136
+ Header fields are hash, author, date, full message; subject and
137
+ body come from split_message (first-line split, not git's
138
+ paragraph-collapsing %s — see there).
139
+
140
+ Each record: hash, author, date, subject, body, diff.
141
+ """
142
+ records: list[dict] = []
143
+ header_re = re.compile(r"^COMMIT\x1f([^\x1e]*)\x1e", re.MULTILINE)
144
+ matches = list(header_re.finditer(raw))
145
+ for index, match in enumerate(matches):
146
+ fields = match.group(1).split("\x1f")
147
+ if len(fields) != 4:
148
+ continue
149
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(raw)
150
+ diff = raw[match.end() : end].strip("\n")
151
+ subject, body = split_message(fields[3])
152
+ records.append(
153
+ {
154
+ "hash": fields[0],
155
+ "author": fields[1],
156
+ "date": fields[2],
157
+ "subject": subject,
158
+ "body": body,
159
+ "diff": diff,
160
+ }
161
+ )
162
+ return records
163
+
164
+
165
+ # ---------------------------------------------------------------- messages
166
+
167
+
168
+ # One left-to-right pass: the optional owner/repo group must be
169
+ # part of the same match, or a bare #N pass would re-match the
170
+ # number inside "owner/repo#N" as a second, same-repo reference.
171
+ PR_PATTERN = re.compile(r"(?:([\w.-]+/[\w.-]+))?#(\d+)")
172
+
173
+
174
+ def parse_pr_refs(*messages: str) -> list[dict]:
175
+ """Extract PR/issue references from commit messages.
176
+
177
+ Returns [{number, repo}] with repo None for same-repo refs.
178
+ Deduplicated, in order of first appearance. A bare #N is a
179
+ reference to a PR *or* an issue — only gh can tell which, so the
180
+ kind is left unresolved until enrichment.
181
+ """
182
+ seen: set[tuple[str, int]] = set()
183
+ refs: list[dict] = []
184
+ for message in messages:
185
+ for match in PR_PATTERN.finditer(message or ""):
186
+ repo, number = match.group(1), int(match.group(2))
187
+ key = (repo or "", number)
188
+ if key not in seen:
189
+ seen.add(key)
190
+ refs.append({"number": number, "repo": repo})
191
+ return refs
192
+
193
+
194
+ AI_TRAILER = re.compile(
195
+ r"Co-Authored-By:.*\b(claude|copilot|chatgpt|codex|gemini|gpt-|"
196
+ r"openai|anthropic|cursor|aider|devin|amazon-?q|tabnine)\b",
197
+ re.IGNORECASE,
198
+ )
199
+ AI_GENERATED = re.compile(
200
+ r"Generated-(with|by):.*\b(ai|claude|copilot|chatgpt|codex|gemini)\b",
201
+ re.IGNORECASE,
202
+ )
203
+
204
+
205
+ REASON_TRAILER = re.compile(
206
+ r"^(Why|Why-Rationale|Why-Alternatives|Reason|Rationale):\s*(.+)$", re.IGNORECASE
207
+ )
208
+
209
+
210
+ def parse_reason_trailers(body: str) -> list[dict]:
211
+ """Why/Why-Rationale/Why-Alternatives/Reason/Rationale trailers from
212
+ the LAST paragraph of a commit body (where git trailers live), so a
213
+ 'Reason:' line in the middle of prose doesn't count. Verbatim."""
214
+ paragraphs = [p for p in (body or "").strip().split("\n\n") if p.strip()]
215
+ if not paragraphs:
216
+ return []
217
+ found = []
218
+ for line in paragraphs[-1].splitlines():
219
+ m = REASON_TRAILER.match(line.strip())
220
+ if m:
221
+ found.append({"name": m.group(1), "value": m.group(2).strip()})
222
+ return found
223
+
224
+
225
+ def parse_ai_trailers(*messages: str) -> list[str]:
226
+ """Commit-metadata lines indicating AI assistance, quoted verbatim.
227
+
228
+ Evidence-based only: only trailer lines in the message count.
229
+ Never guessed from code style."""
230
+ found: list[str] = []
231
+ for message in messages:
232
+ for line in (message or "").splitlines():
233
+ if AI_TRAILER.search(line) or AI_GENERATED.search(line):
234
+ stripped = line.strip()
235
+ if stripped not in found:
236
+ found.append(stripped)
237
+ return found
238
+
239
+
240
+ FIX_RE = re.compile(r"\b(fix|fixes|fixed|fixing|hotfix)\b", re.IGNORECASE)
241
+ REVERT_RE = re.compile(r"\b(revert|reverts|reverted)\b", re.IGNORECASE)
242
+ BREAK_RE = re.compile(r"\b(break|breaks|broken|regression)\b", re.IGNORECASE)
243
+
244
+
245
+ def classify_touch(subject: str, body: str) -> str:
246
+ """Classify a later touch by message pattern. This is INFERENCE
247
+ from wording, and the narrative labels it as such: a message
248
+ saying 'fix' is evidence of wording, not proof of intent."""
249
+ text = f"{subject or ''}\n{body or ''}"
250
+ if REVERT_RE.search(text):
251
+ return "revert"
252
+ if FIX_RE.search(text):
253
+ return "fix"
254
+ return "change"
255
+
256
+
257
+ def mentions_breakage(subject: str, body: str) -> bool:
258
+ text = f"{subject or ''}\n{body or ''}"
259
+ return bool(BREAK_RE.search(text))
260
+
261
+
262
+ # ---------------------------------------------------------------- paths
263
+
264
+
265
+ def is_test_path(path: str) -> bool:
266
+ """Heuristic: is this a test file? Used only to report 'the
267
+ introducing commit also changed test files X' — evidence, not a
268
+ claim that the tests cover these lines."""
269
+ lower = path.lower()
270
+ parts = lower.split("/")
271
+ name = parts[-1]
272
+ return (
273
+ any(part in ("test", "tests") for part in parts[:-1])
274
+ or name.startswith("test_")
275
+ or name.startswith("test.")
276
+ or name.endswith("_test.py")
277
+ or name.endswith("_test.go")
278
+ or name.endswith(".test.js")
279
+ or name.endswith(".spec.js")
280
+ or name.endswith(".spec.ts")
281
+ or name == "conftest.py"
282
+ )
283
+
284
+
285
+ def short_hash(full: str) -> str:
286
+ return full[:7] if len(full) >= 7 else full
287
+
288
+
289
+ def test_file_related(target_path: str, test_path: str) -> bool:
290
+ """Heuristic: is this test file plausibly about the target file?
291
+
292
+ Compares basenames only: strip test markers (test_, _test, .spec)
293
+ and the extension from the test name, then match the target stem
294
+ exactly, or as a whole word (split on _/-) for stems of 3+ chars.
295
+ Single-char stems match exactly only — otherwise stem "a" would
296
+ "relate" to every test file. A heuristic, labeled as such wherever
297
+ its output is shown; the full test-file list stays in --json.
298
+ """
299
+ import os
300
+
301
+ def stem(path: str) -> str:
302
+ base = os.path.basename(path)
303
+ base = base.rsplit(".", 1)[0] if "." in base else base
304
+ return base
305
+
306
+ target = stem(target_path)
307
+ name = stem(test_path)
308
+ for marker in ("test_", "_test", ".spec"):
309
+ name = name.replace(marker, "")
310
+ if not target or not name:
311
+ return False
312
+ if name == target:
313
+ return True
314
+ if len(target) >= 3:
315
+ words = name.replace("-", "_").split("_")
316
+ if target in words:
317
+ return True
318
+ return False
319
+
320
+
321
+ def format_epoch(raw: str) -> str:
322
+ """Blame author-time ('<epoch> <tz>') -> 'YYYY-MM-DD' (UTC).
323
+ Unparseable input passes through unchanged, never crashes."""
324
+ try:
325
+ from datetime import datetime, timezone
326
+
327
+ epoch = int(raw.strip().split(" ", 1)[0])
328
+ return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime("%Y-%m-%d")
329
+ except (ValueError, IndexError, OverflowError, OSError):
330
+ return raw