repometry 0.6.2 → 0.8.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.
Files changed (153) hide show
  1. package/README.md +3 -0
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +79 -0
  4. package/target/main/resources/languages/go/parser.go +602 -0
  5. package/target/main/resources/languages/python/parser.py +312 -0
  6. package/target/main/resources/report/json/report-v2.schema.json +21 -1
  7. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  8. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +12 -3
  9. package/target/main/resources/viewer/files.css +7 -0
  10. package/target/main/resources/viewer/index.html +1 -1
  11. package/target/main/resources/viewer/styles.css +1 -0
  12. package/target/main/ts/api/git/git-reader.d.ts +10 -2
  13. package/target/main/ts/api/git/git-reader.js +74 -35
  14. package/target/main/ts/api/git/git.d.ts +19 -1
  15. package/target/main/ts/api/git/git.js +97 -7
  16. package/target/main/ts/api/import/go-cover.d.ts +13 -0
  17. package/target/main/ts/api/import/go-cover.js +150 -0
  18. package/target/main/ts/api/import/lcov-files.d.ts +6 -1
  19. package/target/main/ts/api/import/lcov-files.js +27 -7
  20. package/target/main/ts/api/process/docker-tool-runner.js +5 -21
  21. package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
  22. package/target/main/ts/api/process/host-language-runner.js +176 -0
  23. package/target/main/ts/api/process/plugin.d.ts +4 -1
  24. package/target/main/ts/api/process/plugin.js +7 -3
  25. package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
  26. package/target/main/ts/api/process/tool-snapshot.js +26 -0
  27. package/target/main/ts/cli/config.d.ts +1 -0
  28. package/target/main/ts/cli/config.js +3 -2
  29. package/target/main/ts/cli/imports.d.ts +1 -0
  30. package/target/main/ts/cli/imports.js +5 -2
  31. package/target/main/ts/cli/main.js +76 -27
  32. package/target/main/ts/cli/reporting.js +3 -3
  33. package/target/main/ts/compose/analysis-files.d.ts +3 -1
  34. package/target/main/ts/compose/analysis-files.js +46 -12
  35. package/target/main/ts/compose/analysis-imports.js +4 -2
  36. package/target/main/ts/compose/analysis-report.d.ts +1 -0
  37. package/target/main/ts/compose/analysis-report.js +20 -15
  38. package/target/main/ts/compose/analysis-repository.d.ts +2 -1
  39. package/target/main/ts/compose/analysis-repository.js +42 -4
  40. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  41. package/target/main/ts/compose/analysis-results.js +3 -0
  42. package/target/main/ts/compose/analysis-sources.d.ts +5 -0
  43. package/target/main/ts/compose/analysis-sources.js +11 -3
  44. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
  45. package/target/main/ts/compose/analyze-snapshot.js +5 -3
  46. package/target/main/ts/compose/diff-coverage.d.ts +2 -1
  47. package/target/main/ts/compose/diff-coverage.js +8 -6
  48. package/target/main/ts/compose/history-cache.d.ts +29 -0
  49. package/target/main/ts/compose/history-cache.js +57 -0
  50. package/target/main/ts/compose/inspect.d.ts +6 -1
  51. package/target/main/ts/compose/inspect.js +10 -10
  52. package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
  53. package/target/main/ts/compose/inspection-coverage.js +9 -0
  54. package/target/main/ts/compose/languages.d.ts +6 -1
  55. package/target/main/ts/compose/languages.js +23 -7
  56. package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
  57. package/target/main/ts/compose/native-language-plugins.js +40 -0
  58. package/target/main/ts/compose/plugin-list.d.ts +7 -3
  59. package/target/main/ts/compose/plugin-list.js +13 -3
  60. package/target/main/ts/compose/prepare-metabranch.js +1 -1
  61. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  62. package/target/main/ts/compose/process-plugins.js +64 -0
  63. package/target/main/ts/compose/review.d.ts +1 -2
  64. package/target/main/ts/compose/review.js +2 -2
  65. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  66. package/target/main/ts/compose/structure-measures.js +57 -0
  67. package/target/main/ts/core/engine/manifest.js +5 -1
  68. package/target/main/ts/core/engine/plan.js +5 -6
  69. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  70. package/target/main/ts/core/model/clone-source.js +0 -1
  71. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  72. package/target/main/ts/core/model/code-structure.js +23 -10
  73. package/target/main/ts/core/model/file-types.d.ts +1 -0
  74. package/target/main/ts/core/model/file-types.js +14 -3
  75. package/target/main/ts/core/model/language.d.ts +2 -0
  76. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  77. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  78. package/target/main/ts/core/model/quality-summary.js +55 -29
  79. package/target/main/ts/core/model/report.d.ts +6 -0
  80. package/target/main/ts/core/model/source.d.ts +2 -0
  81. package/target/main/ts/core/usecases/inspect.d.ts +1 -1
  82. package/target/main/ts/core/usecases/inspect.js +1 -1
  83. package/target/main/ts/plugin.d.ts +1 -1
  84. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  85. package/target/main/ts/plugins/coverage/coverage.js +40 -30
  86. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  87. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  88. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  89. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  90. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  91. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  92. package/target/main/ts/plugins/security/dockerfile.js +51 -52
  93. package/target/main/ts/plugins/structure/structure.js +2 -2
  94. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  95. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  96. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  97. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  98. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  99. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  100. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  101. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  102. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  103. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  104. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  105. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  106. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
  107. package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
  108. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  109. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  110. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  111. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  112. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  113. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  114. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  115. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  116. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  117. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  118. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  119. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  120. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  121. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  122. package/target/main/ts/report/html/app/viewer-profile.js +22 -1
  123. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  124. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  125. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  126. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  127. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  128. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  129. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  130. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  131. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  132. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  133. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  134. package/target/main/ts/report/html/app/viewer.js +1 -7
  135. package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
  136. package/target/main/ts/report/json/projections/commit-summary.js +10 -0
  137. package/target/main/ts/report/json/projections/file-metrics.js +56 -45
  138. package/target/main/ts/report/json/projections/inspection-details.js +33 -14
  139. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  140. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  141. package/target/main/ts/report/json/store/directory.d.ts +3 -0
  142. package/target/main/ts/report/json/store/directory.js +19 -0
  143. package/target/main/ts/report/json/store/local-store.d.ts +14 -2
  144. package/target/main/ts/report/json/store/local-store.js +74 -60
  145. package/target/main/ts/report/json/store/object-store.d.ts +14 -0
  146. package/target/main/ts/report/json/store/object-store.js +73 -0
  147. package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
  148. package/target/main/ts/report/json/store/report-tree.js +290 -0
  149. package/target/main/ts/report/json/store/store-check.d.ts +32 -0
  150. package/target/main/ts/report/json/store/store-check.js +144 -0
  151. package/target/main/ts/report/json/validation/report.d.ts +6 -1
  152. package/target/main/ts/report/json/validation/report.js +10 -4
  153. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +9 -1
