@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
package/ui/forge_ui/export.py
CHANGED
|
@@ -29,7 +29,7 @@ STATIC = server.STATIC_DIR
|
|
|
29
29
|
# groupsview.js is the group page. It is named here before that file exists; _page skips a
|
|
30
30
|
# SCRIPTS entry whose file is absent, so the export still builds.
|
|
31
31
|
SCRIPTS = ('theme.js', 'icons.js', 'datatable.js', 'shell.js', 'runmodel.js', 'cloudmodel.js', 'graph.js', 'gantt.js', 'verifyview.js', 'checksview.js',
|
|
32
|
-
'briefview.js', 'groupsview.js', 'panel.js', 'diffview.js', 'convo.js', 'files.js', 'map3d.js', 'search.js', 'app.js')
|
|
32
|
+
'briefview.js', 'groupsview.js', 'findingsactions.js', 'triageview.js', 'panel.js', 'diffview.js', 'convo.js', 'files.js', 'map3d.js', 'search.js', 'app.js')
|
|
33
33
|
LEFT_OUT = {
|
|
34
34
|
'uikit.js': 'write helpers and the guards that keep a poll from redrawing what a person holds; a snapshot neither writes nor polls',
|
|
35
35
|
'controls.js': 'changes a live run',
|
package/ui/forge_ui/projects.py
CHANGED
|
@@ -15,8 +15,11 @@ Sources, run dirs first:
|
|
|
15
15
|
dataset `forge dataset history --json` for runs whose dir is gone and checkouts that are gone; those rows
|
|
16
16
|
say so and link to no run page or diff
|
|
17
17
|
|
|
18
|
-
Finding statuses
|
|
19
|
-
|
|
18
|
+
Finding statuses come from forge_findings.status.effective (the one rule the CLI and the sweep share): the finding
|
|
19
|
+
record first (duplicate, dismissed, fixed, filed, to-file), then the issue's state in `forge issues` (online, so a
|
|
20
|
+
closed issue is `fixed`; offline when GitHub cannot be asked), then the review row: shadow, unlabelled, superseded
|
|
21
|
+
(a later review of the same task, or a later final review, passed: that does not claim the finding was fixed).
|
|
22
|
+
Only `open` and `to-file` are worked on.
|
|
20
23
|
|
|
21
24
|
Cost: nothing here runs on the page's poll. Each tab's endpoint is read when the tab opens; a run's findings
|
|
22
25
|
are cached by its `updated` time, the CLI answers for CACHE_S, and ?refresh=1 reads everything again.
|
|
@@ -25,15 +28,19 @@ from __future__ import annotations
|
|
|
25
28
|
|
|
26
29
|
import importlib.machinery
|
|
27
30
|
import importlib.util
|
|
31
|
+
import inspect
|
|
28
32
|
import os
|
|
29
33
|
from pathlib import Path
|
|
34
|
+
import sys
|
|
30
35
|
import threading
|
|
31
36
|
import time
|
|
32
37
|
|
|
33
38
|
from forge_ui import executions, findings as F, models, reader, repos
|
|
34
39
|
|
|
35
40
|
ISSUES = Path(__file__).resolve().parents[2] / 'scripts' / 'forge-issues.py'
|
|
41
|
+
SCRIPTS = ISSUES.parent
|
|
36
42
|
CACHE_S = 300
|
|
43
|
+
ONLINE_S = 60 # the online listing may take this long before the offline one is read instead
|
|
37
44
|
_SEVERITIES = ('P0', 'P1', 'P2', 'P3')
|
|
38
45
|
_STATE = {}
|
|
39
46
|
_LOCK = threading.Lock()
|
|
@@ -71,8 +78,8 @@ def project_id(root):
|
|
|
71
78
|
return '%08x' % h
|
|
72
79
|
|
|
73
80
|
|
|
74
|
-
def
|
|
75
|
-
"""`forge issues`
|
|
81
|
+
def parsed_finding(first_line):
|
|
82
|
+
"""The finding `forge issues` parses from a first line ({file, text, ...}), else None.
|
|
76
83
|
The canonical `[P1][CONFIRMED] path:line — text` form first, then the other forms forge issues reads from a
|
|
77
84
|
known_issues.md (`parse_known`), so a tolerated finding written another way still finds its entry."""
|
|
78
85
|
module = issues_module()
|
|
@@ -82,7 +89,77 @@ def fingerprint(first_line):
|
|
|
82
89
|
parsed = module.parse_findings(first_line)
|
|
83
90
|
if not parsed and callable(getattr(module, 'parse_known', None)):
|
|
84
91
|
parsed = module.parse_known(first_line)
|
|
85
|
-
return
|
|
92
|
+
return parsed[0] if parsed else None
|
|
93
|
+
except Exception:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def fingerprint(first_line):
|
|
98
|
+
"""`forge issues`' key for a finding whose first line it can parse, else None (such rows never collapse)."""
|
|
99
|
+
parsed = parsed_finding(first_line)
|
|
100
|
+
if parsed is None:
|
|
101
|
+
return None
|
|
102
|
+
try:
|
|
103
|
+
return issues_module().finding_key(parsed)
|
|
104
|
+
except Exception:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _Record:
|
|
109
|
+
"""forge_findings' store, status and tags and forge_identity, loaded read-only like models.py loads forge_dataset."""
|
|
110
|
+
|
|
111
|
+
def __init__(self, store, status, tags, identity):
|
|
112
|
+
self.store, self.status, self.tags, self.identity = store, status, tags, identity
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def record_modules():
|
|
116
|
+
"""The finding record's modules, or None when they cannot be loaded (rows then keep the old status)."""
|
|
117
|
+
with _LOCK:
|
|
118
|
+
if 'record' in _STATE:
|
|
119
|
+
return _STATE['record']
|
|
120
|
+
found = None
|
|
121
|
+
scripts = str(SCRIPTS)
|
|
122
|
+
inserted = scripts not in sys.path
|
|
123
|
+
if inserted:
|
|
124
|
+
sys.path.insert(0, scripts)
|
|
125
|
+
try:
|
|
126
|
+
import forge_identity
|
|
127
|
+
loaded = {}
|
|
128
|
+
for name in ('status', 'tags', 'store'):
|
|
129
|
+
path = SCRIPTS / 'forge_findings' / (name + '.py')
|
|
130
|
+
module_name = 'forge_findings_%s_for_ui' % name
|
|
131
|
+
spec = importlib.util.spec_from_file_location(
|
|
132
|
+
module_name, path, loader=_ReadOnlyLoader(module_name, str(path)))
|
|
133
|
+
module = importlib.util.module_from_spec(spec)
|
|
134
|
+
spec.loader.exec_module(module)
|
|
135
|
+
loaded[name] = module
|
|
136
|
+
if not (callable(loaded['status'].effective) and callable(loaded['tags'].tags_for)
|
|
137
|
+
and callable(loaded['store'].load) and callable(forge_identity.identity)):
|
|
138
|
+
raise TypeError('not the finding record')
|
|
139
|
+
found = _Record(loaded['store'], loaded['status'], loaded['tags'], forge_identity)
|
|
140
|
+
except Exception:
|
|
141
|
+
found = None
|
|
142
|
+
finally:
|
|
143
|
+
if inserted and scripts in sys.path:
|
|
144
|
+
sys.path.remove(scripts)
|
|
145
|
+
_STATE['record'] = found
|
|
146
|
+
return found
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def read_record(root):
|
|
150
|
+
"""(ident, {fingerprint: entry}) of the repository at `root`; entries are {} when it has no identity or no
|
|
151
|
+
record yet. None when the record cannot be read at all (not loadable, corrupt, no state directory)."""
|
|
152
|
+
modules = record_modules()
|
|
153
|
+
if modules is None or not root:
|
|
154
|
+
return None
|
|
155
|
+
try:
|
|
156
|
+
ident = modules.identity.identity(root)
|
|
157
|
+
if ident is None:
|
|
158
|
+
return None, {}
|
|
159
|
+
data = modules.store.load(ident)
|
|
160
|
+
if isinstance(data, dict) and data.get('version') == 1 and isinstance(data.get('findings'), dict):
|
|
161
|
+
data = data['findings']
|
|
162
|
+
return ident, dict(data) if isinstance(data, dict) else {}
|
|
86
163
|
except Exception:
|
|
87
164
|
return None
|
|
88
165
|
|
|
@@ -340,6 +417,27 @@ def issue_for(index, row, run_path):
|
|
|
340
417
|
return found
|
|
341
418
|
|
|
342
419
|
|
|
420
|
+
def _first_of(row):
|
|
421
|
+
return (row.get('text') or '').split('\n', 1)[0]
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _slug_of(ident):
|
|
425
|
+
try:
|
|
426
|
+
return record_modules().identity.github_slug(ident) or ''
|
|
427
|
+
except Exception:
|
|
428
|
+
return ''
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _issues_call(issues, path, online):
|
|
432
|
+
"""issues(path, online=...) when the callable takes `online`, else issues(path) (it knows one way to ask)."""
|
|
433
|
+
try:
|
|
434
|
+
params = inspect.signature(issues).parameters
|
|
435
|
+
takes = 'online' in params or any(q.kind == q.VAR_KEYWORD for q in params.values())
|
|
436
|
+
except (TypeError, ValueError):
|
|
437
|
+
takes = False
|
|
438
|
+
return issues(path, online=online) if takes else issues(path)
|
|
439
|
+
|
|
440
|
+
|
|
343
441
|
# ---- the cached screen -----------------------------------------------------------------------------
|
|
344
442
|
|
|
345
443
|
class Screen:
|
|
@@ -350,13 +448,29 @@ class Screen:
|
|
|
350
448
|
self.runs = {} # run path -> (updated, occurrences)
|
|
351
449
|
self.cli = {} # key -> (time, value)
|
|
352
450
|
|
|
353
|
-
def
|
|
451
|
+
def _cli_at(self, key, call, refresh, now):
|
|
452
|
+
"""(value, the time it was read) of a CLI answer, cached for CACHE_S."""
|
|
354
453
|
hit = self.cli.get(key)
|
|
355
454
|
if not refresh and hit is not None and now - hit[0] < CACHE_S:
|
|
356
|
-
return hit[1]
|
|
455
|
+
return hit[1], hit[0]
|
|
357
456
|
value = call()
|
|
358
457
|
self.cli[key] = (now, value)
|
|
359
|
-
return value
|
|
458
|
+
return value, now
|
|
459
|
+
|
|
460
|
+
def _cli(self, key, call, refresh, now):
|
|
461
|
+
return self._cli_at(key, call, refresh, now)[0]
|
|
462
|
+
|
|
463
|
+
def _cli_unlocked_at(self, key, call, refresh, now):
|
|
464
|
+
"""`_cli_at` for a caller that does not hold the lock: the cache is read and written under it, the call runs
|
|
465
|
+
outside it, so a slow answer (GitHub, up to ONLINE_S) never holds up the other screens."""
|
|
466
|
+
with self.lock:
|
|
467
|
+
hit = self.cli.get(key)
|
|
468
|
+
if not refresh and hit is not None and now - hit[0] < CACHE_S:
|
|
469
|
+
return hit[1], hit[0]
|
|
470
|
+
value = call()
|
|
471
|
+
with self.lock:
|
|
472
|
+
self.cli[key] = (now, value)
|
|
473
|
+
return value, now
|
|
360
474
|
|
|
361
475
|
def occurrences(self, run):
|
|
362
476
|
hit = self.runs.get(run['path'])
|
|
@@ -377,9 +491,10 @@ class Screen:
|
|
|
377
491
|
projects = self.projects(catalog)
|
|
378
492
|
out = []
|
|
379
493
|
for p in projects.values():
|
|
380
|
-
#
|
|
381
|
-
|
|
382
|
-
|
|
494
|
+
# Rows the finding record and the review rules call open (or to-file): not shadow, unlabelled,
|
|
495
|
+
# superseded, nor closed in the record. The listing of issues needs GitHub, so filed and swept
|
|
496
|
+
# findings are not known here: the Findings tab's own count can be lower still.
|
|
497
|
+
open_findings = self._open_findings(p, collapse([o for run in p['runs'] for o in self.occurrences(run)]))
|
|
383
498
|
out.append(dict(id=p['id'], name=p['name'], root=p['root'], exists=p['exists'], runs=len(p['runs']),
|
|
384
499
|
live=p['live'], last=p['last'], path_only=p['path_only'],
|
|
385
500
|
checkouts=len(checkouts(p)), memory_lines=_memory_lines(p['root']) if p['exists'] else None,
|
|
@@ -387,6 +502,33 @@ class Screen:
|
|
|
387
502
|
out.sort(key=lambda p: p['last'] or 0, reverse=True)
|
|
388
503
|
return dict(projects=out)
|
|
389
504
|
|
|
505
|
+
def _open_findings(self, p, rows):
|
|
506
|
+
record = read_record(p['root']) if p['exists'] else (None, {})
|
|
507
|
+
modules = record_modules()
|
|
508
|
+
if modules is None or record is None:
|
|
509
|
+
return sum(1 for row in rows if not row['superseded'])
|
|
510
|
+
ident, entries = record
|
|
511
|
+
slug = _slug_of(ident) if ident and entries else ''
|
|
512
|
+
count = 0
|
|
513
|
+
for row in rows:
|
|
514
|
+
entry = entries.get(self._record_fp(slug, row)) if entries else None
|
|
515
|
+
if modules.status.effective(entry, None, row) in modules.status.OPEN:
|
|
516
|
+
count += 1
|
|
517
|
+
return count
|
|
518
|
+
|
|
519
|
+
@staticmethod
|
|
520
|
+
def _record_fp(slug, row, issue=None):
|
|
521
|
+
"""The record's key of a row: its issues entry's `fp`, else the one forge-issues computes for its first line."""
|
|
522
|
+
if issue is not None and isinstance(issue.get('fp'), str) and issue['fp']:
|
|
523
|
+
return issue['fp']
|
|
524
|
+
parsed = parsed_finding(_first_of(row))
|
|
525
|
+
if parsed is None:
|
|
526
|
+
return None
|
|
527
|
+
try:
|
|
528
|
+
return issues_module().fingerprint(slug, parsed)
|
|
529
|
+
except Exception:
|
|
530
|
+
return None
|
|
531
|
+
|
|
390
532
|
def detail(self, catalog, pid):
|
|
391
533
|
p = self.project(catalog, pid)
|
|
392
534
|
if p is None:
|
|
@@ -415,8 +557,39 @@ class Screen:
|
|
|
415
557
|
out.add(run['run'])
|
|
416
558
|
return out
|
|
417
559
|
|
|
560
|
+
def _read_issues(self, p, issues, refresh, now):
|
|
561
|
+
"""(listing, online, read_at) of `forge issues` for the project: asked once of the repository's root, online
|
|
562
|
+
first (it knows which issues are closed), offline when that fails or takes over ONLINE_S. Only a root
|
|
563
|
+
that is no checkout, or that gave nothing, sends it through the project's runs (at most three).
|
|
564
|
+
Called without the lock."""
|
|
565
|
+
paths = []
|
|
566
|
+
if p['exists']:
|
|
567
|
+
paths.append(p['root'])
|
|
568
|
+
paths += [run['path'] for run in sorted(p['runs'], key=lambda r: (r.get('repo_worktree') is not None,
|
|
569
|
+
r.get('kind') != 'plan'))[:3]]
|
|
570
|
+
online_failed = False
|
|
571
|
+
for path in paths:
|
|
572
|
+
if not online_failed:
|
|
573
|
+
listing, at = self._cli_unlocked_at(('issues', path, True), lambda: _issues_call(issues, path, True),
|
|
574
|
+
refresh, now)
|
|
575
|
+
if listing is not None:
|
|
576
|
+
return listing, True, at
|
|
577
|
+
online_failed = True
|
|
578
|
+
listing, at = self._cli_unlocked_at(('issues', path, False), lambda: _issues_call(issues, path, False),
|
|
579
|
+
refresh, now)
|
|
580
|
+
if listing is not None:
|
|
581
|
+
return listing, False, at
|
|
582
|
+
return None, False, None
|
|
583
|
+
|
|
418
584
|
def findings(self, catalog, pid, history, issues, refresh=False, now=None):
|
|
419
585
|
now = time.time() if now is None else now
|
|
586
|
+
with self.lock:
|
|
587
|
+
p = self.projects(catalog).get(pid)
|
|
588
|
+
if p is None:
|
|
589
|
+
return None
|
|
590
|
+
# `forge issues` asks GitHub (up to ONLINE_S): never under the lock the project list, the Memories tab and
|
|
591
|
+
# every write's invalidation wait on
|
|
592
|
+
listing, online, read_at = self._read_issues(p, issues, refresh, now)
|
|
420
593
|
with self.lock:
|
|
421
594
|
projects = self.projects(catalog)
|
|
422
595
|
p = projects.get(pid)
|
|
@@ -431,21 +604,31 @@ class Screen:
|
|
|
431
604
|
gone = self._dataset_runs(p, hist, projects) if hist else set()
|
|
432
605
|
if hist:
|
|
433
606
|
occ += _dataset_occurrences(hist, gone)
|
|
434
|
-
# forge issues reads every run of the repository (--all-runs) from any one of them, but needs that run's
|
|
435
|
-
# checkout to name its GitHub repository: runs started in the root first, at most three tries.
|
|
436
|
-
tried = sorted(p['runs'], key=lambda r: (r.get('repo_worktree') is not None, r.get('kind') != 'plan'))[:3]
|
|
437
|
-
listing = None
|
|
438
|
-
for run in tried:
|
|
439
|
-
listing = self._cli(('issues', run['path']), lambda: issues(run['path']), refresh, now)
|
|
440
|
-
if listing is not None:
|
|
441
|
-
break
|
|
442
607
|
index = issue_index(listing)
|
|
443
608
|
paths = {run['key']: run['path'] for run in p['runs']}
|
|
444
609
|
rows = collapse(occ)
|
|
610
|
+
record = read_record(p['root']) if p['exists'] else (None, {})
|
|
611
|
+
modules = record_modules()
|
|
612
|
+
ident, entries = record if record is not None else (None, {})
|
|
613
|
+
slug = (listing or {}).get('repo') if listing is not None else None
|
|
614
|
+
if not isinstance(slug, str):
|
|
615
|
+
slug = _slug_of(ident) if (ident and listing is None) else ''
|
|
445
616
|
for row in rows:
|
|
446
617
|
issue = issue_for(index, row, paths.get(row['run']))
|
|
447
|
-
row['
|
|
448
|
-
|
|
618
|
+
row['record_fp'] = self._record_fp(slug, row, issue)
|
|
619
|
+
if modules is None or record is None:
|
|
620
|
+
row['status'], row['record'], row['tags'], row['draft'] = status_of(row, issue), None, [], None
|
|
621
|
+
else:
|
|
622
|
+
entry = entries.get(row['record_fp']) if row['record_fp'] else None
|
|
623
|
+
parsed = None if issue else parsed_finding(_first_of(row))
|
|
624
|
+
where = ((issue or {}).get('file') or (parsed or {}).get('file')
|
|
625
|
+
or str(row.get('location') or '').rsplit(':', 1)[0])
|
|
626
|
+
row['record'] = entry
|
|
627
|
+
row['status'] = modules.status.effective(entry, issue, row)
|
|
628
|
+
row['tags'] = modules.tags.tags_for(entry, where)
|
|
629
|
+
row['draft'] = entry.get('draft') if isinstance(entry, dict) else None
|
|
630
|
+
row['fileable'] = (issue is not None and row['status'] in ('open', 'to-file')
|
|
631
|
+
and row['source'] == 'run')
|
|
449
632
|
row['origin'] = issue.get('origin') if issue else None
|
|
450
633
|
rows.sort(key=lambda r: (_SEVERITIES.index(r['severity']) if r['severity'] in _SEVERITIES else 9, -(r['at'] or 0)))
|
|
451
634
|
notes = []
|
|
@@ -455,8 +638,12 @@ class Screen:
|
|
|
455
638
|
notes.append('the dataset is off (FORGE_DATASET=off): only the run directories that still exist are read')
|
|
456
639
|
if listing is None:
|
|
457
640
|
notes.append('forge issues could not be read: dismissed and filed findings show as open')
|
|
641
|
+
elif not online:
|
|
642
|
+
notes.append('issue states could not be read from GitHub: filed findings may show as open')
|
|
643
|
+
if modules is None or record is None:
|
|
644
|
+
notes.append('the finding record could not be read')
|
|
458
645
|
return dict(id=pid, rows=rows, notes=notes, runs=len(p['runs']), dataset_runs=len(gone),
|
|
459
|
-
computed=now, available=F.available())
|
|
646
|
+
computed=now, available=F.available(), issues_online=online, issues_read_at=read_at)
|
|
460
647
|
|
|
461
648
|
def memories(self, catalog, pid, learnings, history, refresh=False, now=None):
|
|
462
649
|
now = time.time() if now is None else now
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/* forge-ui finding actions (#161): the pure logic behind the Findings tab's write controls (window.ForgeFindingsActions,
|
|
2
|
+
and a CommonJS module under node:test). No DOM. Nothing is decided here that the server does not decide again: these
|
|
3
|
+
functions only build the request body of each op (or say why it cannot be built), build the `forge findings …` line
|
|
4
|
+
a read-only page offers to copy, and say what a selection allows.
|
|
5
|
+
A row is the Projects answer's finding row: `record_fp` is the record key (null when the row cannot be acted on),
|
|
6
|
+
`status` one of STATUSES, `tags` the effective tags, `record.tags` the stored ones, `fp` and `run` what `forge issues`
|
|
7
|
+
files by. Tested in ui/tests/js/findingsactions.test.js. */
|
|
8
|
+
(function (root, factory) {
|
|
9
|
+
'use strict';
|
|
10
|
+
const api = factory(root);
|
|
11
|
+
if (typeof module === 'object' && module.exports) module.exports = api;
|
|
12
|
+
else root.ForgeFindingsActions = api;
|
|
13
|
+
})(typeof self !== 'undefined' ? self : this, function () {
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
const list = v => Array.isArray(v) ? v : [];
|
|
17
|
+
const MAX_FPS = 200, MAX_FILE = 25, MAX_TAGS = 8, MAX_NOTE = 2000, MAX_REASON = 500, MAX_EDIT_TEXT = 4000, MAX_TITLE = 200, MAX_BODY = 20000;
|
|
18
|
+
const SEVERITIES = ['P0', 'P1', 'P2', 'P3'];
|
|
19
|
+
const OPEN_STATUSES = ['open', 'to-file'];
|
|
20
|
+
const OPS = ['fix', 'dismiss', 'reopen', 'to-file', 'dup', 'tag', 'note', 'edit'];
|
|
21
|
+
const SINGLE = ['dup', 'note', 'edit'];
|
|
22
|
+
const TAG_RE = /^[a-z][a-z0-9-]{0,23}$/, FP_RE = /^[0-9a-f]{12}$/, COMMIT_RE = /^[0-9a-f]{7,40}$/;
|
|
23
|
+
const CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/; // newline and tab are allowed, as the routes allow them
|
|
24
|
+
const PAST = { fix: 'marked fixed', dismiss: 'dismissed', reopen: 'reopened', 'to-file': 'marked to file', dup: 'marked duplicate', tag: 'tagged', note: 'noted', edit: 'edited' };
|
|
25
|
+
|
|
26
|
+
const str = v => typeof v === 'string' ? v : v == null ? '' : String(v);
|
|
27
|
+
const fail = error => ({ error });
|
|
28
|
+
|
|
29
|
+
/* ---------- rows ---------- */
|
|
30
|
+
const selectable = row => !!(row && typeof row.record_fp === 'string' && row.record_fp);
|
|
31
|
+
const isOpen = row => !!row && OPEN_STATUSES.includes(row.status);
|
|
32
|
+
// The tags a person stored on this row. With none stored the row shows the defaults forge derives from the path.
|
|
33
|
+
const storedTags = row => list(row && row.record && row.record.tags).filter(t => typeof t === 'string');
|
|
34
|
+
const tagsOf = row => list(row && row.tags).filter(t => typeof t === 'string');
|
|
35
|
+
const derivedTags = row => !!row && storedTags(row).length === 0;
|
|
36
|
+
function tagsIn(rows) { return Array.from(new Set(list(rows).flatMap(tagsOf))).sort(); }
|
|
37
|
+
function filterByTag(rows, tag) { return tag ? list(rows).filter(r => tagsOf(r).includes(tag)) : list(rows); }
|
|
38
|
+
|
|
39
|
+
/* ---------- the selection ---------- */
|
|
40
|
+
// The selected rows among `rows` (the rows the filters show), in row order, once each. `picked` is a Set of record_fp.
|
|
41
|
+
function selectedRows(rows, picked) {
|
|
42
|
+
const want = picked instanceof Set ? picked : new Set(list(picked)), seen = new Set(), out = [];
|
|
43
|
+
for (const row of list(rows)) {
|
|
44
|
+
if (!selectable(row) || !want.has(row.record_fp) || seen.has(row.record_fp)) continue;
|
|
45
|
+
seen.add(row.record_fp); out.push(row);
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
const fpsOf = rows => list(rows).filter(selectable).map(r => r.record_fp);
|
|
50
|
+
// Which actions a selection (rows already narrowed to the shown ones) allows. `why` says what holds them all back.
|
|
51
|
+
function allowed(selected) {
|
|
52
|
+
const rows = list(selected).filter(selectable), n = rows.length, many = n >= 1 && n <= MAX_FPS, one = n === 1;
|
|
53
|
+
const why = n > MAX_FPS ? `${n} selected: at most ${MAX_FPS} per action` : '';
|
|
54
|
+
return { count: n, why, fix: many, dismiss: many, reopen: many && rows.some(r => r.status !== 'open'), 'to-file': many, tag: many,
|
|
55
|
+
dup: one, note: one, edit: one, file: fileableFps(rows).length > 0 && fileRun(rows) !== null };
|
|
56
|
+
}
|
|
57
|
+
// The fingerprints "File selected" hands to forge issues: rows `forge issues` can file, still open, at most 25.
|
|
58
|
+
// `record_fp`, not `fp`: `fp` is the slug-less key rows collapse by, while `forge issues --only` matches the
|
|
59
|
+
// full fingerprint (with the repository slug), which is what `record_fp` holds.
|
|
60
|
+
function fileableFps(rows) {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const r of list(rows)) {
|
|
63
|
+
if (out.length >= MAX_FILE) break;
|
|
64
|
+
if (r && r.fileable && isOpen(r) && selectable(r) && !out.includes(r.record_fp)) out.push(r.record_fp);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
// The run `forge issues` reads for the filing: the first fileable selected row's.
|
|
69
|
+
function fileRun(rows) {
|
|
70
|
+
const row = list(rows).find(r => r && r.fileable && isOpen(r) && selectable(r) && r.run);
|
|
71
|
+
return row ? row.run : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/* ---------- tags ---------- */
|
|
75
|
+
// "a, b" → {tags, error}. Commas and spaces separate; each tag is a lowercase letter then up to 23 letters, digits or dashes.
|
|
76
|
+
function parseTags(text) {
|
|
77
|
+
const tags = Array.from(new Set(str(text).split(/[\s,]+/).filter(Boolean)));
|
|
78
|
+
if (!tags.length) return { tags: [], error: 'give at least one tag' };
|
|
79
|
+
if (tags.length > MAX_TAGS) return { tags: [], error: `at most ${MAX_TAGS} tags` };
|
|
80
|
+
const bad = tags.find(t => !TAG_RE.test(t));
|
|
81
|
+
if (bad !== undefined) return { tags: [], error: `"${bad}" is not a tag: a lowercase letter, then lowercase letters, digits or dashes, at most 24 characters` };
|
|
82
|
+
return { tags, error: null };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/* ---------- bodies ---------- */
|
|
86
|
+
function checkText(value, name, limit, required) {
|
|
87
|
+
const text = str(value).trim();
|
|
88
|
+
if (!text) return required ? fail(`${name} is required`) : { text: null };
|
|
89
|
+
if (text.length > limit) return fail(`${name} is at most ${limit} characters`);
|
|
90
|
+
if (CONTROL_RE.test(text)) return fail(`${name} cannot hold control characters`);
|
|
91
|
+
return { text };
|
|
92
|
+
}
|
|
93
|
+
// The POST body of one op for these record fingerprints: {body} or {error}. `o` holds what the person typed.
|
|
94
|
+
function bodyFor(op, fps, o) {
|
|
95
|
+
o = o || {};
|
|
96
|
+
if (!OPS.includes(op)) return fail('unknown action');
|
|
97
|
+
const keys = Array.from(new Set(list(fps).filter(f => typeof f === 'string' && f)));
|
|
98
|
+
if (!keys.length) return fail('select a finding first');
|
|
99
|
+
if (SINGLE.includes(op) ? keys.length !== 1 : keys.length > MAX_FPS) return fail(SINGLE.includes(op) ? 'this action takes one finding' : `at most ${MAX_FPS} findings per action`);
|
|
100
|
+
const body = { fps: keys };
|
|
101
|
+
if (op === 'fix') {
|
|
102
|
+
const commit = str(o.commit).trim().toLowerCase(), reason = checkText(o.reason, 'the reason', MAX_REASON, false);
|
|
103
|
+
if (reason.error) return reason;
|
|
104
|
+
if (!commit && reason.text === null) return fail('give a commit or a reason');
|
|
105
|
+
if (commit) { if (!COMMIT_RE.test(commit)) return fail('a commit is 7 to 40 hexadecimal characters'); body.commit = commit; }
|
|
106
|
+
if (reason.text !== null) body.reason = reason.text;
|
|
107
|
+
} else if (op === 'dismiss') {
|
|
108
|
+
const reason = checkText(o.reason, 'the reason', MAX_REASON, true);
|
|
109
|
+
if (reason.error) return reason;
|
|
110
|
+
body.reason = reason.text;
|
|
111
|
+
} else if (op === 'to-file') {
|
|
112
|
+
const title = checkText(o.title, 'the title', MAX_TITLE, false), text = checkText(o.body, 'the body', MAX_BODY, false);
|
|
113
|
+
if (title.error) return title;
|
|
114
|
+
if (text.error) return text;
|
|
115
|
+
if (title.text !== null) body.title = title.text;
|
|
116
|
+
if (text.text !== null) body.body = text.text;
|
|
117
|
+
} else if (op === 'dup') {
|
|
118
|
+
const of = str(o.of).trim();
|
|
119
|
+
if (!FP_RE.test(of)) return fail('pick the finding it duplicates');
|
|
120
|
+
if (of === keys[0]) return fail('a finding cannot duplicate itself');
|
|
121
|
+
body.of = of;
|
|
122
|
+
} else if (op === 'tag') {
|
|
123
|
+
const parsed = Array.isArray(o.tags) ? parseTags(o.tags.join(' ')) : parseTags(o.tags);
|
|
124
|
+
if (parsed.error) return fail(parsed.error);
|
|
125
|
+
body.tags = parsed.tags; body.remove = !!o.remove;
|
|
126
|
+
} else if (op === 'note') {
|
|
127
|
+
const text = checkText(o.text, 'the note', MAX_NOTE, false); // empty text clears the note
|
|
128
|
+
if (text.error) return text;
|
|
129
|
+
body.text = text.text === null ? '' : text.text;
|
|
130
|
+
} else if (op === 'edit') {
|
|
131
|
+
const severity = str(o.severity).trim();
|
|
132
|
+
if (severity && !SEVERITIES.includes(severity)) return fail('the severity is P0, P1, P2 or P3');
|
|
133
|
+
if (!severity && (o.text === undefined || o.text === null)) return fail('give a severity or a text');
|
|
134
|
+
if (severity) body.severity = severity;
|
|
135
|
+
if (o.text !== undefined && o.text !== null) { // an empty text clears the edit
|
|
136
|
+
const text = str(o.text);
|
|
137
|
+
if (text.length > MAX_EDIT_TEXT) return fail(`the text is at most ${MAX_EDIT_TEXT} characters`);
|
|
138
|
+
body.text = text;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return { body };
|
|
142
|
+
}
|
|
143
|
+
const pathOf = (id, op) => '/api/projects/' + encodeURIComponent(id) + '/findings/' + op;
|
|
144
|
+
|
|
145
|
+
/* ---------- the copyable command ---------- */
|
|
146
|
+
// One argument for a POSIX shell: single quotes keep `$`, backticks and quotes literal. A safe word stays bare.
|
|
147
|
+
function shellQuote(value) {
|
|
148
|
+
const text = str(value);
|
|
149
|
+
if (text !== '' && /^[A-Za-z0-9_@%+=:,./-]+$/.test(text) && !text.startsWith('-')) return text;
|
|
150
|
+
return "'" + text.replace(/'/g, "'\\''") + "'";
|
|
151
|
+
}
|
|
152
|
+
// `--name VALUE`, or `--name=VALUE` when the value starts with "-" so the CLI does not read it as a flag.
|
|
153
|
+
const option = (name, value) => { const v = shellQuote(value); return str(value).startsWith('-') ? `--${name}=${v}` : `--${name} ${v}`; };
|
|
154
|
+
// `forge findings <op> REPO FP… …`. What the person has not typed stays a placeholder word (SHA, TEXT, FP, TAG).
|
|
155
|
+
function commandFor(op, repo, fps, o) {
|
|
156
|
+
o = o || {};
|
|
157
|
+
const head = ['forge findings', op, shellQuote(repo)].concat(list(fps).map(shellQuote));
|
|
158
|
+
const has = v => str(v).trim() !== '';
|
|
159
|
+
if (op === 'fix') {
|
|
160
|
+
if (has(o.commit)) head.push(option('commit', str(o.commit).trim()));
|
|
161
|
+
if (has(o.reason)) head.push(option('reason', str(o.reason).trim()));
|
|
162
|
+
if (!has(o.commit) && !has(o.reason)) head.push('--commit SHA');
|
|
163
|
+
} else if (op === 'dismiss') head.push(has(o.reason) ? option('reason', str(o.reason).trim()) : '--reason TEXT');
|
|
164
|
+
else if (op === 'to-file') { if (has(o.title)) head.push(option('title', str(o.title).trim())); if (has(o.body)) head.push('--body-file FILE'); }
|
|
165
|
+
else if (op === 'dup') head.push(has(o.of) ? option('of', str(o.of).trim()) : '--of FP');
|
|
166
|
+
else if (op === 'tag') {
|
|
167
|
+
const tags = Array.isArray(o.tags) ? o.tags : has(o.tags) ? parseTags(o.tags).tags : [];
|
|
168
|
+
head.push('--', ...(tags.length ? tags.map(shellQuote) : ['TAG']), o.remove ? '--remove' : '--add'); // `--` ends the fingerprints
|
|
169
|
+
} else if (op === 'note') { const text = o.text === undefined ? 'TEXT' : str(o.text).trim(); head.push(...(text.startsWith('-') ? ['--', shellQuote(text)] : [shellQuote(text)])); }
|
|
170
|
+
else if (op === 'edit') {
|
|
171
|
+
if (has(o.severity)) head.push(option('severity', str(o.severity).trim()));
|
|
172
|
+
if (o.text !== undefined && o.text !== null) head.push('--text-file FILE');
|
|
173
|
+
if (!has(o.severity) && (o.text === undefined || o.text === null)) head.push('--severity Pn');
|
|
174
|
+
}
|
|
175
|
+
return head.join(' ');
|
|
176
|
+
}
|
|
177
|
+
// The commands a read-only page offers for one row: [{op, label, command}].
|
|
178
|
+
const COMMAND_LABELS = { fix: 'Mark fixed', dismiss: 'Dismiss', reopen: 'Reopen', 'to-file': 'Mark to file', dup: 'Duplicate of…', tag: 'Add a tag', note: 'Note', edit: 'Edit' };
|
|
179
|
+
function commandsFor(repo, row) {
|
|
180
|
+
if (!selectable(row)) return [];
|
|
181
|
+
return OPS.filter(op => op !== 'reopen' || row.status !== 'open').map(op => ({ op, label: COMMAND_LABELS[op], command: commandFor(op, repo, [row.record_fp]) }));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/* ---------- the confirm sentence ---------- */
|
|
185
|
+
const noun = n => `${n} finding${n === 1 ? '' : 's'}`;
|
|
186
|
+
function confirmText(op, count, body) {
|
|
187
|
+
const b = body || {}, n = noun(count);
|
|
188
|
+
if (op === 'fix') return `Mark ${n} fixed${b.commit ? ` by ${b.commit}` : ''}${b.reason ? `: ${b.reason}` : ''}?`;
|
|
189
|
+
if (op === 'dismiss') return `Dismiss ${n}: ${b.reason}?`;
|
|
190
|
+
if (op === 'reopen') return `Reopen ${n}?`;
|
|
191
|
+
if (op === 'to-file') return `Mark ${n} to file${b.title ? ` as "${b.title}"` : ''}?`;
|
|
192
|
+
if (op === 'dup') return `Mark ${n} a duplicate of ${b.of}?`;
|
|
193
|
+
if (op === 'tag') return `${b.remove ? 'Remove' : 'Add'} ${list(b.tags).join(', ')} ${b.remove ? 'from' : 'to'} ${n}?`;
|
|
194
|
+
if (op === 'note') return b.text ? `Set the note of ${n}?` : `Clear the note of ${n}?`;
|
|
195
|
+
if (op === 'edit') return `Edit ${n}${b.severity ? `: severity ${b.severity}` : ''}${b.text !== undefined ? ': replace the text' : ''}?`;
|
|
196
|
+
return `${op} ${n}?`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return { MAX_FPS, MAX_FILE, MAX_TAGS, OPS, SINGLE, PAST, OPEN_STATUSES, selectable, isOpen, storedTags, tagsOf, derivedTags, tagsIn, filterByTag, selectedRows, fpsOf,
|
|
200
|
+
allowed, fileableFps, fileRun, parseTags, bodyFor, pathOf, shellQuote, commandFor, commandsFor, confirmText };
|
|
201
|
+
});
|
|
@@ -39,6 +39,8 @@
|
|
|
39
39
|
<script src="findingsview.js" defer></script>
|
|
40
40
|
<script src="worktreesview.js" defer></script>
|
|
41
41
|
<script src="storageview.js" defer></script>
|
|
42
|
+
<script src="findingsactions.js" defer></script>
|
|
43
|
+
<script src="triageview.js" defer></script>
|
|
42
44
|
<script src="projectsview.js" defer></script>
|
|
43
45
|
<script src="rundelete.js" defer></script>
|
|
44
46
|
<script src="settings.js" defer></script>
|