@giamme/forge 0.19.0 → 0.20.0
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.
- package/CHANGELOG.md +16 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/commands.md +137 -5
- package/docs/forge-ui.md +70 -19
- package/forge +8 -2
- package/package.json +1 -1
- package/references/decompose.md +20 -8
- package/references/memory.md +30 -5
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-issues.py +228 -97
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +6 -4
- package/scripts/forge-schedule.py +63 -7
- package/scripts/forge-sweep.py +199 -44
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +441 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +583 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +603 -0
- package/scripts/forge_identity.py +327 -0
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_side/__init__.py +217 -32
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +658 -5
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/index.html +2 -0
- package/ui/forge_ui/static/projectsview.js +600 -45
- package/ui/forge_ui/static/style.css +59 -0
- package/ui/forge_ui/static/triageview.js +423 -0
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Every review finding of a repository, and what happened to it.
|
|
3
|
+
|
|
4
|
+
show REPO [--status S] [--online]
|
|
5
|
+
fix REPO FP… [--commit SHA] [--reason TEXT]
|
|
6
|
+
dismiss REPO FP… --reason TEXT
|
|
7
|
+
reopen REPO FP…
|
|
8
|
+
to-file REPO FP… [--title T] [--body-file F]
|
|
9
|
+
dup REPO FP --of FP
|
|
10
|
+
tag REPO FP… -- TAG… (--add | --remove)
|
|
11
|
+
note REPO FP TEXT
|
|
12
|
+
edit REPO FP [--severity Pn] [--text-file F]
|
|
13
|
+
triage REPO --spec S [--timeout N] [--max-findings N] [--detach]
|
|
14
|
+
triage-status REPO [N]
|
|
15
|
+
proposals REPO [N]
|
|
16
|
+
apply REPO N PID --approve HASH [--plan-dir DIR]
|
|
17
|
+
reject REPO N PID [--reason TEXT]
|
|
18
|
+
|
|
19
|
+
REPO is a checkout, a linked worktree, or a plan or solo run dir. FP is the
|
|
20
|
+
12-hex fingerprint `show` prints. `--actor` is cli (the default), ui or triage.
|
|
21
|
+
Exit 0 ok, 2 usage, 3 refused, 1 error.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import importlib.util
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import sys
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
SCRIPTS = Path(__file__).resolve().parent
|
|
34
|
+
if str(SCRIPTS) not in sys.path:
|
|
35
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
36
|
+
|
|
37
|
+
import forge_identity # noqa: E402
|
|
38
|
+
from forge_findings import apply as approval, status, store, tags, triage # noqa: E402
|
|
39
|
+
|
|
40
|
+
ACTORS = ("cli", "ui", "triage")
|
|
41
|
+
FP_RE = re.compile(r"[0-9a-f]{12}\Z")
|
|
42
|
+
SEVERITIES = ("P0", "P1", "P2", "P3")
|
|
43
|
+
|
|
44
|
+
COMMANDS = {}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Usage(Exception):
|
|
48
|
+
"""Exit 2. The command line is not usable. Nothing was written."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Refused(Exception):
|
|
52
|
+
"""Exit 3. The record refuses the change. Nothing was written."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Failed(Exception):
|
|
56
|
+
"""Exit 1. The command could not be carried out."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def command(name):
|
|
60
|
+
def wrap(fn):
|
|
61
|
+
COMMANDS[name] = fn
|
|
62
|
+
return fn
|
|
63
|
+
return wrap
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_issues = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def issues():
|
|
70
|
+
"""forge-issues.py, loaded by path: its file name is not importable."""
|
|
71
|
+
global _issues
|
|
72
|
+
if _issues is None:
|
|
73
|
+
spec = importlib.util.spec_from_file_location("forge_issues", SCRIPTS / "forge-issues.py")
|
|
74
|
+
module = importlib.util.module_from_spec(spec)
|
|
75
|
+
spec.loader.exec_module(module)
|
|
76
|
+
_issues = module
|
|
77
|
+
return _issues
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _common():
|
|
81
|
+
parent = argparse.ArgumentParser(add_help=False)
|
|
82
|
+
parent.add_argument("--actor", choices=ACTORS, default="cli",
|
|
83
|
+
help="who is recording this: cli (default), ui or triage")
|
|
84
|
+
parent.add_argument("--json", action="store_true", help="machine-readable output")
|
|
85
|
+
return parent
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _Parser(argparse.ArgumentParser):
|
|
89
|
+
"""Choice errors omit commands whose names start with `_`. The command itself still runs."""
|
|
90
|
+
|
|
91
|
+
def _check_value(self, action, value):
|
|
92
|
+
if action.choices is not None and value not in action.choices:
|
|
93
|
+
shown = [choice for choice in action.choices if not str(choice).startswith("_")]
|
|
94
|
+
message = "invalid choice: %(value)r (choose from %(choices)s)" % {
|
|
95
|
+
"value": value,
|
|
96
|
+
"choices": ", ".join(map(repr, shown)),
|
|
97
|
+
}
|
|
98
|
+
raise argparse.ArgumentError(action, message)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_parser():
|
|
102
|
+
"""The command line. Each subcommand takes --actor and --json; handlers live in COMMANDS."""
|
|
103
|
+
common = _common()
|
|
104
|
+
parser = _Parser(prog="forge findings", description=__doc__,
|
|
105
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
106
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
107
|
+
|
|
108
|
+
show = sub.add_parser("show", parents=[common], help="every finding, with its state")
|
|
109
|
+
show.add_argument("repo", help="checkout, linked worktree, plan dir or solo run dir")
|
|
110
|
+
show.add_argument("--status", action="append", default=None, metavar="S",
|
|
111
|
+
help="keep this status; repeatable; open means open and to-file")
|
|
112
|
+
show.add_argument("--online", action="store_true", help="ask GitHub which findings are already filed")
|
|
113
|
+
|
|
114
|
+
fix = sub.add_parser("fix", parents=[common], help="mark findings fixed")
|
|
115
|
+
fix.add_argument("repo")
|
|
116
|
+
fix.add_argument("fp", nargs="+", metavar="FP")
|
|
117
|
+
fix.add_argument("--commit", help="7 to 40 lowercase hex characters")
|
|
118
|
+
fix.add_argument("--reason", help="at most 500 characters")
|
|
119
|
+
|
|
120
|
+
dismiss = sub.add_parser("dismiss", parents=[common], help="mark findings as needing no work")
|
|
121
|
+
dismiss.add_argument("repo")
|
|
122
|
+
dismiss.add_argument("fp", nargs="+", metavar="FP")
|
|
123
|
+
dismiss.add_argument("--reason", required=True, help="why, at most 500 characters")
|
|
124
|
+
|
|
125
|
+
reopen = sub.add_parser("reopen", parents=[common], help="mark findings open again")
|
|
126
|
+
reopen.add_argument("repo")
|
|
127
|
+
reopen.add_argument("fp", nargs="+", metavar="FP")
|
|
128
|
+
|
|
129
|
+
to_file = sub.add_parser("to-file", parents=[common], help="keep a draft issue for findings")
|
|
130
|
+
to_file.add_argument("repo")
|
|
131
|
+
to_file.add_argument("fp", nargs="+", metavar="FP")
|
|
132
|
+
to_file.add_argument("--title", help="issue title, at most 200 characters")
|
|
133
|
+
to_file.add_argument("--body-file", metavar="F", help="read the issue body from this file")
|
|
134
|
+
|
|
135
|
+
dup = sub.add_parser("dup", parents=[common], help="mark a finding a duplicate of another")
|
|
136
|
+
dup.add_argument("repo")
|
|
137
|
+
dup.add_argument("fp", metavar="FP")
|
|
138
|
+
dup.add_argument("--of", required=True, metavar="FP", help="the finding this one repeats")
|
|
139
|
+
|
|
140
|
+
tag = sub.add_parser("tag", parents=[common],
|
|
141
|
+
help="add or remove tags (-- separates fingerprints from tags)")
|
|
142
|
+
tag.add_argument("repo")
|
|
143
|
+
tag.add_argument("rest", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
|
|
144
|
+
|
|
145
|
+
note = sub.add_parser("note", parents=[common], help="set a finding's note; empty text clears it")
|
|
146
|
+
note.add_argument("repo")
|
|
147
|
+
note.add_argument("fp", metavar="FP")
|
|
148
|
+
note.add_argument("text", help="the note, or empty to clear it")
|
|
149
|
+
|
|
150
|
+
edit = sub.add_parser("edit", parents=[common], help="edit a finding's severity or text")
|
|
151
|
+
edit.add_argument("repo")
|
|
152
|
+
edit.add_argument("fp", metavar="FP")
|
|
153
|
+
edit.add_argument("--severity", choices=SEVERITIES, help="P0, P1, P2 or P3")
|
|
154
|
+
edit.add_argument("--text-file", metavar="F", help="read the replacement text from this file")
|
|
155
|
+
|
|
156
|
+
run = sub.add_parser("triage", parents=[common],
|
|
157
|
+
help="have a read-only model propose duplicates, fixes, tags, issues and plans")
|
|
158
|
+
run.add_argument("repo")
|
|
159
|
+
run.add_argument("--spec", required=True, metavar="S", help="the model, as forge --dwarf names one")
|
|
160
|
+
run.add_argument("--timeout", type=int, default=triage.DEFAULT_TIMEOUT, metavar="N",
|
|
161
|
+
help=f"seconds the model may take (default {triage.DEFAULT_TIMEOUT})")
|
|
162
|
+
run.add_argument("--max-findings", type=int, default=triage.DEFAULT_MAX_FINDINGS, metavar="N",
|
|
163
|
+
help=f"1 to {triage.MAX_FINDINGS_LIMIT}, default {triage.DEFAULT_MAX_FINDINGS}")
|
|
164
|
+
run.add_argument("--detach", action="store_true", help="return at once; the triage goes on in its own session")
|
|
165
|
+
|
|
166
|
+
# No help= keeps it out of the command list; help=SUPPRESS would print "==SUPPRESS==" there.
|
|
167
|
+
job = sub.add_parser("_triage-job", parents=[common])
|
|
168
|
+
job.add_argument("repo")
|
|
169
|
+
job.add_argument("n", type=int)
|
|
170
|
+
job.add_argument("--timeout", type=int, default=triage.DEFAULT_TIMEOUT)
|
|
171
|
+
|
|
172
|
+
state = sub.add_parser("triage-status", parents=[common], help="the state of a triage (the newest by default)")
|
|
173
|
+
state.add_argument("repo")
|
|
174
|
+
state.add_argument("n", nargs="?", type=int, metavar="N")
|
|
175
|
+
|
|
176
|
+
proposals = sub.add_parser("proposals", parents=[common], help="what a triage proposed (the newest by default)")
|
|
177
|
+
proposals.add_argument("repo")
|
|
178
|
+
proposals.add_argument("n", nargs="?", type=int, metavar="N")
|
|
179
|
+
approve = sub.add_parser("apply", parents=[common], help="approve one proposal of a triage, by its hash")
|
|
180
|
+
approve.add_argument("repo")
|
|
181
|
+
approve.add_argument("n", type=int, metavar="N", help="the triage number")
|
|
182
|
+
approve.add_argument("pid", metavar="PID", help="the proposal id, e.g. p3")
|
|
183
|
+
approve.add_argument("--approve", required=True, metavar="HASH", help="the hash `proposals` shows for it")
|
|
184
|
+
approve.add_argument("--plan-dir", metavar="DIR", help="for a plan proposal: where to write the plan dir")
|
|
185
|
+
|
|
186
|
+
refuse = sub.add_parser("reject", parents=[common], help="reject one proposal of a triage")
|
|
187
|
+
refuse.add_argument("repo")
|
|
188
|
+
refuse.add_argument("n", type=int, metavar="N", help="the triage number")
|
|
189
|
+
refuse.add_argument("pid", metavar="PID", help="the proposal id, e.g. p3")
|
|
190
|
+
refuse.add_argument("--reason", help="why, at most 500 characters")
|
|
191
|
+
# metavar is the usage line. _Parser leaves the same internal name out of an invalid-choice error.
|
|
192
|
+
sub.metavar = "{" + ",".join(name for name in sub.choices if not name.startswith("_")) + "}"
|
|
193
|
+
return parser
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def require_ident(path):
|
|
197
|
+
ident = forge_identity.identity(path)
|
|
198
|
+
if ident is None:
|
|
199
|
+
raise Usage(f"{path}: not a repository or run dir")
|
|
200
|
+
return ident
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def fingerprints(values):
|
|
204
|
+
"""The fingerprints of one command, in order, each once. A bad one refuses the whole command."""
|
|
205
|
+
found = []
|
|
206
|
+
for fp in values:
|
|
207
|
+
if not isinstance(fp, str) or FP_RE.fullmatch(fp) is None:
|
|
208
|
+
raise Refused(f"{fp!r} is not a 12-character fingerprint")
|
|
209
|
+
if fp not in found:
|
|
210
|
+
found.append(fp)
|
|
211
|
+
if not found:
|
|
212
|
+
raise Usage("at least one fingerprint")
|
|
213
|
+
return found
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def read_payload(path, label, limit):
|
|
217
|
+
"""The text of a file. `-` and an empty path are not files. Longer than `limit` is refused."""
|
|
218
|
+
if path == "-" or path == "":
|
|
219
|
+
shown = "'-'" if path == "-" else "''"
|
|
220
|
+
raise Usage(f"{label}: {shown} is not accepted; pass a file")
|
|
221
|
+
try:
|
|
222
|
+
with open(path, encoding="utf-8") as handle:
|
|
223
|
+
data = handle.read(limit + 1)
|
|
224
|
+
except UnicodeDecodeError as exc:
|
|
225
|
+
raise Failed(f"{label}: {path}: {exc}") from exc
|
|
226
|
+
except OSError as exc:
|
|
227
|
+
raise Failed(f"{label}: {path}: {exc.strerror or exc}") from exc
|
|
228
|
+
if len(data) > limit:
|
|
229
|
+
raise Refused(f"{label} must be at most {limit} characters")
|
|
230
|
+
return data
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def call_store(fn):
|
|
234
|
+
try:
|
|
235
|
+
return fn()
|
|
236
|
+
except store.Invalid as exc:
|
|
237
|
+
raise Refused(str(exc)) from exc
|
|
238
|
+
except store.Busy as exc:
|
|
239
|
+
raise Refused(str(exc)) from exc
|
|
240
|
+
except store.Corrupt as exc:
|
|
241
|
+
raise Failed(str(exc)) from exc
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def emit(args, fps, changed):
|
|
245
|
+
changed_fps = {fp for fp, _before, _after in changed}
|
|
246
|
+
unchanged = [fp for fp in fps if fp not in changed_fps]
|
|
247
|
+
if args.json:
|
|
248
|
+
print(json.dumps({
|
|
249
|
+
"ok": True,
|
|
250
|
+
"op": args.command,
|
|
251
|
+
"changed": [{"fp": fp, "before": before, "after": after} for fp, before, after in changed],
|
|
252
|
+
"unchanged": unchanged,
|
|
253
|
+
}, indent=2, ensure_ascii=False))
|
|
254
|
+
else:
|
|
255
|
+
print(f"{args.command}: {len(changed)} changed, {len(unchanged)} unchanged")
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def apply(args, fps, fn):
|
|
260
|
+
"""One store call for the whole command. `fn(ident, fps, actor)` returns the store's changed list."""
|
|
261
|
+
ident = require_ident(args.repo)
|
|
262
|
+
fps = fingerprints(fps)
|
|
263
|
+
return emit(args, fps, call_store(lambda: fn(ident, fps, args.actor)))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _wanted(names):
|
|
267
|
+
"""Statuses `--status` keeps. `open` is every status that still needs work."""
|
|
268
|
+
if not names:
|
|
269
|
+
return None
|
|
270
|
+
chosen = set()
|
|
271
|
+
for name in names:
|
|
272
|
+
if name == "open":
|
|
273
|
+
chosen.update(status.OPEN)
|
|
274
|
+
else:
|
|
275
|
+
chosen.add(name)
|
|
276
|
+
return chosen
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _recency(row):
|
|
280
|
+
plan_dir = row.get("plan_dir")
|
|
281
|
+
if isinstance(plan_dir, str) and plan_dir:
|
|
282
|
+
try:
|
|
283
|
+
return os.stat(plan_dir).st_mtime
|
|
284
|
+
except OSError:
|
|
285
|
+
return 0.0
|
|
286
|
+
return 0.0
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _severity_rank(value):
|
|
290
|
+
try:
|
|
291
|
+
return SEVERITIES.index(value)
|
|
292
|
+
except ValueError:
|
|
293
|
+
return len(SEVERITIES)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _place(row, line=None):
|
|
297
|
+
file = row.get("file") if isinstance(row.get("file"), str) else ""
|
|
298
|
+
if line is None:
|
|
299
|
+
line = row.get("line")
|
|
300
|
+
if file and isinstance(line, int) and not isinstance(line, bool):
|
|
301
|
+
return f"{file}:{line}"
|
|
302
|
+
return file or "-"
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _show_line(row, line=None):
|
|
306
|
+
found = [tag for tag in (row.get("tags") or []) if isinstance(tag, str)]
|
|
307
|
+
summary = " ".join(str(row.get("summary") or "").split())
|
|
308
|
+
return (f"{row.get('fp')} {row.get('status')} {row.get('severity') or '-'} "
|
|
309
|
+
f"{','.join(found) if found else '-'} {_place(row, line)} {summary}")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _rows(listed, records):
|
|
313
|
+
rows = []
|
|
314
|
+
seen = set()
|
|
315
|
+
for entry in listed.get("findings") or []:
|
|
316
|
+
if not isinstance(entry, dict):
|
|
317
|
+
continue
|
|
318
|
+
fp = entry.get("fp")
|
|
319
|
+
if fp in seen:
|
|
320
|
+
continue
|
|
321
|
+
seen.add(fp)
|
|
322
|
+
record = records.get(fp)
|
|
323
|
+
row = dict(entry)
|
|
324
|
+
row["record"] = record
|
|
325
|
+
row["tags"] = tags.tags_for(record, entry.get("file"))
|
|
326
|
+
row["status"] = status.effective(record, entry, None)
|
|
327
|
+
rows.append(row)
|
|
328
|
+
rows.sort(key=lambda row: (_severity_rank(row.get("severity")), -_recency(row)))
|
|
329
|
+
return rows
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _collect(repo, ident, online=False):
|
|
333
|
+
"""`(listed, rows, lines)`. `lines` maps a fingerprint to the source line.
|
|
334
|
+
|
|
335
|
+
`finding_entry` does not keep `line`. Remember it here, and do not put it on the entry:
|
|
336
|
+
the issues listing's keys, and the rows a triage stores, stay as they are.
|
|
337
|
+
"""
|
|
338
|
+
records = call_store(lambda: store.load(ident))
|
|
339
|
+
module = issues()
|
|
340
|
+
original = module.finding_entry
|
|
341
|
+
lines = {}
|
|
342
|
+
|
|
343
|
+
def finding_entry(f, *args, **kwargs):
|
|
344
|
+
entry = original(f, *args, **kwargs)
|
|
345
|
+
if isinstance(f, dict) and isinstance(entry, dict):
|
|
346
|
+
line = f.get("line")
|
|
347
|
+
fp = entry.get("fp")
|
|
348
|
+
if isinstance(fp, str) and isinstance(line, int) and not isinstance(line, bool):
|
|
349
|
+
lines[fp] = line
|
|
350
|
+
return entry
|
|
351
|
+
|
|
352
|
+
module.finding_entry = finding_entry
|
|
353
|
+
try:
|
|
354
|
+
listed = module.listing(repo, online=online)
|
|
355
|
+
except module.Busy as exc:
|
|
356
|
+
raise Refused(str(exc)) from exc
|
|
357
|
+
except module.Fail as exc:
|
|
358
|
+
raise Failed(str(exc)) from exc
|
|
359
|
+
finally:
|
|
360
|
+
module.finding_entry = original
|
|
361
|
+
return listed, _rows(listed, records), lines
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def collect(repo, ident, online=False):
|
|
365
|
+
"""`(listed, rows)`: the issues listing of a repository and one row per finding, with its record."""
|
|
366
|
+
listed, rows, _lines = _collect(repo, ident, online=online)
|
|
367
|
+
return listed, rows
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@command("show")
|
|
371
|
+
def cmd_show(args):
|
|
372
|
+
ident = require_ident(args.repo)
|
|
373
|
+
listed, rows, lines = _collect(args.repo, ident, online=bool(args.online))
|
|
374
|
+
chosen = _wanted(args.status)
|
|
375
|
+
if chosen is not None:
|
|
376
|
+
rows = [row for row in rows if row.get("status") in chosen]
|
|
377
|
+
if args.json:
|
|
378
|
+
print(json.dumps({
|
|
379
|
+
"repo": listed.get("repo") or "",
|
|
380
|
+
"root": ident.get("root"),
|
|
381
|
+
"key": ident.get("key"),
|
|
382
|
+
"findings": rows,
|
|
383
|
+
"notes": list(listed.get("notes") or []),
|
|
384
|
+
"warnings": list(listed.get("warnings") or []),
|
|
385
|
+
}, indent=2, ensure_ascii=False))
|
|
386
|
+
else:
|
|
387
|
+
for row in rows:
|
|
388
|
+
print(_show_line(row, lines.get(row.get("fp"))))
|
|
389
|
+
return 0
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@command("fix")
|
|
393
|
+
def cmd_fix(args):
|
|
394
|
+
if args.commit is None and args.reason is None:
|
|
395
|
+
raise Refused("fixed needs a commit and/or a reason")
|
|
396
|
+
fields = {}
|
|
397
|
+
if args.commit is not None:
|
|
398
|
+
fields["commit"] = args.commit
|
|
399
|
+
if args.reason is not None:
|
|
400
|
+
fields["reason"] = args.reason
|
|
401
|
+
return apply(args, args.fp, lambda ident, fps, actor: store.set_status(ident, fps, "fixed", actor, **fields))
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
@command("dismiss")
|
|
405
|
+
def cmd_dismiss(args):
|
|
406
|
+
return apply(args, args.fp,
|
|
407
|
+
lambda ident, fps, actor: store.set_status(ident, fps, "dismissed", actor, reason=args.reason))
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
@command("reopen")
|
|
411
|
+
def cmd_reopen(args):
|
|
412
|
+
return apply(args, args.fp, lambda ident, fps, actor: store.set_status(ident, fps, "open", actor))
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
@command("to-file")
|
|
416
|
+
def cmd_to_file(args):
|
|
417
|
+
kwargs = {"status": "to-file"}
|
|
418
|
+
if args.title is not None or args.body_file is not None:
|
|
419
|
+
body = read_payload(args.body_file, "--body-file", store.MAX_BODY) if args.body_file is not None else ""
|
|
420
|
+
kwargs["draft"] = {"title": args.title or "", "body": body}
|
|
421
|
+
return apply(args, args.fp, lambda ident, fps, actor: store.update(ident, fps, actor, **kwargs))
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
@command("dup")
|
|
425
|
+
def cmd_dup(args):
|
|
426
|
+
fps = fingerprints([args.fp])
|
|
427
|
+
of = fingerprints([args.of])[0]
|
|
428
|
+
if fps[0] == of:
|
|
429
|
+
raise Refused(f"{fps[0]}: a finding cannot be a duplicate of itself")
|
|
430
|
+
return apply(args, fps, lambda ident, found, actor: store.mark_duplicate(ident, found[0], of, actor))
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _take_common(args, tokens):
|
|
434
|
+
"""`--json` and `--actor` inside a remainder, which argparse does not parse."""
|
|
435
|
+
kept = []
|
|
436
|
+
index = 0
|
|
437
|
+
while index < len(tokens):
|
|
438
|
+
token = tokens[index]
|
|
439
|
+
if token == "--json":
|
|
440
|
+
args.json = True
|
|
441
|
+
index += 1
|
|
442
|
+
continue
|
|
443
|
+
if token == "--actor" or token.startswith("--actor="):
|
|
444
|
+
if token == "--actor":
|
|
445
|
+
if index + 1 >= len(tokens):
|
|
446
|
+
raise Usage("--actor needs one of cli, ui, triage")
|
|
447
|
+
value = tokens[index + 1]
|
|
448
|
+
index += 2
|
|
449
|
+
else:
|
|
450
|
+
value = token.split("=", 1)[1]
|
|
451
|
+
index += 1
|
|
452
|
+
if value not in ACTORS:
|
|
453
|
+
raise Usage(f"--actor must be one of {', '.join(ACTORS)}")
|
|
454
|
+
args.actor = value
|
|
455
|
+
continue
|
|
456
|
+
kept.append(token)
|
|
457
|
+
index += 1
|
|
458
|
+
return kept
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _parse_tag(tokens):
|
|
462
|
+
"""(fps, tags, 'add'|'remove'). `--` separates fingerprints from tags; tags may follow the flag."""
|
|
463
|
+
modes = [token for token in tokens if token in ("--add", "--remove")]
|
|
464
|
+
if not modes:
|
|
465
|
+
raise Usage("tag needs --add or --remove")
|
|
466
|
+
if len(modes) != 1:
|
|
467
|
+
raise Usage("tag takes one of --add or --remove")
|
|
468
|
+
mode = modes[0][2:]
|
|
469
|
+
if "--" in tokens:
|
|
470
|
+
dash = tokens.index("--")
|
|
471
|
+
before, after = tokens[:dash], tokens[dash + 1:]
|
|
472
|
+
fps = [token for token in before if token != modes[0]]
|
|
473
|
+
found = [token for token in after if token != modes[0]]
|
|
474
|
+
else:
|
|
475
|
+
flag = tokens.index(modes[0])
|
|
476
|
+
fps, found = tokens[:flag], tokens[flag + 1:]
|
|
477
|
+
for token in fps + found:
|
|
478
|
+
if token.startswith("-"):
|
|
479
|
+
raise Usage(f"tag: unknown option {token}")
|
|
480
|
+
if not fps:
|
|
481
|
+
raise Usage("tag needs a fingerprint")
|
|
482
|
+
if not found:
|
|
483
|
+
raise Usage("tag needs a tag")
|
|
484
|
+
return fps, found, mode
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@command("tag")
|
|
488
|
+
def cmd_tag(args):
|
|
489
|
+
fps, found, mode = _parse_tag(_take_common(args, list(args.rest or [])))
|
|
490
|
+
if mode == "add":
|
|
491
|
+
return apply(args, fps, lambda ident, items, actor: store.add_tags(ident, items, found, actor))
|
|
492
|
+
return apply(args, fps, lambda ident, items, actor: store.remove_tags(ident, items, found, actor))
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
@command("note")
|
|
496
|
+
def cmd_note(args):
|
|
497
|
+
return apply(args, [args.fp], lambda ident, fps, actor: store.set_note(ident, fps[0], args.text, actor))
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@command("edit")
|
|
501
|
+
def cmd_edit(args):
|
|
502
|
+
if args.severity is None and args.text_file is None:
|
|
503
|
+
raise Usage("edit needs --severity or --text-file")
|
|
504
|
+
text = read_payload(args.text_file, "--text-file", store.MAX_EDIT_TEXT) if args.text_file is not None else None
|
|
505
|
+
severity = args.severity
|
|
506
|
+
return apply(args, [args.fp],
|
|
507
|
+
lambda ident, fps, actor: store.set_edit(ident, fps[0], actor, severity=severity, text=text))
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _checkout(ident):
|
|
511
|
+
checkout = ident.get("checkout")
|
|
512
|
+
return checkout if isinstance(checkout, str) else ""
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _triage_call(fn):
|
|
516
|
+
try:
|
|
517
|
+
return fn()
|
|
518
|
+
except triage.Refused as exc:
|
|
519
|
+
raise Refused(str(exc)) from exc
|
|
520
|
+
except triage.Failed as exc:
|
|
521
|
+
raise Failed(str(exc)) from exc
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _job_argv(args, n):
|
|
525
|
+
"""The hidden job's command line: this script again, as a process of its own."""
|
|
526
|
+
return [sys.executable, str(Path(__file__).resolve()), "_triage-job", os.path.abspath(args.repo), str(n),
|
|
527
|
+
"--timeout", str(args.timeout)]
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
@command("triage")
|
|
531
|
+
def cmd_triage(args):
|
|
532
|
+
if args.timeout < 0:
|
|
533
|
+
raise Usage("--timeout must not be negative")
|
|
534
|
+
if not 1 <= args.max_findings <= triage.MAX_FINDINGS_LIMIT:
|
|
535
|
+
raise Usage(f"--max-findings must be 1 to {triage.MAX_FINDINGS_LIMIT}")
|
|
536
|
+
ident = require_ident(args.repo)
|
|
537
|
+
checkout = _checkout(ident)
|
|
538
|
+
_listed, rows = collect(args.repo, ident)
|
|
539
|
+
n, dest = _triage_call(lambda: triage.start(
|
|
540
|
+
ident, rows, args.spec, checkout, max_findings=args.max_findings, actor=args.actor))
|
|
541
|
+
if args.detach:
|
|
542
|
+
triage.detach(dest, _job_argv(args, n))
|
|
543
|
+
out = {"triage": n, "state": "running"}
|
|
544
|
+
else:
|
|
545
|
+
final = triage.run_job(dest, checkout, n, timeout=args.timeout)
|
|
546
|
+
triage.write_done(dest, 0 if final.get("state") == "done" else 1)
|
|
547
|
+
out = {"triage": n, **{k: final[k] for k in ("state", "reason", "proposals") if k in final}}
|
|
548
|
+
if args.json:
|
|
549
|
+
print(json.dumps(out, ensure_ascii=False))
|
|
550
|
+
else:
|
|
551
|
+
extra = out.get("reason") or (f"{out['proposals']} proposals" if "proposals" in out else "")
|
|
552
|
+
print(f"triage {n}: {out['state']}" + (f" ({extra})" if extra else ""))
|
|
553
|
+
return 1 if out["state"] == "failed" else 0
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
@command("_triage-job")
|
|
557
|
+
def cmd_triage_job(args):
|
|
558
|
+
ident = require_ident(args.repo)
|
|
559
|
+
found = triage.triage_dir(ident["key"], args.n)
|
|
560
|
+
if found is None:
|
|
561
|
+
raise Refused(f"no triage {args.n}")
|
|
562
|
+
final = triage.run_job(found[1], _checkout(ident), args.n, timeout=args.timeout)
|
|
563
|
+
return 0 if final.get("state") == "done" else 1
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _find_triage(args):
|
|
567
|
+
"""`(n, dir)` of the triage asked for, or the newest. Refused when there is none."""
|
|
568
|
+
ident = require_ident(args.repo)
|
|
569
|
+
found = triage.triage_dir(ident["key"], args.n)
|
|
570
|
+
if found is None:
|
|
571
|
+
raise Refused(f"no triage {args.n}" if args.n is not None else "no triage has run for this repository")
|
|
572
|
+
return found
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
@command("triage-status")
|
|
576
|
+
def cmd_triage_status(args):
|
|
577
|
+
n, dest = _find_triage(args)
|
|
578
|
+
state = triage.read_state(dest)
|
|
579
|
+
if state is None:
|
|
580
|
+
raise Refused(f"triage {n} has no state")
|
|
581
|
+
if args.json:
|
|
582
|
+
print(json.dumps({"triage": n, "dir": str(dest), **state}, indent=2, ensure_ascii=False))
|
|
583
|
+
else:
|
|
584
|
+
extra = state.get("reason") or (f"{state['proposals']} proposals" if "proposals" in state else "")
|
|
585
|
+
print(f"triage {n}: {state.get('state')}" + (f" ({extra})" if extra else "")
|
|
586
|
+
+ f" {state.get('findings', 0)} findings {state.get('spec', '-')}")
|
|
587
|
+
return 0
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _proposal_line(item):
|
|
591
|
+
kind = item.get("kind")
|
|
592
|
+
if kind in ("duplicate", "fixed"):
|
|
593
|
+
target = f"{item.get('fp')}" + (f" of {item.get('of')}" if kind == "duplicate" else "")
|
|
594
|
+
else:
|
|
595
|
+
target = ",".join(item.get("fps") or [])
|
|
596
|
+
label = " ".join(str(item.get("title") or "").split())
|
|
597
|
+
if kind == "tag":
|
|
598
|
+
label = ",".join(item.get("tags") or [])
|
|
599
|
+
return f"{item.get('id')} {item.get('hash')} {item.get('state')} {kind} {target}" + (f" {label}" if label else "")
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
@command("proposals")
|
|
603
|
+
def cmd_proposals(args):
|
|
604
|
+
n, dest = _find_triage(args)
|
|
605
|
+
data = triage.read_json(dest / "proposals.json")
|
|
606
|
+
if not isinstance(data, dict) or not isinstance(data.get("proposals"), list):
|
|
607
|
+
state = triage.read_state(dest) or {}
|
|
608
|
+
raise Refused(f"triage {n} has no proposals ({state.get('state', 'no state')})")
|
|
609
|
+
if args.json:
|
|
610
|
+
print(json.dumps(data, indent=2, ensure_ascii=False))
|
|
611
|
+
else:
|
|
612
|
+
for item in data["proposals"]:
|
|
613
|
+
print(_proposal_line(item))
|
|
614
|
+
return 0
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _approval_call(fn):
|
|
618
|
+
try:
|
|
619
|
+
return fn()
|
|
620
|
+
except approval.Refused as exc:
|
|
621
|
+
raise Refused(str(exc)) from exc
|
|
622
|
+
except approval.Failed as exc:
|
|
623
|
+
raise Failed(str(exc)) from exc
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _decision(args, result, verb):
|
|
627
|
+
if args.json:
|
|
628
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
629
|
+
return 0
|
|
630
|
+
print(f"{verb} {result['proposal'].get('id')}: {len(result['changed'])} changed")
|
|
631
|
+
if result.get("plan_dir"):
|
|
632
|
+
print(f"plan dir: {result['plan_dir']}")
|
|
633
|
+
print(f"next: {result['next']}")
|
|
634
|
+
return 0
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
@command("apply")
|
|
638
|
+
def cmd_apply(args):
|
|
639
|
+
ident = require_ident(args.repo)
|
|
640
|
+
result = _approval_call(lambda: approval.apply(
|
|
641
|
+
ident, args.n, args.pid, args.approve, lambda: collect(args.repo, ident)[1],
|
|
642
|
+
actor=args.actor, plan_dir=args.plan_dir))
|
|
643
|
+
return _decision(args, result, "applied")
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
@command("reject")
|
|
647
|
+
def cmd_reject(args):
|
|
648
|
+
ident = require_ident(args.repo)
|
|
649
|
+
result = _approval_call(lambda: approval.reject(ident, args.n, args.pid, actor=args.actor, reason=args.reason))
|
|
650
|
+
return _decision(args, result, "rejected")
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def report(exc, code, args):
|
|
654
|
+
message = " ".join(str(exc).split())
|
|
655
|
+
print(f"forge findings: {message}", file=sys.stderr)
|
|
656
|
+
if getattr(args, "json", False):
|
|
657
|
+
print(json.dumps({"ok": False, "error": message}, ensure_ascii=False))
|
|
658
|
+
return code
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def main(argv=None):
|
|
662
|
+
parser = build_parser()
|
|
663
|
+
args = parser.parse_args(argv)
|
|
664
|
+
try:
|
|
665
|
+
return COMMANDS[args.command](args)
|
|
666
|
+
except Usage as exc:
|
|
667
|
+
return report(exc, 2, args)
|
|
668
|
+
except Refused as exc:
|
|
669
|
+
return report(exc, 3, args)
|
|
670
|
+
except Failed as exc:
|
|
671
|
+
return report(exc, 1, args)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
if __name__ == "__main__":
|
|
675
|
+
sys.exit(main())
|