repometry 0.8.0 → 0.9.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 (52) hide show
  1. package/README.md +24 -23
  2. package/package.json +1 -1
  3. package/target/main/resources/languages/go/parser.go +25 -5
  4. package/target/main/resources/languages/python/parser.py +12 -1
  5. package/target/main/resources/report/json/config-v1.schema.json +0 -1
  6. package/target/main/resources/report/json/report-v2.schema.json +12 -0
  7. package/target/main/ts/api/gh/github.d.ts +3 -1
  8. package/target/main/ts/api/gh/github.js +39 -54
  9. package/target/main/ts/api/git/changes.d.ts +6 -1
  10. package/target/main/ts/api/git/changes.js +19 -10
  11. package/target/main/ts/api/git/line-changes.d.ts +6 -0
  12. package/target/main/ts/api/git/line-changes.js +57 -0
  13. package/target/main/ts/cli/config.d.ts +2 -1
  14. package/target/main/ts/cli/config.js +12 -5
  15. package/target/main/ts/cli/main.js +33 -38
  16. package/target/main/ts/compose/review.d.ts +24 -13
  17. package/target/main/ts/compose/review.js +44 -32
  18. package/target/main/ts/core/model/changes.d.ts +29 -0
  19. package/target/main/ts/core/model/code-structure.d.ts +2 -0
  20. package/target/main/ts/core/model/code-structure.js +8 -2
  21. package/target/main/ts/core/model/finding.d.ts +6 -0
  22. package/target/main/ts/core/model/finding.js +23 -8
  23. package/target/main/ts/core/model/pull-review.d.ts +52 -30
  24. package/target/main/ts/core/model/pull-review.js +4 -1
  25. package/target/main/ts/core/usecases/review-effect.d.ts +18 -0
  26. package/target/main/ts/core/usecases/review-effect.js +37 -0
  27. package/target/main/ts/core/usecases/review-match.d.ts +14 -0
  28. package/target/main/ts/core/usecases/review-match.js +72 -0
  29. package/target/main/ts/core/usecases/review-position.d.ts +14 -0
  30. package/target/main/ts/core/usecases/review-position.js +53 -0
  31. package/target/main/ts/core/usecases/review-scope.d.ts +21 -0
  32. package/target/main/ts/core/usecases/review-scope.js +41 -0
  33. package/target/main/ts/core/usecases/review.d.ts +32 -21
  34. package/target/main/ts/core/usecases/review.js +89 -114
  35. package/target/main/ts/index.d.ts +4 -3
  36. package/target/main/ts/index.js +1 -1
  37. package/target/main/ts/plugins/duplication/duplication.js +1 -1
  38. package/target/main/ts/plugins/language-js/babel-provider.js +4 -2
  39. package/target/main/ts/plugins/language-js/function-facts.d.ts +3 -3
  40. package/target/main/ts/plugins/language-js/function-facts.js +3 -15
  41. package/target/main/ts/plugins/language-js/qualified-names.d.ts +11 -0
  42. package/target/main/ts/plugins/language-js/qualified-names.js +63 -0
  43. package/target/main/ts/plugins/language-js/structural-observations.d.ts +2 -1
  44. package/target/main/ts/plugins/language-js/structural-observations.js +18 -14
  45. package/target/main/ts/plugins/maintainability/structural-smells.js +3 -2
  46. package/target/main/ts/report/html/app/viewer-chart-bars.js +9 -5
  47. package/target/main/ts/report/json/store/pull-review-store.d.ts +0 -1
  48. package/target/main/ts/report/json/store/pull-review-store.js +2 -20
  49. package/target/main/ts/report/json/wire/pull-review-model.d.ts +49 -2
  50. package/target/main/ts/report/json/wire/pull-review-model.js +2 -0
  51. package/target/main/ts/report/markdown/pull-review.d.ts +5 -0
  52. package/target/main/ts/report/markdown/pull-review.js +122 -0
package/README.md CHANGED
@@ -15,37 +15,38 @@
15
15
 
16
16
  Git can serve as a project’s single source of truth for code, tests, docs, and CI configuration. Repometry lets you keep coverage and maintainability metrics alongside your code, commit by commit.
17
17
 
