repometry 0.7.0 → 0.8.1
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/README.md +23 -20
- package/package.json +1 -1
- package/target/main/resources/config/process-plugins-v1.schema.json +4 -0
- package/target/main/resources/languages/go/parser.go +602 -0
- package/target/main/resources/languages/python/parser.py +312 -0
- package/target/main/resources/report/json/viewer-inspection-v1.schema.json +2 -1
- package/target/main/resources/viewer/files.css +1 -0
- package/target/main/ts/api/git/git-reader.d.ts +10 -2
- package/target/main/ts/api/git/git-reader.js +74 -35
- package/target/main/ts/api/git/git.d.ts +19 -1
- package/target/main/ts/api/git/git.js +97 -7
- package/target/main/ts/api/import/go-cover.d.ts +13 -0
- package/target/main/ts/api/import/go-cover.js +150 -0
- package/target/main/ts/api/import/lcov-files.d.ts +6 -1
- package/target/main/ts/api/import/lcov-files.js +27 -7
- package/target/main/ts/api/process/docker-tool-runner.js +5 -21
- package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
- package/target/main/ts/api/process/host-language-runner.js +176 -0
- package/target/main/ts/api/process/plugin.d.ts +4 -1
- package/target/main/ts/api/process/plugin.js +7 -3
- package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
- package/target/main/ts/api/process/tool-snapshot.js +26 -0
- package/target/main/ts/cli/imports.d.ts +1 -0
- package/target/main/ts/cli/imports.js +5 -2
- package/target/main/ts/cli/main.js +46 -15
- package/target/main/ts/compose/analysis-files.d.ts +2 -1
- package/target/main/ts/compose/analysis-files.js +19 -5
- package/target/main/ts/compose/analysis-imports.js +2 -1
- package/target/main/ts/compose/analysis-report.d.ts +1 -0
- package/target/main/ts/compose/analysis-report.js +13 -12
- package/target/main/ts/compose/analysis-repository.d.ts +2 -1
- package/target/main/ts/compose/analysis-repository.js +42 -4
- package/target/main/ts/compose/analysis-sources.d.ts +5 -0
- package/target/main/ts/compose/analysis-sources.js +10 -3
- package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
- package/target/main/ts/compose/analyze-snapshot.js +5 -3
- package/target/main/ts/compose/diff-coverage.d.ts +2 -1
- package/target/main/ts/compose/diff-coverage.js +8 -6
- package/target/main/ts/compose/history-cache.d.ts +29 -0
- package/target/main/ts/compose/history-cache.js +57 -0
- package/target/main/ts/compose/inspect.d.ts +6 -1
- package/target/main/ts/compose/inspect.js +10 -10
- package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
- package/target/main/ts/compose/inspection-coverage.js +9 -0
- package/target/main/ts/compose/languages.d.ts +6 -1
- package/target/main/ts/compose/languages.js +19 -6
- package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
- package/target/main/ts/compose/native-language-plugins.js +40 -0
- package/target/main/ts/compose/plugin-list.d.ts +3 -8
- package/target/main/ts/compose/plugin-list.js +12 -5
- package/target/main/ts/compose/prepare-metabranch.js +1 -1
- package/target/main/ts/compose/process-plugins.js +6 -5
- package/target/main/ts/compose/review.d.ts +1 -2
- package/target/main/ts/compose/review.js +2 -2
- package/target/main/ts/core/engine/plan.js +5 -6
- package/target/main/ts/core/engine/plugin.d.ts +2 -0
- package/target/main/ts/core/model/file-types.d.ts +1 -0
- package/target/main/ts/core/model/file-types.js +14 -3
- package/target/main/ts/core/model/quality-summary.js +2 -0
- package/target/main/ts/core/model/source.d.ts +2 -0
- package/target/main/ts/core/usecases/inspect.d.ts +1 -1
- package/target/main/ts/core/usecases/inspect.js +1 -1
- package/target/main/ts/plugins/security/dockerfile.js +6 -15
- package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
- package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
- package/target/main/ts/report/html/app/viewer-profile.js +9 -2
- package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
- package/target/main/ts/report/json/projections/commit-summary.js +5 -0
- package/target/main/ts/report/json/projections/file-metrics.js +39 -44
- package/target/main/ts/report/json/projections/inspection-details.js +3 -2
- package/target/main/ts/report/json/store/directory.d.ts +3 -0
- package/target/main/ts/report/json/store/directory.js +19 -0
- package/target/main/ts/report/json/store/local-store.d.ts +14 -2
- package/target/main/ts/report/json/store/local-store.js +74 -60
- package/target/main/ts/report/json/store/object-store.d.ts +14 -0
- package/target/main/ts/report/json/store/object-store.js +73 -0
- package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
- package/target/main/ts/report/json/store/report-tree.js +290 -0
- package/target/main/ts/report/json/store/store-check.d.ts +32 -0
- package/target/main/ts/report/json/store/store-check.js +144 -0
- package/target/main/ts/report/json/validation/report.d.ts +6 -1
- package/target/main/ts/report/json/validation/report.js +10 -4
- package/target/main/ts/report/json/wire/inspection-details-model.d.ts +1 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Repository-scoped Python structure provider for Repometry."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from bisect import bisect_left, bisect_right
|
|
5
|
+
import hashlib
|
|
6
|
+
import io
|
|
7
|
+
from itertools import accumulate, groupby
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
import tokenize
|
|
11
|
+
import warnings
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DECISION_NODES = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.ExceptHandler, ast.IfExp)
|
|
15
|
+
MATCH_CASE = getattr(ast, "match_case", ())
|
|
16
|
+
MATCH = getattr(ast, "Match", ())
|
|
17
|
+
CALLABLES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
|
|
18
|
+
LOOPS = (ast.For, ast.AsyncFor, ast.While)
|
|
19
|
+
TRY_NODES = (ast.Try, getattr(ast, "TryStar", ast.Try))
|
|
20
|
+
COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def irrefutable(pattern):
|
|
24
|
+
if isinstance(pattern, ast.MatchAs):
|
|
25
|
+
return pattern.pattern is None or irrefutable(pattern.pattern)
|
|
26
|
+
return isinstance(pattern, ast.MatchOr) and any(irrefutable(choice) for choice in pattern.patterns)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def decisions(node):
|
|
30
|
+
if isinstance(node, DECISION_NODES):
|
|
31
|
+
return 1
|
|
32
|
+
if isinstance(node, ast.BoolOp):
|
|
33
|
+
return len(node.values) - 1
|
|
34
|
+
if isinstance(node, MATCH_CASE):
|
|
35
|
+
return int(not irrefutable(node.pattern)) + int(node.guard is not None)
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def boolean_operators(node):
|
|
40
|
+
if isinstance(node, ast.BoolOp):
|
|
41
|
+
for index, value in enumerate(node.values):
|
|
42
|
+
if index > 0:
|
|
43
|
+
yield type(node.op)
|
|
44
|
+
yield from boolean_operators(value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Scope:
|
|
48
|
+
def __init__(self):
|
|
49
|
+
self.cyclomatic = 1
|
|
50
|
+
self.cognitive = 0
|
|
51
|
+
self.returns = 0
|
|
52
|
+
self.depth = 0
|
|
53
|
+
self.deepest = None
|
|
54
|
+
|
|
55
|
+
def block(self, node, depth, flat=False):
|
|
56
|
+
self.cognitive += 1 if flat else 1 + depth
|
|
57
|
+
if depth + 1 > self.depth:
|
|
58
|
+
self.depth = depth + 1
|
|
59
|
+
self.deepest = node
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Structure:
|
|
63
|
+
def __init__(self, lines):
|
|
64
|
+
self.lines = lines
|
|
65
|
+
self.cyclomatic_functions = []
|
|
66
|
+
self.cognitive_functions = []
|
|
67
|
+
self.observations = []
|
|
68
|
+
self.cognitive = 0
|
|
69
|
+
self.classes = 0
|
|
70
|
+
self.names = []
|
|
71
|
+
|
|
72
|
+
def analyze(self, tree):
|
|
73
|
+
module = Scope()
|
|
74
|
+
self.visit(tree, module)
|
|
75
|
+
self.finish_scope(module, "Module")
|
|
76
|
+
self.observe("file-complexity", self.cognitive, "File cognitive complexity")
|
|
77
|
+
for rows in (self.cyclomatic_functions, self.cognitive_functions):
|
|
78
|
+
rows.sort(key=lambda item: (item["line"], item["column"]))
|
|
79
|
+
|
|
80
|
+
def visit(self, node, scope, depth=0, parent=None, chained=False):
|
|
81
|
+
if isinstance(node, CALLABLES):
|
|
82
|
+
self.visit_function(node, scope, depth)
|
|
83
|
+
return
|
|
84
|
+
if isinstance(node, ast.ClassDef):
|
|
85
|
+
self.visit_class(node, scope, depth)
|
|
86
|
+
return
|
|
87
|
+
scope.cyclomatic += decisions(node)
|
|
88
|
+
if isinstance(node, ast.Return):
|
|
89
|
+
scope.returns += 1
|
|
90
|
+
if isinstance(node, ast.BoolOp) and not isinstance(parent, ast.BoolOp):
|
|
91
|
+
operators = list(boolean_operators(node))
|
|
92
|
+
scope.cognitive += sum(1 for _ in groupby(operators))
|
|
93
|
+
self.observe("boolean-logic", len(operators), "Logical operators in one expression", node)
|
|
94
|
+
|
|
95
|
+
if isinstance(node, ast.If):
|
|
96
|
+
self.visit_if(node, scope, depth, chained)
|
|
97
|
+
elif isinstance(node, COMPREHENSIONS):
|
|
98
|
+
self.visit_comprehension(node, scope, depth)
|
|
99
|
+
elif isinstance(node, MATCH_CASE):
|
|
100
|
+
self.visit(node.pattern, scope, depth)
|
|
101
|
+
if node.guard is not None:
|
|
102
|
+
scope.block(node.guard, depth)
|
|
103
|
+
depth += 1
|
|
104
|
+
self.visit(node.guard, scope, depth)
|
|
105
|
+
self.visit_all(node.body, scope, depth)
|
|
106
|
+
elif isinstance(node, TRY_NODES):
|
|
107
|
+
self.visit_all(node.body, scope, depth)
|
|
108
|
+
self.visit_all(node.handlers, scope, depth)
|
|
109
|
+
self.visit_else(node.orelse, scope, depth)
|
|
110
|
+
self.visit_all(node.finalbody, scope, depth)
|
|
111
|
+
else:
|
|
112
|
+
if isinstance(node, (*LOOPS, ast.ExceptHandler, ast.IfExp)) or isinstance(node, MATCH):
|
|
113
|
+
scope.block(node, depth)
|
|
114
|
+
depth += 1
|
|
115
|
+
if isinstance(node, LOOPS) and node.orelse:
|
|
116
|
+
scope.cognitive += 1
|
|
117
|
+
for child in ast.iter_child_nodes(node):
|
|
118
|
+
self.visit(child, scope, depth, node)
|
|
119
|
+
|
|
120
|
+
def visit_if(self, node, scope, depth, chained):
|
|
121
|
+
scope.block(node, depth, flat=chained)
|
|
122
|
+
self.visit(node.test, scope, depth + 1)
|
|
123
|
+
self.visit_all(node.body, scope, depth + 1)
|
|
124
|
+
alternate = node.orelse
|
|
125
|
+
if (len(alternate) == 1 and isinstance(alternate[0], ast.If)
|
|
126
|
+
and alternate[0].col_offset == node.col_offset):
|
|
127
|
+
self.visit(alternate[0], scope, depth, chained=True)
|
|
128
|
+
else:
|
|
129
|
+
self.visit_else(alternate, scope, depth)
|
|
130
|
+
|
|
131
|
+
def visit_else(self, body, scope, depth):
|
|
132
|
+
if body:
|
|
133
|
+
scope.cognitive += 1
|
|
134
|
+
self.visit_all(body, scope, depth + 1)
|
|
135
|
+
|
|
136
|
+
def visit_comprehension(self, node, scope, depth):
|
|
137
|
+
for generator in node.generators:
|
|
138
|
+
scope.cyclomatic += 1 + len(generator.ifs)
|
|
139
|
+
scope.block(node, depth)
|
|
140
|
+
depth += 1
|
|
141
|
+
self.visit(generator.target, scope, depth)
|
|
142
|
+
self.visit(generator.iter, scope, depth)
|
|
143
|
+
for condition in generator.ifs:
|
|
144
|
+
scope.block(condition, depth)
|
|
145
|
+
depth += 1
|
|
146
|
+
self.visit(condition, scope, depth)
|
|
147
|
+
values = (node.key, node.value) if isinstance(node, ast.DictComp) else (node.elt,)
|
|
148
|
+
self.visit_all(values, scope, depth)
|
|
149
|
+
|
|
150
|
+
def visit_header(self, node, scope, depth):
|
|
151
|
+
for field, value in ast.iter_fields(node):
|
|
152
|
+
if field == "body":
|
|
153
|
+
continue
|
|
154
|
+
if isinstance(value, ast.AST):
|
|
155
|
+
self.visit(value, scope, depth)
|
|
156
|
+
elif isinstance(value, list):
|
|
157
|
+
self.visit_all(value, scope, depth)
|
|
158
|
+
|
|
159
|
+
def visit_function(self, node, enclosing, depth):
|
|
160
|
+
self.visit_header(node, enclosing, depth)
|
|
161
|
+
name = getattr(node, "name", None)
|
|
162
|
+
location = {"line": node.lineno, "column": codepoint_column(self.lines, node.lineno, node.col_offset) + 1}
|
|
163
|
+
if name is not None:
|
|
164
|
+
self.names.append(name)
|
|
165
|
+
location["name"] = ".".join(self.names)
|
|
166
|
+
label = location.get("name", "(anonymous)")
|
|
167
|
+
scope = Scope()
|
|
168
|
+
body = [node.body] if isinstance(node, ast.Lambda) else node.body
|
|
169
|
+
self.visit_all(body, scope, 0)
|
|
170
|
+
if name is not None:
|
|
171
|
+
self.names.pop()
|
|
172
|
+
self.cyclomatic_functions.append({**location, "value": scope.cyclomatic})
|
|
173
|
+
self.cognitive_functions.append({**location, "value": scope.cognitive})
|
|
174
|
+
args = node.args
|
|
175
|
+
parameters = (len(args.posonlyargs) + len(args.args) + len(args.kwonlyargs)
|
|
176
|
+
+ int(args.vararg is not None) + int(args.kwarg is not None))
|
|
177
|
+
self.observe("function-parameters", parameters, f"{label} · Parameters", node)
|
|
178
|
+
self.observe("return-statements", scope.returns, f"{label} · Return statements", node)
|
|
179
|
+
self.observe("function-complexity", scope.cognitive, f"{label} · Cognitive complexity", node)
|
|
180
|
+
self.finish_scope(scope, label)
|
|
181
|
+
|
|
182
|
+
def visit_class(self, node, enclosing, depth):
|
|
183
|
+
self.classes += 1
|
|
184
|
+
self.visit_header(node, enclosing, depth)
|
|
185
|
+
self.names.append(node.name)
|
|
186
|
+
scope = Scope()
|
|
187
|
+
self.visit_all(node.body, scope, 0)
|
|
188
|
+
self.finish_scope(scope, ".".join(self.names))
|
|
189
|
+
self.names.pop()
|
|
190
|
+
|
|
191
|
+
def visit_all(self, nodes, scope, depth):
|
|
192
|
+
for node in nodes:
|
|
193
|
+
self.visit(node, scope, depth)
|
|
194
|
+
|
|
195
|
+
def finish_scope(self, scope, label):
|
|
196
|
+
self.cognitive += scope.cognitive
|
|
197
|
+
if scope.deepest is not None:
|
|
198
|
+
self.observe("nested-control-flow", scope.depth, f"{label} · Control-flow depth", scope.deepest)
|
|
199
|
+
|
|
200
|
+
def observe(self, rule, value, label, node=None):
|
|
201
|
+
observation = {"rule": rule, "value": value, "label": label}
|
|
202
|
+
if node is not None:
|
|
203
|
+
observation.update(line=node.lineno, endLine=node.end_lineno)
|
|
204
|
+
self.observations.append(observation)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def codepoint_column(lines, line, byte_offset):
|
|
208
|
+
# AST offsets are UTF-8 bytes, even for files with a different source encoding.
|
|
209
|
+
return len(lines[line - 1].encode("utf-8")[:byte_offset].decode("utf-8"))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def clone_candidates(path, tree, lines, starts, code_lines, min_lines, min_nodes):
|
|
213
|
+
candidates = []
|
|
214
|
+
|
|
215
|
+
def walk(value, normalize_literal=False):
|
|
216
|
+
if isinstance(value, ast.AST):
|
|
217
|
+
exact = [type(value).__name__]
|
|
218
|
+
similar = exact.copy()
|
|
219
|
+
nodes = 1
|
|
220
|
+
for field, child in ast.iter_fields(value):
|
|
221
|
+
child_exact, child_similar, count = walk(child, isinstance(value, ast.Constant) and field == "value")
|
|
222
|
+
exact.append((field, child_exact))
|
|
223
|
+
similar.append((field, child_similar))
|
|
224
|
+
nodes += count
|
|
225
|
+
exact, similar = fingerprint(exact), fingerprint(similar)
|
|
226
|
+
if nodes >= min_nodes and isinstance(value, (ast.stmt, ast.Lambda, ast.ExceptHandler)):
|
|
227
|
+
consider(value, exact, similar, nodes)
|
|
228
|
+
return exact, similar, nodes
|
|
229
|
+
if isinstance(value, list):
|
|
230
|
+
parts = [walk(item) for item in value]
|
|
231
|
+
return [item[0] for item in parts], [item[1] for item in parts], sum(item[2] for item in parts)
|
|
232
|
+
# Preserve literal kinds and syntactic flags while normalizing names and literal values.
|
|
233
|
+
kind = type(value).__name__
|
|
234
|
+
exact = (kind, hex(value) if type(value) is int else repr(value))
|
|
235
|
+
similar = (kind,) if normalize_literal or isinstance(value, str) else exact
|
|
236
|
+
return exact, similar, 0
|
|
237
|
+
|
|
238
|
+
def consider(node, exact, similar, nodes):
|
|
239
|
+
line, end_line = node.lineno, node.end_lineno
|
|
240
|
+
code_count = bisect_right(code_lines, end_line) - bisect_left(code_lines, line)
|
|
241
|
+
if code_count >= min_lines:
|
|
242
|
+
start = starts[line - 1] + codepoint_column(lines, line, node.col_offset)
|
|
243
|
+
end = starts[end_line - 1] + codepoint_column(lines, end_line, node.end_col_offset)
|
|
244
|
+
candidates.append({"start": start, "end": end, "line": line, "endLine": end_line,
|
|
245
|
+
"codeLines": code_count, "nodes": nodes, "exact": exact, "similar": similar})
|
|
246
|
+
|
|
247
|
+
if len(code_lines) >= min_lines:
|
|
248
|
+
walk(tree)
|
|
249
|
+
return {"path": path, "scheme": "python-ast/v1", "codeLines": code_lines, "candidates": candidates}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def fingerprint(parts):
|
|
253
|
+
encoded = json.dumps(parts, separators=(",", ":")).encode("ascii")
|
|
254
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def analyze(path, min_lines, min_nodes):
|
|
258
|
+
with open(path, "rb") as file:
|
|
259
|
+
raw = file.read()
|
|
260
|
+
normalized = raw.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
|
|
261
|
+
physical_lines = normalized.count(b"\n") + int(bool(normalized) and not normalized.endswith(b"\n"))
|
|
262
|
+
encoding, _ = tokenize.detect_encoding(io.BytesIO(normalized).readline)
|
|
263
|
+
decoded = raw.decode(encoding)
|
|
264
|
+
source = decoded.replace("\r\n", "\n").replace("\r", "\n")
|
|
265
|
+
lines = source.split("\n")[:physical_lines]
|
|
266
|
+
with warnings.catch_warnings():
|
|
267
|
+
warnings.simplefilter("ignore")
|
|
268
|
+
tree = ast.parse(source)
|
|
269
|
+
|
|
270
|
+
comment_lines = {
|
|
271
|
+
item.start[0]
|
|
272
|
+
for item in tokenize.generate_tokens(io.StringIO(source).readline)
|
|
273
|
+
if item.type == tokenize.COMMENT and not item.line[:item.start[1]].strip()
|
|
274
|
+
}
|
|
275
|
+
code_lines = [number for number, line in enumerate(lines, 1) if line.strip() and number not in comment_lines]
|
|
276
|
+
structure = Structure(lines)
|
|
277
|
+
structure.analyze(tree)
|
|
278
|
+
starts = list(accumulate(map(len, io.StringIO(decoded, newline="")), initial=0))
|
|
279
|
+
return {
|
|
280
|
+
"path": path,
|
|
281
|
+
"lines": physical_lines,
|
|
282
|
+
"functions": len(structure.cyclomatic_functions),
|
|
283
|
+
"cyclomaticFunctions": structure.cyclomatic_functions,
|
|
284
|
+
"cognitiveFunctions": structure.cognitive_functions,
|
|
285
|
+
"cognitiveComplexity": structure.cognitive,
|
|
286
|
+
"classes": structure.classes,
|
|
287
|
+
"commentLines": len(comment_lines),
|
|
288
|
+
"codeLines": code_lines,
|
|
289
|
+
"observations": structure.observations,
|
|
290
|
+
"clones": clone_candidates(path, tree, lines, starts, code_lines, min_lines, min_nodes),
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def main():
|
|
295
|
+
request = json.load(sys.stdin.buffer)
|
|
296
|
+
files = request["inputs"]["files"]["files"]
|
|
297
|
+
duplication = request.get("settings", {}).get("duplication", {})
|
|
298
|
+
min_lines, min_nodes = duplication.get("minCodeLines", 12), duplication.get("minNodes", 50)
|
|
299
|
+
structures = []
|
|
300
|
+
for file in files:
|
|
301
|
+
path = file["path"]
|
|
302
|
+
try:
|
|
303
|
+
structures.append(analyze(path, min_lines, min_nodes))
|
|
304
|
+
except (OSError, SyntaxError, ValueError, LookupError, RecursionError, tokenize.TokenError):
|
|
305
|
+
print(json.dumps({
|
|
306
|
+
"kind": "diagnostic", "severity": "warning", "message": f"Could not analyze Python file {path!r}."
|
|
307
|
+
}))
|
|
308
|
+
print(json.dumps({"kind": "product", "contract": "repometry.code-structures/v1", "value": structures}))
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
if __name__ == "__main__":
|
|
312
|
+
main()
|
|
@@ -156,7 +156,8 @@
|
|
|
156
156
|
"id": { "type": "string" },
|
|
157
157
|
"label": { "type": "string" },
|
|
158
158
|
"extensions": { "type": "array", "items": { "type": "string" } },
|
|
159
|
-
"globs": { "type": "array", "items": { "type": "string" } }
|
|
159
|
+
"globs": { "type": "array", "items": { "type": "string" } },
|
|
160
|
+
"unavailableReason": { "type": "string" }
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
},
|
|
@@ -557,6 +557,7 @@ code.fx-function-name { font-size: .75rem; color: var(--secondary); }
|
|
|
557
557
|
.profile-claims { display: grid; gap: .5rem; margin: 0; padding: 0; list-style: none; }
|
|
558
558
|
.profile-claims > li { display: grid; grid-template-columns: minmax(6rem, auto) minmax(0, 1fr); gap: .75rem; align-items: baseline; }
|
|
559
559
|
.profile-claim { font-size: .875rem; color: var(--ink); }
|
|
560
|
+
.profile-claim-patterns { display: flex; flex-wrap: wrap; align-items: baseline; gap: .375rem .75rem; }
|
|
560
561
|
.profile-chips { display: flex; flex-wrap: wrap; gap: .375rem; margin: 0; padding: 0; list-style: none; }
|
|
561
562
|
.profile-chips li { padding: .0625rem .5rem; border-radius: 5px; background: var(--surface-2); color: var(--ink); font: .8125rem/1.6 var(--mono); overflow-wrap: anywhere; }
|
|
562
563
|
.profile-rule { font-size: .8125rem; font-weight: 600; }
|
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
import type { Subject } from '../../core/model/snapshot.js';
|
|
2
|
+
import type { ObjectSource } from '../../report/json/store/report-tree.js';
|
|
2
3
|
import type { Report, ReportReader } from '../../report/json/validation/report.js';
|
|
3
4
|
import type { CommitSummary } from '../../report/json/wire/summary-model.js';
|
|
5
|
+
/** Reads a report store straight from a Git revision of a storage branch, without a checkout. */
|
|
4
6
|
export declare class GitReportReader implements ReportReader {
|
|
5
7
|
private readonly directory;
|
|
6
8
|
private readonly revision;
|
|
7
9
|
private snapshot?;
|
|
10
|
+
private readonly cache;
|
|
11
|
+
private readonly blobs;
|
|
8
12
|
constructor(directory: string, revision: string);
|
|
9
13
|
read(subject: Subject): Promise<Report>;
|
|
10
14
|
list(): Promise<readonly Report[]>;
|
|
11
15
|
listSummaries(): Promise<readonly CommitSummary[]>;
|
|
12
|
-
private
|
|
13
|
-
private
|
|
16
|
+
private refreshMaintainability;
|
|
17
|
+
private reportIds;
|
|
18
|
+
private text;
|
|
19
|
+
private objects;
|
|
14
20
|
private pinnedSnapshot;
|
|
15
21
|
private resolveSnapshot;
|
|
16
22
|
}
|
|
23
|
+
/** Report objects as a storage branch revision holds them, to read or to restore a local store from. */
|
|
24
|
+
export declare function gitReportObjects(directory: string, revision: string): Promise<ObjectSource>;
|
|
@@ -1,59 +1,83 @@
|
|
|
1
1
|
import { checkMetaManifest } from '../../report/json/validation/metabranch.js';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { GitBlobReader, gitTreeFiles } from './git.js';
|
|
3
|
+
import { qualitySummary } from '../../core/model/quality-summary.js';
|
|
4
|
+
import { utf8 } from '../../core/model/snapshot.js';
|
|
5
|
+
import { compareReports, readStoredReport, validSubjectId } from '../../report/json/validation/report.js';
|
|
6
|
+
import { headerSummary } from '../../report/json/store/local-store.js';
|
|
7
|
+
import { ObjectCache, objectPath, storedObjects } from '../../report/json/store/report-tree.js';
|
|
8
|
+
import { commitSummary, expandSummaryCatalog, needsMaintainabilityRefresh, orderSummaries } from '../../report/json/projections/commit-summary.js';
|
|
5
9
|
import { validateSummaryIndex } from '../../report/json/validation/summary-validation.js';
|
|
10
|
+
/** Reads a report store straight from a Git revision of a storage branch, without a checkout. */
|
|
6
11
|
export class GitReportReader {
|
|
7
12
|
directory;
|
|
8
13
|
revision;
|
|
9
14
|
snapshot;
|
|
15
|
+
cache = new ObjectCache();
|
|
16
|
+
blobs;
|
|
10
17
|
constructor(directory, revision) {
|
|
11
18
|
this.directory = directory;
|
|
12
19
|
this.revision = revision;
|
|
20
|
+
this.blobs = new GitBlobReader(directory);
|
|
13
21
|
}
|
|
14
22
|
async read(subject) {
|
|
15
23
|
if (subject.kind !== 'commit' || !validSubjectId('commit', subject.id))
|
|
16
24
|
throw new Error('Metabranch reports require a full source commit ID');
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
if (!entry)
|
|
25
|
+
const tree = await this.pinnedSnapshot();
|
|
26
|
+
const text = await this.text(tree, `commits/${subject.id}/report.json`);
|
|
27
|
+
if (text === undefined)
|
|
21
28
|
throw Object.assign(new Error(`No report for ${subject.id} in ${this.revision}`), { code: 'ENOENT' });
|
|
22
|
-
return
|
|
29
|
+
return readStoredReport(text, subject, this.objects(tree));
|
|
23
30
|
}
|
|
24
31
|
async list() {
|
|
25
|
-
|
|
32
|
+
const reports = [];
|
|
33
|
+
for (const id of await this.reportIds(await this.pinnedSnapshot()))
|
|
34
|
+
reports.push(await this.read({ kind: 'commit', id }));
|
|
35
|
+
return reports.sort(compareReports);
|
|
26
36
|
}
|
|
27
37
|
async listSummaries() {
|
|
28
|
-
const
|
|
29
|
-
const [
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
]);
|
|
33
|
-
const file = index.find(entry => entry.path === 'summary.json');
|
|
34
|
-
if (file) {
|
|
35
|
-
const value = JSON.parse(await gitBlobText(this.directory, file.oid));
|
|
38
|
+
const tree = await this.pinnedSnapshot();
|
|
39
|
+
const [ids, index] = await Promise.all([this.reportIds(tree), this.text(tree, 'summary.json')]);
|
|
40
|
+
if (index !== undefined) {
|
|
41
|
+
const value = JSON.parse(index);
|
|
36
42
|
if (!validateSummaryIndex(value))
|
|
37
43
|
throw new Error(`Invalid Repometry summary in ${this.revision}`);
|
|
38
44
|
const shas = new Set(value.commits.map(row => row.sha));
|
|
39
|
-
if (shas.size === value.commits.length &&
|
|
40
|
-
&& value.commits.every(row => row.revision && row.counts && !row.detail))
|
|
41
|
-
return expandSummaryCatalog(value);
|
|
45
|
+
if (shas.size === value.commits.length && ids.length === shas.size && ids.every(id => shas.has(id))
|
|
46
|
+
&& value.commits.every(row => row.revision && row.counts && !row.detail)) {
|
|
47
|
+
return this.refreshMaintainability(expandSummaryCatalog(value));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Without a complete summary.json, each report's first line carries its summary row.
|
|
51
|
+
const rows = [];
|
|
52
|
+
for (const id of ids) {
|
|
53
|
+
const text = await this.text(tree, `commits/${id}/report.json`);
|
|
54
|
+
if (text !== undefined)
|
|
55
|
+
rows.push(headerSummary(text, id) ?? commitSummary(await readStoredReport(text, { kind: 'commit', id }, this.objects(tree))));
|
|
42
56
|
}
|
|
43
|
-
return orderSummaries(
|
|
57
|
+
return orderSummaries(rows);
|
|
44
58
|
}
|
|
45
|
-
|
|
46
|
-
|
|
59
|
+
refreshMaintainability(rows) {
|
|
60
|
+
if (!rows.some(needsMaintainabilityRefresh))
|
|
61
|
+
return rows;
|
|
62
|
+
return Promise.all(rows.map(async (row) => {
|
|
63
|
+
if (!needsMaintainabilityRefresh(row))
|
|
64
|
+
return row;
|
|
65
|
+
const report = await this.read({ kind: 'commit', id: row.sha });
|
|
66
|
+
return { ...row, quality: { ...row.quality, maintainability: qualitySummary(report).maintainability } };
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
async reportIds(tree) {
|
|
70
|
+
return (await gitTreeFiles(this.directory, tree, 'commits')).flatMap(({ path }) => {
|
|
47
71
|
const id = /^commits\/([a-f0-9]+)\/report\.json$/.exec(path)?.[1];
|
|
48
|
-
return id && validSubjectId('commit', id) ? [
|
|
72
|
+
return id && validSubjectId('commit', id) ? [id] : [];
|
|
49
73
|
});
|
|
50
74
|
}
|
|
51
|
-
async
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return
|
|
75
|
+
async text(tree, path) {
|
|
76
|
+
const [blob] = await this.blobs.read([`${tree}:${path}`]);
|
|
77
|
+
return blob === undefined ? undefined : utf8(blob);
|
|
78
|
+
}
|
|
79
|
+
objects(tree) {
|
|
80
|
+
return treeObjects(this.blobs, tree, this.cache);
|
|
57
81
|
}
|
|
58
82
|
pinnedSnapshot() {
|
|
59
83
|
this.snapshot ??= this.resolveSnapshot().catch(error => {
|
|
@@ -63,12 +87,27 @@ export class GitReportReader {
|
|
|
63
87
|
return this.snapshot;
|
|
64
88
|
}
|
|
65
89
|
async resolveSnapshot() {
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
if (
|
|
90
|
+
const tree = await pinnedTree(this.blobs, this.directory, this.revision);
|
|
91
|
+
const manifest = await this.text(tree, 'manifest.json');
|
|
92
|
+
if (manifest === undefined)
|
|
69
93
|
throw new Error(`No Repometry manifest in ${this.revision}`);
|
|
70
|
-
checkMetaManifest(
|
|
71
|
-
return
|
|
94
|
+
checkMetaManifest(manifest);
|
|
95
|
+
return tree;
|
|
72
96
|
}
|
|
73
97
|
}
|
|
98
|
+
/** Report objects as a storage branch revision holds them, to read or to restore a local store from. */
|
|
99
|
+
export async function gitReportObjects(directory, revision) {
|
|
100
|
+
const blobs = new GitBlobReader(directory);
|
|
101
|
+
return treeObjects(blobs, await pinnedTree(blobs, directory, revision));
|
|
102
|
+
}
|
|
103
|
+
/** The tree a revision names, a commit's root tree or the tree itself, so later reads cannot move with the branch. */
|
|
104
|
+
async function pinnedTree(blobs, directory, revision) {
|
|
105
|
+
const tree = await blobs.id(`${revision}^{tree}`);
|
|
106
|
+
if (tree === undefined)
|
|
107
|
+
throw new Error(`${revision} is not a commit or tree in ${directory}`);
|
|
108
|
+
return tree;
|
|
109
|
+
}
|
|
110
|
+
function treeObjects(blobs, tree, cache) {
|
|
111
|
+
return storedObjects(ids => blobs.read(ids.map(id => `${tree}:${objectPath(id)}`)), cache);
|
|
112
|
+
}
|
|
74
113
|
//# sourceMappingURL=git-reader.js.map
|
|
@@ -17,6 +17,24 @@ interface GitFile {
|
|
|
17
17
|
readonly size?: number;
|
|
18
18
|
}
|
|
19
19
|
export declare function gitTreeFiles(directory: string, commit: string, prefix?: string, includeSize?: boolean): Promise<readonly GitFile[]>;
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Reads blobs named like `<tree>:<path>` through one long-lived `git cat-file --batch`: requests stream in and answers
|
|
22
|
+
* come back in order. A name Git cannot find reads as undefined. The process keeps Node alive only while it owes answers.
|
|
23
|
+
*/
|
|
24
|
+
export declare class GitBlobReader {
|
|
25
|
+
private readonly directory;
|
|
26
|
+
private child?;
|
|
27
|
+
private readonly pending;
|
|
28
|
+
private chunks;
|
|
29
|
+
constructor(directory: string);
|
|
30
|
+
read(names: readonly string[]): Promise<(Buffer | undefined)[]>;
|
|
31
|
+
/** The ID of the object a name resolves to, such as the tree of `<revision>^{tree}`. */
|
|
32
|
+
id(name: string): Promise<string | undefined>;
|
|
33
|
+
private request;
|
|
34
|
+
private start;
|
|
35
|
+
private receive;
|
|
36
|
+
private answer;
|
|
37
|
+
private stop;
|
|
38
|
+
}
|
|
21
39
|
export declare function readGitCommit(directory: string, revision: string, excludes: (path: string) => boolean, isSource: (path: string) => boolean, claims?: (path: string) => boolean): Promise<SourceSnapshot>;
|
|
22
40
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { realpath } from 'node:fs/promises';
|
|
2
|
-
import { execFile, spawnSync } from 'node:child_process';
|
|
2
|
+
import { execFile, spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
4
|
import { comparePaths, isExcludedDirectory, textLineCount, utf8 } from '../../core/model/snapshot.js';
|
|
5
5
|
import { isClaimedText, maxClaimedFileBytes } from '../../core/model/source.js';
|
|
@@ -89,11 +89,100 @@ export async function gitTreeFiles(directory, commit, prefix, includeSize = fals
|
|
|
89
89
|
}
|
|
90
90
|
return entries;
|
|
91
91
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Reads blobs named like `<tree>:<path>` through one long-lived `git cat-file --batch`: requests stream in and answers
|
|
94
|
+
* come back in order. A name Git cannot find reads as undefined. The process keeps Node alive only while it owes answers.
|
|
95
|
+
*/
|
|
96
|
+
export class GitBlobReader {
|
|
97
|
+
directory;
|
|
98
|
+
child;
|
|
99
|
+
pending = [];
|
|
100
|
+
chunks = [];
|
|
101
|
+
constructor(directory) {
|
|
102
|
+
this.directory = directory;
|
|
103
|
+
}
|
|
104
|
+
read(names) {
|
|
105
|
+
return Promise.all(names.map(name => this.request(name, 'blob')));
|
|
106
|
+
}
|
|
107
|
+
/** The ID of the object a name resolves to, such as the tree of `<revision>^{tree}`. */
|
|
108
|
+
id(name) {
|
|
109
|
+
return this.request(name, 'id');
|
|
110
|
+
}
|
|
111
|
+
request(name, want) {
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
if (/[\r\n]/.test(name))
|
|
114
|
+
throw new Error('Invalid Git object name');
|
|
115
|
+
const child = this.child ?? this.start();
|
|
116
|
+
if (this.pending.length === 0)
|
|
117
|
+
setHeld(child, true);
|
|
118
|
+
this.pending.push({ name, want, resolve, reject });
|
|
119
|
+
child.stdin.write(`${name}\n`);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
start() {
|
|
123
|
+
const child = spawn('git', ['--no-replace-objects', 'cat-file', '--batch'], { cwd: this.directory, env });
|
|
124
|
+
const errors = [];
|
|
125
|
+
child.stdout.on('data', (chunk) => this.receive(chunk));
|
|
126
|
+
child.stderr.on('data', (chunk) => errors.push(chunk));
|
|
127
|
+
const stop = (error) => this.stop(child, error);
|
|
128
|
+
child.on('error', stop);
|
|
129
|
+
child.stdin.on('error', stop);
|
|
130
|
+
child.on('close', () => stop(new Error(`git cat-file stopped: ${Buffer.concat(errors).toString('utf8').trim()}`)));
|
|
131
|
+
setHeld(child, false);
|
|
132
|
+
this.child = child;
|
|
133
|
+
return child;
|
|
134
|
+
}
|
|
135
|
+
receive(chunk) {
|
|
136
|
+
this.chunks.push(chunk);
|
|
137
|
+
let buffer = this.chunks.length === 1 ? chunk : Buffer.concat(this.chunks);
|
|
138
|
+
for (let request = this.pending[0]; request; request = this.pending[0]) {
|
|
139
|
+
const end = buffer.indexOf(10);
|
|
140
|
+
if (end < 0)
|
|
141
|
+
break;
|
|
142
|
+
const header = buffer.toString('utf8', 0, end);
|
|
143
|
+
if (header === `${request.name} missing`) {
|
|
144
|
+
buffer = buffer.subarray(end + 1);
|
|
145
|
+
this.answer(undefined);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const [, id, type, length] = /^([a-f0-9]+) ([a-z]+) (\d+)$/.exec(header) ?? [];
|
|
149
|
+
const size = Number(length);
|
|
150
|
+
if (!Number.isSafeInteger(size) || (request.want === 'blob' && type !== 'blob')) {
|
|
151
|
+
this.stop(this.child, new Error(`Unexpected Git object: ${request.name}`));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (buffer.length < end + size + 2)
|
|
155
|
+
break;
|
|
156
|
+
const blob = Buffer.from(buffer.subarray(end + 1, end + 1 + size));
|
|
157
|
+
buffer = buffer.subarray(end + size + 2);
|
|
158
|
+
this.answer(request.want === 'blob' ? blob : id);
|
|
159
|
+
}
|
|
160
|
+
this.chunks = buffer.length ? [buffer] : [];
|
|
161
|
+
}
|
|
162
|
+
answer(value) {
|
|
163
|
+
const request = this.pending.shift();
|
|
164
|
+
if (this.pending.length === 0 && this.child)
|
|
165
|
+
setHeld(this.child, false);
|
|
166
|
+
request.resolve(value);
|
|
167
|
+
}
|
|
168
|
+
stop(child, error) {
|
|
169
|
+
if (this.child !== child)
|
|
170
|
+
return;
|
|
171
|
+
this.child = undefined;
|
|
172
|
+
this.chunks = [];
|
|
173
|
+
for (const request of this.pending.splice(0))
|
|
174
|
+
request.reject(error);
|
|
175
|
+
child.kill();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** A reader with nothing to answer must not keep the process running. */
|
|
179
|
+
function setHeld(child, held) {
|
|
180
|
+
for (const handle of [child, child.stdout, child.stdin, child.stderr]) {
|
|
181
|
+
if (held)
|
|
182
|
+
handle.ref();
|
|
183
|
+
else
|
|
184
|
+
handle.unref();
|
|
185
|
+
}
|
|
97
186
|
}
|
|
98
187
|
export async function readGitCommit(directory, revision, excludes, isSource, claims) {
|
|
99
188
|
const id = await resolveGitCommit(directory, revision);
|
|
@@ -123,7 +212,8 @@ export async function readGitCommit(directory, revision, excludes, isSource, cla
|
|
|
123
212
|
}
|
|
124
213
|
files.sort((left, right) => comparePaths(left.path, right.path));
|
|
125
214
|
const inventory = tracked.filter(({ path }) => !generated.has(path)).map(({ path, oid, size }) => ({ path, lines: counts.get(oid) ?? null, ...(size === undefined ? {} : { bytes: size }) }));
|
|
126
|
-
|
|
215
|
+
const blobIds = new Map(tracked.map(({ path, oid }) => [path, oid]));
|
|
216
|
+
return { subject: { kind: 'commit', id }, files, blobIds, inventory, generatedExcluded: [...generated].sort(comparePaths),
|
|
127
217
|
...(oversized.size ? { oversizedClaims: [...oversized].sort(comparePaths) } : {}) };
|
|
128
218
|
}
|
|
129
219
|
function inventoryLineCounts(directory, entries, sources, capture) {
|