git-janitor 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_janitor/git.py ADDED
@@ -0,0 +1,359 @@
1
+ from collections.abc import Sequence
2
+ from dataclasses import dataclass
3
+ from datetime import UTC, datetime
4
+ from pathlib import Path
5
+ import subprocess
6
+ from subprocess import CompletedProcess
7
+
8
+ from git_janitor.model import Branch, Commit, Worktree
9
+
10
+
11
+ class GitError(RuntimeError):
12
+ pass
13
+
14
+
15
+ def _git(args: Sequence[str], cwd: Path, input: str | None = None) -> CompletedProcess[str]:
16
+ try:
17
+ return subprocess.run(
18
+ ["git", *args],
19
+ cwd=cwd,
20
+ input=input,
21
+ capture_output=True,
22
+ text=True,
23
+ errors="surrogateescape",
24
+ check=False,
25
+ )
26
+ except FileNotFoundError as exc:
27
+ if not cwd.is_dir():
28
+ raise GitError(f"Directory does not exist: {cwd}") from exc
29
+ raise GitError("git is not installed.") from exc
30
+
31
+
32
+ def run_git(*args: str, cwd: Path, input: str | None = None) -> str:
33
+ result = _git(args, cwd, input)
34
+ if result.returncode != 0:
35
+ raise GitError(f"git {' '.join(args)} failed: {result.stderr.strip()}")
36
+ return result.stdout
37
+
38
+
39
+ def succeeds(*args: str, cwd: Path) -> bool:
40
+ return _git(args, cwd).returncode == 0
41
+
42
+
43
+ def list_branches(cwd: Path) -> list[Branch]:
44
+ output = run_git(
45
+ "for-each-ref",
46
+ "--format=%(refname:lstrip=2)%00%(objectname)%00%(upstream:remotename)"
47
+ "%00%(upstream:remoteref)%00%(upstream:track)",
48
+ "refs/heads",
49
+ cwd=cwd,
50
+ )
51
+ branches = []
52
+ for line in _lines(output):
53
+ name, tip, remote, remote_ref, track = line.split("\0")
54
+ has_remote = remote not in ("", ".")
55
+ branches.append(
56
+ Branch(
57
+ name=name,
58
+ tip=tip,
59
+ upstream_remote=remote if has_remote else None,
60
+ upstream_branch=remote_ref.removeprefix("refs/heads/") if has_remote else None,
61
+ upstream_gone=track == "[gone]",
62
+ )
63
+ )
64
+ return branches
65
+
66
+
67
+ def _lines(output: str) -> list[str]:
68
+ """Split git output on newlines only, unlike `str.splitlines`."""
69
+ return [line for line in output.split("\n") if line]
70
+
71
+
72
+ def is_ancestor(ancestor: str, descendant: str, cwd: Path) -> bool:
73
+ result = _git(["merge-base", "--is-ancestor", ancestor, descendant], cwd)
74
+ if result.returncode not in (0, 1):
75
+ raise GitError(f"git merge-base --is-ancestor failed: {result.stderr.strip()}")
76
+ return result.returncode == 0
77
+
78
+
79
+ def reflog_time(ref: str, cwd: Path) -> datetime | None:
80
+ """When `ref`'s reflog was last written, if it has one."""
81
+ result = _git(["log", "-g", "-1", "--date=unix", "--format=%gd", ref], cwd)
82
+ selector = result.stdout.strip()
83
+ if result.returncode != 0 or not selector.endswith("}"):
84
+ return None
85
+ return datetime.fromtimestamp(int(selector.rsplit("@{", 1)[1][:-1]), tz=UTC)
86
+
87
+
88
+ def worktree_activity(worktree: Worktree, repo: Path) -> datetime | None:
89
+ """When a linked worktree was created or its HEAD last moved.
90
+
91
+ Read from the worktree's admin directory, so it works when the worktree's directory is
92
+ missing. Other files there, like the index, are rewritten by ordinary commands such as
93
+ `git status`.
94
+ """
95
+ if worktree.admin_dir is None:
96
+ return None
97
+ times = [reflog_time(f"worktrees/{worktree.admin_dir.name}/HEAD", cwd=repo)]
98
+ try:
99
+ created = (worktree.admin_dir / "commondir").stat().st_mtime
100
+ times.append(datetime.fromtimestamp(created, tz=UTC))
101
+ except OSError:
102
+ pass
103
+ return max((t for t in times if t is not None), default=None)
104
+
105
+
106
+ def ref_exists(ref: str, cwd: Path) -> bool:
107
+ return succeeds("rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}", cwd=cwd)
108
+
109
+
110
+ def commits_between(base: str, tip: str, cwd: Path, exclude: str | None = None) -> list[Commit]:
111
+ """Commits reachable from `tip` but not from `base` or `exclude`, oldest first."""
112
+ excluded = [f"^{base}"] + ([f"^{exclude}"] if exclude else [])
113
+ output = run_git("log", "--reverse", "--format=%H%x00%s", tip, *excluded, "--", cwd=cwd)
114
+ return [Commit(*line.split("\0", 1)) for line in _lines(output)]
115
+
116
+
117
+ def tree_id(commit: str, cwd: Path) -> str:
118
+ """The ID of `commit`'s tree, read from the commit object alone."""
119
+ return run_git(
120
+ "log", "-1", "--no-show-signature", "--format=%T", commit, "--", cwd=cwd
121
+ ).strip()
122
+
123
+
124
+ def has_commit(sha: str, cwd: Path) -> bool:
125
+ return succeeds("cat-file", "-e", f"{sha}^{{commit}}", cwd=cwd)
126
+
127
+
128
+ def fetch_objects(remote: str, ref: str, cwd: Path) -> None:
129
+ """Fetch the objects for `ref` without creating any local refs."""
130
+ run_git("fetch", "--quiet", "--no-write-fetch-head", remote, ref, cwd=cwd)
131
+
132
+
133
+ def remote_url(remote: str, cwd: Path) -> str:
134
+ return run_git("remote", "get-url", remote, cwd=cwd).strip()
135
+
136
+
137
+ def fetch(remote: str, cwd: Path) -> None:
138
+ run_git("fetch", "--prune", remote, cwd=cwd)
139
+
140
+
141
+ def list_worktrees(cwd: Path) -> list[Worktree]:
142
+ output = run_git("worktree", "list", "--porcelain", "-z", cwd=cwd)
143
+ admin_dirs = _worktree_admin_dirs(cwd)
144
+ worktrees = []
145
+ for record in output.split("\0\0"):
146
+ if not record.strip("\0"):
147
+ continue
148
+ fields = {}
149
+ for line in record.split("\0"):
150
+ key, _, value = line.partition(" ")
151
+ fields[key] = value
152
+ path = Path(fields["worktree"])
153
+ branch = fields.get("branch")
154
+ if branch:
155
+ branch = branch.removeprefix("refs/heads/")
156
+ elif "detached" in fields and "prunable" not in fields and path.is_dir():
157
+ branch = _in_progress_branch(path)
158
+ worktrees.append(
159
+ Worktree(
160
+ path=path,
161
+ head=fields.get("HEAD", ""),
162
+ branch=branch,
163
+ is_main=not worktrees,
164
+ locked="locked" in fields,
165
+ prunable="prunable" in fields,
166
+ admin_dir=admin_dirs.get(path.resolve()),
167
+ )
168
+ )
169
+ return worktrees
170
+
171
+
172
+ def _worktree_admin_dirs(cwd: Path) -> dict[Path, Path]:
173
+ """Map linked worktree paths to their admin directories."""
174
+ common_dir = cwd / run_git("rev-parse", "--git-common-dir", cwd=cwd).strip()
175
+ admin_dirs = {}
176
+ for admin_dir in (common_dir / "worktrees").glob("*/"):
177
+ try:
178
+ dot_git = Path((admin_dir / "gitdir").read_text().strip())
179
+ except OSError:
180
+ continue
181
+ admin_dirs[dot_git.parent.resolve()] = admin_dir.resolve()
182
+ return admin_dirs
183
+
184
+
185
+ def _in_progress_branch(worktree: Path) -> str | None:
186
+ """The branch being rebased or bisected in a worktree, which git lists as detached."""
187
+ rebase_merge, rebase_apply, bisect_start = _lines(
188
+ run_git(
189
+ "rev-parse",
190
+ "--git-path",
191
+ "rebase-merge/head-name",
192
+ "--git-path",
193
+ "rebase-apply/head-name",
194
+ "--git-path",
195
+ "BISECT_START",
196
+ cwd=worktree,
197
+ )
198
+ )
199
+ for head_name in (worktree / rebase_merge, worktree / rebase_apply):
200
+ if head_name.is_file():
201
+ ref = head_name.read_text().strip()
202
+ if ref.startswith("refs/heads/"):
203
+ return ref.removeprefix("refs/heads/")
204
+ start = worktree / bisect_start
205
+ if start.is_file():
206
+ name = start.read_text().strip()
207
+ if succeeds("show-ref", "--verify", "--quiet", f"refs/heads/{name}", cwd=worktree):
208
+ return name
209
+ return None
210
+
211
+
212
+ @dataclass(frozen=True, slots=True)
213
+ class WorktreeStatus:
214
+ changed: tuple[str, ...]
215
+ untracked: tuple[str, ...]
216
+ ignored: tuple[str, ...]
217
+ """Ignored paths. A wholly ignored directory is one entry ending in `/`."""
218
+
219
+
220
+ def worktree_status(cwd: Path) -> WorktreeStatus:
221
+ output = run_git(
222
+ "--no-optional-locks",
223
+ "status",
224
+ "--porcelain=v2",
225
+ "-z",
226
+ "--untracked-files=normal",
227
+ "--ignored=matching",
228
+ cwd=cwd,
229
+ )
230
+ changed, untracked, ignored = [], [], []
231
+ tokens = iter(output.split("\0"))
232
+ for token in tokens:
233
+ match token[:1]:
234
+ case "1":
235
+ changed.append(token.split(" ", 8)[8])
236
+ case "2":
237
+ changed.append(token.split(" ", 9)[9])
238
+ next(tokens) # Original path of a rename or copy
239
+ case "u":
240
+ changed.append(token.split(" ", 10)[10])
241
+ case "?":
242
+ untracked.append(token[2:])
243
+ case "!":
244
+ ignored.append(token[2:])
245
+ return WorktreeStatus(
246
+ changed=tuple(changed), untracked=tuple(untracked), ignored=tuple(ignored)
247
+ )
248
+
249
+
250
+ def skipped_changes(cwd: Path) -> list[str]:
251
+ """Tracked files that `git status` doesn't check, because they're marked skip-worktree or
252
+ assume-unchanged, and that may differ from the index.
253
+
254
+ Only regular files are compared with the index; anything else that exists counts as changed,
255
+ as do paths that can't be passed to `hash-object` safely.
256
+ """
257
+ entries = {} # Path to index blob, for regular files
258
+ changed = []
259
+ for entry in run_git("ls-files", "-v", "-s", "-z", cwd=cwd).split("\0"):
260
+ if not entry or not (entry[0] == "S" or entry[0].islower()):
261
+ continue
262
+ info, path = entry.split("\t", 1)
263
+ _, mode, blob, _ = info.split(" ")
264
+ # hash-object reads paths one per line and unquotes those starting with `"`, and reading
265
+ # git's output as text turns `\r` into `\n`
266
+ if "\n" in path or path.startswith('"'):
267
+ changed.append(path)
268
+ continue
269
+ file = cwd / path
270
+ if not file.exists(follow_symlinks=False):
271
+ continue
272
+ # hash-object follows symlinks
273
+ if file.is_file(follow_symlinks=False) and mode in ("100644", "100755"):
274
+ entries[path] = blob
275
+ else:
276
+ changed.append(path)
277
+ if entries:
278
+ hashes = _lines(run_git("hash-object", "--stdin-paths", cwd=cwd, input="\n".join(entries)))
279
+ changed.extend(
280
+ path for (path, blob), oid in zip(entries.items(), hashes, strict=True) if blob != oid
281
+ )
282
+ return sorted(changed)
283
+
284
+
285
+ def populated_submodules(cwd: Path) -> list[str]:
286
+ """Submodules in the index whose directories have a `.git`, as git checks before removing a
287
+ worktree.
288
+ """
289
+ paths = set()
290
+ for entry in run_git("ls-files", "-s", "-z", cwd=cwd).split("\0"):
291
+ if not entry.startswith("160000 "):
292
+ continue
293
+ path = entry.split("\t", 1)[1]
294
+ if (cwd / path / ".git").exists():
295
+ paths.add(path)
296
+ return sorted(paths)
297
+
298
+
299
+ def has_submodule_git_dirs(worktree: Worktree) -> bool:
300
+ """Whether the worktree's git directory has a `modules` directory, which holds the git
301
+ directories of its submodules.
302
+
303
+ A linked worktree's is read from its admin directory, so it works when the worktree's
304
+ directory is missing.
305
+ """
306
+ git_dir = worktree.admin_dir
307
+ if git_dir is None:
308
+ if not worktree.path.exists():
309
+ raise ValueError(f"git directory not found for worktree {worktree.path}")
310
+ git_dir = Path(run_git("rev-parse", "--absolute-git-dir", cwd=worktree.path).strip())
311
+ return (git_dir / "modules").is_dir()
312
+
313
+
314
+ def ignore_sources(paths: Sequence[str], cwd: Path) -> dict[str, str]:
315
+ """Map each ignored path to the ignore file whose rule matched it."""
316
+ # A `./` prefix stops check-ignore from reading paths like `:x` as pathspec magic
317
+ result = _git(
318
+ ["check-ignore", "-v", "-z", "--stdin"], cwd, input="\0".join(f"./{p}" for p in paths)
319
+ )
320
+ if result.returncode == 1:
321
+ return {}
322
+ if result.returncode != 0:
323
+ raise GitError(f"git check-ignore failed: {result.stderr.strip()}")
324
+ fields = result.stdout.split("\0")
325
+ return {fields[i + 3].removeprefix("./"): fields[i] for i in range(0, len(fields) - 3, 4)}
326
+
327
+
328
+ def tracked_files(paths: Sequence[str], cwd: Path) -> set[str]:
329
+ """The subset of `paths` that git tracks."""
330
+ if not paths:
331
+ return set()
332
+ output = run_git("--literal-pathspecs", "ls-files", "-z", "--", *paths, cwd=cwd)
333
+ return {path for path in output.split("\0") if path}
334
+
335
+
336
+ def config_get_all(key: str, cwd: Path) -> list[str]:
337
+ return _lines(_git(["config", "--get-all", key], cwd).stdout)
338
+
339
+
340
+ IN_PROGRESS_MARKERS = {
341
+ "rebase-merge": "rebase",
342
+ "rebase-apply": "rebase",
343
+ "MERGE_HEAD": "merge",
344
+ "CHERRY_PICK_HEAD": "cherry-pick",
345
+ "REVERT_HEAD": "revert",
346
+ "BISECT_LOG": "bisect",
347
+ }
348
+
349
+
350
+ def operations_in_progress(cwd: Path) -> list[str]:
351
+ """Names of operations (merge, rebase, ...) in progress in the worktree at `cwd`."""
352
+ args = [arg for marker in IN_PROGRESS_MARKERS for arg in ("--git-path", marker)]
353
+ paths = _lines(run_git("rev-parse", *args, cwd=cwd))
354
+ operations = []
355
+ for marker, path in zip(IN_PROGRESS_MARKERS, paths, strict=True):
356
+ operation = IN_PROGRESS_MARKERS[marker]
357
+ if (cwd / path).exists() and operation not in operations:
358
+ operations.append(operation)
359
+ return operations
git_janitor/github.py ADDED
@@ -0,0 +1,166 @@
1
+ from collections.abc import Callable, Sequence
2
+ from dataclasses import dataclass, field
3
+ import itertools
4
+ import json
5
+ import re
6
+ import subprocess
7
+ from typing import Protocol
8
+ from urllib.parse import urlparse
9
+
10
+ from git_janitor.model import PullRequest, PullRequestState
11
+
12
+
13
+ class GitHubError(RuntimeError):
14
+ pass
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class GitHubData:
19
+ name_with_owner: str
20
+ default_branch: str
21
+ pull_requests: dict[str, list[PullRequest]] = field(default_factory=dict)
22
+ """Pull requests keyed by head branch name."""
23
+ pull_requests_by_commit: dict[str, list[PullRequest]] = field(default_factory=dict)
24
+ """Pull requests that GitHub associates with each commit."""
25
+
26
+
27
+ class GitHubClient(Protocol):
28
+ def fetch(
29
+ self, remote_url: str, head_names: Sequence[str], commits: Sequence[str] = ()
30
+ ) -> GitHubData: ...
31
+
32
+
33
+ PULL_REQUESTS_PER_HEAD = 20
34
+
35
+ PULL_REQUEST_FIELDS = (
36
+ "number url state baseRefName headRefName headRefOid mergeCommit { oid } "
37
+ "baseRepository { nameWithOwner }"
38
+ )
39
+
40
+
41
+ def run_gh(args: Sequence[str]) -> str:
42
+ try:
43
+ result = subprocess.run(["gh", *args], capture_output=True, text=True, check=False)
44
+ except FileNotFoundError as exc:
45
+ raise GitHubError("GitHub CLI ('gh') is not installed.") from exc
46
+ if result.returncode != 0:
47
+ raise GitHubError(f"gh {args[0]} failed: {result.stderr.strip()}")
48
+ return result.stdout
49
+
50
+
51
+ class GhGitHubClient:
52
+ """Queries GitHub's GraphQL API through the `gh` CLI, which handles authentication."""
53
+
54
+ def __init__(
55
+ self, run_gh: Callable[[Sequence[str]], str] = run_gh, batch_size: int = 50
56
+ ) -> None:
57
+ self.run_gh = run_gh
58
+ self.batch_size = batch_size
59
+
60
+ def fetch(
61
+ self, remote_url: str, head_names: Sequence[str], commits: Sequence[str] = ()
62
+ ) -> GitHubData:
63
+ host, owner, name = parse_remote_url(remote_url)
64
+ items = [("head", head) for head in head_names] + [("commit", sha) for sha in commits]
65
+ batches = list(itertools.batched(items, self.batch_size)) or [()]
66
+ by_head: dict[str, list[PullRequest]] = {}
67
+ by_commit: dict[str, list[PullRequest]] = {}
68
+ for batch in batches:
69
+ repository = self._query(host, owner, name, batch)
70
+ try:
71
+ name_with_owner = repository["nameWithOwner"]
72
+ default_branch_ref = repository["defaultBranchRef"]
73
+ for i, (kind, value) in enumerate(batch):
74
+ if kind == "head":
75
+ nodes = repository[f"pr{i}"]["nodes"]
76
+ by_head[value] = _pull_requests(nodes, name_with_owner)
77
+ else:
78
+ commit = repository[f"c{i}"]
79
+ nodes = commit["associatedPullRequests"]["nodes"] if commit else []
80
+ by_commit[value] = _pull_requests(nodes, name_with_owner)
81
+ except (KeyError, TypeError, ValueError) as exc:
82
+ raise GitHubError(f"Unexpected response from GitHub: {exc!r}") from exc
83
+ if not default_branch_ref:
84
+ raise GitHubError(f"{name_with_owner} has no default branch.")
85
+ return GitHubData(
86
+ name_with_owner=name_with_owner,
87
+ default_branch=default_branch_ref["name"],
88
+ pull_requests=by_head,
89
+ pull_requests_by_commit=by_commit,
90
+ )
91
+
92
+ def _query(self, host: str, owner: str, name: str, items: Sequence[tuple[str, str]]) -> dict:
93
+ pull_requests = (
94
+ f"first: {PULL_REQUESTS_PER_HEAD}, orderBy: {{field: CREATED_AT, direction: DESC}}"
95
+ )
96
+ nodes = f"{{ nodes {{ {PULL_REQUEST_FIELDS} }} }}"
97
+ variables = ""
98
+ aliases = ""
99
+ for i, (kind, _) in enumerate(items):
100
+ if kind == "head":
101
+ variables += f", $head{i}: String!"
102
+ aliases += f"pr{i}: pullRequests(headRefName: $head{i}, {pull_requests}) {nodes} "
103
+ else:
104
+ variables += f", $commit{i}: GitObjectID!"
105
+ aliases += (
106
+ f"c{i}: object(oid: $commit{i}) {{ ... on Commit {{ "
107
+ f"associatedPullRequests({pull_requests}) {nodes} }} }} "
108
+ )
109
+ query = (
110
+ f"query($owner: String!, $name: String!{variables}) {{ "
111
+ f"repository(owner: $owner, name: $name) {{ "
112
+ f"nameWithOwner defaultBranchRef {{ name }} {aliases}}} }}"
113
+ )
114
+ args = ["api", "graphql", "--hostname", host, "-f", f"query={query}"]
115
+ args += ["-f", f"owner={owner}", "-f", f"name={name}"]
116
+ for i, (kind, value) in enumerate(items):
117
+ args += ["-f", f"{kind}{i}={value}"]
118
+ try:
119
+ response = json.loads(self.run_gh(args))
120
+ except json.JSONDecodeError as exc:
121
+ raise GitHubError(f"Unexpected response from GitHub: {exc}") from exc
122
+ if response.get("errors"):
123
+ raise GitHubError(f"GitHub API error: {response['errors']}")
124
+ repository = response.get("data", {}).get("repository")
125
+ if repository is None:
126
+ raise GitHubError(f"Repository {owner}/{name} not found on {host}.")
127
+ return repository
128
+
129
+
130
+ SCP_LIKE_URL = re.compile(r"^(?:[^@/]+@)?(?P<host>[^:/]+):(?P<path>[^/].*)$")
131
+
132
+
133
+ def parse_remote_url(url: str) -> tuple[str, str, str]:
134
+ """Parse a GitHub remote URL into (host, owner, repository name)."""
135
+ if "://" in url:
136
+ parsed = urlparse(url)
137
+ host, path = parsed.hostname, parsed.path
138
+ elif match := SCP_LIKE_URL.match(url):
139
+ host, path = match["host"], match["path"]
140
+ else:
141
+ host, path = None, ""
142
+ parts = path.strip("/").removesuffix(".git").split("/")
143
+ if not host or len(parts) != 2 or not all(parts):
144
+ raise GitHubError(f"Remote URL is not a GitHub repository: {url}")
145
+ return host, parts[0], parts[1]
146
+
147
+
148
+ def _pull_requests(nodes: list[dict], name_with_owner: str) -> list[PullRequest]:
149
+ """Parse pull request nodes, keeping only those into the repository `name_with_owner`.
150
+
151
+ A commit's associated pull requests can include ones in other repositories of its fork
152
+ network.
153
+ """
154
+ return [
155
+ PullRequest(
156
+ number=node["number"],
157
+ url=node["url"],
158
+ state=PullRequestState(node["state"]),
159
+ base=node["baseRefName"],
160
+ head_name=node["headRefName"],
161
+ head_oid=node["headRefOid"],
162
+ merge_oid=node["mergeCommit"] and node["mergeCommit"]["oid"],
163
+ )
164
+ for node in nodes
165
+ if node["baseRepository"]["nameWithOwner"].lower() == name_with_owner.lower()
166
+ ]