18
- ## Requirements
18
+ ## Demo
19
+ [https://idleware.github.io/repometry/](https://idleware.github.io/repometry/)
19
20
 
20
- Node.js 24 or newer.
21
+ ## Requirements
21
22
 
22
- ## Usage
23
+ Node.js >=24
23
24
 
24
- Run these commands in your repository.
25
+ ## Install
25
26
 
26
27
  ```sh
27
- # Analyze HEAD and save its inspection under .repometry/.
28
- npx repometry analyze
29
-
30
- # Build history for the last 50 commits, oldest first, skipping saved inspections.
31
- npx repometry analyze HEAD~50..HEAD --skip-saved
32
-
33
- # Import coverage and scanner results. Repeat --import for each file.
34
- npx repometry analyze --import lcov=coverage/lcov.info --import sarif=results.sarif
28
+ # Run without installing.
29
+ npx repometry help
35
30
 
36
- # Open the report locally on a free port. Use --port 3030 to choose a port.
37
- npx repometry view
38
-
39
- # Export a static report to .repometry/report/html. Use -o DIR for another folder.
40
- npx repometry report html
31
+ # Or install the repometry command.
32
+ npm install --global repometry
33
+ ```
41
34
 
42
- # Check saved inspections. --repair restores missing data from a copy.
43
- npx repometry store check --repair --from git:repometry
35
+ ## Usage
44
36
 
45
- # List supported formats and get help for a command.
46
- npx repometry plugins
47
- npx repometry help analyze
48
- ```
37
+ Run these commands in your repository. Without an install, start each with `npx`.
38
+
39
+ | Command | What it does |
40
+ | --- | --- |
41
+ | `repometry analyze` | Analyze HEAD and save its inspection under `.repometry/`. |
42
+ | `repometry analyze HEAD~50..HEAD --skip-saved` | Build history for the last 50 commits, oldest first, skipping saved inspections. |
43
+ | `repometry analyze --import lcov=coverage/lcov.info --import sarif=results.sarif` | Import coverage and scanner results. Repeat `--import` for each file. |
44
+ | `repometry view` | Open the report locally on a free port. Use `--port 3030` to choose a port. |
45
+ | `repometry report html` | Export a static report to `.repometry/report/html`. Use `-o DIR` for another folder. |
46
+ | `repometry review origin/main --import lcov=coverage/lcov.info` | Report the issues a change adds or worsens on the lines it changes, and their coverage. |
47
+ | `repometry store check --repair --from git:origin/repometry` | Check saved inspections. `--repair` restores missing data from a copy. |
48
+ | `repometry plugins` | List supported formats. |
49
+ | `repometry help analyze` | Get help for a command. |
49
50
 
50
51
  A report shows everything the store holds, so publish it only where you would publish that data.
51
52
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -57,6 +57,7 @@ type observation struct {
57
57
  Label string `json:"label"`
58
58
  Line int `json:"line"`
59
59
  EndLine int `json:"endLine"`
60
+ Anchor string `json:"anchor,omitempty"`
60
61
  }
61
62
 
62
63
  type duplicationSettings struct {
@@ -266,6 +267,7 @@ type structureMetrics struct {
266
267
  cognitive []functionComplexity
267
268
  observations []observation
268
269
  cognitiveTotal int
270
+ anchors []string
269
271
  }
270
272
 
271
273
  type flow struct {
@@ -289,10 +291,19 @@ func measureStructure(file *ast.File, layout sourceLayout) structureMetrics {
289
291
  return metrics
290
292
  }
291
293
 
294
+ // observe records an observation inside the innermost function being measured, or at module level.
292
295
  func (m *structureMetrics) observe(rule string, value int, label string, node ast.Node) {
296
+ anchor := ""
297
+ if len(m.anchors) > 0 {
298
+ anchor = m.anchors[len(m.anchors)-1]
299
+ }
300
+ m.observeAt(rule, value, label, node, anchor)
301
+ }
302
+
303
+ func (m *structureMetrics) observeAt(rule string, value int, label string, node ast.Node, anchor string) {
293
304
  start, end := m.layout.tokens.Offset(node.Pos()), m.layout.end(node.End())
294
305
  m.observations = append(m.observations, observation{
295
- Rule: rule, Value: value, Label: label, Line: m.layout.line(start), EndLine: m.layout.line(end - 1),
306
+ Rule: rule, Value: value, Label: label, Line: m.layout.line(start), EndLine: m.layout.line(end - 1), Anchor: anchor,
296
307
  })
297
308
  }
298
309
 
@@ -407,10 +418,19 @@ func (m *structureMetrics) measureFunction(node ast.Node, body *ast.BlockStmt, s
407
418
  m.cyclomatic = append(m.cyclomatic, position)
408
419
  m.cognitive = append(m.cognitive, position)
409
420
 
421
+ anchor := name
422
+ if anchor == "" {
423
+ anchor = "(anonymous)"
424
+ if len(m.anchors) > 0 {
425
+ anchor = m.anchors[len(m.anchors)-1] + ".(anonymous)"
426
+ }
427
+ }
410
428
  own := flow{cyclomatic: 1}
411
429
  forChildren(node, func(child ast.Node) {
412
430
  if child == body {
431
+ m.anchors = append(m.anchors, anchor)
413
432
  m.visit(child, &own, 0, token.ILLEGAL, false)
433
+ m.anchors = m.anchors[:len(m.anchors)-1]
414
434
  } else {
415
435
  m.visit(child, outer, depth, token.ILLEGAL, false)
416
436
  }
@@ -431,11 +451,11 @@ func (m *structureMetrics) measureFunction(node ast.Node, body *ast.BlockStmt, s
431
451
  params += len(field.Names)
432
452
  }
433
453
  }
434
- m.observe("function-parameters", params, label+" · Parameters", node)
435
- m.observe("return-statements", own.returns, label+" · Return statements", node)
436
- m.observe("function-complexity", own.cognitive, label+" · Cognitive complexity", node)
454
+ m.observeAt("function-parameters", params, label+" · Parameters", node, anchor)
455
+ m.observeAt("return-statements", own.returns, label+" · Return statements", node, anchor)
456
+ m.observeAt("function-complexity", own.cognitive, label+" · Cognitive complexity", node, anchor)
437
457
  if own.deepest != nil {
438
- m.observe("nested-control-flow", own.maxDepth, label+" · Control-flow depth", own.deepest)
458
+ m.observeAt("nested-control-flow", own.maxDepth, label+" · Control-flow depth", own.deepest, anchor)
439
459
  }
440
460
  }
441
461
 
@@ -68,6 +68,7 @@ class Structure:
68
68
  self.cognitive = 0
69
69
  self.classes = 0
70
70
  self.names = []
71
+ self.anchors = []
71
72
 
72
73
  def analyze(self, tree):
73
74
  module = Scope()
@@ -164,8 +165,10 @@ class Structure:
164
165
  self.names.append(name)
165
166
  location["name"] = ".".join(self.names)
166
167
  label = location.get("name", "(anonymous)")
168
+ anchor = location.get("name") or ".".join(self.anchors[-1:] + ["(anonymous)"])
167
169
  scope = Scope()
168
170
  body = [node.body] if isinstance(node, ast.Lambda) else node.body
171
+ self.anchors.append(anchor)
169
172
  self.visit_all(body, scope, 0)
170
173
  if name is not None:
171
174
  self.names.pop()
@@ -174,18 +177,23 @@ class Structure:
174
177
  args = node.args
175
178
  parameters = (len(args.posonlyargs) + len(args.args) + len(args.kwonlyargs)
176
179
  + int(args.vararg is not None) + int(args.kwarg is not None))
180
+ # The function's own observations carry its anchor, which is still on top of the stack.
177
181
  self.observe("function-parameters", parameters, f"{label} · Parameters", node)
178
182
  self.observe("return-statements", scope.returns, f"{label} · Return statements", node)
179
183
  self.observe("function-complexity", scope.cognitive, f"{label} · Cognitive complexity", node)
180
184
  self.finish_scope(scope, label)
185
+ self.anchors.pop()
181
186
 
182
187
  def visit_class(self, node, enclosing, depth):
183
188
  self.classes += 1
184
189
  self.visit_header(node, enclosing, depth)
185
190
  self.names.append(node.name)
191
+ anchor = ".".join(self.names)
186
192
  scope = Scope()
193
+ self.anchors.append(anchor)
187
194
  self.visit_all(node.body, scope, 0)
188
- self.finish_scope(scope, ".".join(self.names))
195
+ self.finish_scope(scope, anchor)
196
+ self.anchors.pop()
189
197
  self.names.pop()
190
198
 
191
199
  def visit_all(self, nodes, scope, depth):
@@ -198,9 +206,12 @@ class Structure:
198
206
  self.observe("nested-control-flow", scope.depth, f"{label} · Control-flow depth", scope.deepest)
199
207
 
200
208
  def observe(self, rule, value, label, node=None):
209
+ """Records an observation; inside a function or class it carries that scope's anchor."""
201
210
  observation = {"rule": rule, "value": value, "label": label}
202
211
  if node is not None:
203
212
  observation.update(line=node.lineno, endLine=node.end_lineno)
213
+ if self.anchors:
214
+ observation["anchor"] = self.anchors[-1]
204
215
  self.observations.append(observation)
205
216
 
206
217
 
@@ -25,7 +25,6 @@
25
25
  "branch": { "type": "string", "minLength": 1 },
26
26
  "minCoverage": { "type": "number", "minimum": 0, "maximum": 100 },
27
27
  "minLines": { "type": "integer", "minimum": 0 },
28
- "maxCoverageDrop": { "type": "number", "minimum": 0, "maximum": 100 },
29
28
  "maxNewIssues": { "type": "integer", "minimum": 0 }
30
29
  },
31
30
  "additionalProperties": false,
@@ -455,6 +455,18 @@
455
455
  },
456
456
  "additionalProperties": false
457
457
  }
458
+ },
459
+ "value": {
460
+ "type": "number",
461
+ "minimum": 0
462
+ },
463
+ "limit": {
464
+ "type": "number",
465
+ "minimum": 0
466
+ },
467
+ "anchor": {
468
+ "type": "string",
469
+ "minLength": 1
458
470
  }
459
471
  },
460
472
  "dependentRequired": {
@@ -3,4 +3,6 @@ import type { PullReview } from '../../core/model/pull-review.js';
3
3
  import type { Report } from '../../core/model/report.js';
4
4
  export declare function writeGitHubResult(report: Report): Promise<void>;
5
5
  export declare function writeGitHubDiffCoverage(report: DiffCoverageReport): Promise<void>;
6
- export declare function writeGitHubReview(report: PullReview, repository?: string): Promise<void>;
6
+ /** The number of the pull request whose event started this GitHub Actions run, if any. */
7
+ export declare function gitHubPullRequest(): Promise<number | undefined>;
8
+ export declare function writeGitHubReview(review: PullReview, markdown: string, repository: string): Promise<void>;
@@ -1,5 +1,7 @@
1
- import { appendFile, realpath } from 'node:fs/promises';
1
+ import { appendFile, readFile, realpath } from 'node:fs/promises';
2
2
  import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { isRecord } from '../../core/engine/plugin.js';
4
+ import { annotationLimit } from '../../core/model/pull-review.js';
3
5
  export async function writeGitHubResult(report) {
4
6
  const { output, summary } = githubFiles();
5
7
  await appendFile(output, `subject=${report.subject.id}\nstatus=${report.status}\n`);
@@ -22,65 +24,48 @@ export async function writeGitHubDiffCoverage(report) {
22
24
  ...policy, '', '',
23
25
  ].join('\n'));
24
26
  }
25
- export async function writeGitHubReview(report, repository) {
26
- const { output, summary } = githubFiles();
27
- const { diff, coverage, findings } = report;
28
- await appendFile(output, [
29
- `status=${diff.status}`, `percent=${diff.percent ?? ''}`, `decision=${diff.gate?.status ?? ''}`,
30
- `review-base=${report.base}`, `review-head=${report.head}`, `diff-covered=${diff.covered}`, `diff-total=${diff.total}`,
31
- `coverage-percent=${coverage.head?.value ?? ''}`, `coverage-delta=${coverage.delta ?? ''}`,
32
- `coverage-decision=${coverage.gate?.status ?? ''}`,
33
- `new-issues=${findings.qualityCount ?? ''}`, `issues-decision=${findings.gate?.status ?? ''}`, '',
34
- ].join('\n'));
35
- const label = report.number === null ? 'Repometry review' : `Repometry review · PR #${report.number}`;
36
- const totals = [
37
- '| Check | Result | Gate |',
38
- '| --- | --- | --- |',
39
- `| Total coverage | ${percent(coverage.base?.value)} → ${percent(coverage.head?.value)} | ${coverage.gate ? `${coverage.gate.status}, max drop ${coverage.gate.maxDrop} pp` : '—'} |`,
40
- `| Changed-line coverage | ${percent(diff.percent)} (${diff.covered}/${diff.total}), ${diff.status} | ${diff.gate ? `${diff.gate.status}, min ${diff.gate.minimumPercent}% on ${diff.gate.minimumLines}+ lines` : '—'} |`,
41
- `| New quality issues | ${findings.qualityCount ?? 'Unavailable'} | ${findings.gate ? `${findings.gate.status}, max ${findings.gate.maximum}` : '—'} |`,
42
- ];
43
- const files = diff.files.slice(0, 50).map(file => {
44
- const result = file.covered === null || file.total === null ? '—' : `${file.covered}/${file.total}`;
45
- const missed = file.covered === null || file.total === null ? '—' : String(file.total - file.covered);
46
- return `| ${pathCode(file.path)} | ${file.addedLines} | ${result} | ${missed} |`;
47
- });
48
- const changes = files.length === 0 ? [] : ['', '### Changed files', '',
49
- '| File | Added lines | Covered / measured | Missed |',
50
- '| --- | ---: | ---: | ---: |', ...files,
51
- ...(diff.files.length > files.length ? ['', `Showing ${files.length} of ${diff.files.length} files.`] : [])];
52
- await appendFile(summary, [`## ${label}`, '', `\`${report.base}\` → \`${report.head}\``, '',
53
- ...totals, ...(diff.gaps.length ? ['', `Coverage gaps in ${diff.gaps.length} records.`] : []), ...changes, '', '',
54
- ].join('\n'));
55
- if (repository !== undefined && diff.uncovered.length > 0)
56
- await annotateUncovered(diff.uncovered, repository);
57
- }
58
- function percent(value) {
59
- return value == null ? '—' : `${value.toFixed(2)}%`;
27
+ /** The number of the pull request whose event started this GitHub Actions run, if any. */
28
+ export async function gitHubPullRequest() {
29
+ const path = process.env.GITHUB_EVENT_PATH;
30
+ if (!path)
31
+ return undefined;
32
+ const event = JSON.parse(await readFile(path, 'utf8'));
33
+ const pull = isRecord(event) ? event.pull_request : undefined;
34
+ const number = isRecord(pull) ? pull.number : undefined;
35
+ return typeof number === 'number' && Number.isSafeInteger(number) && number > 0 ? number : undefined;
60
36
  }
61
- function pathCode(value) {
62
- const clean = value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
63
- .replaceAll('|', '&#124;').replaceAll('\r', ' ').replaceAll('\n', ' ');
64
- return `<code>${clean}</code>`;
37
+ export async function writeGitHubReview(review, markdown, repository) {
38
+ const { output, summary } = githubFiles();
39
+ const count = (effect) => review.issues.filter(issue => issue.effect === effect).length;
40
+ await appendFile(output, [`verdict=${review.verdict}`, ...['new', 'worsened', 'improved', 'touched'].map(effect => `${effect}=${count(effect)}`),
41
+ `changed-coverage=${review.coverage.percent ?? ''}`, ''].join('\n'));
42
+ await appendFile(summary, markdown);
43
+ const annotate = await annotator(repository);
44
+ review.issues.filter(issue => issue.effect === 'new' || issue.effect === 'worsened').slice(0, annotationLimit)
45
+ .forEach(({ effect, finding }) => annotate('error', `Repometry: ${effect} issue`, finding, finding.message));
46
+ review.coverage.uncovered.slice(0, annotationLimit).forEach(({ path, first, last }) => annotate('warning', 'Repometry: not covered', { path, line: first, endLine: last }, `Changed lines ${first}${last > first ? `–${last}` : ''} are not covered`));
65
47
  }
66
- async function annotateUncovered(uncovered, repository) {
48
+ /** Writes workflow annotations for paths inside the checkout, relative to the workspace GitHub shows them in. */
49
+ async function annotator(repository) {
67
50
  const [workspace, root] = await Promise.all([realpath(process.env.GITHUB_WORKSPACE ?? process.cwd()), realpath(repository)]);
68
51
  const prefix = relative(workspace, root);
69
- if (isAbsolute(prefix) || prefix.split(sep).includes('..'))
70
- return;
71
- let count = 0;
72
- for (const { path, lines } of uncovered) {
52
+ const inside = !isAbsolute(prefix) && !prefix.split(sep).includes('..');
53
+ return (kind, title, { path, line, endLine }, message) => {
54
+ if (!inside || path === undefined)
55
+ return;
73
56
  const checkoutPath = relative(workspace, resolve(root, path));
74
57
  if (isAbsolute(checkoutPath) || checkoutPath.split(sep).includes('..'))
75
- continue;
76
- const file = checkoutPath.split(sep).join('/').replaceAll('%', '%25').replaceAll('\r', '%0D')
77
- .replaceAll('\n', '%0A').replaceAll(':', '%3A').replaceAll(',', '%2C');
78
- for (const line of lines) {
79
- process.stderr.write(`::warning file=${file},line=${line},title=Repometry diff coverage::Changed line is not covered\n`);
80
- if (++count === 10)
81
- return;
82
- }
83
- }
58
+ return;
59
+ const properties = [`file=${property(checkoutPath.split(sep).join('/'))}`,
60
+ ...line === undefined ? [] : [`line=${line}`, `endLine=${endLine ?? line}`], `title=${property(title)}`];
61
+ process.stderr.write(`::${kind} ${properties.join(',')}::${data(message)}\n`);
62
+ };
63
+ }
64
+ function data(value) {
65
+ return value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
66
+ }
67
+ function property(value) {
68
+ return data(value).replaceAll(':', '%3A').replaceAll(',', '%2C');
84
69
  }
85
70
  function githubFiles() {
86
71
  const output = process.env.GITHUB_OUTPUT;
@@ -1,12 +1,15 @@
1
1
  import type { SourceSnapshot } from '../../core/model/snapshot.js';
2
- import type { GitChanges, LineRange } from '../../core/model/changes.js';
2
+ import type { GitChanges, LineHunk, LineRange } from '../../core/model/changes.js';
3
3
  export type { GitChanges, LineRange } from '../../core/model/changes.js';
4
+ export declare const oid: RegExp;
5
+ export declare const regularFile: RegExp;
4
6
  export declare const diffMethod: {
5
7
  readonly algorithm: 'myers';
6
8
  readonly indentHeuristic: false;
7
9
  readonly renameThresholdPercent: 50;
8
10
  readonly renameLimit: 1000;
9
11
  };
12
+ export declare const stableDiff: readonly ['--no-color', '--no-ext-diff', '--no-textconv', "--diff-algorithm=myers", '--no-indent-heuristic'];
10
13
  export declare function findMergeBase(repository: string, base: string, head: string): Promise<string>;
11
14
  export declare function readChanges(repository: string, base: string, head: SourceSnapshot, excludes: (path: string) => boolean, isSource: (path: string) => boolean): Promise<GitChanges>;
12
15
  interface RawChange {
@@ -20,3 +23,5 @@ interface RawChange {
20
23
  }
21
24
  export declare function rawChanges(text: string): readonly RawChange[];
22
25
  export declare function addedRanges(patch: string): readonly LineRange[];
26
+ export declare function removedRanges(patch: string): readonly LineRange[];
27
+ export declare function patchHunks(patch: string): readonly LineHunk[];
@@ -1,9 +1,9 @@
1
1
  import { gitText, gitUtf8 } from './git.js';
2
2
  import { physicalLines, utf8 } from '../../core/model/snapshot.js';
3
- const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
4
- const regularFile = /^100(?:644|755)$/;
3
+ export const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
4
+ export const regularFile = /^100(?:644|755)$/;
5
5
  export const diffMethod = { algorithm: 'myers', indentHeuristic: false, renameThresholdPercent: 50, renameLimit: 1000 };
6
- const stableDiff = ['--no-color', '--no-ext-diff', '--no-textconv', `--diff-algorithm=${diffMethod.algorithm}`, '--no-indent-heuristic'];
6
+ export const stableDiff = ['--no-color', '--no-ext-diff', '--no-textconv', `--diff-algorithm=${diffMethod.algorithm}`, '--no-indent-heuristic'];
7
7
  export async function findMergeBase(repository, base, head) {
8
8
  if (!oid.test(base) || !oid.test(head))
9
9
  throw new Error('Merge base requires full commit IDs');
@@ -13,7 +13,7 @@ export async function findMergeBase(repository, base, head) {
13
13
  }
14
14
  catch (error) {
15
15
  if (error instanceof Error && 'code' in error && error.code === 1) {
16
- throw new Error('No merge base found. Make the histories for both commits available locally.');
16
+ throw new Error('No merge base found. Make the histories of both commits available locally, for example with fetch-depth: 0 on actions/checkout.');
17
17
  }
18
18
  throw error;
19
19
  }
@@ -89,13 +89,22 @@ export function rawChanges(text) {
89
89
  return changes;
90
90
  }
91
91
  export function addedRanges(patch) {
92
+ return lineRanges(patchHunks(patch).map(hunk => hunk.head));
93
+ }
94
+ export function removedRanges(patch) {
95
+ return lineRanges(patchHunks(patch).map(hunk => hunk.base));
96
+ }
97
+ export function patchHunks(patch) {
98
+ return patch.split('\n').flatMap(line => {
99
+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: |$)/.exec(line);
100
+ return match ? [{ base: { first: Number(match[1]), count: Number(match[2] ?? 1) },
101
+ head: { first: Number(match[3]), count: Number(match[4] ?? 1) } }] : [];
102
+ });
103
+ }
104
+ /** The changed lines of one side of the hunks, which Git reports in order and without overlap. */
105
+ function lineRanges(sides) {
92
106
  const ranges = [];
93
- for (const line of patch.split('\n')) {
94
- const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@(?: |$)/.exec(line);
95
- if (!match)
96
- continue;
97
- const first = Number(match[1]);
98
- const count = Number(match[2] ?? 1);
107
+ for (const { first, count } of sides) {
99
108
  if (count === 0)
100
109
  continue;
101
110
  const last = first + count - 1;
@@ -0,0 +1,6 @@
1
+ import type { LineChanges } from '../../core/model/changes.js';
2
+ /**
3
+ * The changed lines of every regular file between two commits, on both sides, following renames. A binary file, or one
4
+ * whose line breaks Git and parsers may count differently, changes as a whole.
5
+ */
6
+ export declare function readLineChanges(repository: string, base: string, head: string): Promise<LineChanges>;
@@ -0,0 +1,57 @@
1
+ import { addedRanges, diffMethod, oid, patchHunks, rawChanges, regularFile, removedRanges, stableDiff } from './changes.js';
2
+ import { GitBlobReader, gitText, gitUtf8 } from './git.js';
3
+ /**
4
+ * The changed lines of every regular file between two commits, on both sides, following renames. A binary file, or one
5
+ * whose line breaks Git and parsers may count differently, changes as a whole.
6
+ */
7
+ export async function readLineChanges(repository, base, head) {
8
+ if (!oid.test(base) || !oid.test(head))
9
+ throw new Error('Git diff requires full commit IDs');
10
+ if (base === head)
11
+ return { files: [] };
12
+ const raw = await gitUtf8(repository, ['diff', ...stableDiff, '--raw', '-z', '--no-abbrev',
13
+ `--find-renames=${diffMethod.renameThresholdPercent}%`, `-l${diffMethod.renameLimit}`, base, head, '--']);
14
+ const blobs = new GitBlobReader(repository);
15
+ const files = [];
16
+ // One file at a time: a large change must not start a Git process per file at once.
17
+ for (const change of rawChanges(raw)) {
18
+ const file = await fileChange(repository, blobs, change);
19
+ if (file)
20
+ files.push(file);
21
+ }
22
+ return { files };
23
+ }
24
+ async function fileChange(repository, blobs, change) {
25
+ const path = regularFile.test(change.mode) ? change.path : null;
26
+ const { previous } = change;
27
+ if (path === null && previous === undefined)
28
+ return undefined;
29
+ const text = (id) => id === undefined ? Promise.resolve('') : blobs.read([id]).then(([bytes]) => lineText(bytes));
30
+ const [headText, baseText] = await Promise.all([text(path === null ? undefined : change.oid), text(previous?.oid)]);
31
+ const file = { path, previous: previous?.path ?? null };
32
+ if (headText === undefined || baseText === undefined)
33
+ return { ...file, added: [], removed: [], whole: true, hunks: [] };
34
+ if (path === null || previous === undefined) {
35
+ return { ...file, added: wholeRange(headText), removed: wholeRange(baseText), whole: false, hunks: [] };
36
+ }
37
+ const patch = await gitText(repository, ['diff', ...stableDiff, '--text', '--unified=0', '--inter-hunk-context=0', previous.oid, change.oid, '--']);
38
+ return { ...file, added: addedRanges(patch), removed: removedRanges(patch), whole: false, hunks: patchHunks(patch) };
39
+ }
40
+ /** Text whose lines Git numbers the same way parsers do, or undefined. */
41
+ function lineText(bytes) {
42
+ if (bytes === undefined)
43
+ return undefined;
44
+ let text;
45
+ try {
46
+ text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ return /\0|\r(?!\n)|[\u2028\u2029]/.test(text) ? undefined : text;
52
+ }
53
+ function wholeRange(text) {
54
+ const count = text.split('\n').length - Number(text.endsWith('\n'));
55
+ return text === '' ? [] : [{ first: 1, last: count }];
56
+ }
57
+ //# sourceMappingURL=line-changes.js.map
@@ -1,4 +1,6 @@
1
1
  import type { Invocation } from './arguments.js';
2
+ /** The configuration file in effect, or undefined under --no-config. */
3
+ export declare function configFile(root: string, input: Invocation): string | undefined;
2
4
  export declare function readConfig(root: string, input: Invocation): Promise<{
3
5
  exclude: readonly string[];
4
6
  ignore: readonly import("../index.js").FindingIgnoreRule[];
@@ -9,6 +11,5 @@ export declare function readConfig(root: string, input: Invocation): Promise<{
9
11
  branch: string | undefined;
10
12
  minCoverage: string | undefined;
11
13
  minLines: string | undefined;
12
- maxCoverageDrop: string | undefined;
13
14
  maxNewIssues: string | undefined;
14
15
  }>;
@@ -5,7 +5,7 @@ import { normalizeProfile } from '../core/profile/profile.js';
5
5
  import { readProcessPlugins } from '../compose/process-plugins.js';
6
6
  import { invocationDirectory } from './store.js';
7
7
  const keys = new Set(['$schema', 'exclude', 'ignore', 'imports', 'reports', 'sources', 'branch',
8
- 'minCoverage', 'minLines', 'maxCoverageDrop', 'maxNewIssues', 'plugins']);
8
+ 'minCoverage', 'minLines', 'maxNewIssues', 'plugins']);
9
9
  function parseConfig(value) {
10
10
  if (!isRecord(value) || Object.keys(value).some(key => !keys.has(key)))
11
11
  throw new Error('Invalid Repometry JSON configuration');
@@ -14,16 +14,23 @@ function parseConfig(value) {
14
14
  return { ...profile, plugins: readProcessPlugins(value.plugins), imports: list(value.imports, 'imports'), reports: list(value.reports, 'reports'),
15
15
  sources: string(value.sources, 'sources'), branch: string(value.branch, 'branch'),
16
16
  minCoverage: number(value.minCoverage, 'minCoverage'), minLines: number(value.minLines, 'minLines'),
17
- maxCoverageDrop: number(value.maxCoverageDrop, 'maxCoverageDrop'), maxNewIssues: number(value.maxNewIssues, 'maxNewIssues') };
17
+ maxNewIssues: number(value.maxNewIssues, 'maxNewIssues') };
18
18
  }
19
- export async function readConfig(root, input) {
19
+ /** The configuration file in effect, or undefined under --no-config. */
20
+ export function configFile(root, input) {
20
21
  const explicit = input.text('config');
21
22
  if (input.flag('no-config')) {
22
23
  if (explicit !== undefined)
23
24
  throw new Error('Choose --config or --no-config');
24
- return parseConfig({});
25
+ return undefined;
25
26
  }
26
- const file = explicit === undefined ? resolve(root, 'repometry.config.json') : resolve(invocationDirectory(input), explicit);
27
+ return explicit === undefined ? resolve(root, 'repometry.config.json') : resolve(invocationDirectory(input), explicit);
28
+ }
29
+ export async function readConfig(root, input) {
30
+ const explicit = input.text('config');
31
+ const file = configFile(root, input);
32
+ if (file === undefined)
33
+ return parseConfig({});
27
34
  let json;
28
35
  try {
29
36
  json = await readFile(file, 'utf8');