graphlore 0.7.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.
graphlore/history.py ADDED
@@ -0,0 +1,198 @@
1
+ """Files that change together, read from the project's git history.
2
+
3
+ Two files that keep changing in the same commits are coupled whether or not
4
+ the code says so: a schema and the query that reads it, a handler and the
5
+ client that calls it, two modules sharing a convention. This is code-maat's
6
+ measure, at file level: per file the commits that touch it (``revs``), per pair
7
+ the commits that touch both (``shared``) and their ``degree`` —
8
+ ``shared / ((revs a + revs b) / 2)``. A pair is coupled from 3 shared commits
9
+ and a degree of 0.3.
10
+
11
+ The history is read with one local ``git log`` (no network), the last
12
+ 1000 commits that are not merges, from the project directory down
13
+ (``--relative``); renames are followed to the file's current name, and a file
14
+ git no longer tracks is left out. A commit that touches more than 30 files (a
15
+ reformat, a mass rename, a vendored update) says nothing about which of them
16
+ belong together and is skipped. A shallow clone, or fewer than 10 commits, is
17
+ reported as such: no coupling is then no finding.
18
+
19
+ The result is cached per project directory and ``HEAD``, so a new commit is
20
+ read on the next call and nothing else is.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import subprocess
26
+ from dataclasses import dataclass, field
27
+ from itertools import combinations
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from . import config
32
+
33
+ MAX_COMMITS = 1000
34
+ BULK_FILES = 30
35
+ MIN_SHARED = 3
36
+ MIN_DEGREE = 0.3
37
+ MIN_COMMITS = 10
38
+
39
+ _HISTORY_CACHE: dict[tuple[str, str], History] = {}
40
+ _HISTORY_CACHE_MAX = 8
41
+
42
+
43
+ @dataclass
44
+ class History:
45
+ """What the history says about files changing together."""
46
+
47
+ commits: int = 0
48
+ shallow: bool = False
49
+ skipped_bulk: int = 0
50
+ head: str = ""
51
+ # why there is no usable history ("not a git repository", …); "" when read
52
+ reason: str = ""
53
+ revs: dict[str, int] = field(default_factory=dict)
54
+ shared: dict[tuple[str, str], int] = field(default_factory=dict)
55
+
56
+ @property
57
+ def usable(self) -> bool:
58
+ return not self.reason and self.commits >= MIN_COMMITS
59
+
60
+ def degree(self, a: str, b: str) -> float:
61
+ n = self.shared.get((a, b) if a < b else (b, a), 0)
62
+ mean = (self.revs.get(a, 0) + self.revs.get(b, 0)) / 2
63
+ return n / mean if mean else 0.0
64
+
65
+ def coupled(self, a: str, b: str) -> tuple[int, float] | None:
66
+ """(shared commits, degree) when the two files change together."""
67
+ if a == b:
68
+ return None
69
+ n = self.shared.get((a, b) if a < b else (b, a), 0)
70
+ if n < MIN_SHARED:
71
+ return None
72
+ d = self.degree(a, b)
73
+ return (n, d) if d >= MIN_DEGREE else None
74
+
75
+ def coupled_pairs(self) -> list[tuple[str, str, int, float]]:
76
+ """Every coupled pair, strongest first."""
77
+ out = []
78
+ for (a, b), n in self.shared.items():
79
+ if n < MIN_SHARED:
80
+ continue
81
+ d = self.degree(a, b)
82
+ if d >= MIN_DEGREE:
83
+ out.append((a, b, n, d))
84
+ out.sort(key=lambda r: (-r[3], -r[2], r[0], r[1]))
85
+ return out
86
+
87
+ def partners(self, f: str) -> list[tuple[str, int, float]]:
88
+ """The files `f` changes together with, strongest first."""
89
+ out = []
90
+ for (a, b), n in self.shared.items():
91
+ if f not in (a, b) or n < MIN_SHARED:
92
+ continue
93
+ other = b if a == f else a
94
+ d = self.degree(a, b)
95
+ if d >= MIN_DEGREE:
96
+ out.append((other, n, d))
97
+ out.sort(key=lambda r: (-r[2], -r[1], r[0]))
98
+ return out
99
+
100
+ def payload(self) -> dict[str, Any]:
101
+ out: dict[str, Any] = {
102
+ "commits": self.commits, "shallow": self.shallow,
103
+ "skipped_bulk": self.skipped_bulk,
104
+ }
105
+ note = self.note()
106
+ if note:
107
+ out["note"] = note
108
+ return out
109
+
110
+ def note(self) -> str:
111
+ """Why the history cannot show what changes together; "" when it can."""
112
+ if self.reason:
113
+ return f"no history read ({self.reason}): files changing together are not known"
114
+ if self.shallow and self.commits < MIN_COMMITS:
115
+ return (f"a shallow clone with {self.commits} commit(s): files changing "
116
+ "together are not known (fetch more history: git fetch --deepen=1000)")
117
+ if self.commits < MIN_COMMITS:
118
+ return (f"only {self.commits} commit(s) of history: too few to tell which "
119
+ "files change together")
120
+ return ""
121
+
122
+
123
+ def _git(args: list[str], cwd: Path, timeout: int = 30) -> str | None:
124
+ try:
125
+ proc = subprocess.run(
126
+ ["git", *args], cwd=str(cwd), capture_output=True, text=True,
127
+ encoding="utf-8", errors="replace", timeout=timeout,
128
+ )
129
+ except Exception:
130
+ return None
131
+ return proc.stdout if proc.returncode == 0 else None
132
+
133
+
134
+ _Counts = tuple[int, int, dict[str, int], dict[tuple[str, str], int]]
135
+
136
+
137
+ def _parse(log: str, tracked: set[str]) -> _Counts:
138
+ """(commits, bulk commits skipped, revs, shared) from `git log --name-status`
139
+ output, newest commit first."""
140
+ current: dict[str, str] = {} # a name a file had once -> its name now
141
+ commits = bulk = 0
142
+ revs: dict[str, int] = {}
143
+ shared: dict[tuple[str, str], int] = {}
144
+ for record in log.split("\x1e"):
145
+ lines = [ln for ln in record.splitlines() if ln.strip()]
146
+ if not lines:
147
+ continue
148
+ files: set[str] = set()
149
+ for ln in lines[1:]:
150
+ parts = ln.split("\t")
151
+ status = parts[0][:1]
152
+ if status in ("R", "C") and len(parts) >= 3:
153
+ old, new = parts[1], parts[2]
154
+ now = current.get(new, new)
155
+ files.add(now)
156
+ if status == "R":
157
+ # older commits name the file by its old path
158
+ current[old] = now
159
+ elif len(parts) >= 2:
160
+ files.add(current.get(parts[1], parts[1]))
161
+ files &= tracked
162
+ commits += 1
163
+ if len(files) > BULK_FILES:
164
+ bulk += 1
165
+ continue
166
+ for f in files:
167
+ revs[f] = revs.get(f, 0) + 1
168
+ for a, b in combinations(sorted(files), 2):
169
+ shared[(a, b)] = shared.get((a, b), 0) + 1
170
+ return commits, bulk, revs, shared
171
+
172
+
173
+ def history(project_dir: Path | None = None) -> History:
174
+ """The co-change history of the project directory (cached on its HEAD)."""
175
+ root = Path(project_dir or config.PROJECT_DIR)
176
+ head = (_git(["rev-parse", "HEAD"], root, timeout=10) or "").strip()
177
+ if not head:
178
+ return History(reason="not a git repository, or no commit yet")
179
+ key = (str(root.resolve()), head)
180
+ cached = _HISTORY_CACHE.get(key)
181
+ if cached is not None:
182
+ return cached
183
+ shallow = (_git(["rev-parse", "--is-shallow-repository"], root, timeout=10)
184
+ or "").strip() == "true"
185
+ log = _git(["log", "--no-merges", f"-n{MAX_COMMITS}", "--name-status", "-M",
186
+ "--format=%x1e%H", "--relative", "--", "."], root)
187
+ files = _git(["ls-files", "-z"], root)
188
+ if log is None or files is None:
189
+ out = History(head=head, shallow=shallow, reason="git log failed")
190
+ else:
191
+ tracked = {f for f in files.split("\0") if f}
192
+ commits, bulk, revs, shared = _parse(log, tracked)
193
+ out = History(commits=commits, shallow=shallow, skipped_bulk=bulk, head=head,
194
+ revs=revs, shared=shared)
195
+ if len(_HISTORY_CACHE) >= _HISTORY_CACHE_MAX:
196
+ _HISTORY_CACHE.pop(next(iter(_HISTORY_CACHE)), None)
197
+ _HISTORY_CACHE[key] = out
198
+ return out