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/gitops.py ADDED
@@ -0,0 +1,366 @@
1
+ """Git + gh subprocess access. Local first; gh is best-effort only.
2
+
3
+ Every function here raises GitError on failure so the CLI can turn
4
+ it into a clean exit-2 message instead of a traceback. No function
5
+ in this module ever writes to the repo, and no function ever sends
6
+ anything except the optional read-only `gh pr view` / `gh issue view` /
7
+ `gh api .../commits/<sha>/pulls`
8
+ enrichment (which the caller can disable with --no-gh).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ ZERO_HASH = "0" * 40
19
+
20
+
21
+ class GitError(Exception):
22
+ """A git (or gh) invocation failed, or the repo state is unusable."""
23
+
24
+
25
+ def run_git(repo: Path, args: list[str], timeout: int = 60) -> str:
26
+ """Run git in repo, return stdout. Raises GitError on any failure.
27
+
28
+ errors="replace" is deliberate: a file with non-UTF-8 bytes (or a
29
+ binary file) must render with replacement characters, never crash
30
+ the CLI with a UnicodeDecodeError traceback.
31
+ """
32
+ try:
33
+ proc = subprocess.run(
34
+ ["git", "-C", str(repo)] + args,
35
+ capture_output=True,
36
+ text=True,
37
+ errors="replace",
38
+ timeout=timeout,
39
+ )
40
+ except FileNotFoundError as exc:
41
+ raise GitError("git is not installed or not on PATH") from exc
42
+ except subprocess.TimeoutExpired as exc:
43
+ raise GitError(
44
+ f"git timed out: git {' '.join(args)} "
45
+ "(for large histories, try a smaller range or --blame-only)"
46
+ ) from exc
47
+ if proc.returncode != 0:
48
+ detail = (proc.stderr or proc.stdout or "").strip().splitlines()
49
+ raise GitError(f"git {' '.join(args)} failed: {detail[0] if detail else 'unknown error'}")
50
+ return proc.stdout
51
+
52
+
53
+ def find_repo_root(start: Path) -> Path:
54
+ """Return the repo root containing start, or raise GitError."""
55
+ out = run_git(start, ["rev-parse", "--show-toplevel"])
56
+ root = Path(out.strip())
57
+ if not root.is_dir():
58
+ raise GitError(f"not a git repository: {start}")
59
+ return root
60
+
61
+
62
+ def resolve_repo_file(repo: Path, file_arg: str) -> str:
63
+ """Resolve file_arg to a repo-relative path, verifying it is tracked.
64
+
65
+ file_arg may be absolute or relative to the caller's cwd. Returns
66
+ the repo-relative path (posix form) git expects.
67
+ """
68
+ candidate = Path(file_arg)
69
+ if not candidate.is_absolute():
70
+ candidate = Path.cwd() / candidate
71
+ candidate = candidate.resolve()
72
+ try:
73
+ rel = candidate.relative_to(repo.resolve())
74
+ except ValueError as exc:
75
+ raise GitError(f"file is outside this repository: {file_arg}") from exc
76
+ rel_posix = rel.as_posix()
77
+ tracked = run_git(repo, ["ls-files", "--", rel_posix]).strip()
78
+ if not tracked:
79
+ raise GitError(f"file is not tracked by git: {file_arg}")
80
+ return rel_posix
81
+
82
+
83
+ IGNORE_REVS_DEFAULT = ".git-blame-ignore-revs"
84
+
85
+
86
+ def ignore_revs_file(repo: Path) -> tuple[str | None, bool]:
87
+ """(revs file, already configured) for blame's ignore-revs list.
88
+
89
+ blame.ignoreRevsFile is applied by git itself; otherwise a
90
+ <repo>/.git-blame-ignore-revs (the GitHub convention) is passed
91
+ explicitly. (None, False) when neither exists.
92
+ """
93
+ try:
94
+ configured = run_git(repo, ["config", "--get", "blame.ignoreRevsFile"]).strip()
95
+ except GitError:
96
+ configured = ""
97
+ if configured:
98
+ return configured, True
99
+ if (repo / IGNORE_REVS_DEFAULT).is_file():
100
+ return IGNORE_REVS_DEFAULT, False
101
+ return None, False
102
+
103
+
104
+ def count_revs(path: Path) -> int:
105
+ """Revision lines in an ignore-revs file (comments/blanks excluded)."""
106
+ try:
107
+ text = path.read_text(encoding="utf-8", errors="replace")
108
+ except OSError:
109
+ return 0
110
+ return sum(1 for line in text.splitlines() if line.split("#", 1)[0].strip())
111
+
112
+
113
+ def blame_porcelain(
114
+ repo: Path, relpath: str, start: int, end: int, extra: list[str] | None = None
115
+ ) -> str:
116
+ """git blame --porcelain for a line range. -w ignores whitespace
117
+ differences; -C attributes lines moved from another file in the
118
+ same commit to their origin (labeled in output). extra carries
119
+ ignore-revs options."""
120
+ return run_git(
121
+ repo,
122
+ ["blame", "--porcelain", "-w", "-C", *(extra or []), "-L", f"{start},{end}", "--", relpath],
123
+ )
124
+
125
+
126
+ def split_message(message: str) -> tuple[str, str]:
127
+ """Split a raw commit message into (subject, body).
128
+
129
+ Subject is the FIRST LINE, body is the rest after one blank
130
+ separator line. This deliberately does NOT use git's %s/%b:
131
+ git defines %s as the first PARAGRAPH (lines joined with spaces),
132
+ so a message with no blank line after the first line ("fix bug
133
+ \\nmore detail") collapses into one space-joined subject and an
134
+ empty body — gitstory would then display a wall of text as the
135
+ "subject" and claim the reason is undocumented beyond it, when
136
+ the evidence was right there. First-line splitting keeps the
137
+ headline a headline and the detail detail, for every message
138
+ shape, blank line or not.
139
+ """
140
+ text = (message or "").rstrip("\n")
141
+ if not text:
142
+ return "", ""
143
+ lines = text.split("\n")
144
+ subject = lines[0]
145
+ body = "\n".join(lines[1:])
146
+ if body.startswith("\n"):
147
+ body = body[1:]
148
+ return subject, body
149
+
150
+
151
+ def line_history(repo: Path, relpath: str, start: int, end: int) -> str:
152
+ """git log -L for a line range: one record per commit that touched
153
+ the range, newest first, each with a range-scoped diff.
154
+
155
+ Record format: COMMIT<US>hash<US>author<US>date<US>full-message
156
+ <RS> then the diff (%B, raw message — see split_message for why
157
+ %s/%b is not used). -L follows renames, so a renamed file's
158
+ history still traces.
159
+ """
160
+ fmt = "COMMIT%x1f%H%x1f%an%x1f%ad%x1f%B%x1e"
161
+ return run_git(
162
+ repo,
163
+ ["log", f"--format={fmt}", "--date=iso-strict", "-L", f"{start},{end}:{relpath}"],
164
+ )
165
+
166
+
167
+ def commit_metadata(repo: Path, commit: str) -> dict:
168
+ """Author/date/subject/body for one commit (fallback when the -L
169
+ record for an introducing commit is missing, e.g. moved code)."""
170
+ fmt = "%H%x1f%an%x1f%ad%x1f%B"
171
+ out = run_git(repo, ["show", "-s", f"--format={fmt}", "--date=iso-strict", commit])
172
+ fields = out.strip("\n").split("\x1f")
173
+ if len(fields) != 4:
174
+ raise GitError(f"could not read commit metadata: {commit}")
175
+ subject, body = split_message(fields[3])
176
+ return {
177
+ "hash": fields[0],
178
+ "author": fields[1],
179
+ "date": fields[2],
180
+ "subject": subject,
181
+ "body": body,
182
+ }
183
+
184
+
185
+ def commit_files(repo: Path, commit: str) -> list[str]:
186
+ """Files changed by a commit (no renames resolved — raw paths).
187
+
188
+ --first-parent is a no-op for ordinary commits and the only sane
189
+ choice for merges: without it, `git show` on a merge yields a
190
+ combined diff whose file list is empty and whose diff format
191
+ would pollute the replaced-lines parse."""
192
+ out = run_git(repo, ["show", "--first-parent", "--name-only", "--format=", commit])
193
+ return [line for line in out.splitlines() if line.strip()]
194
+
195
+
196
+ def commit_diff_for_path(repo: Path, commit: str, relpath: str) -> str:
197
+ """Diff of one commit restricted to one path (empty if untouched)."""
198
+ return run_git(repo, ["show", "--first-parent", "--format=", commit, "--", relpath])
199
+
200
+
201
+ def parse_remote(repo: Path) -> tuple[str | None, str | None]:
202
+ """Return (host, 'owner/repo') for origin, else (None, None).
203
+
204
+ Any host with an owner/repo-shaped URL parses: github.com and
205
+ GitHub Enterprise hosts both work with gh (Enterprise via
206
+ GH_HOST). A non-GitHub remote (GitLab, etc.) also parses to a
207
+ slug, and its gh lookups simply fail best-effort into
208
+ "unresolved" — never a fabricated link.
209
+ """
210
+ try:
211
+ url = run_git(repo, ["remote", "get-url", "origin"]).strip()
212
+ except GitError:
213
+ return None, None
214
+ slug_m = re.search(r"[/:]([\w.-]+/[\w.-]+?)(?:\.git)?$", url)
215
+ if not slug_m:
216
+ return None, None
217
+ host_m = re.search(r"(?:@|://)([^:/]+)[:/]", url)
218
+ host = host_m.group(1) if host_m else None
219
+ return host, slug_m.group(1)
220
+
221
+
222
+ def parse_github_remote(repo: Path) -> str | None:
223
+ """Return 'owner/repo' for origin, else None (see parse_remote)."""
224
+ _host, slug = parse_remote(repo)
225
+ return slug
226
+
227
+
228
+ def gh_available() -> bool:
229
+ return shutil.which("gh") is not None
230
+
231
+
232
+ def _gh_json(args: list[str], timeout: int, host: str | None):
233
+ """Run a read-only gh command and parse its JSON stdout; None on ANY failure."""
234
+ import json
235
+ import os
236
+
237
+ env = dict(os.environ)
238
+ if host and host != "github.com":
239
+ env["GH_HOST"] = host
240
+ # Resolve via PATH/PATHEXT so a gh.cmd/.bat wrapper works on Windows too.
241
+ gh = shutil.which("gh")
242
+ if gh is None:
243
+ return None
244
+ try:
245
+ proc = subprocess.run(
246
+ [gh, *args],
247
+ capture_output=True,
248
+ text=True,
249
+ timeout=timeout,
250
+ stdin=subprocess.DEVNULL,
251
+ env=env,
252
+ )
253
+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
254
+ return None
255
+ if proc.returncode != 0:
256
+ return None
257
+ try:
258
+ return json.loads(proc.stdout)
259
+ except ValueError:
260
+ return None
261
+
262
+
263
+ def gh_commit_pull(
264
+ repo_slug: str, sha: str, timeout: int = 20, host: str | None = None
265
+ ) -> dict | None | bool:
266
+ """The PR that introduced a commit, via
267
+ `gh api repos/{slug}/commits/{sha}/pulls` (read-only).
268
+
269
+ Returns the PR dict, False when GitHub lists no PR for the commit,
270
+ or None when the lookup itself failed.
271
+ """
272
+ data = _gh_json(["api", f"repos/{repo_slug}/commits/{sha}/pulls"], timeout, host)
273
+ if not isinstance(data, list):
274
+ return None
275
+ pull = next((p for p in data if isinstance(p, dict) and "number" in p), None)
276
+ if pull is None:
277
+ return False
278
+ return {
279
+ "number": pull["number"],
280
+ "title": pull.get("title"),
281
+ "state": "MERGED"
282
+ if pull.get("merged_at")
283
+ else str(pull.get("state") or "").upper() or None,
284
+ "url": pull.get("html_url"),
285
+ "body": pull.get("body") or "",
286
+ "reviews": [],
287
+ }
288
+
289
+
290
+ def gh_view(
291
+ repo_slug: str, kind: str, number: int, timeout: int = 20, host: str | None = None
292
+ ) -> dict | None:
293
+ """Best-effort read-only gh lookup. Returns a dict with title,
294
+ state, url — or None on ANY failure (missing gh, no auth, no such
295
+ PR/issue, timeout). Never raises: enrichment must never break the
296
+ narrative. For non-github.com hosts, GH_HOST routes gh to the
297
+ Enterprise host."""
298
+ fields = "title,state,url,body,reviews" if kind == "pr" else "title,state,url"
299
+ data = _gh_json(
300
+ [kind, "view", str(number), "--json", fields, "--repo", repo_slug], timeout, host
301
+ )
302
+ if not isinstance(data, dict) or "title" not in data:
303
+ return None
304
+ found = {"title": data["title"], "state": data.get("state"), "url": data.get("url")}
305
+ if kind == "pr":
306
+ found["body"] = data.get("body") or ""
307
+ found["reviews"] = [
308
+ {
309
+ "author": ((r.get("author") or {}).get("login") or "unknown"),
310
+ "body": r.get("body") or "",
311
+ }
312
+ for r in (data.get("reviews") or [])
313
+ if isinstance(r, dict)
314
+ ]
315
+ return found
316
+
317
+
318
+ def importers(repo: Path, relpath: str) -> list[str]:
319
+ """Files that import this module, via read-only `git grep`.
320
+
321
+ HEURISTIC, labeled as such wherever shown: the dotted path from
322
+ the repo root (pkg/auth.py -> pkg.auth) is grepped in import
323
+ statements, plus the last segment as a relative import. A match
324
+ is evidence of coupling, not proof these lines are covered, and
325
+ a common top-level name (utils.py) will match unrelated
326
+ importers — which is why the list is capped in text output and
327
+ full in --json. The target file itself is excluded. Returns []
328
+ when nothing matches; raises GitError only on a real git failure
329
+ (grep exit 1 means "no matches", not an error).
330
+ """
331
+ stem = relpath.rsplit(".", 1)[0] if "." in relpath.rsplit("/", 1)[-1] else relpath
332
+ dotted = stem.replace("/", ".")
333
+ last = dotted.rsplit(".", 1)[-1]
334
+ patterns = [f"import {dotted}", f"from {dotted} import"]
335
+ if last != dotted:
336
+ patterns.append(f"from .{last} import")
337
+ # -w matters: without it, "import cli" would match "import click"
338
+ # and "import pkg.auth" would match "import pkg.auth2" — substring
339
+ # false positives on exactly the short names that need care.
340
+ args = ["grep", "-l", "-I", "-w", "-F"]
341
+ for pattern in patterns:
342
+ args += ["-e", pattern]
343
+ args += ["--", "."]
344
+ try:
345
+ proc = subprocess.run(
346
+ ["git", "-C", str(repo)] + args,
347
+ capture_output=True,
348
+ text=True,
349
+ errors="replace",
350
+ timeout=30,
351
+ )
352
+ except FileNotFoundError as exc:
353
+ raise GitError("git is not installed or not on PATH") from exc
354
+ except subprocess.TimeoutExpired as exc:
355
+ raise GitError("git grep timed out") from exc
356
+ if proc.returncode == 1:
357
+ return []
358
+ if proc.returncode != 0:
359
+ detail = (proc.stderr or "").strip().splitlines()
360
+ raise GitError(f"git grep failed: {detail[0] if detail else 'unknown error'}")
361
+ found = [
362
+ line.strip()
363
+ for line in proc.stdout.splitlines()
364
+ if line.strip() and line.strip() != relpath
365
+ ]
366
+ return sorted(set(found))