changemap 1.0.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.
- changemap/__init__.py +3 -0
- changemap/__main__.py +7 -0
- changemap/cache.py +308 -0
- changemap/cli.py +306 -0
- changemap/delta.py +454 -0
- changemap/doctor.py +131 -0
- changemap/errors.py +5 -0
- changemap/feedback.py +71 -0
- changemap/flows.py +368 -0
- changemap/git.py +223 -0
- changemap/naming.py +72 -0
- changemap/others.py +119 -0
- changemap/outline.py +301 -0
- changemap/page.html +6530 -0
- changemap/page.py +43 -0
- changemap/parallel.py +249 -0
- changemap/pipeline.py +111 -0
- changemap/plan.py +334 -0
- changemap/py.typed +0 -0
- changemap/reader.py +753 -0
- changemap/readers/__init__.py +139 -0
- changemap/readers/_skip.py +50 -0
- changemap/readers/_treesitter.py +171 -0
- changemap/readers/base.py +170 -0
- changemap/readers/cpp.py +932 -0
- changemap/readers/html.py +333 -0
- changemap/readers/java.py +737 -0
- changemap/readers/python.py +894 -0
- changemap/readers/rust.py +1224 -0
- changemap/readers/typescript.py +1313 -0
- changemap/remote.py +767 -0
- changemap/scope.py +137 -0
- changemap/snapshot.py +251 -0
- changemap/watch.py +469 -0
- changemap-1.0.0.dist-info/METADATA +347 -0
- changemap-1.0.0.dist-info/RECORD +39 -0
- changemap-1.0.0.dist-info/WHEEL +4 -0
- changemap-1.0.0.dist-info/entry_points.txt +2 -0
- changemap-1.0.0.dist-info/licenses/LICENSE +202 -0
changemap/__init__.py
ADDED
changemap/__main__.py
ADDED
changemap/cache.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""An on-disk cache of parsed files, keyed by git blob id.
|
|
2
|
+
|
|
3
|
+
A blob id names the exact bytes of a file, so what was read from it never goes stale. What can go stale
|
|
4
|
+
is the reader: each row carries the reader's stamp (`readers.stamp`), so a changed reader makes only the
|
|
5
|
+
rows of its own language read again. Per blob the cache keeps the file's definitions (small, needed for
|
|
6
|
+
every file of the project) and what only linking needs: its calls, local types and constants (large).
|
|
7
|
+
|
|
8
|
+
One SQLite file in WAL mode. Reads are bulk queries; writes are one transaction per batch. The file is
|
|
9
|
+
trimmed to a size cap, least recently used rows first. The cache is only a speed-up: if it cannot be
|
|
10
|
+
opened or written, the tool carries on without it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import os
|
|
17
|
+
import sqlite3
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
import zlib
|
|
21
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import NamedTuple
|
|
24
|
+
|
|
25
|
+
FORMAT = 7 # the shape of a stored row; a new number starts a new file
|
|
26
|
+
CAP_MB = 1024 # the file is trimmed to this size; CHANGEMAP_CACHE_MAX_MB changes it
|
|
27
|
+
TOUCH_AFTER = 3600 # seconds; a row read again within this time is not marked as used again
|
|
28
|
+
CHUNK = 20_000 if sqlite3.sqlite_version_info >= (3, 32, 0) else 500 # how many `?` one statement may hold
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Entry(NamedTuple):
|
|
32
|
+
"""What is kept of one parsed file."""
|
|
33
|
+
|
|
34
|
+
why: str | None # None when it was read; else the reason it is not (see readers._skip)
|
|
35
|
+
skeleton: bytes | None # the record without its calls
|
|
36
|
+
calls: bytes | None # the calls of each function (not returned by `lookup`)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cache_dir() -> Path:
|
|
40
|
+
"""The user's cache folder for this tool, the way each system expects it."""
|
|
41
|
+
override = os.environ.get("CHANGEMAP_CACHE_DIR")
|
|
42
|
+
if override:
|
|
43
|
+
return Path(override)
|
|
44
|
+
home = Path.home()
|
|
45
|
+
if sys.platform == "win32":
|
|
46
|
+
return Path(os.environ.get("LOCALAPPDATA") or home / "AppData" / "Local") / "changemap" / "Cache"
|
|
47
|
+
if sys.platform == "darwin":
|
|
48
|
+
return home / "Library" / "Caches" / "changemap"
|
|
49
|
+
return Path(os.environ.get("XDG_CACHE_HOME") or home / ".cache") / "changemap"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cache_file() -> Path:
|
|
53
|
+
return cache_dir() / f"parsed-f{FORMAT}.sqlite"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def result_key(*parts: str) -> str:
|
|
57
|
+
"""A key for page data: the changemap code that made it (every source file of the package and the Python
|
|
58
|
+
version) and the parts that name the input, such as the two commit ids."""
|
|
59
|
+
hasher = hashlib.sha1(f"{sys.version_info[:2]}".encode(), usedforsecurity=False)
|
|
60
|
+
root = Path(__file__).parent
|
|
61
|
+
for path in sorted(root.rglob("*.py")):
|
|
62
|
+
try:
|
|
63
|
+
hasher.update(path.relative_to(root).as_posix().encode() + path.read_bytes())
|
|
64
|
+
except OSError:
|
|
65
|
+
continue
|
|
66
|
+
for part in parts:
|
|
67
|
+
hasher.update(b"\0" + part.encode())
|
|
68
|
+
return hasher.hexdigest()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def cap_bytes() -> int:
|
|
72
|
+
try:
|
|
73
|
+
return int(float(os.environ.get("CHANGEMAP_CACHE_MAX_MB", CAP_MB)) * 1_000_000)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return CAP_MB * 1_000_000
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Cache:
|
|
79
|
+
"""Parsed files by blob id. With `enabled=False` it remembers nothing."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, enabled: bool = True):
|
|
82
|
+
self._db: sqlite3.Connection | None = None
|
|
83
|
+
self._stale: list[bytes] = [] # blobs read now that were last marked as used long ago
|
|
84
|
+
self.path = cache_file()
|
|
85
|
+
if not enabled:
|
|
86
|
+
return
|
|
87
|
+
try:
|
|
88
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
db = sqlite3.connect(self.path, timeout=30)
|
|
90
|
+
db.execute("PRAGMA auto_vacuum=INCREMENTAL") # only takes effect on a new file
|
|
91
|
+
db.execute("PRAGMA journal_mode=WAL")
|
|
92
|
+
db.execute("PRAGMA synchronous=NORMAL")
|
|
93
|
+
db.execute(
|
|
94
|
+
"CREATE TABLE IF NOT EXISTS parsed (blob BLOB PRIMARY KEY, stamp TEXT NOT NULL, why TEXT,"
|
|
95
|
+
" skeleton BLOB, calls BLOB, seen INTEGER NOT NULL)"
|
|
96
|
+
)
|
|
97
|
+
db.execute(
|
|
98
|
+
"CREATE TABLE IF NOT EXISTS results (key TEXT PRIMARY KEY, data BLOB NOT NULL, seen INTEGER NOT NULL)"
|
|
99
|
+
)
|
|
100
|
+
db.commit()
|
|
101
|
+
self._db = db
|
|
102
|
+
except (OSError, sqlite3.Error):
|
|
103
|
+
self._db = None
|
|
104
|
+
else:
|
|
105
|
+
self._drop_old_files()
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def persistent(self) -> bool:
|
|
109
|
+
"""True when what is put here is kept for the next call."""
|
|
110
|
+
return self._db is not None
|
|
111
|
+
|
|
112
|
+
def _drop_old_files(self) -> None:
|
|
113
|
+
"""Files an older changemap made in this folder are no longer read; remove them."""
|
|
114
|
+
try:
|
|
115
|
+
for old in self.path.parent.glob("index-*.sqlite*"):
|
|
116
|
+
old.unlink(missing_ok=True)
|
|
117
|
+
except OSError:
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
def lookup(self, wanted: Mapping[str, str]) -> dict[str, Entry]:
|
|
121
|
+
"""The entries (without calls) of the blobs that are kept under the stamp given for each blob id."""
|
|
122
|
+
found: dict[str, Entry] = {}
|
|
123
|
+
if self._db is None:
|
|
124
|
+
return found
|
|
125
|
+
ids = list(wanted)
|
|
126
|
+
try:
|
|
127
|
+
for part in _chunks(ids):
|
|
128
|
+
marks = ",".join("?" * len(part))
|
|
129
|
+
rows = self._db.execute(
|
|
130
|
+
f"SELECT blob, stamp, why, skeleton, seen FROM parsed WHERE blob IN ({marks})",
|
|
131
|
+
[bytes.fromhex(b) for b in part],
|
|
132
|
+
)
|
|
133
|
+
horizon = time.time() - TOUCH_AFTER
|
|
134
|
+
for raw, stamp, why, skeleton, seen in rows:
|
|
135
|
+
blob = raw.hex()
|
|
136
|
+
if stamp != wanted[blob]:
|
|
137
|
+
continue
|
|
138
|
+
found[blob] = Entry(why, skeleton, None)
|
|
139
|
+
if seen < horizon:
|
|
140
|
+
self._stale.append(raw)
|
|
141
|
+
except sqlite3.Error:
|
|
142
|
+
return {}
|
|
143
|
+
return found
|
|
144
|
+
|
|
145
|
+
def known(self, stamps: Mapping[str, str]) -> set[str]:
|
|
146
|
+
"""The blob ids among `stamps` (blob id -> reader stamp) that are kept and still valid."""
|
|
147
|
+
if self._db is None:
|
|
148
|
+
return set()
|
|
149
|
+
found: set[str] = set()
|
|
150
|
+
try:
|
|
151
|
+
for part in _chunks(list(stamps)):
|
|
152
|
+
marks = ",".join("?" * len(part))
|
|
153
|
+
rows = self._db.execute(
|
|
154
|
+
f"SELECT blob, stamp FROM parsed WHERE blob IN ({marks})", [bytes.fromhex(b) for b in part]
|
|
155
|
+
)
|
|
156
|
+
found.update(raw.hex() for raw, stamp in rows if stamp == stamps[raw.hex()])
|
|
157
|
+
except sqlite3.Error:
|
|
158
|
+
return set()
|
|
159
|
+
return found
|
|
160
|
+
|
|
161
|
+
def get(self, blobs: Iterable[str]) -> set[str]:
|
|
162
|
+
"""The blob ids that are kept, under any reader stamp. Only for callers that ask whether a file is kept
|
|
163
|
+
and have no stamp to give; use `known` where the file's path is at hand."""
|
|
164
|
+
if self._db is None:
|
|
165
|
+
return set()
|
|
166
|
+
found: set[str] = set()
|
|
167
|
+
try:
|
|
168
|
+
for part in _chunks(list(blobs)):
|
|
169
|
+
marks = ",".join("?" * len(part))
|
|
170
|
+
rows = self._db.execute(
|
|
171
|
+
f"SELECT blob FROM parsed WHERE blob IN ({marks})", [bytes.fromhex(b) for b in part]
|
|
172
|
+
)
|
|
173
|
+
found.update(raw.hex() for (raw,) in rows)
|
|
174
|
+
except sqlite3.Error:
|
|
175
|
+
return set()
|
|
176
|
+
return found
|
|
177
|
+
|
|
178
|
+
def calls(self, blobs: Iterable[str]) -> dict[str, bytes]:
|
|
179
|
+
"""The stored calls of these blobs."""
|
|
180
|
+
found: dict[str, bytes] = {}
|
|
181
|
+
if self._db is None:
|
|
182
|
+
return found
|
|
183
|
+
try:
|
|
184
|
+
for part in _chunks(list(blobs)):
|
|
185
|
+
marks = ",".join("?" * len(part))
|
|
186
|
+
rows = self._db.execute(
|
|
187
|
+
f"SELECT blob, calls FROM parsed WHERE blob IN ({marks}) AND calls IS NOT NULL",
|
|
188
|
+
[bytes.fromhex(b) for b in part],
|
|
189
|
+
)
|
|
190
|
+
found.update((raw.hex(), calls) for raw, calls in rows)
|
|
191
|
+
except sqlite3.Error:
|
|
192
|
+
return {}
|
|
193
|
+
return found
|
|
194
|
+
|
|
195
|
+
def put(self, rows: Iterable[tuple[str, str, Entry]]) -> None:
|
|
196
|
+
"""Keep (blob id, reader stamp, entry) rows, all in one transaction."""
|
|
197
|
+
if self._db is None:
|
|
198
|
+
return
|
|
199
|
+
now = int(time.time())
|
|
200
|
+
try:
|
|
201
|
+
with self._db:
|
|
202
|
+
self._db.executemany(
|
|
203
|
+
"INSERT OR REPLACE INTO parsed VALUES (?, ?, ?, ?, ?, ?)",
|
|
204
|
+
((bytes.fromhex(blob), stamp, e.why, e.skeleton, e.calls, now) for blob, stamp, e in rows),
|
|
205
|
+
)
|
|
206
|
+
except sqlite3.Error:
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
def result(self, key: str) -> str | None:
|
|
210
|
+
"""The page data kept under this key (see `result_key`), as JSON text."""
|
|
211
|
+
if self._db is None:
|
|
212
|
+
return None
|
|
213
|
+
try:
|
|
214
|
+
row = self._db.execute("SELECT data FROM results WHERE key = ?", (key,)).fetchone()
|
|
215
|
+
if row is None:
|
|
216
|
+
return None
|
|
217
|
+
self._db.execute("UPDATE results SET seen = ? WHERE key = ?", (int(time.time()), key))
|
|
218
|
+
self._db.commit()
|
|
219
|
+
return zlib.decompress(row[0]).decode()
|
|
220
|
+
except (sqlite3.Error, zlib.error, UnicodeDecodeError):
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
def put_result(self, key: str, text: str) -> None:
|
|
224
|
+
if self._db is None:
|
|
225
|
+
return
|
|
226
|
+
try:
|
|
227
|
+
with self._db:
|
|
228
|
+
self._db.execute(
|
|
229
|
+
"INSERT OR REPLACE INTO results VALUES (?, ?, ?)",
|
|
230
|
+
(key, zlib.compress(text.encode(), 1), int(time.time())),
|
|
231
|
+
)
|
|
232
|
+
except sqlite3.Error:
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
def size(self) -> int:
|
|
236
|
+
"""Bytes the cache holds on disk (not counting space the file has freed)."""
|
|
237
|
+
if self._db is None:
|
|
238
|
+
return 0
|
|
239
|
+
try:
|
|
240
|
+
pages, size, free = (
|
|
241
|
+
next(self._db.execute(f"PRAGMA {p}"))[0] for p in ("page_count", "page_size", "freelist_count")
|
|
242
|
+
)
|
|
243
|
+
except sqlite3.Error:
|
|
244
|
+
return 0
|
|
245
|
+
return int((pages - free) * size)
|
|
246
|
+
|
|
247
|
+
def count(self) -> int:
|
|
248
|
+
if self._db is None:
|
|
249
|
+
return 0
|
|
250
|
+
try:
|
|
251
|
+
return int(next(self._db.execute("SELECT COUNT(*) FROM parsed"))[0])
|
|
252
|
+
except sqlite3.Error:
|
|
253
|
+
return 0
|
|
254
|
+
|
|
255
|
+
def clear(self) -> None:
|
|
256
|
+
"""Forget everything and give the disk space back."""
|
|
257
|
+
if self._db is None:
|
|
258
|
+
return
|
|
259
|
+
try:
|
|
260
|
+
self._db.execute("DELETE FROM parsed")
|
|
261
|
+
self._db.execute("DELETE FROM results")
|
|
262
|
+
self._db.commit()
|
|
263
|
+
self._db.execute("PRAGMA incremental_vacuum")
|
|
264
|
+
self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
265
|
+
except sqlite3.Error:
|
|
266
|
+
pass
|
|
267
|
+
|
|
268
|
+
def close(self) -> None:
|
|
269
|
+
if self._db is None:
|
|
270
|
+
return
|
|
271
|
+
try:
|
|
272
|
+
self._mark_used()
|
|
273
|
+
self._trim()
|
|
274
|
+
except sqlite3.Error:
|
|
275
|
+
pass
|
|
276
|
+
finally:
|
|
277
|
+
self._db.close()
|
|
278
|
+
self._db = None
|
|
279
|
+
|
|
280
|
+
def _mark_used(self) -> None:
|
|
281
|
+
if self._db is not None and self._stale:
|
|
282
|
+
with self._db:
|
|
283
|
+
self._db.executemany(
|
|
284
|
+
"UPDATE parsed SET seen = ? WHERE blob = ?", ((int(time.time()), raw) for raw in self._stale)
|
|
285
|
+
)
|
|
286
|
+
self._stale = []
|
|
287
|
+
|
|
288
|
+
def _trim(self) -> None:
|
|
289
|
+
"""Drop the least recently used rows while the file is over its cap, down to four fifths of it."""
|
|
290
|
+
cap = cap_bytes()
|
|
291
|
+
if self._db is None or self.size() <= cap:
|
|
292
|
+
return
|
|
293
|
+
while self.size() > cap * 0.8:
|
|
294
|
+
with self._db:
|
|
295
|
+
self._db.execute("DELETE FROM results WHERE seen < ?", (int(time.time()) - 7 * 86400,))
|
|
296
|
+
gone = self._db.execute(
|
|
297
|
+
"DELETE FROM parsed WHERE rowid IN (SELECT rowid FROM parsed ORDER BY seen LIMIT"
|
|
298
|
+
" MAX(1, (SELECT COUNT(*) FROM parsed) / 10))"
|
|
299
|
+
).rowcount
|
|
300
|
+
self._db.execute("PRAGMA incremental_vacuum")
|
|
301
|
+
if gone <= 0:
|
|
302
|
+
break
|
|
303
|
+
self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _chunks(ids: list[str]) -> Iterator[list[str]]:
|
|
307
|
+
for start in range(0, len(ids), CHUNK):
|
|
308
|
+
yield ids[start : start + CHUNK]
|
changemap/cli.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""The `changemap` command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import webbrowser
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from changemap import __version__, doctor, feedback, outline, page, pipeline, plan, remote, snapshot, watch
|
|
14
|
+
from changemap.cache import Cache
|
|
15
|
+
from changemap.errors import ChangemapError
|
|
16
|
+
from changemap.git import Repo, run
|
|
17
|
+
|
|
18
|
+
DESCRIPTION = """\
|
|
19
|
+
Make one offline HTML page: a clickable map of what a pull request changed.
|
|
20
|
+
|
|
21
|
+
examples:
|
|
22
|
+
changemap this branch against where it left the default branch
|
|
23
|
+
changemap main topic two commits, branches or tags
|
|
24
|
+
changemap pr 123 pull request 123 of this repository (uses gh; without it, reads origin)
|
|
25
|
+
changemap https://github.com/OWNER/REPO/pull/123
|
|
26
|
+
a pull request or compare link, read from the server with no clone
|
|
27
|
+
changemap https://gitlab.com/GROUP/PROJECT/-/merge_requests/5
|
|
28
|
+
also Gitea, Forgejo, Codeberg, Azure DevOps and Bitbucket Cloud
|
|
29
|
+
changemap --remote URL BASE HEAD two commits or refs on any git server, with no clone
|
|
30
|
+
changemap --plan plan.json a plan file drawn on the code at HEAD
|
|
31
|
+
changemap --plan plan.json BASE HEAD
|
|
32
|
+
the plan against what was built from BASE to HEAD
|
|
33
|
+
changemap --plan plan.json URL the same, for a pull request or compare link on a server
|
|
34
|
+
changemap --watch [BASE] serve the working tree and redraw the page as files change
|
|
35
|
+
changemap doctor check git, Python, the language packages, gh and the cache folder
|
|
36
|
+
changemap feedback draft an issue about changemap itself
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
EPILOG = """\
|
|
40
|
+
exit codes:
|
|
41
|
+
0 the page was written
|
|
42
|
+
1 `changemap doctor` found a problem
|
|
43
|
+
2 a plain error (the message says what to do) or a command typed wrong; nothing was written
|
|
44
|
+
|
|
45
|
+
Without a clone, changemap keeps a small throwaway repository in your cache folder (deleted after 30 days
|
|
46
|
+
unused) and fetches into it only the two commits and the source files it reads, in one request. It contacts
|
|
47
|
+
only the git server, with your own git login, so private repositories work and git never asks for a
|
|
48
|
+
password; and, for a pull request link, that site's web API once or twice for the title and the base
|
|
49
|
+
(through gh if installed). Nothing else leaves the machine.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parser() -> argparse.ArgumentParser:
|
|
54
|
+
parser = argparse.ArgumentParser(
|
|
55
|
+
prog="changemap",
|
|
56
|
+
description=DESCRIPTION,
|
|
57
|
+
epilog=EPILOG,
|
|
58
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument("refs", nargs="*", metavar="BASE HEAD", help="two commits or refs; or: pr NUMBER")
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--out",
|
|
63
|
+
type=Path,
|
|
64
|
+
default=Path("changemap.html"),
|
|
65
|
+
metavar="FILE",
|
|
66
|
+
help="where to write the page (default changemap.html)",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument("--open", action="store_true", help="open the page in the browser")
|
|
69
|
+
parser.add_argument("--json", type=Path, metavar="FILE", help="also write the data file agents read")
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--outline",
|
|
72
|
+
type=Path,
|
|
73
|
+
metavar="FILE",
|
|
74
|
+
help="also write a short outline of the flows for an agent (- is stdout)",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--flows", type=Path, metavar="FILE", help="flows an agent wrote: named paths through the changed functions"
|
|
78
|
+
)
|
|
79
|
+
parser.add_argument(
|
|
80
|
+
"--repo", type=Path, default=Path(), metavar="DIR", help="a repository other than the current folder"
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument("--remote", metavar="URL", help="read BASE HEAD from this git server, with no clone")
|
|
83
|
+
parser.add_argument("--plan", type=Path, metavar="FILE", help="draw a plan file on the code at HEAD")
|
|
84
|
+
parser.add_argument("--no-cache", action="store_true", help="do not keep or reuse parsed files between runs")
|
|
85
|
+
parser.add_argument(
|
|
86
|
+
"--watch", action="store_true", help="serve the working tree against BASE and redraw as files change"
|
|
87
|
+
)
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"--port", type=int, default=0, metavar="N", help="with --watch, the port to serve on (default: a free one)"
|
|
90
|
+
)
|
|
91
|
+
parser.add_argument("--version", action="version", version=f"changemap {__version__}")
|
|
92
|
+
return parser
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
96
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
97
|
+
try:
|
|
98
|
+
if args[:1] == ["doctor"]:
|
|
99
|
+
return _doctor("--clear-cache" in args[1:])
|
|
100
|
+
if args[:1] == ["feedback"]:
|
|
101
|
+
return _feedback(args[1:])
|
|
102
|
+
return _compare(_parser().parse_args(args))
|
|
103
|
+
except ChangemapError as problem:
|
|
104
|
+
print(f"changemap: {problem}", file=sys.stderr)
|
|
105
|
+
return 2
|
|
106
|
+
except KeyboardInterrupt:
|
|
107
|
+
return 130
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _doctor(clear_cache: bool = False) -> int:
|
|
111
|
+
text, ok = doctor.report(clear_cache=clear_cache)
|
|
112
|
+
print(text)
|
|
113
|
+
return 0 if ok else 1
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _compare(args: argparse.Namespace) -> int:
|
|
117
|
+
target = remote.parse(args.refs, args.remote)
|
|
118
|
+
if target and args.watch:
|
|
119
|
+
raise ChangemapError("--watch needs a local repository, not a web address or --remote.")
|
|
120
|
+
gh_info = None
|
|
121
|
+
if not target and args.refs[:1] == ["pr"] and not args.plan and not args.watch:
|
|
122
|
+
number = _pr_number(args.refs)
|
|
123
|
+
local = Repo.open(args.repo)
|
|
124
|
+
gh_info = _gh_view(local, number)
|
|
125
|
+
if gh_info is None: # no gh, or gh cannot say: read the server the clone came from, as a web address
|
|
126
|
+
target = remote.target_for_origin(local, number)
|
|
127
|
+
repo = remote.bare_repo(target) if target else Repo.open(args.repo)
|
|
128
|
+
if args.watch:
|
|
129
|
+
if args.plan or len(args.refs) > 1:
|
|
130
|
+
raise ChangemapError("--watch takes at most one commit: changemap --watch [BASE].")
|
|
131
|
+
base = repo.commit(args.refs[0]) if args.refs else repo.merge_base(repo.default_branch(), "HEAD")
|
|
132
|
+
return watch.run(
|
|
133
|
+
repo, base, port=args.port, open_browser=args.open, use_cache=not args.no_cache, flows=args.flows
|
|
134
|
+
)
|
|
135
|
+
cache = Cache(enabled=not args.no_cache)
|
|
136
|
+
try:
|
|
137
|
+
if args.plan:
|
|
138
|
+
if not target and len(args.refs) not in (0, 2):
|
|
139
|
+
raise ChangemapError(
|
|
140
|
+
"--plan takes no commits (it draws the plan on HEAD), two, or a web address: "
|
|
141
|
+
"--plan FILE [BASE HEAD | URL]."
|
|
142
|
+
)
|
|
143
|
+
data, said = _plan(repo, cache, args.plan, args.refs, target, args.flows)
|
|
144
|
+
else:
|
|
145
|
+
if target:
|
|
146
|
+
base, head, title, url, said, about = remote.fetch(repo, target, cache)
|
|
147
|
+
else:
|
|
148
|
+
base, head, title, url, said, about = _commits(repo, args.refs, gh_info)
|
|
149
|
+
data = pipeline.build(
|
|
150
|
+
repo,
|
|
151
|
+
base,
|
|
152
|
+
head,
|
|
153
|
+
cache=cache,
|
|
154
|
+
title=title,
|
|
155
|
+
url=url,
|
|
156
|
+
agent_flows=args.flows,
|
|
157
|
+
about=about,
|
|
158
|
+
need=remote.needs(repo, target) if target else None,
|
|
159
|
+
)
|
|
160
|
+
finally:
|
|
161
|
+
cache.close()
|
|
162
|
+
out: Path = args.out
|
|
163
|
+
try:
|
|
164
|
+
page.write(data, out)
|
|
165
|
+
if args.json:
|
|
166
|
+
page.write_json(data, args.json)
|
|
167
|
+
if args.outline:
|
|
168
|
+
outline.write(data, args.outline)
|
|
169
|
+
except OSError as problem:
|
|
170
|
+
raise ChangemapError(
|
|
171
|
+
f"Could not write {problem.filename}. Check that the folder exists and can be written."
|
|
172
|
+
) from None
|
|
173
|
+
print(said, file=sys.stderr)
|
|
174
|
+
for note in data.get("flow_notes", []):
|
|
175
|
+
print(note, file=sys.stderr)
|
|
176
|
+
skipped = data.get("skipped")
|
|
177
|
+
if isinstance(skipped, list) and skipped:
|
|
178
|
+
print(f"Skipped {len(skipped)} source file(s) that were not read; the page lists them.", file=sys.stderr)
|
|
179
|
+
print(out.resolve(), file=sys.stderr if str(args.outline) == "-" else sys.stdout)
|
|
180
|
+
if args.open:
|
|
181
|
+
webbrowser.open(out.resolve().as_uri())
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _plan(
|
|
186
|
+
repo: Repo, cache: Cache, path: Path, refs: list[str], target: remote.Target | None, flows: Path | None
|
|
187
|
+
) -> tuple[dict[str, Any], str]:
|
|
188
|
+
plan_file = plan.load(path)
|
|
189
|
+
if target:
|
|
190
|
+
base, head, _, url, said, _ = remote.fetch(repo, target, cache)
|
|
191
|
+
data = pipeline.build_against_plan(
|
|
192
|
+
repo, plan_file, base, head, cache=cache, url=url, agent_flows=flows, need=remote.needs(repo, target)
|
|
193
|
+
)
|
|
194
|
+
return data, f"{said} Judged the plan '{data['title']}' against it."
|
|
195
|
+
if refs:
|
|
196
|
+
data = pipeline.build_against_plan(repo, plan_file, refs[0], refs[1], cache=cache, agent_flows=flows)
|
|
197
|
+
return data, f"Judged the plan '{data['title']}' against what was built from {refs[0]} to {refs[1]}."
|
|
198
|
+
if flows:
|
|
199
|
+
raise ChangemapError("--flows needs a change to read: give BASE HEAD (or a web address) after the plan.")
|
|
200
|
+
head = repo.commit("HEAD")
|
|
201
|
+
snaps, _ = snapshot.load(repo, [head], cache)
|
|
202
|
+
data = plan.build(plan_file, snaps[0], "", repo.remote_url())
|
|
203
|
+
return data, f"Drew the plan '{data['title']}' on HEAD ({head[:7]})."
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _pr_number(refs: list[str]) -> int:
|
|
207
|
+
if len(refs) != 2 or not refs[1].isdigit():
|
|
208
|
+
raise ChangemapError("Give the pull request number: changemap pr 123")
|
|
209
|
+
return int(refs[1])
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _commits(repo: Repo, refs: list[str], gh_info: dict[str, str] | None = None) -> tuple[str, str, str, str, str, str]:
|
|
213
|
+
"""Work out (base sha, head sha, title, repo url, one line saying what is compared, description).
|
|
214
|
+
|
|
215
|
+
The title and description are empty unless a pull request gave them."""
|
|
216
|
+
if refs[:1] == ["pr"]:
|
|
217
|
+
if gh_info is None:
|
|
218
|
+
raise ChangemapError("Give the pull request number: changemap pr 123")
|
|
219
|
+
return _pull_request(repo, _pr_number(refs), gh_info)
|
|
220
|
+
if len(refs) == 2:
|
|
221
|
+
base, head = repo.commit(refs[0]), repo.commit(refs[1])
|
|
222
|
+
return base, head, "", "", f"Compared {refs[0]} ({base[:7]}) with {refs[1]} ({head[:7]}).", ""
|
|
223
|
+
if refs:
|
|
224
|
+
raise ChangemapError("Give two commits (changemap BASE HEAD), a pull request (changemap pr 123), or nothing.")
|
|
225
|
+
head = repo.commit("HEAD")
|
|
226
|
+
branch = repo.default_branch()
|
|
227
|
+
base = repo.merge_base(branch, head)
|
|
228
|
+
if base == head:
|
|
229
|
+
raise ChangemapError(
|
|
230
|
+
f"HEAD is already part of {branch}, so there is nothing to compare. "
|
|
231
|
+
"Switch to your branch, or give two commits."
|
|
232
|
+
)
|
|
233
|
+
return (
|
|
234
|
+
base,
|
|
235
|
+
head,
|
|
236
|
+
"",
|
|
237
|
+
"",
|
|
238
|
+
f"Compared where this branch left {branch} ({base[:7]}) with HEAD ({head[:7]}).",
|
|
239
|
+
"",
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _gh_view(repo: Repo, number: int) -> dict[str, str] | None:
|
|
244
|
+
"""What gh says about pull request `number`, or None when gh is missing or cannot say."""
|
|
245
|
+
if not _has_gh():
|
|
246
|
+
return None
|
|
247
|
+
done = run(["gh", "pr", "view", str(number), "--json", "baseRefOid,headRefOid,title,url,body"], cwd=repo.path)
|
|
248
|
+
if done.returncode != 0:
|
|
249
|
+
return None
|
|
250
|
+
info: dict[str, str] = json.loads(done.stdout)
|
|
251
|
+
return info
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _pull_request(repo: Repo, number: int, info: dict[str, str]) -> tuple[str, str, str, str, str, str]:
|
|
255
|
+
base, head = info["baseRefOid"], info["headRefOid"]
|
|
256
|
+
for sha, ref in ((head, f"refs/pull/{number}/head"), (base, base)):
|
|
257
|
+
if not repo.has_commit(sha):
|
|
258
|
+
repo.git("fetch", "--quiet", "origin", ref)
|
|
259
|
+
if not (repo.has_commit(base) and repo.has_commit(head)):
|
|
260
|
+
raise ChangemapError(
|
|
261
|
+
f"Could not fetch the commits of pull request {number}. "
|
|
262
|
+
f"Run `git fetch origin pull/{number}/head` and try again."
|
|
263
|
+
)
|
|
264
|
+
url = info["url"].rsplit("/pull/", 1)[0]
|
|
265
|
+
said = f"Compared pull request {number} ({base[:7]} to {head[:7]})."
|
|
266
|
+
return base, head, info["title"], url, said, info.get("body") or ""
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _has_gh() -> bool:
|
|
270
|
+
try:
|
|
271
|
+
return run(["gh", "--version"]).returncode == 0
|
|
272
|
+
except ChangemapError:
|
|
273
|
+
return False
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _feedback(args: list[str]) -> int:
|
|
277
|
+
parser = argparse.ArgumentParser(prog="changemap feedback", description="Draft an issue about changemap itself.")
|
|
278
|
+
parser.add_argument(
|
|
279
|
+
"--kind", choices=sorted(feedback.KINDS), default="other", help="arrow, screen, crash, idea or other"
|
|
280
|
+
)
|
|
281
|
+
parser.add_argument("--title", help="the issue title")
|
|
282
|
+
parser.add_argument("--body-file", type=Path, metavar="F", help="a text file with what you want to say")
|
|
283
|
+
parser.add_argument("--send", action="store_true", help="file the issue with gh, after you type yes")
|
|
284
|
+
parser.add_argument("--yes", action="store_true", help="with --send, do not ask")
|
|
285
|
+
opts = parser.parse_args(args)
|
|
286
|
+
body = None
|
|
287
|
+
if opts.body_file:
|
|
288
|
+
try:
|
|
289
|
+
body = opts.body_file.read_text(encoding="utf-8")
|
|
290
|
+
except OSError:
|
|
291
|
+
raise ChangemapError(f"Could not read {opts.body_file}. Check the path.") from None
|
|
292
|
+
title = opts.title or f"feedback: {feedback.KINDS[opts.kind].lower()}"
|
|
293
|
+
text, facts = feedback.draft(opts.kind, body)
|
|
294
|
+
print(f"{title}\n\n{text}")
|
|
295
|
+
print(f"To send it yourself: {feedback.link(title, facts)}")
|
|
296
|
+
print("Check the text above for code, file paths, names and URLs from your own repository, and remove them.")
|
|
297
|
+
if opts.send and (opts.yes or _agrees("File this issue on GitHub? Type yes to send: ")):
|
|
298
|
+
print(feedback.send(title, text))
|
|
299
|
+
return 0
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _agrees(question: str) -> bool:
|
|
303
|
+
try:
|
|
304
|
+
return input(question).strip().lower() == "yes"
|
|
305
|
+
except EOFError:
|
|
306
|
+
return False
|