@@ -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()
@@ -91,6 +91,20 @@
91
91
  "$ref": "#/$defs/finding"
92
92
  }
93
93
  },
94
+ "ruleSkips": {
95
+ "type": "array",
96
+ "items": {
97
+ "type": "object",
98
+ "required": ["path", "plugin", "rules", "reason"],
99
+ "properties": {
100
+ "path": { "type": "string" },
101
+ "plugin": { "type": "string" },
102
+ "rules": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "type": "string" } },
103
+ "reason": { "const": "unmeasured" }
104
+ },
105
+ "additionalProperties": false
106
+ }
107
+ },
94
108
  "pluginData": {
95
109
  "type": "object",
96
110
  "required": ["metrics", "measured", "rules", "products"],
@@ -134,7 +148,13 @@
134
148
  "bytes": { "type": "integer", "minimum": 0 },
135
149
  "language": { "type": "string" },
136
150
  "provider": { "type": "string", "minLength": 1 },
137
- "analysed": { "type": "boolean" }
151
+ "analysed": { "type": "boolean" },
152
+ "unmeasured": {
153
+ "type": "array",
154
+ "uniqueItems": true,
155
+ "items": { "enum": ["functions", "cyclomaticComplexity", "cognitiveComplexity", "classes",
156
+ "commentLines", "codeLines", "duplication", "structuralRules"] }
157
+ }
138
158
  },
139
159
  "additionalProperties": false
140
160
  }
@@ -134,6 +134,15 @@
134
134
  "debtRatio": {
135
135
  "$ref": "#/$defs/ratio"
136
136
  },
137
+ "gradeCoverage": {
138
+ "type": "object",
139
+ "required": ["measuredFiles", "totalFiles"],
140
+ "properties": {
141
+ "measuredFiles": { "type": "integer", "minimum": 0 },
142
+ "totalFiles": { "type": "integer", "minimum": 0 }
143
+ },
144
+ "additionalProperties": false
145
+ },
137
146
  "grade": {
138
147
  "enum": [
139
148
  "A",
@@ -129,7 +129,6 @@
129
129
  "additionalProperties": false,
130
130
  "required": [
131
131
  "id",
132
- "extensions",
133
132
  "excludedPaths",
134
133
  "excludedDirectories",
135
134
  "rules",
@@ -146,10 +145,20 @@
146
145
  "null"
147
146
  ]
148
147
  },
149
- "extensions": {
148
+ "languages": {
150
149
  "type": "array",
151
150
  "items": {
152
- "type": "string"
151
+ "type": "object",
152
+ "additionalProperties": false,
153
+ "required": ["plugin", "id", "label", "extensions", "globs"],
154
+ "properties": {
155
+ "plugin": { "type": "string" },
156
+ "id": { "type": "string" },
157
+ "label": { "type": "string" },
158
+ "extensions": { "type": "array", "items": { "type": "string" } },
159
+ "globs": { "type": "array", "items": { "type": "string" } },
160
+ "unavailableReason": { "type": "string" }
161
+ }
153
162
  }
154
163
  },
155
164
  "excludedPaths": {
@@ -553,6 +553,11 @@ code.fx-function-name { font-size: .75rem; color: var(--secondary); }
553
553
  .profile-facts dt { color: var(--secondary); font-size: .875rem; }
554
554
  .profile-facts dd { margin: 0; }
555
555
  .profile-facts code { font-size: .8125rem; }
556
+ /* Each language on its own line: its name, then the patterns of the files its plugin reads. */
557
+ .profile-claims { display: grid; gap: .5rem; margin: 0; padding: 0; list-style: none; }
558
+ .profile-claims > li { display: grid; grid-template-columns: minmax(6rem, auto) minmax(0, 1fr); gap: .75rem; align-items: baseline; }
559
+ .profile-claim { font-size: .875rem; color: var(--ink); }
560
+ .profile-claim-patterns { display: flex; flex-wrap: wrap; align-items: baseline; gap: .375rem .75rem; }
556
561
  .profile-chips { display: flex; flex-wrap: wrap; gap: .375rem; margin: 0; padding: 0; list-style: none; }
557
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; }
558
563
  .profile-rule { font-size: .8125rem; font-weight: 600; }
@@ -607,3 +612,5 @@ code.fx-function-name { font-size: .75rem; color: var(--secondary); }
607
612
  .fx-source-meta .fx-source-forge:hover { color: var(--accent-strong); }
608
613
  .fx-occurrence-away { padding: .375rem 0 0; font-size: .8125rem; }
609
614
  .fx-occurrence-away .fx-source-forge { color: var(--secondary); }
615
+ /* A total over files that do not all carry the measure: the title says in how many it was measured. */
616
+ .fx-table .fx-partial { text-decoration: underline dotted; text-decoration-color: var(--muted); text-underline-offset: 3px; }
@@ -51,7 +51,7 @@
51
51
  <div class="verdicts" role="tablist" aria-label="Quality area">
52
52
  <div class="verdict">
53
53
  <span id="maintainability" class="mark grade"></span>
54
- <span class="verdict-text"><button type="button" role="tab" class="verdict-tab" data-metric="debt" aria-controls="trend" aria-describedby="maintainability maintainability-detail">Maintainability</button><span id="maintainability-detail" class="verdict-detail"></span></span>
54
+ <span class="verdict-text"><button type="button" role="tab" class="verdict-tab" data-metric="debt" aria-controls="trend" aria-describedby="maintainability maintainability-detail maintainability-scope">Maintainability</button><span id="maintainability-detail" class="verdict-detail"></span><span id="maintainability-scope" class="verdict-detail verdict-more" hidden></span></span>
55
55
  </div>
56
56
  <div class="verdict">
57
57
  <span id="coverage-mark" class="mark ring" aria-hidden="true"></span>
@@ -421,6 +421,7 @@ a.tc-tip-entry:hover { background: var(--surface-2); }
421
421
 
422
422
  /* Trends page */
423
423
  .trend-nav { display: grid; gap: 1.125rem; }
424
+ .trend-group-note { margin: -.2rem 0 .3rem; padding: 0 .5rem 0 .75rem; color: var(--muted); font-size: .75rem; }
424
425
  .trend-group h3 { display: flex; align-items: center; justify-content: space-between; gap: .75rem; min-height: 1.5rem; margin: 0 0 .3rem; padding: 0 .5rem 0 .75rem; color: var(--muted); font-size: .75rem; font-weight: 600; letter-spacing: .07em; text-transform: uppercase; }
425
426
  /* A group's reading: the maintainability grade, or the coverage in its grade's colour, as the badges show them. */
426
427
  .trend-reading { flex: none; min-width: 1.25rem; padding: 0 .4rem; border-radius: 999px; background: var(--rule); color: var(--secondary); font-size: .75rem; font-weight: 600; letter-spacing: 0; line-height: 1.25rem; text-align: center; text-transform: none; font-variant-numeric: tabular-nums; }
@@ -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 reportEntries;
13
- private readEntries;
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 { gitBlobText, gitTreeFiles, resolveGitCommit } from './git.js';
3
- import { compareReports, readReportText, validSubjectId } from '../../report/json/validation/report.js';
4
- import { commitSummary, expandSummaryCatalog, orderSummaries } from '../../report/json/projections/commit-summary.js';
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 commit = await this.pinnedSnapshot();
18
- const path = `commits/${subject.id}/report.json`;
19
- const entry = (await gitTreeFiles(this.directory, commit, path)).find(item => item.path === path);
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 readReportText(await gitBlobText(this.directory, entry.oid), subject);
29
+ return readStoredReport(text, subject, this.objects(tree));
23
30
  }
24
31
  async list() {
25
- return this.readEntries(await this.reportEntries(await this.pinnedSnapshot()));
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 commit = await this.pinnedSnapshot();
29
- const [entries, index] = await Promise.all([
30
- this.reportEntries(commit),
31
- gitTreeFiles(this.directory, commit, 'summary.json'),
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 && entries.length === shas.size && entries.every(({ id }) => shas.has(id))
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((await this.readEntries(entries)).map(commitSummary));
57
+ return orderSummaries(rows);
44
58
  }
45
- async reportEntries(commit) {
46
- return (await gitTreeFiles(this.directory, commit, 'commits')).flatMap(({ path, oid }) => {
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) ? [{ id, oid }] : [];
72
+ return id && validSubjectId('commit', id) ? [id] : [];
49
73
  });
50
74
  }
51
- async readEntries(entries) {
52
- const reports = [];
53
- for (const { id, oid } of entries) {
54
- reports.push(readReportText(await gitBlobText(this.directory, oid), { kind: 'commit', id }));
55
- }
56
- return reports.sort(compareReports);
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 commit = await resolveGitCommit(this.directory, this.revision);
67
- const entry = (await gitTreeFiles(this.directory, commit, 'manifest.json')).find(item => item.path === 'manifest.json');
68
- if (!entry)
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(await gitBlobText(this.directory, entry.oid));
71
- return commit;
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
- export declare function gitBlobText(directory: string, oid: string): Promise<string>;
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 {};