walkdiff 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +83 -3
- package/app-ui/assets/{index-CW9T4O2t.js → index-BRMcNFUc.js} +1 -1
- package/app-ui/index.html +1 -1
- package/package.json +2 -1
- package/report-ui/assets/index-CFriIC6-.css +1 -0
- package/report-ui/assets/index-DOjOcj6E.js +81 -0
- package/report-ui/index.html +2 -2
- package/walkdiff.mjs +1951 -58
- package/report-ui/assets/index-CNwloc-G.css +0 -1
- package/report-ui/assets/index-CjDznYrY.js +0 -81
package/walkdiff.mjs
CHANGED
|
@@ -7,10 +7,11 @@ import { parseArgs, promisify } from "node:util";
|
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { createHash, randomBytes } from "node:crypto";
|
|
9
9
|
import { Language, Parser } from "web-tree-sitter";
|
|
10
|
-
import { LineCounter, isMap, isPair, isScalar, isSeq, parse, parseAllDocuments } from "yaml";
|
|
10
|
+
import { LineCounter, isMap, isPair, isScalar, isSeq, parse, parseAllDocuments, parseDocument } from "yaml";
|
|
11
|
+
import { Kind, parse as parse$1, print } from "graphql";
|
|
11
12
|
import { homedir, tmpdir } from "node:os";
|
|
12
13
|
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
-
import { parse as parse$
|
|
14
|
+
import { parse as parse$2 } from "smol-toml";
|
|
14
15
|
import Anthropic from "@anthropic-ai/sdk";
|
|
15
16
|
import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
|
|
16
17
|
import { inflateRawSync } from "node:zlib";
|
|
@@ -1090,6 +1091,7 @@ const CheckId = {
|
|
|
1090
1091
|
OsvDatabase: "osvDatabase",
|
|
1091
1092
|
DependencyTrust: "dependencyTrust",
|
|
1092
1093
|
NpmReleases: "npmReleases",
|
|
1094
|
+
Hotspots: "hotspots",
|
|
1093
1095
|
Zizmor: "zizmor",
|
|
1094
1096
|
Poutine: "poutine",
|
|
1095
1097
|
Ruff: "ruff",
|
|
@@ -1425,6 +1427,10 @@ const LogLevel = {
|
|
|
1425
1427
|
Warn: "warn",
|
|
1426
1428
|
Error: "error"
|
|
1427
1429
|
};
|
|
1430
|
+
// packages/review-model/src/fileHistory.ts
|
|
1431
|
+
var HistoryUnavailableError = class extends Error {
|
|
1432
|
+
name = "HistoryUnavailableError";
|
|
1433
|
+
};
|
|
1428
1434
|
// packages/engine/src/blobs.ts
|
|
1429
1435
|
const NEWLINE = 10;
|
|
1430
1436
|
/**
|
|
@@ -5442,6 +5448,955 @@ function isCodeFinding(finding) {
|
|
|
5442
5448
|
function lineKey(finding) {
|
|
5443
5449
|
return finding.location === null || finding.location.line === null ? void 0 : `${finding.location.path}\0${finding.location.line}`;
|
|
5444
5450
|
}
|
|
5451
|
+
// packages/engine/src/risk/breaking/apiSchemas/apiChange.ts
|
|
5452
|
+
/** What changed in an API's contract, in terms every schema format shares. */
|
|
5453
|
+
const ApiChangeKind = {
|
|
5454
|
+
/** An HTTP operation or an RPC is gone. */
|
|
5455
|
+
OperationRemoved: "operation-removed",
|
|
5456
|
+
/** A type, message or enum is gone. */
|
|
5457
|
+
TypeRemoved: "type-removed",
|
|
5458
|
+
/** A field clients read or send is gone. */
|
|
5459
|
+
FieldRemoved: "field-removed",
|
|
5460
|
+
EnumValueRemoved: "enum-value-removed",
|
|
5461
|
+
TypeChanged: "type-changed",
|
|
5462
|
+
/** A new input that clients must now send. */
|
|
5463
|
+
RequiredAdded: "required-added",
|
|
5464
|
+
/** An input that was optional must now be sent. */
|
|
5465
|
+
BecameRequired: "became-required",
|
|
5466
|
+
/** An output field that was always there can now be missing or null. */
|
|
5467
|
+
BecameOptional: "became-optional",
|
|
5468
|
+
/** A protobuf field or enum value keeps its name but changes its number, which the wire format uses. */
|
|
5469
|
+
NumberChanged: "number-changed"
|
|
5470
|
+
};
|
|
5471
|
+
/** Reads one schema file, naming it in any error so the report can say which file it couldn't read. */
|
|
5472
|
+
function readFile$1(file, read) {
|
|
5473
|
+
try {
|
|
5474
|
+
return read(file.text);
|
|
5475
|
+
} catch (error) {
|
|
5476
|
+
throw new Error(`${file.path}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
5477
|
+
}
|
|
5478
|
+
}
|
|
5479
|
+
const WORDING$1 = {
|
|
5480
|
+
[ApiChangeKind.OperationRemoved]: {
|
|
5481
|
+
title: (subject) => `${subject} removed from the API`,
|
|
5482
|
+
breaks: "Clients that call it will get errors."
|
|
5483
|
+
},
|
|
5484
|
+
[ApiChangeKind.TypeRemoved]: {
|
|
5485
|
+
title: (subject) => `Type ${subject} removed`,
|
|
5486
|
+
breaks: "Clients that use it will no longer build or validate."
|
|
5487
|
+
},
|
|
5488
|
+
[ApiChangeKind.FieldRemoved]: {
|
|
5489
|
+
title: (subject) => `${subject} removed`,
|
|
5490
|
+
breaks: "Clients that read or send it will break."
|
|
5491
|
+
},
|
|
5492
|
+
[ApiChangeKind.EnumValueRemoved]: {
|
|
5493
|
+
title: (subject) => `Enum value ${subject} removed`,
|
|
5494
|
+
breaks: "Clients that send it will be rejected, and those that match on it will miss it."
|
|
5495
|
+
},
|
|
5496
|
+
[ApiChangeKind.TypeChanged]: {
|
|
5497
|
+
title: (subject, change) => `${subject} changed type${change === void 0 ? "" : ` from ${change}`}`,
|
|
5498
|
+
breaks: "Clients that send or read the old type will break."
|
|
5499
|
+
},
|
|
5500
|
+
[ApiChangeKind.RequiredAdded]: {
|
|
5501
|
+
title: (subject) => `${subject} is new and required`,
|
|
5502
|
+
breaks: "Clients that don't send it yet will be rejected."
|
|
5503
|
+
},
|
|
5504
|
+
[ApiChangeKind.BecameRequired]: {
|
|
5505
|
+
title: (subject) => `${subject} is now required`,
|
|
5506
|
+
breaks: "Clients that leave it out will be rejected."
|
|
5507
|
+
},
|
|
5508
|
+
[ApiChangeKind.BecameOptional]: {
|
|
5509
|
+
title: (subject) => `${subject} can now be missing`,
|
|
5510
|
+
breaks: "Clients that assume it's always there can fail on responses without it."
|
|
5511
|
+
},
|
|
5512
|
+
[ApiChangeKind.NumberChanged]: {
|
|
5513
|
+
title: (subject, change) => `${subject} changed number${change === void 0 ? "" : ` from ${change}`}`,
|
|
5514
|
+
breaks: "Data written with the old number is read as a different field, or lost, by every client and service still using the old schema."
|
|
5515
|
+
}
|
|
5516
|
+
};
|
|
5517
|
+
const ACTION = "Keep the old form alongside the new one until clients have moved, or release it as a new API version.";
|
|
5518
|
+
/** A finding for one API change in `path`, rated higher when it breaks clients already running. */
|
|
5519
|
+
function apiChangeFinding(format, change) {
|
|
5520
|
+
const wording = WORDING$1[change.kind];
|
|
5521
|
+
const subject = codeSpan(change.subject);
|
|
5522
|
+
return findingAt({
|
|
5523
|
+
id: `breaking.api-${change.kind}`,
|
|
5524
|
+
category: RiskCategory.BreakingChange,
|
|
5525
|
+
severity: change.breaksDeployedClients === true ? RiskSeverity.High : RiskSeverity.Medium,
|
|
5526
|
+
title: `${format.name}: ${wording.title(subject, change.change)}`,
|
|
5527
|
+
detail: `${wording.breaks} ${ACTION}`
|
|
5528
|
+
}, change.path, change.line, change.subject);
|
|
5529
|
+
}
|
|
5530
|
+
// packages/engine/src/risk/breaking/apiSchemas/graphql.ts
|
|
5531
|
+
/**
|
|
5532
|
+
* GraphQL schema files (SDL). Types are compared by name, with `extend type` merged into the type
|
|
5533
|
+
* it extends: removed types, fields, arguments and enum values, retyped fields, output fields that
|
|
5534
|
+
* can now be null, and inputs that became required. A schema is often split across files, so all
|
|
5535
|
+
* the PR's GraphQL files are read as one: a type that moves to another file is compared with
|
|
5536
|
+
* itself there, and each change is placed in the file the type is in now.
|
|
5537
|
+
*/
|
|
5538
|
+
const SCHEMA_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
5539
|
+
".graphql",
|
|
5540
|
+
".graphqls",
|
|
5541
|
+
".gql"
|
|
5542
|
+
]);
|
|
5543
|
+
const NON_NULL = "!";
|
|
5544
|
+
const TypeKind = {
|
|
5545
|
+
Object: "object",
|
|
5546
|
+
Input: "input",
|
|
5547
|
+
Enum: "enum",
|
|
5548
|
+
Other: "other"
|
|
5549
|
+
};
|
|
5550
|
+
const GRAPHQL = {
|
|
5551
|
+
name: "GraphQL",
|
|
5552
|
+
matches: (path) => SCHEMA_EXTENSIONS.has(extname(path).toLowerCase()),
|
|
5553
|
+
compare: (before, after) => compareSchemas$1(readSchemas(before), readSchemas(after))
|
|
5554
|
+
};
|
|
5555
|
+
function compareSchemas$1(old, now) {
|
|
5556
|
+
return [...old].flatMap(([name, previous]) => {
|
|
5557
|
+
const current = now.get(name);
|
|
5558
|
+
if (current === void 0) return [{
|
|
5559
|
+
kind: ApiChangeKind.TypeRemoved,
|
|
5560
|
+
subject: name,
|
|
5561
|
+
path: previous.path,
|
|
5562
|
+
line: null,
|
|
5563
|
+
breaksDeployedClients: true
|
|
5564
|
+
}];
|
|
5565
|
+
if (current.kind !== previous.kind) return [{
|
|
5566
|
+
kind: ApiChangeKind.TypeChanged,
|
|
5567
|
+
subject: name,
|
|
5568
|
+
change: `${previous.kind} to ${current.kind}`,
|
|
5569
|
+
path: current.path,
|
|
5570
|
+
line: current.line,
|
|
5571
|
+
breaksDeployedClients: true
|
|
5572
|
+
}];
|
|
5573
|
+
switch (current.kind) {
|
|
5574
|
+
case TypeKind.Object: return outputMemberChanges(name, previous, current);
|
|
5575
|
+
case TypeKind.Input: return inputMemberChanges(name, previous, current);
|
|
5576
|
+
case TypeKind.Enum: return [...previous.values].filter((value) => !current.values.has(value)).map((value) => ({
|
|
5577
|
+
kind: ApiChangeKind.EnumValueRemoved,
|
|
5578
|
+
subject: `${name}.${value}`,
|
|
5579
|
+
path: current.path,
|
|
5580
|
+
line: current.line,
|
|
5581
|
+
breaksDeployedClients: true
|
|
5582
|
+
}));
|
|
5583
|
+
case TypeKind.Other: return [];
|
|
5584
|
+
}
|
|
5585
|
+
});
|
|
5586
|
+
}
|
|
5587
|
+
/** Fields of object types and interfaces, which clients select and read. */
|
|
5588
|
+
function outputMemberChanges(typeName, previous, current) {
|
|
5589
|
+
return [...previous.members].flatMap(([name, member]) => {
|
|
5590
|
+
const subject = `${typeName}.${name}`;
|
|
5591
|
+
const now = current.members.get(name);
|
|
5592
|
+
if (now === void 0) return [{
|
|
5593
|
+
kind: ApiChangeKind.FieldRemoved,
|
|
5594
|
+
subject,
|
|
5595
|
+
path: current.path,
|
|
5596
|
+
line: current.line,
|
|
5597
|
+
breaksDeployedClients: true
|
|
5598
|
+
}];
|
|
5599
|
+
return [...outputTypeChange(subject, member.type, now), ...argumentChanges(subject, member.arguments, now)];
|
|
5600
|
+
});
|
|
5601
|
+
}
|
|
5602
|
+
function outputTypeChange(subject, before, now) {
|
|
5603
|
+
const { type: after, path, line } = now;
|
|
5604
|
+
if (withoutNonNull(before) !== withoutNonNull(after)) return [{
|
|
5605
|
+
kind: ApiChangeKind.TypeChanged,
|
|
5606
|
+
subject,
|
|
5607
|
+
change: `${before} to ${after}`,
|
|
5608
|
+
path,
|
|
5609
|
+
line,
|
|
5610
|
+
breaksDeployedClients: true
|
|
5611
|
+
}];
|
|
5612
|
+
return nonNullCount(after) < nonNullCount(before) ? [{
|
|
5613
|
+
kind: ApiChangeKind.BecameOptional,
|
|
5614
|
+
subject,
|
|
5615
|
+
path,
|
|
5616
|
+
line
|
|
5617
|
+
}] : [];
|
|
5618
|
+
}
|
|
5619
|
+
function inputTypeChange(subject, before, after, path, line) {
|
|
5620
|
+
if (withoutNonNull(before) !== withoutNonNull(after)) return [{
|
|
5621
|
+
kind: ApiChangeKind.TypeChanged,
|
|
5622
|
+
subject,
|
|
5623
|
+
change: `${before} to ${after}`,
|
|
5624
|
+
path,
|
|
5625
|
+
line,
|
|
5626
|
+
breaksDeployedClients: true
|
|
5627
|
+
}];
|
|
5628
|
+
return nonNullCount(after) > nonNullCount(before) ? [{
|
|
5629
|
+
kind: ApiChangeKind.BecameRequired,
|
|
5630
|
+
subject,
|
|
5631
|
+
path,
|
|
5632
|
+
line,
|
|
5633
|
+
breaksDeployedClients: true
|
|
5634
|
+
}] : [];
|
|
5635
|
+
}
|
|
5636
|
+
function argumentChanges(fieldName, before, now) {
|
|
5637
|
+
const { arguments: after, path, line } = now;
|
|
5638
|
+
const removed = [...before.keys()].filter((name) => !after.has(name)).map((name) => ({
|
|
5639
|
+
kind: ApiChangeKind.FieldRemoved,
|
|
5640
|
+
subject: `${fieldName}(${name}:)`,
|
|
5641
|
+
path,
|
|
5642
|
+
line,
|
|
5643
|
+
breaksDeployedClients: true
|
|
5644
|
+
}));
|
|
5645
|
+
const changed = [...after].flatMap(([name, argument]) => {
|
|
5646
|
+
const subject = `${fieldName}(${name}:)`;
|
|
5647
|
+
const previous = before.get(name);
|
|
5648
|
+
if (previous === void 0) return isRequired(argument) ? [{
|
|
5649
|
+
kind: ApiChangeKind.RequiredAdded,
|
|
5650
|
+
subject,
|
|
5651
|
+
path,
|
|
5652
|
+
line,
|
|
5653
|
+
breaksDeployedClients: true
|
|
5654
|
+
}] : [];
|
|
5655
|
+
return inputTypeChange(subject, previous.type, argument.type, path, line);
|
|
5656
|
+
});
|
|
5657
|
+
return [...removed, ...changed];
|
|
5658
|
+
}
|
|
5659
|
+
/** Fields of input types, which clients send. */
|
|
5660
|
+
function inputMemberChanges(typeName, before, after) {
|
|
5661
|
+
const removed = [...before.members.keys()].filter((name) => !after.members.has(name)).map((name) => ({
|
|
5662
|
+
kind: ApiChangeKind.FieldRemoved,
|
|
5663
|
+
subject: `${typeName}.${name}`,
|
|
5664
|
+
path: after.path,
|
|
5665
|
+
line: after.line,
|
|
5666
|
+
breaksDeployedClients: true
|
|
5667
|
+
}));
|
|
5668
|
+
const changed = [...after.members].flatMap(([name, member]) => {
|
|
5669
|
+
const subject = `${typeName}.${name}`;
|
|
5670
|
+
const previous = before.members.get(name);
|
|
5671
|
+
if (previous === void 0) return isRequired(member) ? [{
|
|
5672
|
+
kind: ApiChangeKind.RequiredAdded,
|
|
5673
|
+
subject,
|
|
5674
|
+
path: member.path,
|
|
5675
|
+
line: member.line,
|
|
5676
|
+
breaksDeployedClients: true
|
|
5677
|
+
}] : [];
|
|
5678
|
+
return inputTypeChange(subject, previous.type, member.type, member.path, member.line);
|
|
5679
|
+
});
|
|
5680
|
+
return [...removed, ...changed];
|
|
5681
|
+
}
|
|
5682
|
+
function isRequired(input) {
|
|
5683
|
+
return input.type.endsWith(NON_NULL) && !input.hasDefault;
|
|
5684
|
+
}
|
|
5685
|
+
function withoutNonNull(type) {
|
|
5686
|
+
return type.replaceAll(NON_NULL, "");
|
|
5687
|
+
}
|
|
5688
|
+
function nonNullCount(type) {
|
|
5689
|
+
return type.split(NON_NULL).length - 1;
|
|
5690
|
+
}
|
|
5691
|
+
/** Every type the files define, with `extend` merged in, wherever in the files it is. */
|
|
5692
|
+
function readSchemas(files) {
|
|
5693
|
+
const types = /* @__PURE__ */ new Map();
|
|
5694
|
+
for (const file of files) readFile$1(file, (text) => addTypes(types, file.path, text));
|
|
5695
|
+
return types;
|
|
5696
|
+
}
|
|
5697
|
+
function addTypes(types, path, text) {
|
|
5698
|
+
if (text.trim() === "") return;
|
|
5699
|
+
const lineStarts = [0, ...[...text.matchAll(/\n/g)].map((match) => match.index + 1)];
|
|
5700
|
+
const lineAt = (offset) => offset === void 0 ? 1 : lineStarts.findLastIndex((start) => start <= offset) + 1;
|
|
5701
|
+
for (const definition of parse$1(text).definitions) {
|
|
5702
|
+
const read = typeParts(definition);
|
|
5703
|
+
if (read === void 0) continue;
|
|
5704
|
+
const type = types.get(read.name) ?? {
|
|
5705
|
+
path,
|
|
5706
|
+
kind: read.kind,
|
|
5707
|
+
line: lineAt(definition.loc?.start),
|
|
5708
|
+
members: /* @__PURE__ */ new Map(),
|
|
5709
|
+
values: /* @__PURE__ */ new Set()
|
|
5710
|
+
};
|
|
5711
|
+
for (const member of read.fields) type.members.set(member.name.value, memberOf(member, path, lineAt));
|
|
5712
|
+
for (const value of read.values) type.values.add(value);
|
|
5713
|
+
types.set(read.name, type);
|
|
5714
|
+
}
|
|
5715
|
+
}
|
|
5716
|
+
function typeParts(definition) {
|
|
5717
|
+
switch (definition.kind) {
|
|
5718
|
+
case Kind.OBJECT_TYPE_DEFINITION:
|
|
5719
|
+
case Kind.OBJECT_TYPE_EXTENSION:
|
|
5720
|
+
case Kind.INTERFACE_TYPE_DEFINITION:
|
|
5721
|
+
case Kind.INTERFACE_TYPE_EXTENSION: return {
|
|
5722
|
+
name: definition.name.value,
|
|
5723
|
+
kind: TypeKind.Object,
|
|
5724
|
+
fields: definition.fields ?? [],
|
|
5725
|
+
values: []
|
|
5726
|
+
};
|
|
5727
|
+
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
|
|
5728
|
+
case Kind.INPUT_OBJECT_TYPE_EXTENSION: return {
|
|
5729
|
+
name: definition.name.value,
|
|
5730
|
+
kind: TypeKind.Input,
|
|
5731
|
+
fields: definition.fields ?? [],
|
|
5732
|
+
values: []
|
|
5733
|
+
};
|
|
5734
|
+
case Kind.ENUM_TYPE_DEFINITION:
|
|
5735
|
+
case Kind.ENUM_TYPE_EXTENSION: return {
|
|
5736
|
+
name: definition.name.value,
|
|
5737
|
+
kind: TypeKind.Enum,
|
|
5738
|
+
fields: [],
|
|
5739
|
+
values: (definition.values ?? []).map((value) => value.name.value)
|
|
5740
|
+
};
|
|
5741
|
+
case Kind.UNION_TYPE_DEFINITION:
|
|
5742
|
+
case Kind.UNION_TYPE_EXTENSION:
|
|
5743
|
+
case Kind.SCALAR_TYPE_DEFINITION:
|
|
5744
|
+
case Kind.SCALAR_TYPE_EXTENSION: return {
|
|
5745
|
+
name: definition.name.value,
|
|
5746
|
+
kind: TypeKind.Other,
|
|
5747
|
+
fields: [],
|
|
5748
|
+
values: []
|
|
5749
|
+
};
|
|
5750
|
+
default: return;
|
|
5751
|
+
}
|
|
5752
|
+
}
|
|
5753
|
+
function memberOf(member, path, lineAt) {
|
|
5754
|
+
const argumentNodes = member.kind === Kind.FIELD_DEFINITION ? member.arguments ?? [] : [];
|
|
5755
|
+
return {
|
|
5756
|
+
path,
|
|
5757
|
+
type: print(member.type),
|
|
5758
|
+
line: lineAt(member.loc?.start),
|
|
5759
|
+
arguments: new Map(argumentNodes.map((argument) => [argument.name.value, {
|
|
5760
|
+
type: print(argument.type),
|
|
5761
|
+
hasDefault: argument.defaultValue !== void 0
|
|
5762
|
+
}])),
|
|
5763
|
+
hasDefault: member.kind === Kind.INPUT_VALUE_DEFINITION && member.defaultValue !== void 0
|
|
5764
|
+
};
|
|
5765
|
+
}
|
|
5766
|
+
// packages/engine/src/risk/dependencies/fields.ts
|
|
5767
|
+
function isRecord(value) {
|
|
5768
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5769
|
+
}
|
|
5770
|
+
function field(value, key) {
|
|
5771
|
+
return isRecord(value) ? value[key] : void 0;
|
|
5772
|
+
}
|
|
5773
|
+
function stringField(value, key) {
|
|
5774
|
+
const found = field(value, key);
|
|
5775
|
+
return typeof found === "string" ? found : void 0;
|
|
5776
|
+
}
|
|
5777
|
+
function recordOrEmpty(value) {
|
|
5778
|
+
return isRecord(value) ? value : {};
|
|
5779
|
+
}
|
|
5780
|
+
// packages/engine/src/risk/breaking/apiSchemas/openApi.ts
|
|
5781
|
+
/**
|
|
5782
|
+
* OpenAPI 3 and Swagger 2 specs, in YAML or JSON. Each operation is compared with its earlier
|
|
5783
|
+
* version: removed operations, new or newly required parameters and request fields, removed or
|
|
5784
|
+
* retyped response fields, and enum values clients can no longer send. Only the top level of a
|
|
5785
|
+
* request or response body is compared, after following `$ref`s and `allOf` within the file.
|
|
5786
|
+
*/
|
|
5787
|
+
const SPEC_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
5788
|
+
".yaml",
|
|
5789
|
+
".yml",
|
|
5790
|
+
".json"
|
|
5791
|
+
]);
|
|
5792
|
+
const SPEC_MARKER = /^\s*\{?\s*["']?(?:openapi|swagger)["']?\s*:/m;
|
|
5793
|
+
const HTTP_METHODS = /* @__PURE__ */ new Set([
|
|
5794
|
+
"get",
|
|
5795
|
+
"put",
|
|
5796
|
+
"post",
|
|
5797
|
+
"delete",
|
|
5798
|
+
"options",
|
|
5799
|
+
"head",
|
|
5800
|
+
"patch",
|
|
5801
|
+
"trace"
|
|
5802
|
+
]);
|
|
5803
|
+
const SUCCESS_STATUS = /^2(?:\d\d|XX)$/;
|
|
5804
|
+
const JSON_MEDIA_TYPE = "application/json";
|
|
5805
|
+
const LOCAL_REF = "#/";
|
|
5806
|
+
const MAX_REF_DEPTH = 32;
|
|
5807
|
+
const OPEN_API = {
|
|
5808
|
+
name: "OpenAPI",
|
|
5809
|
+
matches: (path, text) => SPEC_EXTENSIONS.has(extname(path).toLowerCase()) && SPEC_MARKER.test(text),
|
|
5810
|
+
compare: (before, after) => before.flatMap((old) => {
|
|
5811
|
+
const now = after.find((file) => file.path === old.path) ?? {
|
|
5812
|
+
path: old.path,
|
|
5813
|
+
text: ""
|
|
5814
|
+
};
|
|
5815
|
+
return compareSpecs(readFile$1(old, readSpec), readFile$1(now, readSpec)).map((change) => ({
|
|
5816
|
+
...change,
|
|
5817
|
+
path: old.path
|
|
5818
|
+
}));
|
|
5819
|
+
})
|
|
5820
|
+
};
|
|
5821
|
+
function compareSpecs(old, now) {
|
|
5822
|
+
return [...old.operations.values()].flatMap((previous) => {
|
|
5823
|
+
const current = now.operations.get(previous.name);
|
|
5824
|
+
if (current === void 0) return [{
|
|
5825
|
+
kind: ApiChangeKind.OperationRemoved,
|
|
5826
|
+
subject: previous.name,
|
|
5827
|
+
line: now.lineOf(["paths", previous.path]),
|
|
5828
|
+
breaksDeployedClients: true
|
|
5829
|
+
}];
|
|
5830
|
+
const line = now.lineOf([
|
|
5831
|
+
"paths",
|
|
5832
|
+
current.path,
|
|
5833
|
+
current.method
|
|
5834
|
+
]);
|
|
5835
|
+
return [
|
|
5836
|
+
...inputChanges(previous.parameters, current.parameters, (key) => `${current.name} ${key} parameter`, line),
|
|
5837
|
+
...!previous.bodyRequired && current.bodyRequired ? [{
|
|
5838
|
+
kind: ApiChangeKind.BecameRequired,
|
|
5839
|
+
subject: `${current.name} request body`,
|
|
5840
|
+
line
|
|
5841
|
+
}] : [],
|
|
5842
|
+
...inputChanges(previous.requestFields, current.requestFields, (name) => `${current.name} request: ${name}`, line),
|
|
5843
|
+
...outputChanges(previous.responseFields, current.responseFields, (name) => `${current.name} response: ${name}`, line)
|
|
5844
|
+
];
|
|
5845
|
+
});
|
|
5846
|
+
}
|
|
5847
|
+
/** What clients send: they break when something new is required, or a value they send stops being accepted. */
|
|
5848
|
+
function inputChanges(old, now, subjectOf, line) {
|
|
5849
|
+
return [...now].flatMap(([key, current]) => {
|
|
5850
|
+
const subject = subjectOf(key);
|
|
5851
|
+
const previous = old.get(key);
|
|
5852
|
+
if (previous === void 0) return current.required ? [{
|
|
5853
|
+
kind: ApiChangeKind.RequiredAdded,
|
|
5854
|
+
subject,
|
|
5855
|
+
line
|
|
5856
|
+
}] : [];
|
|
5857
|
+
const removedValues = previous.enumValues.filter((value) => current.enumValues.length > 0 && !current.enumValues.includes(value));
|
|
5858
|
+
return [
|
|
5859
|
+
...!previous.required && current.required ? [{
|
|
5860
|
+
kind: ApiChangeKind.BecameRequired,
|
|
5861
|
+
subject,
|
|
5862
|
+
line
|
|
5863
|
+
}] : [],
|
|
5864
|
+
...typeChange(previous, current, subject, line),
|
|
5865
|
+
...removedValues.map((value) => ({
|
|
5866
|
+
kind: ApiChangeKind.EnumValueRemoved,
|
|
5867
|
+
subject: `${subject} = ${value}`,
|
|
5868
|
+
line
|
|
5869
|
+
}))
|
|
5870
|
+
];
|
|
5871
|
+
});
|
|
5872
|
+
}
|
|
5873
|
+
/** What clients read: they break when a field they read is gone, retyped or no longer always there. */
|
|
5874
|
+
function outputChanges(old, now, subjectOf, line) {
|
|
5875
|
+
return [...old].flatMap(([key, previous]) => {
|
|
5876
|
+
const subject = subjectOf(key);
|
|
5877
|
+
const current = now.get(key);
|
|
5878
|
+
if (current === void 0) return [{
|
|
5879
|
+
kind: ApiChangeKind.FieldRemoved,
|
|
5880
|
+
subject,
|
|
5881
|
+
line,
|
|
5882
|
+
breaksDeployedClients: true
|
|
5883
|
+
}];
|
|
5884
|
+
return [...previous.required && !current.required ? [{
|
|
5885
|
+
kind: ApiChangeKind.BecameOptional,
|
|
5886
|
+
subject,
|
|
5887
|
+
line
|
|
5888
|
+
}] : [], ...typeChange(previous, current, subject, line)];
|
|
5889
|
+
});
|
|
5890
|
+
}
|
|
5891
|
+
function typeChange(previous, current, subject, line) {
|
|
5892
|
+
if (previous.type === void 0 || current.type === void 0 || previous.type === current.type) return [];
|
|
5893
|
+
return [{
|
|
5894
|
+
kind: ApiChangeKind.TypeChanged,
|
|
5895
|
+
subject,
|
|
5896
|
+
change: `${previous.type} to ${current.type}`,
|
|
5897
|
+
line
|
|
5898
|
+
}];
|
|
5899
|
+
}
|
|
5900
|
+
function readSpec(text) {
|
|
5901
|
+
const lineCounter = new LineCounter();
|
|
5902
|
+
const document = parseDocument(text, { lineCounter });
|
|
5903
|
+
const [error] = document.errors;
|
|
5904
|
+
if (error !== void 0) throw error;
|
|
5905
|
+
const spec = document.toJS();
|
|
5906
|
+
const operations = /* @__PURE__ */ new Map();
|
|
5907
|
+
for (const [path, item] of Object.entries(recordOrEmpty(field(spec, "paths")))) {
|
|
5908
|
+
const shared = arrayOf$1(field(item, "parameters"));
|
|
5909
|
+
for (const [method, operation] of Object.entries(recordOrEmpty(item))) {
|
|
5910
|
+
if (!HTTP_METHODS.has(method)) continue;
|
|
5911
|
+
const read = readOperation(spec, path, method, operation, shared);
|
|
5912
|
+
operations.set(read.name, read);
|
|
5913
|
+
}
|
|
5914
|
+
}
|
|
5915
|
+
return {
|
|
5916
|
+
operations,
|
|
5917
|
+
lineOf: (keys) => lineOfKeys(document, lineCounter, keys)
|
|
5918
|
+
};
|
|
5919
|
+
}
|
|
5920
|
+
function readOperation(spec, path, method, operation, shared) {
|
|
5921
|
+
const parameters = /* @__PURE__ */ new Map();
|
|
5922
|
+
let bodyRequired = false;
|
|
5923
|
+
let bodySchema;
|
|
5924
|
+
for (const raw of [...shared, ...arrayOf$1(field(operation, "parameters"))]) {
|
|
5925
|
+
const parameter = resolve$1(spec, raw);
|
|
5926
|
+
const name = stringField(parameter, "name");
|
|
5927
|
+
const place = stringField(parameter, "in");
|
|
5928
|
+
if (name === void 0 || place === void 0) continue;
|
|
5929
|
+
if (place === "body") {
|
|
5930
|
+
bodySchema = field(parameter, "schema");
|
|
5931
|
+
bodyRequired = field(parameter, "required") === true;
|
|
5932
|
+
continue;
|
|
5933
|
+
}
|
|
5934
|
+
const schema = field(parameter, "schema") ?? parameter;
|
|
5935
|
+
parameters.set(`${place} ${name}`, {
|
|
5936
|
+
required: field(parameter, "required") === true || place === "path",
|
|
5937
|
+
type: typeOf(spec, schema),
|
|
5938
|
+
enumValues: enumOf(spec, schema)
|
|
5939
|
+
});
|
|
5940
|
+
}
|
|
5941
|
+
const requestBody = resolve$1(spec, field(operation, "requestBody"));
|
|
5942
|
+
if (requestBody !== void 0) {
|
|
5943
|
+
bodySchema = mediaSchema(field(requestBody, "content"));
|
|
5944
|
+
bodyRequired = field(requestBody, "required") === true;
|
|
5945
|
+
}
|
|
5946
|
+
return {
|
|
5947
|
+
name: `${method.toUpperCase()} ${path}`,
|
|
5948
|
+
path,
|
|
5949
|
+
method,
|
|
5950
|
+
parameters,
|
|
5951
|
+
bodyRequired,
|
|
5952
|
+
requestFields: fieldsOf(spec, bodySchema),
|
|
5953
|
+
responseFields: fieldsOf(spec, successSchema(spec, field(operation, "responses")))
|
|
5954
|
+
};
|
|
5955
|
+
}
|
|
5956
|
+
function successSchema(spec, responses) {
|
|
5957
|
+
const status = Object.keys(recordOrEmpty(responses)).filter((code) => SUCCESS_STATUS.test(code)).sort().at(0);
|
|
5958
|
+
if (status === void 0) return void 0;
|
|
5959
|
+
const response = resolve$1(spec, field(responses, status));
|
|
5960
|
+
return field(response, "schema") ?? mediaSchema(field(response, "content"));
|
|
5961
|
+
}
|
|
5962
|
+
function mediaSchema(content) {
|
|
5963
|
+
const media = recordOrEmpty(content);
|
|
5964
|
+
return field(media[JSON_MEDIA_TYPE] ?? Object.values(media).at(0), "schema");
|
|
5965
|
+
}
|
|
5966
|
+
/** The top-level fields of a body schema, through `$ref`, `allOf` and, for a list, its items. */
|
|
5967
|
+
function fieldsOf(spec, schema) {
|
|
5968
|
+
const fields = /* @__PURE__ */ new Map();
|
|
5969
|
+
const resolved = resolve$1(spec, schema);
|
|
5970
|
+
if (field(resolved, "type") === "array") return fieldsOf(spec, field(resolved, "items"));
|
|
5971
|
+
const parts = [resolved, ...arrayOf$1(field(resolved, "allOf")).map((part) => resolve$1(spec, part))];
|
|
5972
|
+
const required = new Set(parts.flatMap((part) => arrayOf$1(field(part, "required")).filter((name) => typeof name === "string")));
|
|
5973
|
+
for (const part of parts) for (const [name, property] of Object.entries(recordOrEmpty(field(part, "properties")))) fields.set(name, {
|
|
5974
|
+
required: required.has(name),
|
|
5975
|
+
type: typeOf(spec, property),
|
|
5976
|
+
enumValues: enumOf(spec, property)
|
|
5977
|
+
});
|
|
5978
|
+
return fields;
|
|
5979
|
+
}
|
|
5980
|
+
function typeOf(spec, schema, depth = 0) {
|
|
5981
|
+
const reference = stringField(schema, "$ref");
|
|
5982
|
+
const resolved = resolve$1(spec, schema);
|
|
5983
|
+
const type = field(resolved, "type");
|
|
5984
|
+
if (type === "array" && depth < MAX_REF_DEPTH) return `array of ${typeOf(spec, field(resolved, "items"), depth + 1) ?? "anything"}`;
|
|
5985
|
+
if (typeof type === "string") return type;
|
|
5986
|
+
if (Array.isArray(type)) return type.join(" or ");
|
|
5987
|
+
return reference?.split("/").at(-1);
|
|
5988
|
+
}
|
|
5989
|
+
function enumOf(spec, schema) {
|
|
5990
|
+
return arrayOf$1(field(resolve$1(spec, schema), "enum")).map(String);
|
|
5991
|
+
}
|
|
5992
|
+
/** Follows a local `$ref` such as `#/components/schemas/User`; other references are left as they are. */
|
|
5993
|
+
function resolve$1(spec, value) {
|
|
5994
|
+
let current = value;
|
|
5995
|
+
for (let depth = 0; depth < MAX_REF_DEPTH; depth++) {
|
|
5996
|
+
const reference = stringField(current, "$ref");
|
|
5997
|
+
if (reference?.startsWith(LOCAL_REF) !== true) return current;
|
|
5998
|
+
current = reference.slice(2).split("/").map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).reduce((node, segment) => isRecord(node) ? node[segment] : void 0, spec);
|
|
5999
|
+
}
|
|
6000
|
+
return current;
|
|
6001
|
+
}
|
|
6002
|
+
function arrayOf$1(value) {
|
|
6003
|
+
return Array.isArray(value) ? value : [];
|
|
6004
|
+
}
|
|
6005
|
+
/** The line of the deepest of `keys` the document still has, so a removed item points at what holds it. */
|
|
6006
|
+
function lineOfKeys(document, lineCounter, keys) {
|
|
6007
|
+
let node = document.contents;
|
|
6008
|
+
let line = null;
|
|
6009
|
+
for (const key of keys) {
|
|
6010
|
+
if (!isMap(node)) break;
|
|
6011
|
+
const pair = node.items.find((item) => isScalar(item.key) && String(item.key.value) === key);
|
|
6012
|
+
if (pair === void 0 || !isScalar(pair.key) || pair.key.range === void 0 || pair.key.range === null) break;
|
|
6013
|
+
line = lineCounter.linePos(pair.key.range[0]).line;
|
|
6014
|
+
node = pair.value;
|
|
6015
|
+
}
|
|
6016
|
+
return line;
|
|
6017
|
+
}
|
|
6018
|
+
// packages/engine/src/risk/breaking/apiSchemas/protobuf.ts
|
|
6019
|
+
/**
|
|
6020
|
+
* Protocol Buffers schemas (`.proto`). Messages, enums and services are compared by their full
|
|
6021
|
+
* name, with the package: removed or retyped RPCs, fields and enum values whose number changed,
|
|
6022
|
+
* retyped fields, and fields or values removed without reserving their number. The wire format
|
|
6023
|
+
* identifies a field by its number, so a changed number breaks every client and service already
|
|
6024
|
+
* deployed, while a removed name breaks code built against the schema.
|
|
6025
|
+
*
|
|
6026
|
+
* All the PR's `.proto` files are read as one, so a message moved to another file is compared with
|
|
6027
|
+
* itself there. This reads only what a contract consists of; options, extensions and groups are
|
|
6028
|
+
* skipped.
|
|
6029
|
+
*/
|
|
6030
|
+
const PROTO_EXTENSION = ".proto";
|
|
6031
|
+
const MAX_FIELD_NUMBER = 536870911;
|
|
6032
|
+
const FIELD_LABELS = /* @__PURE__ */ new Set([
|
|
6033
|
+
"optional",
|
|
6034
|
+
"repeated",
|
|
6035
|
+
"required"
|
|
6036
|
+
]);
|
|
6037
|
+
const PROTOBUF = {
|
|
6038
|
+
name: "Protobuf",
|
|
6039
|
+
matches: (path) => extname(path).toLowerCase() === PROTO_EXTENSION,
|
|
6040
|
+
compare: (before, after) => compareSchemas(readProtos(before), readProtos(after))
|
|
6041
|
+
};
|
|
6042
|
+
function compareSchemas(old, now) {
|
|
6043
|
+
return [
|
|
6044
|
+
...rpcChanges(old.rpcs, now.rpcs),
|
|
6045
|
+
...definitionChanges(old.messages, now.messages, "field"),
|
|
6046
|
+
...definitionChanges(old.enums, now.enums, "value")
|
|
6047
|
+
];
|
|
6048
|
+
}
|
|
6049
|
+
function rpcChanges(old, now) {
|
|
6050
|
+
return [...old].flatMap(([name, previous]) => {
|
|
6051
|
+
const current = now.get(name);
|
|
6052
|
+
if (current === void 0) return [{
|
|
6053
|
+
kind: ApiChangeKind.OperationRemoved,
|
|
6054
|
+
subject: name,
|
|
6055
|
+
path: previous.path,
|
|
6056
|
+
line: null,
|
|
6057
|
+
breaksDeployedClients: true
|
|
6058
|
+
}];
|
|
6059
|
+
const before = `${previous.request} → ${previous.response}`;
|
|
6060
|
+
const after = `${current.request} → ${current.response}`;
|
|
6061
|
+
return before === after ? [] : [{
|
|
6062
|
+
kind: ApiChangeKind.TypeChanged,
|
|
6063
|
+
subject: name,
|
|
6064
|
+
change: `${before} to ${after}`,
|
|
6065
|
+
path: current.path,
|
|
6066
|
+
line: current.line,
|
|
6067
|
+
breaksDeployedClients: true
|
|
6068
|
+
}];
|
|
6069
|
+
});
|
|
6070
|
+
}
|
|
6071
|
+
function definitionChanges(old, now, member) {
|
|
6072
|
+
return [...old].flatMap(([name, previous]) => {
|
|
6073
|
+
const current = now.get(name);
|
|
6074
|
+
if (current === void 0) return [{
|
|
6075
|
+
kind: ApiChangeKind.TypeRemoved,
|
|
6076
|
+
subject: name,
|
|
6077
|
+
path: previous.path,
|
|
6078
|
+
line: null
|
|
6079
|
+
}];
|
|
6080
|
+
return [...previous.fields].flatMap(([fieldName, field]) => memberChanges(`${name}.${fieldName}`, field, current, fieldName, member));
|
|
6081
|
+
});
|
|
6082
|
+
}
|
|
6083
|
+
function memberChanges(subject, previous, current, name, member) {
|
|
6084
|
+
const now = current.fields.get(name);
|
|
6085
|
+
if (now === void 0) {
|
|
6086
|
+
if (![...current.fields.values()].some((field) => field.number === previous.number) && isReserved(current.reserved, previous.number)) return [];
|
|
6087
|
+
return [{
|
|
6088
|
+
kind: member === "field" ? ApiChangeKind.FieldRemoved : ApiChangeKind.EnumValueRemoved,
|
|
6089
|
+
subject,
|
|
6090
|
+
path: current.path,
|
|
6091
|
+
line: current.line
|
|
6092
|
+
}];
|
|
6093
|
+
}
|
|
6094
|
+
const path = current.path;
|
|
6095
|
+
const line = now.line;
|
|
6096
|
+
return [...now.number === previous.number ? [] : [{
|
|
6097
|
+
kind: ApiChangeKind.NumberChanged,
|
|
6098
|
+
subject,
|
|
6099
|
+
change: `${previous.number} to ${now.number}`,
|
|
6100
|
+
path,
|
|
6101
|
+
line,
|
|
6102
|
+
breaksDeployedClients: true
|
|
6103
|
+
}], ...now.type === previous.type ? [] : [{
|
|
6104
|
+
kind: ApiChangeKind.TypeChanged,
|
|
6105
|
+
subject,
|
|
6106
|
+
change: `${previous.type} to ${now.type}`,
|
|
6107
|
+
path,
|
|
6108
|
+
line,
|
|
6109
|
+
breaksDeployedClients: true
|
|
6110
|
+
}]];
|
|
6111
|
+
}
|
|
6112
|
+
function isReserved(reserved, number) {
|
|
6113
|
+
return reserved.ranges.some(([low, high]) => number >= low && number <= high);
|
|
6114
|
+
}
|
|
6115
|
+
const TOKEN = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_.][\w.]*|-?\d+|\S/g;
|
|
6116
|
+
function tokenize(text) {
|
|
6117
|
+
const tokens = [];
|
|
6118
|
+
let line = 1;
|
|
6119
|
+
let lastIndex = 0;
|
|
6120
|
+
for (const match of text.matchAll(TOKEN)) {
|
|
6121
|
+
line += countNewlines(text, lastIndex, match.index);
|
|
6122
|
+
lastIndex = match.index;
|
|
6123
|
+
if (!match[0].startsWith("//") && !match[0].startsWith("/*")) tokens.push({
|
|
6124
|
+
text: match[0],
|
|
6125
|
+
line
|
|
6126
|
+
});
|
|
6127
|
+
}
|
|
6128
|
+
return tokens;
|
|
6129
|
+
}
|
|
6130
|
+
function countNewlines(text, from, to) {
|
|
6131
|
+
let count = 0;
|
|
6132
|
+
for (let index = text.indexOf("\n", from); index !== -1 && index < to; index = text.indexOf("\n", index + 1)) count++;
|
|
6133
|
+
return count;
|
|
6134
|
+
}
|
|
6135
|
+
/** Reads tokens front to back; each read method consumes what it reads. */
|
|
6136
|
+
var ProtoReader = class {
|
|
6137
|
+
position = 0;
|
|
6138
|
+
tokens;
|
|
6139
|
+
path;
|
|
6140
|
+
schema;
|
|
6141
|
+
/** Adds what one file defines to `schema`, which the PR's other files add to as well. */
|
|
6142
|
+
constructor(schema, path, text) {
|
|
6143
|
+
this.schema = schema;
|
|
6144
|
+
this.path = path;
|
|
6145
|
+
this.tokens = tokenize(text);
|
|
6146
|
+
}
|
|
6147
|
+
readFile() {
|
|
6148
|
+
let scope = "";
|
|
6149
|
+
while (!this.atEnd()) {
|
|
6150
|
+
const word = this.next().text;
|
|
6151
|
+
if (word === "package") {
|
|
6152
|
+
scope = `${this.next().text}.`;
|
|
6153
|
+
this.expect(";");
|
|
6154
|
+
} else if (word === "message") this.readMessage(scope);
|
|
6155
|
+
else if (word === "enum") this.readEnum(scope);
|
|
6156
|
+
else if (word === "service") this.readService(scope);
|
|
6157
|
+
else if (this.peek() === "{") this.skipBlock();
|
|
6158
|
+
else this.skipStatement();
|
|
6159
|
+
}
|
|
6160
|
+
}
|
|
6161
|
+
readMessage(scope) {
|
|
6162
|
+
const { text: name, line } = this.next();
|
|
6163
|
+
const fullName = `${scope}${name}`;
|
|
6164
|
+
const message = {
|
|
6165
|
+
path: this.path,
|
|
6166
|
+
line,
|
|
6167
|
+
fields: /* @__PURE__ */ new Map(),
|
|
6168
|
+
reserved: { ranges: [] }
|
|
6169
|
+
};
|
|
6170
|
+
this.schema.messages.set(fullName, message);
|
|
6171
|
+
this.expect("{");
|
|
6172
|
+
this.readMembers(message, `${fullName}.`);
|
|
6173
|
+
}
|
|
6174
|
+
readMembers(message, scope) {
|
|
6175
|
+
while (!this.atEnd() && this.peek() !== "}") {
|
|
6176
|
+
const word = this.peek();
|
|
6177
|
+
if (word === "option" || word === "extensions" || word === "extend" || word === "group") {
|
|
6178
|
+
this.skipStatementOrBlock();
|
|
6179
|
+
continue;
|
|
6180
|
+
}
|
|
6181
|
+
if (word !== "message" && word !== "enum" && word !== "oneof" && word !== "reserved") {
|
|
6182
|
+
this.readField(message);
|
|
6183
|
+
continue;
|
|
6184
|
+
}
|
|
6185
|
+
this.next();
|
|
6186
|
+
if (word === "message") this.readMessage(scope);
|
|
6187
|
+
else if (word === "enum") this.readEnum(scope);
|
|
6188
|
+
else if (word === "reserved") this.readReserved(message.reserved);
|
|
6189
|
+
else {
|
|
6190
|
+
this.next();
|
|
6191
|
+
this.expect("{");
|
|
6192
|
+
this.readMembers(message, scope);
|
|
6193
|
+
}
|
|
6194
|
+
}
|
|
6195
|
+
this.next();
|
|
6196
|
+
}
|
|
6197
|
+
readField(message) {
|
|
6198
|
+
const first = this.next();
|
|
6199
|
+
const label = FIELD_LABELS.has(first.text) ? `${first.text} ` : "";
|
|
6200
|
+
const type = label === "" ? this.readType(first.text) : this.readType(this.next().text);
|
|
6201
|
+
const name = this.next().text;
|
|
6202
|
+
if (this.peek() === "=") {
|
|
6203
|
+
this.next();
|
|
6204
|
+
message.fields.set(name, {
|
|
6205
|
+
type: `${label}${type}`,
|
|
6206
|
+
number: Number(this.next().text),
|
|
6207
|
+
line: first.line
|
|
6208
|
+
});
|
|
6209
|
+
}
|
|
6210
|
+
this.skipStatement();
|
|
6211
|
+
}
|
|
6212
|
+
readType(first) {
|
|
6213
|
+
if (first !== "map" || this.peek() !== "<") return first;
|
|
6214
|
+
const parts = [];
|
|
6215
|
+
while (!this.atEnd() && this.peek() !== ">") parts.push(this.next().text);
|
|
6216
|
+
this.next();
|
|
6217
|
+
return `map${parts.join("").replace(",", ", ")}>`;
|
|
6218
|
+
}
|
|
6219
|
+
readEnum(scope) {
|
|
6220
|
+
const { text: name, line } = this.next();
|
|
6221
|
+
const values = {
|
|
6222
|
+
path: this.path,
|
|
6223
|
+
line,
|
|
6224
|
+
fields: /* @__PURE__ */ new Map(),
|
|
6225
|
+
reserved: { ranges: [] }
|
|
6226
|
+
};
|
|
6227
|
+
this.schema.enums.set(`${scope}${name}`, values);
|
|
6228
|
+
this.expect("{");
|
|
6229
|
+
while (!this.atEnd() && this.peek() !== "}") {
|
|
6230
|
+
const token = this.next();
|
|
6231
|
+
if (token.text === "reserved") this.readReserved(values.reserved);
|
|
6232
|
+
else if (token.text === "option") this.skipStatement();
|
|
6233
|
+
else if (this.peek() === "=") {
|
|
6234
|
+
this.next();
|
|
6235
|
+
values.fields.set(token.text, {
|
|
6236
|
+
type: "",
|
|
6237
|
+
number: Number(this.next().text),
|
|
6238
|
+
line: token.line
|
|
6239
|
+
});
|
|
6240
|
+
this.skipStatement();
|
|
6241
|
+
} else this.skipStatement();
|
|
6242
|
+
}
|
|
6243
|
+
this.next();
|
|
6244
|
+
}
|
|
6245
|
+
readReserved(reserved) {
|
|
6246
|
+
while (!this.atEnd() && this.peek() !== ";") {
|
|
6247
|
+
const token = this.next().text;
|
|
6248
|
+
if (token === "," || /^["']/.test(token)) continue;
|
|
6249
|
+
const low = Number(token);
|
|
6250
|
+
if (this.peek() === "to") {
|
|
6251
|
+
this.next();
|
|
6252
|
+
const end = this.next().text;
|
|
6253
|
+
reserved.ranges.push([low, end === "max" ? MAX_FIELD_NUMBER : Number(end)]);
|
|
6254
|
+
} else reserved.ranges.push([low, low]);
|
|
6255
|
+
}
|
|
6256
|
+
this.next();
|
|
6257
|
+
}
|
|
6258
|
+
readService(scope) {
|
|
6259
|
+
const service = `${scope}${this.next().text}`;
|
|
6260
|
+
this.expect("{");
|
|
6261
|
+
while (!this.atEnd() && this.peek() !== "}") {
|
|
6262
|
+
const token = this.next();
|
|
6263
|
+
if (token.text !== "rpc") {
|
|
6264
|
+
this.skipStatementOrBlock();
|
|
6265
|
+
continue;
|
|
6266
|
+
}
|
|
6267
|
+
const name = this.next().text;
|
|
6268
|
+
const request = this.readRpcType();
|
|
6269
|
+
this.next();
|
|
6270
|
+
const response = this.readRpcType();
|
|
6271
|
+
this.schema.rpcs.set(`${service}.${name}`, {
|
|
6272
|
+
path: this.path,
|
|
6273
|
+
request,
|
|
6274
|
+
response,
|
|
6275
|
+
line: token.line
|
|
6276
|
+
});
|
|
6277
|
+
this.skipStatementOrBlock();
|
|
6278
|
+
}
|
|
6279
|
+
this.next();
|
|
6280
|
+
}
|
|
6281
|
+
readRpcType() {
|
|
6282
|
+
this.expect("(");
|
|
6283
|
+
const parts = [];
|
|
6284
|
+
while (!this.atEnd() && this.peek() !== ")") parts.push(this.next().text);
|
|
6285
|
+
this.next();
|
|
6286
|
+
return parts.join(" ");
|
|
6287
|
+
}
|
|
6288
|
+
skipStatementOrBlock() {
|
|
6289
|
+
while (!this.atEnd() && this.peek() !== ";" && this.peek() !== "{") this.next();
|
|
6290
|
+
if (this.peek() === "{") this.skipBlock();
|
|
6291
|
+
if (this.peek() === ";") this.next();
|
|
6292
|
+
}
|
|
6293
|
+
skipStatement() {
|
|
6294
|
+
let depth = 0;
|
|
6295
|
+
while (!this.atEnd()) {
|
|
6296
|
+
const text = this.next().text;
|
|
6297
|
+
if (text === "[" || text === "(") depth++;
|
|
6298
|
+
else if (text === "]" || text === ")") depth--;
|
|
6299
|
+
else if (text === ";" && depth <= 0) return;
|
|
6300
|
+
}
|
|
6301
|
+
}
|
|
6302
|
+
skipBlock() {
|
|
6303
|
+
let depth = 0;
|
|
6304
|
+
while (!this.atEnd()) {
|
|
6305
|
+
const text = this.next().text;
|
|
6306
|
+
if (text === "{") depth++;
|
|
6307
|
+
else if (text === "}" && --depth === 0) return;
|
|
6308
|
+
}
|
|
6309
|
+
}
|
|
6310
|
+
expect(text) {
|
|
6311
|
+
const token = this.next();
|
|
6312
|
+
if (token.text !== text) throw new SyntaxError(`expected "${text}" on line ${token.line}, found "${token.text}"`);
|
|
6313
|
+
}
|
|
6314
|
+
peek() {
|
|
6315
|
+
return this.tokens[this.position]?.text;
|
|
6316
|
+
}
|
|
6317
|
+
next() {
|
|
6318
|
+
const token = this.tokens[this.position];
|
|
6319
|
+
if (token === void 0) throw new SyntaxError("the file ends in the middle of a definition");
|
|
6320
|
+
this.position++;
|
|
6321
|
+
return token;
|
|
6322
|
+
}
|
|
6323
|
+
atEnd() {
|
|
6324
|
+
return this.position >= this.tokens.length;
|
|
6325
|
+
}
|
|
6326
|
+
};
|
|
6327
|
+
function readProtos(files) {
|
|
6328
|
+
const schema = {
|
|
6329
|
+
messages: /* @__PURE__ */ new Map(),
|
|
6330
|
+
enums: /* @__PURE__ */ new Map(),
|
|
6331
|
+
rpcs: /* @__PURE__ */ new Map()
|
|
6332
|
+
};
|
|
6333
|
+
for (const file of files) readFile$1(file, (text) => new ProtoReader(schema, file.path, text).readFile());
|
|
6334
|
+
return schema;
|
|
6335
|
+
}
|
|
6336
|
+
// packages/engine/src/risk/breaking/apiSchemas/scanApiSchemas.ts
|
|
6337
|
+
const FORMATS$2 = [
|
|
6338
|
+
OPEN_API,
|
|
6339
|
+
GRAPHQL,
|
|
6340
|
+
PROTOBUF
|
|
6341
|
+
];
|
|
6342
|
+
/**
|
|
6343
|
+
* Compares the API schemas a PR touches with their versions at the merge base. A format is only
|
|
6344
|
+
* compared when the PR changes or deletes one of its files: a new schema file can't break anyone.
|
|
6345
|
+
*/
|
|
6346
|
+
async function scanApiSchemas(repoDir, base, files) {
|
|
6347
|
+
const scan = {
|
|
6348
|
+
findings: [],
|
|
6349
|
+
notChecked: []
|
|
6350
|
+
};
|
|
6351
|
+
for (const [format, { before, after }] of await filesByFormat(repoDir, base, files)) {
|
|
6352
|
+
if (before.length === 0) continue;
|
|
6353
|
+
try {
|
|
6354
|
+
scan.findings.push(...format.compare(before, after).map((change) => apiChangeFinding(format, change)));
|
|
6355
|
+
} catch (error) {
|
|
6356
|
+
scan.notChecked.push({
|
|
6357
|
+
check: `${format.name} breaking changes`,
|
|
6358
|
+
reason: `couldn't read ${error instanceof Error ? error.message : String(error)}`
|
|
6359
|
+
});
|
|
6360
|
+
}
|
|
6361
|
+
}
|
|
6362
|
+
return scan;
|
|
6363
|
+
}
|
|
6364
|
+
async function filesByFormat(repoDir, base, files) {
|
|
6365
|
+
const relevant = files.filter((file) => !isThirdParty(file) && !isTestPath(file.diff.path));
|
|
6366
|
+
const earlier = relevant.filter((file) => file.diff.status !== FileChangeStatus.Added);
|
|
6367
|
+
const blobs = await readBlobs(repoDir, earlier.map((file) => ({
|
|
6368
|
+
commit: base,
|
|
6369
|
+
path: previousPathOf$3(file.diff)
|
|
6370
|
+
})));
|
|
6371
|
+
const before = new Map(earlier.flatMap((file, index) => {
|
|
6372
|
+
const text = blobs.at(index)?.toString("utf8");
|
|
6373
|
+
return text === void 0 ? [] : [[file, text]];
|
|
6374
|
+
}));
|
|
6375
|
+
const byFormat = /* @__PURE__ */ new Map();
|
|
6376
|
+
for (const file of relevant) {
|
|
6377
|
+
const earlierText = before.get(file);
|
|
6378
|
+
const after = file.diff.status === FileChangeStatus.Deleted ? "" : file.after;
|
|
6379
|
+
const format = FORMATS$2.find((candidate) => candidate.matches(file.diff.path, after === void 0 || after === "" ? earlierText ?? "" : after));
|
|
6380
|
+
if (format === void 0 || after === void 0) continue;
|
|
6381
|
+
const entry = byFormat.get(format) ?? {
|
|
6382
|
+
before: [],
|
|
6383
|
+
after: []
|
|
6384
|
+
};
|
|
6385
|
+
if (earlierText !== void 0) entry.before.push({
|
|
6386
|
+
path: file.diff.path,
|
|
6387
|
+
text: earlierText
|
|
6388
|
+
});
|
|
6389
|
+
entry.after.push({
|
|
6390
|
+
path: file.diff.path,
|
|
6391
|
+
text: after
|
|
6392
|
+
});
|
|
6393
|
+
byFormat.set(format, entry);
|
|
6394
|
+
}
|
|
6395
|
+
return byFormat;
|
|
6396
|
+
}
|
|
6397
|
+
function previousPathOf$3(diff) {
|
|
6398
|
+
return diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied ? diff.previousPath : diff.path;
|
|
6399
|
+
}
|
|
5445
6400
|
// packages/engine/src/risk/breaking/codeMentions.ts
|
|
5446
6401
|
const MAX_FILES_FOR_A_COMMON_WORD = 25;
|
|
5447
6402
|
const MAX_FILES_FOR_A_SPECIFIC_NAME = 200;
|
|
@@ -6476,16 +7431,21 @@ async function scanBreakingChanges(scan) {
|
|
|
6476
7431
|
const mentions = await mentionsInCode(scan.repoDir, scan.head, names);
|
|
6477
7432
|
const renamesInEnvFiles = new Set(configChanges.filter((change) => change.kind === ConfigChangeKind.RenamedVariable).map((change) => change.name));
|
|
6478
7433
|
const config = configChanges.filter((change) => change.kind !== ConfigChangeKind.ReplacedRead || !renamesInEnvFiles.has(change.name)).flatMap((change) => configChangeFinding(change, mentions.get(change.name)) ?? []);
|
|
6479
|
-
|
|
6480
|
-
|
|
6481
|
-
|
|
6482
|
-
|
|
6483
|
-
|
|
6484
|
-
|
|
6485
|
-
|
|
6486
|
-
|
|
6487
|
-
|
|
6488
|
-
|
|
7434
|
+
const apiSchemas = await scanApiSchemas(scan.repoDir, scan.base, scan.scanned);
|
|
7435
|
+
return {
|
|
7436
|
+
findings: [
|
|
7437
|
+
...scanPublicApi({
|
|
7438
|
+
files: scan.files,
|
|
7439
|
+
versions: scan.versions,
|
|
7440
|
+
headTexts,
|
|
7441
|
+
surface
|
|
7442
|
+
}),
|
|
7443
|
+
...apiSchemas.findings,
|
|
7444
|
+
...schemaChanges.map((change) => schemaChangeFinding(change, mentions.get(change.name))),
|
|
7445
|
+
...config
|
|
7446
|
+
],
|
|
7447
|
+
notChecked: apiSchemas.notChecked
|
|
7448
|
+
};
|
|
6489
7449
|
}
|
|
6490
7450
|
// packages/engine/src/risk/dependencies/osv.ts
|
|
6491
7451
|
const OSV_API = "https://api.osv.dev/v1";
|
|
@@ -6776,20 +7736,6 @@ function addReplacement(replacements, words) {
|
|
|
6776
7736
|
function unquote(word) {
|
|
6777
7737
|
return word.replace(/^["`]|["`]$/g, "");
|
|
6778
7738
|
}
|
|
6779
|
-
// packages/engine/src/risk/dependencies/fields.ts
|
|
6780
|
-
function isRecord(value) {
|
|
6781
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6782
|
-
}
|
|
6783
|
-
function field(value, key) {
|
|
6784
|
-
return isRecord(value) ? value[key] : void 0;
|
|
6785
|
-
}
|
|
6786
|
-
function stringField(value, key) {
|
|
6787
|
-
const found = field(value, key);
|
|
6788
|
-
return typeof found === "string" ? found : void 0;
|
|
6789
|
-
}
|
|
6790
|
-
function recordOrEmpty(value) {
|
|
6791
|
-
return isRecord(value) ? value : {};
|
|
6792
|
-
}
|
|
6793
7739
|
// packages/engine/src/risk/dependencies/maven.ts
|
|
6794
7740
|
const COMMENT_OPEN = "<!--";
|
|
6795
7741
|
const COMMENT_CLOSE = "-->";
|
|
@@ -6931,7 +7877,7 @@ function buildCoordinates(text) {
|
|
|
6931
7877
|
return [...fromStrings, ...fromMaps];
|
|
6932
7878
|
}
|
|
6933
7879
|
function catalogCoordinates(text) {
|
|
6934
|
-
const catalog = parse$
|
|
7880
|
+
const catalog = parse$2(text);
|
|
6935
7881
|
const versions = recordOrEmpty(field(catalog, "versions"));
|
|
6936
7882
|
return Object.values(recordOrEmpty(field(catalog, "libraries"))).flatMap((library) => {
|
|
6937
7883
|
if (typeof library === "string") {
|
|
@@ -7087,7 +8033,7 @@ function parsePackageJson(text) {
|
|
|
7087
8033
|
return declared;
|
|
7088
8034
|
}
|
|
7089
8035
|
function parseCargoToml(text) {
|
|
7090
|
-
const manifest = parse$
|
|
8036
|
+
const manifest = parse$2(text);
|
|
7091
8037
|
const declared = /* @__PURE__ */ new Map();
|
|
7092
8038
|
const sections = [
|
|
7093
8039
|
field(manifest, "dependencies"),
|
|
@@ -7109,7 +8055,7 @@ function cargoSource(value) {
|
|
|
7109
8055
|
return field(value, "workspace") === true ? "workspace:" : void 0;
|
|
7110
8056
|
}
|
|
7111
8057
|
function parsePyproject(text) {
|
|
7112
|
-
const manifest = parse$
|
|
8058
|
+
const manifest = parse$2(text);
|
|
7113
8059
|
const declared = /* @__PURE__ */ new Map();
|
|
7114
8060
|
const project = field(manifest, "project");
|
|
7115
8061
|
const requirementLists = [field(project, "dependencies"), ...Object.values(recordOrEmpty(field(project, "optional-dependencies")))];
|
|
@@ -7148,7 +8094,7 @@ function parsePackageLock(text) {
|
|
|
7148
8094
|
});
|
|
7149
8095
|
}
|
|
7150
8096
|
function tomlPackages$1(text, ecosystem) {
|
|
7151
|
-
const packages = field(parse$
|
|
8097
|
+
const packages = field(parse$2(text), "package");
|
|
7152
8098
|
return (Array.isArray(packages) ? packages : []).flatMap((entry) => {
|
|
7153
8099
|
const name = stringField(entry, "name");
|
|
7154
8100
|
const version = stringField(entry, "version");
|
|
@@ -7637,7 +8583,7 @@ const RegistryStatus = {
|
|
|
7637
8583
|
Missing: "missing"
|
|
7638
8584
|
};
|
|
7639
8585
|
const NEW_PACKAGE_DAYS = 30;
|
|
7640
|
-
const MS_PER_DAY = 864e5;
|
|
8586
|
+
const MS_PER_DAY$1 = 864e5;
|
|
7641
8587
|
const MIN_NAME_LENGTH_TO_COMPARE = 5;
|
|
7642
8588
|
const MAX_LOOKUPS = 100;
|
|
7643
8589
|
const CONCURRENT_LOOKUPS = 8;
|
|
@@ -7703,7 +8649,7 @@ async function inBatches(items, size, work) {
|
|
|
7703
8649
|
}
|
|
7704
8650
|
function registryFindings(entry, found, now, allowedLicenses) {
|
|
7705
8651
|
if (found.status === RegistryStatus.Missing) return [missingFinding(entry)];
|
|
7706
|
-
const days = Math.floor((now.getTime() - found.firstPublished.getTime()) / MS_PER_DAY);
|
|
8652
|
+
const days = Math.floor((now.getTime() - found.firstPublished.getTime()) / MS_PER_DAY$1);
|
|
7707
8653
|
const isPopular = POPULAR_PACKAGES[entry.ecosystem].has(entry.name);
|
|
7708
8654
|
return [...days < NEW_PACKAGE_DAYS && !isPopular ? [newPackageFinding(entry, days)] : [], ...licenseFindings(entry, found.license, allowedLicenses)];
|
|
7709
8655
|
}
|
|
@@ -9302,7 +10248,7 @@ const FROM_PYPI = {
|
|
|
9302
10248
|
};
|
|
9303
10249
|
const LOCAL = { kind: OriginKind.Local };
|
|
9304
10250
|
function tomlPackages(text, read, normalizeName = (name) => name) {
|
|
9305
|
-
const packages = field(parse$
|
|
10251
|
+
const packages = field(parse$2(text), "package");
|
|
9306
10252
|
return (Array.isArray(packages) ? packages : []).flatMap((entry) => {
|
|
9307
10253
|
const name = stringField(entry, "name");
|
|
9308
10254
|
const version = stringField(entry, "version");
|
|
@@ -9388,6 +10334,20 @@ function readGoSum(text) {
|
|
|
9388
10334
|
}];
|
|
9389
10335
|
});
|
|
9390
10336
|
}
|
|
10337
|
+
// packages/engine/src/risk/supplyChain/lockfileReaders.ts
|
|
10338
|
+
const LOCKFILE_READERS = [
|
|
10339
|
+
PACKAGE_LOCK,
|
|
10340
|
+
YARN_LOCK,
|
|
10341
|
+
PNPM_LOCK,
|
|
10342
|
+
CARGO_LOCK,
|
|
10343
|
+
UV_LOCK,
|
|
10344
|
+
POETRY_LOCK,
|
|
10345
|
+
GO_SUM
|
|
10346
|
+
];
|
|
10347
|
+
/** The reader for a lockfile at `path`, by its file name; undefined for anything else. */
|
|
10348
|
+
function lockfileReaderFor(path) {
|
|
10349
|
+
return LOCKFILE_READERS.find((reader) => reader.matches(basename(path)));
|
|
10350
|
+
}
|
|
9391
10351
|
// packages/engine/src/risk/supplyChain/scanSupplyChain.ts
|
|
9392
10352
|
const SUPPLY_CHAIN_CHECK$1 = {
|
|
9393
10353
|
name: "Supply chain",
|
|
@@ -9400,15 +10360,6 @@ const NPM_RELEASES_RUN = {
|
|
|
9400
10360
|
detail: "who published upgraded npm packages, and whether they kept provenance",
|
|
9401
10361
|
security: true
|
|
9402
10362
|
};
|
|
9403
|
-
const LOCKFILE_READERS = [
|
|
9404
|
-
PACKAGE_LOCK,
|
|
9405
|
-
YARN_LOCK,
|
|
9406
|
-
PNPM_LOCK,
|
|
9407
|
-
CARGO_LOCK,
|
|
9408
|
-
UV_LOCK,
|
|
9409
|
-
POETRY_LOCK,
|
|
9410
|
-
GO_SUM
|
|
9411
|
-
];
|
|
9412
10363
|
/**
|
|
9413
10364
|
* How the packages a PR depends on reach the build, separately from whether they're vulnerable:
|
|
9414
10365
|
* lockfile entries that change source or content, gain install scripts or move a private name to a
|
|
@@ -9465,7 +10416,7 @@ async function readLockfiles(request, outcome) {
|
|
|
9465
10416
|
return lockfiles.flatMap(({ diff }, index) => {
|
|
9466
10417
|
const before = blobs.at(2 * index)?.toString("utf8");
|
|
9467
10418
|
const after = blobs.at(2 * index + 1)?.toString("utf8");
|
|
9468
|
-
const reader =
|
|
10419
|
+
const reader = lockfileReaderFor(diff.path);
|
|
9469
10420
|
if (after === void 0 || reader === void 0) return [];
|
|
9470
10421
|
try {
|
|
9471
10422
|
return [{
|
|
@@ -9486,10 +10437,7 @@ async function readLockfiles(request, outcome) {
|
|
|
9486
10437
|
}
|
|
9487
10438
|
function isReadableLockfile(file) {
|
|
9488
10439
|
if (file.diff.status === FileChangeStatus.Deleted || file.noise?.kind === NoiseKind.Vendored || isTestPath(file.diff.path)) return false;
|
|
9489
|
-
return
|
|
9490
|
-
}
|
|
9491
|
-
function readerFor(path) {
|
|
9492
|
-
return LOCKFILE_READERS.find((reader) => reader.matches(basename(path)));
|
|
10440
|
+
return lockfileReaderFor(file.diff.path) !== void 0;
|
|
9493
10441
|
}
|
|
9494
10442
|
function previousPathOf$1(diff) {
|
|
9495
10443
|
return diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied ? diff.previousPath : diff.path;
|
|
@@ -10033,6 +10981,760 @@ const BUILT_IN_RULES_CHECK = {
|
|
|
10033
10981
|
function inWords(items) {
|
|
10034
10982
|
return items.length <= 1 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1) ?? ""}`;
|
|
10035
10983
|
}
|
|
10984
|
+
// packages/engine/src/risk/docsDrift/docMentions.ts
|
|
10985
|
+
const DOC_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
10986
|
+
".md",
|
|
10987
|
+
".mdx",
|
|
10988
|
+
".markdown",
|
|
10989
|
+
".rst",
|
|
10990
|
+
".adoc",
|
|
10991
|
+
".asciidoc"
|
|
10992
|
+
]);
|
|
10993
|
+
const HISTORY_FILE = /change|history|release|news|migrat|upgrad|deprecat|breaking/i;
|
|
10994
|
+
const MAX_DOC_FILES = 2e3;
|
|
10995
|
+
const MAX_DOC_BYTES = 1e6;
|
|
10996
|
+
/**
|
|
10997
|
+
* Finds where the docs at `head` still use each retired name. A line naming both the old name and
|
|
10998
|
+
* its replacement is describing the rename, so it doesn't count.
|
|
10999
|
+
*/
|
|
11000
|
+
async function staleMentions(repoDir, head, retired) {
|
|
11001
|
+
if (retired.length === 0) return [];
|
|
11002
|
+
const docs = (await docFiles(repoDir, head)).slice(0, MAX_DOC_FILES);
|
|
11003
|
+
const blobs = await readBlobs(repoDir, docs.map((path) => ({
|
|
11004
|
+
commit: head,
|
|
11005
|
+
path
|
|
11006
|
+
})));
|
|
11007
|
+
const matchers = retired.map((name) => ({
|
|
11008
|
+
retired: name,
|
|
11009
|
+
uses: wordPattern(name.name),
|
|
11010
|
+
describesRename: name.replacement === void 0 ? void 0 : wordPattern(name.replacement)
|
|
11011
|
+
}));
|
|
11012
|
+
return docs.flatMap((path, index) => {
|
|
11013
|
+
const blob = blobs.at(index);
|
|
11014
|
+
if (blob === void 0 || blob.length > MAX_DOC_BYTES) return [];
|
|
11015
|
+
const lines = blob.toString("utf8").split("\n");
|
|
11016
|
+
return matchers.flatMap(({ retired: name, uses, describesRename }) => {
|
|
11017
|
+
const hits = lines.flatMap((text, row) => uses.test(text) && describesRename?.test(text) !== true ? [{
|
|
11018
|
+
line: row + 1,
|
|
11019
|
+
text: text.trim()
|
|
11020
|
+
}] : []);
|
|
11021
|
+
const first = hits.at(0);
|
|
11022
|
+
return first === void 0 ? [] : [{
|
|
11023
|
+
retired: name,
|
|
11024
|
+
path,
|
|
11025
|
+
line: first.line,
|
|
11026
|
+
text: first.text,
|
|
11027
|
+
count: hits.length
|
|
11028
|
+
}];
|
|
11029
|
+
});
|
|
11030
|
+
});
|
|
11031
|
+
}
|
|
11032
|
+
async function docFiles(repoDir, head) {
|
|
11033
|
+
return (await runGit([
|
|
11034
|
+
"ls-tree",
|
|
11035
|
+
"-r",
|
|
11036
|
+
"-z",
|
|
11037
|
+
"--name-only",
|
|
11038
|
+
head
|
|
11039
|
+
], {
|
|
11040
|
+
cwd: repoDir,
|
|
11041
|
+
env: ISOLATED_CONFIG_ENV
|
|
11042
|
+
})).split("\0").filter((path) => DOC_EXTENSIONS.has(extname(path).toLowerCase()) && !HISTORY_FILE.test(basename(path)) && !isNoiseByPath(path) && !isTestPath(path));
|
|
11043
|
+
}
|
|
11044
|
+
function wordPattern(name) {
|
|
11045
|
+
return new RegExp(`(?<![\\p{L}\\p{N}_$-])${escapeRegExp$1(name)}(?![\\p{L}\\p{N}_$-])`, "u");
|
|
11046
|
+
}
|
|
11047
|
+
// packages/engine/src/risk/docsDrift/parameterDocs.ts
|
|
11048
|
+
const AT_PARAM = /@param\s+(?:\{[^}]*\}\s+)?\[?\$?([A-Za-z_$][\w$]*)/g;
|
|
11049
|
+
const REST_PARAM = /:param\s+(?:[\w[\], .]+\s+)?([A-Za-z_]\w*)\s*:/g;
|
|
11050
|
+
const SECTION_HEADER = /^(\s*)(#+\s*)?(?:Args|Arguments|Parameters|Keyword Args|Keyword Arguments)\s*:?\s*$/;
|
|
11051
|
+
const LINE_DOC_PREFIX = /^\s*\/\/[/!] ?/;
|
|
11052
|
+
const UNDERLINE = /^\s*-{3,}\s*$/;
|
|
11053
|
+
const SECTION_ENTRY = /^\s*(?:[*-]\s+`)?\*{0,2}([A-Za-z_]\w*)`?\s*(?:\([^)]*\))?\s*[:-]/;
|
|
11054
|
+
const NAME_MARKERS = /^[*&$.]+/;
|
|
11055
|
+
const RECEIVERS = /* @__PURE__ */ new Set([
|
|
11056
|
+
"self",
|
|
11057
|
+
"cls",
|
|
11058
|
+
"this"
|
|
11059
|
+
]);
|
|
11060
|
+
/**
|
|
11061
|
+
* Doc comments that no longer match their function's parameters, in functions the PR changed.
|
|
11062
|
+
* Only parameters the PR added or removed are compared: a doc comment that was already out of
|
|
11063
|
+
* date isn't this PR's doing.
|
|
11064
|
+
*/
|
|
11065
|
+
function parameterDrift(files) {
|
|
11066
|
+
return files.filter((file) => !isTestPath(file.diff.path)).flatMap((file) => changedUnitsOf(file).flatMap((unit) => driftIn(file.diff.path, unit)));
|
|
11067
|
+
}
|
|
11068
|
+
function driftIn(path, unit) {
|
|
11069
|
+
const after = snapshotAfter(unit);
|
|
11070
|
+
const facts = unit.facts;
|
|
11071
|
+
if (after === void 0 || facts === null || isTestUnit(unit)) return [];
|
|
11072
|
+
const documented = documentedParameters(after.text);
|
|
11073
|
+
if (documented.size === 0) return [];
|
|
11074
|
+
const stale = facts.parametersRemoved.map(plainName).filter((name) => documented.has(name));
|
|
11075
|
+
const missing = facts.parametersAdded.map(plainName).filter((name) => !documented.has(name) && !RECEIVERS.has(name));
|
|
11076
|
+
return stale.length === 0 && missing.length === 0 ? [] : [{
|
|
11077
|
+
path,
|
|
11078
|
+
line: after.startLine,
|
|
11079
|
+
unit: unit.qualifiedName,
|
|
11080
|
+
stale,
|
|
11081
|
+
missing
|
|
11082
|
+
}];
|
|
11083
|
+
}
|
|
11084
|
+
function snapshotAfter(unit) {
|
|
11085
|
+
switch (unit.change.kind) {
|
|
11086
|
+
case UnitChangeKind.Modified:
|
|
11087
|
+
case UnitChangeKind.Renamed:
|
|
11088
|
+
case UnitChangeKind.MovedIn: return unit.change.after;
|
|
11089
|
+
case UnitChangeKind.Added:
|
|
11090
|
+
case UnitChangeKind.Removed:
|
|
11091
|
+
case UnitChangeKind.MovedOut: return;
|
|
11092
|
+
}
|
|
11093
|
+
}
|
|
11094
|
+
function plainName(name) {
|
|
11095
|
+
return name.replace(NAME_MARKERS, "");
|
|
11096
|
+
}
|
|
11097
|
+
/** The parameter names a function's doc comment describes, in any of the common styles. */
|
|
11098
|
+
function documentedParameters(text) {
|
|
11099
|
+
const names = new Set([...text.matchAll(AT_PARAM), ...text.matchAll(REST_PARAM)].map((match) => match[1] ?? ""));
|
|
11100
|
+
const lines = text.split("\n").map((line) => line.replace(LINE_DOC_PREFIX, ""));
|
|
11101
|
+
lines.forEach((line, index) => {
|
|
11102
|
+
const header = SECTION_HEADER.exec(line);
|
|
11103
|
+
if (header === null) return;
|
|
11104
|
+
const underlined = UNDERLINE.test(lines.at(index + 1) ?? "");
|
|
11105
|
+
const markdown = header[2] !== void 0;
|
|
11106
|
+
const body = lines.slice(index + (underlined ? 2 : 1));
|
|
11107
|
+
const start = markdown ? body.findIndex((entry) => entry.trim() !== "") : 0;
|
|
11108
|
+
for (const name of sectionEntries(body.slice(Math.max(start, 0)), (header[1] ?? "").length, underlined || markdown)) names.add(name);
|
|
11109
|
+
});
|
|
11110
|
+
names.delete("");
|
|
11111
|
+
return names;
|
|
11112
|
+
}
|
|
11113
|
+
/**
|
|
11114
|
+
* Entries of a section, which ends at a blank line, the next title, or a line less indented than
|
|
11115
|
+
* its header. Entries all share one indent: Google style indents them under the header and NumPy
|
|
11116
|
+
* style keeps them level with it. Their descriptions sit deeper, and can contain colons.
|
|
11117
|
+
*/
|
|
11118
|
+
function sectionEntries(lines, headerIndent, entriesLevel) {
|
|
11119
|
+
const names = [];
|
|
11120
|
+
let entryIndent = entriesLevel ? headerIndent : void 0;
|
|
11121
|
+
for (const line of lines) {
|
|
11122
|
+
if (line.trim() === "" || SECTION_HEADER.test(line)) break;
|
|
11123
|
+
const indent = line.length - line.trimStart().length;
|
|
11124
|
+
if (indent < headerIndent || !entriesLevel && indent === headerIndent) break;
|
|
11125
|
+
entryIndent ??= indent;
|
|
11126
|
+
const name = indent === entryIndent ? SECTION_ENTRY.exec(line)?.[1] : void 0;
|
|
11127
|
+
if (name !== void 0) names.push(name);
|
|
11128
|
+
}
|
|
11129
|
+
return names;
|
|
11130
|
+
}
|
|
11131
|
+
// packages/engine/src/risk/docsDrift/retiredNames.ts
|
|
11132
|
+
/** What kind of name a PR retires, which says who notices when docs still use it. */
|
|
11133
|
+
const RetiredNameKind = {
|
|
11134
|
+
/** A command-line option: whoever copies it from the docs gets an error. */
|
|
11135
|
+
CliFlag: "cliFlag",
|
|
11136
|
+
/** An environment variable or config key: a deployment set up from the docs silently misses it. */
|
|
11137
|
+
Setting: "setting",
|
|
11138
|
+
/** A function, class or other unit: whoever reads the docs looks for code that isn't there. */
|
|
11139
|
+
Code: "code"
|
|
11140
|
+
};
|
|
11141
|
+
const FLAG_IN_CODE = /(?:["'`]|^\s*)(--[a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?![\w-])/g;
|
|
11142
|
+
const DOCUMENTED_UNIT_CHANGES = /* @__PURE__ */ new Set([UnitChangeKind.Removed, UnitChangeKind.Renamed]);
|
|
11143
|
+
/**
|
|
11144
|
+
* Names the PR removes or renames: units, command-line options in code, environment variables and
|
|
11145
|
+
* config keys. A name only counts once nothing the PR adds still uses it; whether code elsewhere
|
|
11146
|
+
* still uses it is for the caller to rule out.
|
|
11147
|
+
*/
|
|
11148
|
+
function retiredNames(files, scanned) {
|
|
11149
|
+
const kept = new Set(scanned.flatMap((file) => addedLines(file.diff).flatMap((line) => [...line.content.matchAll(FLAG_IN_CODE)].map((match) => match[1] ?? ""))));
|
|
11150
|
+
const names = [
|
|
11151
|
+
...retiredUnits(files),
|
|
11152
|
+
...retiredFlags(scanned, kept),
|
|
11153
|
+
...retiredSettings(scanned)
|
|
11154
|
+
];
|
|
11155
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11156
|
+
return names.filter((retired) => {
|
|
11157
|
+
if (seen.has(retired.name)) return false;
|
|
11158
|
+
seen.add(retired.name);
|
|
11159
|
+
return true;
|
|
11160
|
+
});
|
|
11161
|
+
}
|
|
11162
|
+
function retiredUnits(files) {
|
|
11163
|
+
return files.filter((file) => !isTestPath(file.diff.path)).flatMap((file) => changedUnitsOf(file)).filter((unit) => DOCUMENTED_UNIT_CHANGES.has(unit.change.kind) && !isTestUnit(unit)).flatMap((unit) => {
|
|
11164
|
+
const before = unit.change.kind === UnitChangeKind.Renamed ? unit.change.previousName : unit.name;
|
|
11165
|
+
if (!isSpecificName(before)) return [];
|
|
11166
|
+
return [{
|
|
11167
|
+
name: before,
|
|
11168
|
+
kind: RetiredNameKind.Code,
|
|
11169
|
+
replacement: unit.change.kind === UnitChangeKind.Renamed ? unit.name : void 0
|
|
11170
|
+
}];
|
|
11171
|
+
});
|
|
11172
|
+
}
|
|
11173
|
+
function retiredFlags(scanned, kept) {
|
|
11174
|
+
return scanned.filter((file) => languageSpecFor(file.diff.path) !== void 0 && !isThirdParty(file) && !isTestPath(file.diff.path)).flatMap((file) => removedLines(file.diff).flatMap((line) => [...line.content.matchAll(FLAG_IN_CODE)].map((match) => match[1] ?? ""))).filter((flag) => flag !== "" && !kept.has(flag)).map((flag) => ({
|
|
11175
|
+
name: flag,
|
|
11176
|
+
kind: RetiredNameKind.CliFlag,
|
|
11177
|
+
replacement: void 0
|
|
11178
|
+
}));
|
|
11179
|
+
}
|
|
11180
|
+
const RETIRED_SETTINGS = /* @__PURE__ */ new Set([
|
|
11181
|
+
ConfigChangeKind.RemovedVariable,
|
|
11182
|
+
ConfigChangeKind.RenamedVariable,
|
|
11183
|
+
ConfigChangeKind.ReplacedRead,
|
|
11184
|
+
ConfigChangeKind.RemovedKey
|
|
11185
|
+
]);
|
|
11186
|
+
function retiredSettings(scanned) {
|
|
11187
|
+
return findConfigChanges(scanned).filter((change) => RETIRED_SETTINGS.has(change.kind)).map((change) => ({
|
|
11188
|
+
name: change.name,
|
|
11189
|
+
kind: RetiredNameKind.Setting,
|
|
11190
|
+
replacement: change.newName
|
|
11191
|
+
}));
|
|
11192
|
+
}
|
|
11193
|
+
// packages/engine/src/risk/docsDrift/docsDriftCheck.ts
|
|
11194
|
+
const DOCS_DRIFT = "docsDrift";
|
|
11195
|
+
const DOCS_DRIFT_DIMENSION = {
|
|
11196
|
+
id: DOCS_DRIFT,
|
|
11197
|
+
label: "Docs drift",
|
|
11198
|
+
kind: DimensionKind.Review,
|
|
11199
|
+
advice: "Update the docs to match."
|
|
11200
|
+
};
|
|
11201
|
+
const DOCS_DRIFT_RUN = {
|
|
11202
|
+
name: "Docs drift",
|
|
11203
|
+
detail: "docs that still use names this PR removes or renames, and doc comments that no longer match their parameters"
|
|
11204
|
+
};
|
|
11205
|
+
const LEADING_DASHES = /^--/;
|
|
11206
|
+
const STALE_WORDING = {
|
|
11207
|
+
[RetiredNameKind.CliFlag]: {
|
|
11208
|
+
id: "docs.stale-flag",
|
|
11209
|
+
severity: RiskSeverity.Medium,
|
|
11210
|
+
consequence: "Whoever copies the command from the docs gets an error."
|
|
11211
|
+
},
|
|
11212
|
+
[RetiredNameKind.Setting]: {
|
|
11213
|
+
id: "docs.stale-setting",
|
|
11214
|
+
severity: RiskSeverity.Medium,
|
|
11215
|
+
consequence: "A deployment set up from the docs sets a name nothing reads, and the setting silently has no effect."
|
|
11216
|
+
},
|
|
11217
|
+
[RetiredNameKind.Code]: {
|
|
11218
|
+
id: "docs.stale-name",
|
|
11219
|
+
severity: RiskSeverity.Low,
|
|
11220
|
+
consequence: "Readers will look for code that isn't there."
|
|
11221
|
+
}
|
|
11222
|
+
};
|
|
11223
|
+
/**
|
|
11224
|
+
* Docs that this PR leaves out of date: prose that still uses a name it removes or renames, and
|
|
11225
|
+
* doc comments that describe parameters a changed function no longer takes. Reads only the
|
|
11226
|
+
* repository, so it runs offline.
|
|
11227
|
+
*/
|
|
11228
|
+
const DOCS_DRIFT_CHECK = {
|
|
11229
|
+
step: AnalysisStep.CheckingBreakingChanges,
|
|
11230
|
+
dimensions: [DOCS_DRIFT_DIMENSION],
|
|
11231
|
+
run: async ({ request, scanned }) => {
|
|
11232
|
+
const retired = await stillRetiredAtHead(request.repoDir, request.head, retiredNames(request.files, scanned));
|
|
11233
|
+
const findings = [...(await staleMentions(request.repoDir, request.head, retired)).map(staleMentionFinding), ...parameterDrift(request.files).map(parameterFinding)];
|
|
11234
|
+
return {
|
|
11235
|
+
findings: creditedTo(DOCS_DRIFT_RUN.name, findings),
|
|
11236
|
+
checksRun: [DOCS_DRIFT_RUN],
|
|
11237
|
+
notChecked: []
|
|
11238
|
+
};
|
|
11239
|
+
}
|
|
11240
|
+
};
|
|
11241
|
+
/**
|
|
11242
|
+
* Docs only go stale for a name nothing uses any more: code at head that still names it, anywhere,
|
|
11243
|
+
* means it's still there, perhaps defined in another file.
|
|
11244
|
+
*/
|
|
11245
|
+
async function stillRetiredAtHead(repoDir, head, retired) {
|
|
11246
|
+
if (retired.length === 0) return [];
|
|
11247
|
+
const searched = (name) => name.name.replace(LEADING_DASHES, "");
|
|
11248
|
+
const inCode = await filesMentioning(repoDir, head, [...new Set(retired.map(searched))]);
|
|
11249
|
+
return retired.filter((name) => (inCode.get(searched(name)) ?? []).every(isTestPath));
|
|
11250
|
+
}
|
|
11251
|
+
function staleMentionFinding(mention) {
|
|
11252
|
+
const { retired } = mention;
|
|
11253
|
+
const wording = STALE_WORDING[retired.kind];
|
|
11254
|
+
const change = retired.replacement === void 0 ? "removes it" : `renames it to ${codeSpan(retired.replacement)}`;
|
|
11255
|
+
const more = mention.count > 1 ? ` This file mentions it ${mention.count} times.` : "";
|
|
11256
|
+
return findingAt({
|
|
11257
|
+
id: wording.id,
|
|
11258
|
+
category: DOCS_DRIFT,
|
|
11259
|
+
severity: wording.severity,
|
|
11260
|
+
title: `Docs still mention ${codeSpan(retired.name)}`,
|
|
11261
|
+
detail: `This PR ${change}.${more} ${wording.consequence}`
|
|
11262
|
+
}, mention.path, mention.line, mention.text);
|
|
11263
|
+
}
|
|
11264
|
+
function parameterFinding(drift) {
|
|
11265
|
+
const stale = drift.stale.length === 0 ? "" : `still describes ${drift.stale.map(codeSpan).join(", ")}, which it no longer takes`;
|
|
11266
|
+
const missing = drift.missing.length === 0 ? "" : `doesn't describe ${drift.missing.map(codeSpan).join(", ")}`;
|
|
11267
|
+
return findingAt({
|
|
11268
|
+
id: "docs.parameters",
|
|
11269
|
+
category: DOCS_DRIFT,
|
|
11270
|
+
severity: RiskSeverity.Low,
|
|
11271
|
+
title: `Doc comment of ${codeSpan(drift.unit)} doesn't match its parameters`,
|
|
11272
|
+
detail: `It ${[stale, missing].filter((part) => part !== "").join(", and ")}. Editors and generated docs show this text to everyone who calls it.`
|
|
11273
|
+
}, drift.path, drift.line, null);
|
|
11274
|
+
}
|
|
11275
|
+
// packages/engine/src/risk/hotspots/hotspotsCheck.ts
|
|
11276
|
+
/**
|
|
11277
|
+
* Hotspots: changed files whose recent history says to look harder, because they keep needing
|
|
11278
|
+
* fixes, change far more often than most, or had a change reverted just before this PR. History
|
|
11279
|
+
* is read up to the merge base, so the PR's own commits never count.
|
|
11280
|
+
*
|
|
11281
|
+
* The limits below are judgement calls rather than measured values, chosen so a file has to stand
|
|
11282
|
+
* out: a busy project's ordinary files change a few times a month, and a fix now and then is normal.
|
|
11283
|
+
*/
|
|
11284
|
+
const HISTORY_DAYS = 365;
|
|
11285
|
+
const RECENT_REVERT_DAYS = 90;
|
|
11286
|
+
const MIN_CHANGES_FOR_CHURN = 30;
|
|
11287
|
+
const MIN_FIXES = 5;
|
|
11288
|
+
const MIN_FIX_SHARE = .25;
|
|
11289
|
+
const MAX_FILES = 60;
|
|
11290
|
+
const MS_PER_DAY = 864e5;
|
|
11291
|
+
const FIX_SUBJECT = /\b(?:fix(?:e[sd]|ing)?|bug(?:fix)?|hotfix|regression|crash(?:es|ed)?|broken)\b/i;
|
|
11292
|
+
const NOT_A_BUG = /\b(?:typos?|lint(?:ing)?|format(?:ting)?|style|docs?|readme|tests?|ci|build|deps|dependenc(?:y|ies))\b/i;
|
|
11293
|
+
const REVERT_SUBJECT = /^revert\b/i;
|
|
11294
|
+
const HOTSPOT = "hotspot";
|
|
11295
|
+
const HOTSPOT_DIMENSION = {
|
|
11296
|
+
id: HOTSPOT,
|
|
11297
|
+
label: "Hotspot",
|
|
11298
|
+
kind: DimensionKind.Context,
|
|
11299
|
+
advice: ""
|
|
11300
|
+
};
|
|
11301
|
+
const HOTSPOTS_NAME = "Hotspots";
|
|
11302
|
+
const HOTSPOTS_RUN = {
|
|
11303
|
+
name: HOTSPOTS_NAME,
|
|
11304
|
+
detail: `each changed file's commits in the ${HISTORY_DAYS} days before this PR`
|
|
11305
|
+
};
|
|
11306
|
+
const CLOSER_LOOK = "Files like this tend to keep needing fixes, so this change deserves a closer look than its size suggests.";
|
|
11307
|
+
const HOTSPOTS_CHECK = {
|
|
11308
|
+
step: AnalysisStep.CheckingBreakingChanges,
|
|
11309
|
+
dimensions: [HOTSPOT_DIMENSION],
|
|
11310
|
+
run: async (context) => {
|
|
11311
|
+
if (context.request.disabledChecks.has(CheckId.Hotspots)) return {
|
|
11312
|
+
findings: [],
|
|
11313
|
+
checksRun: [],
|
|
11314
|
+
notChecked: [{
|
|
11315
|
+
check: HOTSPOTS_NAME,
|
|
11316
|
+
reason: TURNED_OFF_IN_SETTINGS
|
|
11317
|
+
}]
|
|
11318
|
+
};
|
|
11319
|
+
const candidates = historyCandidates(context).slice(0, MAX_FILES);
|
|
11320
|
+
if (candidates.length === 0) return {
|
|
11321
|
+
findings: [],
|
|
11322
|
+
checksRun: [],
|
|
11323
|
+
notChecked: []
|
|
11324
|
+
};
|
|
11325
|
+
const baseDate = await commitDate(context.request.repoDir, context.request.base);
|
|
11326
|
+
try {
|
|
11327
|
+
const since = /* @__PURE__ */ new Date(baseDate.getTime() - HISTORY_DAYS * MS_PER_DAY);
|
|
11328
|
+
const histories = await context.request.history({
|
|
11329
|
+
paths: candidates.map((candidate) => candidate.before),
|
|
11330
|
+
until: context.request.base,
|
|
11331
|
+
since
|
|
11332
|
+
});
|
|
11333
|
+
const findings = candidates.flatMap(({ before, path }) => {
|
|
11334
|
+
const history = histories.get(before);
|
|
11335
|
+
const found = history === void 0 ? void 0 : hotspotFinding(path, history, baseDate);
|
|
11336
|
+
return found === void 0 ? [] : [found];
|
|
11337
|
+
});
|
|
11338
|
+
return {
|
|
11339
|
+
findings: creditedTo(HOTSPOTS_NAME, findings),
|
|
11340
|
+
checksRun: [HOTSPOTS_RUN],
|
|
11341
|
+
notChecked: []
|
|
11342
|
+
};
|
|
11343
|
+
} catch (error) {
|
|
11344
|
+
if (!(error instanceof HistoryUnavailableError)) throw error;
|
|
11345
|
+
return {
|
|
11346
|
+
findings: [],
|
|
11347
|
+
checksRun: [],
|
|
11348
|
+
notChecked: [{
|
|
11349
|
+
check: HOTSPOTS_NAME,
|
|
11350
|
+
reason: `no history to read: ${error.message}`
|
|
11351
|
+
}]
|
|
11352
|
+
};
|
|
11353
|
+
}
|
|
11354
|
+
}
|
|
11355
|
+
};
|
|
11356
|
+
/** Code files the PR changes that existed before it: a new file has no history to speak of. */
|
|
11357
|
+
function historyCandidates({ scanned }) {
|
|
11358
|
+
return scanned.filter(({ diff }) => diff.status !== FileChangeStatus.Added && diff.status !== FileChangeStatus.Deleted).map(({ diff }) => ({
|
|
11359
|
+
before: diff.status === FileChangeStatus.Renamed ? diff.previousPath : diff.path,
|
|
11360
|
+
path: diff.path
|
|
11361
|
+
})).filter(({ path }) => languageFor(path) !== void 0 && !isTestPath(path) && !isNoiseByPath(path));
|
|
11362
|
+
}
|
|
11363
|
+
async function commitDate(repoDir, commit) {
|
|
11364
|
+
return new Date((await runGit([
|
|
11365
|
+
"show",
|
|
11366
|
+
"-s",
|
|
11367
|
+
"--format=%cI",
|
|
11368
|
+
commit
|
|
11369
|
+
], {
|
|
11370
|
+
cwd: repoDir,
|
|
11371
|
+
env: ISOLATED_CONFIG_ENV
|
|
11372
|
+
})).trim());
|
|
11373
|
+
}
|
|
11374
|
+
function isFix(commit) {
|
|
11375
|
+
return FIX_SUBJECT.test(commit.subject) && !NOT_A_BUG.test(commit.subject) && !REVERT_SUBJECT.test(commit.subject);
|
|
11376
|
+
}
|
|
11377
|
+
/** A finding for a file whose history stands out, or undefined when it doesn't. */
|
|
11378
|
+
function hotspotFinding(path, history, baseDate) {
|
|
11379
|
+
const { commits, total } = history;
|
|
11380
|
+
const fixes = commits.filter(isFix).length;
|
|
11381
|
+
const authors = new Set(commits.map((commit) => commit.author)).size;
|
|
11382
|
+
const revert = commits.find((commit) => REVERT_SUBJECT.test(commit.subject) && daysBefore(baseDate, commit.committedAt) <= RECENT_REVERT_DAYS);
|
|
11383
|
+
const fixProne = fixes >= MIN_FIXES && fixes / Math.max(commits.length, 1) >= MIN_FIX_SHARE;
|
|
11384
|
+
if (revert === void 0 && !fixProne && !(total >= MIN_CHANGES_FOR_CHURN)) return void 0;
|
|
11385
|
+
const atLeast = commits.length < total ? "at least " : "";
|
|
11386
|
+
const facts = `In the year before this PR, ${total} commits by ${atLeast}${authors} ${authors === 1 ? "person" : "people"} changed it, and ${atLeast}${fixes} of them fixed something.`;
|
|
11387
|
+
const reverted = revert === void 0 ? "" : ` ${revert.sha.slice(0, 8)} reverted a change ${describeDaysAgo(daysBefore(baseDate, revert.committedAt))}: "${revert.subject}".`;
|
|
11388
|
+
return findingAt({
|
|
11389
|
+
id: revert !== void 0 ? "hotspot.recently-reverted" : fixProne ? "hotspot.fix-prone" : "hotspot.churn",
|
|
11390
|
+
category: HOTSPOT,
|
|
11391
|
+
severity: RiskSeverity.Low,
|
|
11392
|
+
title: revert !== void 0 ? "Had a change reverted recently" : fixProne ? `Often fixed: ${atLeast}${fixes} of ${total} changes in the past year` : `Changes often: ${total} commits in the past year`,
|
|
11393
|
+
detail: `${facts}${reverted} ${CLOSER_LOOK}`
|
|
11394
|
+
}, path, null, null);
|
|
11395
|
+
}
|
|
11396
|
+
function daysBefore(baseDate, timestamp) {
|
|
11397
|
+
return Math.floor((baseDate.getTime() - new Date(timestamp).getTime()) / MS_PER_DAY);
|
|
11398
|
+
}
|
|
11399
|
+
function describeDaysAgo(days) {
|
|
11400
|
+
if (days <= 1) return "the day before";
|
|
11401
|
+
if (days < 14) return `${days} days before`;
|
|
11402
|
+
return `${Math.round(days / 7)} weeks before`;
|
|
11403
|
+
}
|
|
11404
|
+
// packages/engine/src/risk/scope/areas.ts
|
|
11405
|
+
const PACKAGE_MANIFESTS = /* @__PURE__ */ new Set([
|
|
11406
|
+
"package.json",
|
|
11407
|
+
"Cargo.toml",
|
|
11408
|
+
"go.mod",
|
|
11409
|
+
"pyproject.toml",
|
|
11410
|
+
"setup.py",
|
|
11411
|
+
"pom.xml",
|
|
11412
|
+
"build.gradle",
|
|
11413
|
+
"build.gradle.kts",
|
|
11414
|
+
"composer.json",
|
|
11415
|
+
"Gemfile",
|
|
11416
|
+
"mix.exs",
|
|
11417
|
+
"pubspec.yaml"
|
|
11418
|
+
]);
|
|
11419
|
+
const REPOSITORY_ROOT = "";
|
|
11420
|
+
/**
|
|
11421
|
+
* The workspace packages at `head`: every folder below the root with a package manifest, with
|
|
11422
|
+
* what `package.json`, `Cargo.toml` and `go.mod` say about their names and dependencies.
|
|
11423
|
+
*/
|
|
11424
|
+
async function workspacePackages(repoDir, head) {
|
|
11425
|
+
const manifests = (await runGit([
|
|
11426
|
+
"ls-tree",
|
|
11427
|
+
"-r",
|
|
11428
|
+
"-z",
|
|
11429
|
+
"--name-only",
|
|
11430
|
+
head
|
|
11431
|
+
], {
|
|
11432
|
+
cwd: repoDir,
|
|
11433
|
+
env: ISOLATED_CONFIG_ENV
|
|
11434
|
+
})).split("\0").filter((path) => PACKAGE_MANIFESTS.has(posix.basename(path)) && !path.includes("node_modules/") && dirname(path) !== ".");
|
|
11435
|
+
const blobs = await readBlobs(repoDir, manifests.map((path) => ({
|
|
11436
|
+
commit: head,
|
|
11437
|
+
path
|
|
11438
|
+
})));
|
|
11439
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
11440
|
+
manifests.forEach((path, index) => {
|
|
11441
|
+
const root = dirname(path);
|
|
11442
|
+
const read = readManifest(posix.basename(path), blobs.at(index)?.toString("utf8") ?? "");
|
|
11443
|
+
const known = byRoot.get(root);
|
|
11444
|
+
byRoot.set(root, {
|
|
11445
|
+
root,
|
|
11446
|
+
name: known?.name ?? read.name,
|
|
11447
|
+
dependsOn: /* @__PURE__ */ new Set([...known?.dependsOn ?? [], ...read.dependsOn])
|
|
11448
|
+
});
|
|
11449
|
+
});
|
|
11450
|
+
return [...byRoot.values()];
|
|
11451
|
+
}
|
|
11452
|
+
const NO_FACTS = {
|
|
11453
|
+
name: void 0,
|
|
11454
|
+
dependsOn: []
|
|
11455
|
+
};
|
|
11456
|
+
const NPM_DEPENDENCY_SECTIONS = [
|
|
11457
|
+
"dependencies",
|
|
11458
|
+
"devDependencies",
|
|
11459
|
+
"peerDependencies",
|
|
11460
|
+
"optionalDependencies"
|
|
11461
|
+
];
|
|
11462
|
+
const CARGO_DEPENDENCY_SECTIONS = [
|
|
11463
|
+
"dependencies",
|
|
11464
|
+
"dev-dependencies",
|
|
11465
|
+
"build-dependencies"
|
|
11466
|
+
];
|
|
11467
|
+
const GO_MODULE = /^module\s+(\S+)/m;
|
|
11468
|
+
const GO_REQUIREMENT = /^\s*(?:require\s+)?([\w.\-/]+\.[\w.\-/]+)\s+v\S+/gm;
|
|
11469
|
+
function readManifest(fileName, text) {
|
|
11470
|
+
try {
|
|
11471
|
+
if (fileName === "package.json") {
|
|
11472
|
+
const manifest = JSON.parse(text);
|
|
11473
|
+
return {
|
|
11474
|
+
name: stringField(manifest, "name"),
|
|
11475
|
+
dependsOn: NPM_DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(recordOrEmpty(field(manifest, section))))
|
|
11476
|
+
};
|
|
11477
|
+
}
|
|
11478
|
+
if (fileName === "Cargo.toml") {
|
|
11479
|
+
const manifest = parse$2(text);
|
|
11480
|
+
return {
|
|
11481
|
+
name: stringField(field(manifest, "package"), "name"),
|
|
11482
|
+
dependsOn: CARGO_DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(recordOrEmpty(field(manifest, section))))
|
|
11483
|
+
};
|
|
11484
|
+
}
|
|
11485
|
+
if (fileName === "go.mod") return {
|
|
11486
|
+
name: GO_MODULE.exec(text)?.[1],
|
|
11487
|
+
dependsOn: [...text.matchAll(GO_REQUIREMENT)].map((match) => match[1] ?? "")
|
|
11488
|
+
};
|
|
11489
|
+
} catch {}
|
|
11490
|
+
return NO_FACTS;
|
|
11491
|
+
}
|
|
11492
|
+
/** The behaviour changes of each package they fall in, by the deepest package folder holding them. */
|
|
11493
|
+
function areasOf(behaviour, packages) {
|
|
11494
|
+
const deepestFirst = packages.map((workspace) => workspace.root).sort((a, b) => b.length - a.length);
|
|
11495
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
11496
|
+
for (const file of behaviour) {
|
|
11497
|
+
const root = deepestFirst.find((candidate) => file.diff.path.startsWith(`${candidate}/`)) ?? REPOSITORY_ROOT;
|
|
11498
|
+
const files = byRoot.get(root);
|
|
11499
|
+
if (files === void 0) byRoot.set(root, [file]);
|
|
11500
|
+
else files.push(file);
|
|
11501
|
+
}
|
|
11502
|
+
return [...byRoot].map(([root, files]) => ({
|
|
11503
|
+
root,
|
|
11504
|
+
files,
|
|
11505
|
+
units: files.reduce((sum, file) => sum + changedUnitsOf(file).filter((unit) => isBehaviourChange(unit.change)).length, 0)
|
|
11506
|
+
}));
|
|
11507
|
+
}
|
|
11508
|
+
/**
|
|
11509
|
+
* Groups areas that belong together: one declares a dependency on the other, its added lines name
|
|
11510
|
+
* a unit the other changes, or a changed unit's traced callers are in the other. Layers of one
|
|
11511
|
+
* feature, such as a data format, the code writing it and the page reading it, usually depend on
|
|
11512
|
+
* each other without calling each other's new code. Two groups have nothing tying them together.
|
|
11513
|
+
*/
|
|
11514
|
+
function connectedGroups(areas, packages) {
|
|
11515
|
+
const byRoot = new Map(packages.map((workspace) => [workspace.root, workspace]));
|
|
11516
|
+
const declares = (from, to) => {
|
|
11517
|
+
const target = byRoot.get(to.root)?.name;
|
|
11518
|
+
return target !== void 0 && byRoot.get(from.root)?.dependsOn.has(target) === true;
|
|
11519
|
+
};
|
|
11520
|
+
const parent = areas.map((_, index) => index);
|
|
11521
|
+
const find = (index) => {
|
|
11522
|
+
let root = index;
|
|
11523
|
+
while (parent[root] !== root) root = parent[root] ?? root;
|
|
11524
|
+
return root;
|
|
11525
|
+
};
|
|
11526
|
+
areas.forEach((from, fromIndex) => {
|
|
11527
|
+
const uses = mentionMatcher(from);
|
|
11528
|
+
areas.forEach((to, toIndex) => {
|
|
11529
|
+
const linked = declares(from, to) || uses !== void 0 && usesAny(to, uses) || isCalledFrom(from, to);
|
|
11530
|
+
if (fromIndex !== toIndex && linked) parent[find(toIndex)] = find(fromIndex);
|
|
11531
|
+
});
|
|
11532
|
+
});
|
|
11533
|
+
const groups = /* @__PURE__ */ new Map();
|
|
11534
|
+
areas.forEach((area, index) => {
|
|
11535
|
+
const group = groups.get(find(index));
|
|
11536
|
+
if (group === void 0) groups.set(find(index), [area]);
|
|
11537
|
+
else group.push(area);
|
|
11538
|
+
});
|
|
11539
|
+
return [...groups.values()];
|
|
11540
|
+
}
|
|
11541
|
+
function mentionMatcher(area) {
|
|
11542
|
+
const names = [...new Set(area.files.flatMap((file) => changedUnitsOf(file).map((unit) => unit.name)).filter(isSpecificName))];
|
|
11543
|
+
if (names.length === 0) return void 0;
|
|
11544
|
+
return new RegExp(`(?<![\\p{L}\\p{N}_$])(?:${names.map(escapeRegExp$1).join("|")})(?![\\p{L}\\p{N}_$])`, "u");
|
|
11545
|
+
}
|
|
11546
|
+
function usesAny(area, names) {
|
|
11547
|
+
return area.files.some((file) => addedLines(file.diff).some((line) => names.test(line.content)));
|
|
11548
|
+
}
|
|
11549
|
+
function isCalledFrom(from, to) {
|
|
11550
|
+
const paths = new Set(to.files.map((file) => file.diff.path));
|
|
11551
|
+
return from.files.some((file) => changedUnitsOf(file).some((unit) => unit.impact?.status === UnitImpactStatus.Traced && unit.impact.references.some((reference) => paths.has(reference.path))));
|
|
11552
|
+
}
|
|
11553
|
+
// packages/engine/src/risk/scope/concerns.ts
|
|
11554
|
+
/** What kind of work a changed file carries, as far as mixing concerns goes. */
|
|
11555
|
+
const Concern = {
|
|
11556
|
+
/** Code whose behaviour changes: units added, removed, or edited beyond formatting and comments. */
|
|
11557
|
+
Behaviour: "behaviour",
|
|
11558
|
+
/** Code that's only reformatted, re-commented, renamed or moved. */
|
|
11559
|
+
TidyUp: "tidyUp",
|
|
11560
|
+
/** A lockfile; how many packages it upgrades decides whether it's a concern of its own. */
|
|
11561
|
+
Dependencies: "dependencies",
|
|
11562
|
+
/** Tests, docs, CI and config, which normally travel with the change they belong to. */
|
|
11563
|
+
Neutral: "neutral",
|
|
11564
|
+
/** Generated or vendored files, which say nothing about what the author meant to change. */
|
|
11565
|
+
Ignored: "ignored"
|
|
11566
|
+
};
|
|
11567
|
+
const UNPARSED_CODE = /* @__PURE__ */ new Set([
|
|
11568
|
+
".rb",
|
|
11569
|
+
".php",
|
|
11570
|
+
".swift",
|
|
11571
|
+
".scala",
|
|
11572
|
+
".sh",
|
|
11573
|
+
".sql",
|
|
11574
|
+
".lua",
|
|
11575
|
+
".ex",
|
|
11576
|
+
".exs",
|
|
11577
|
+
".erl",
|
|
11578
|
+
".clj",
|
|
11579
|
+
".dart",
|
|
11580
|
+
".r",
|
|
11581
|
+
".pl"
|
|
11582
|
+
]);
|
|
11583
|
+
const IDENTICAL_MOVE = 100;
|
|
11584
|
+
function concernOf(file) {
|
|
11585
|
+
const { diff, noise, syntax } = file;
|
|
11586
|
+
if (noise?.kind === NoiseKind.Lockfile) return Concern.Dependencies;
|
|
11587
|
+
if (noise !== null) return Concern.Ignored;
|
|
11588
|
+
if (isTestPath(diff.path)) return Concern.Neutral;
|
|
11589
|
+
if ((diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied) && diff.similarity === IDENTICAL_MOVE) return Concern.TidyUp;
|
|
11590
|
+
if (syntax.status !== SyntaxAnalysisStatus.Analyzed) return UNPARSED_CODE.has(extname(diff.path).toLowerCase()) ? Concern.Behaviour : Concern.Neutral;
|
|
11591
|
+
const units = changedUnitsOf(file);
|
|
11592
|
+
if (units.some((unit) => isBehaviourChange(unit.change))) return Concern.Behaviour;
|
|
11593
|
+
return units.length > 0 ? Concern.TidyUp : Concern.Neutral;
|
|
11594
|
+
}
|
|
11595
|
+
// packages/engine/src/risk/scope/scopeCheck.ts
|
|
11596
|
+
/**
|
|
11597
|
+
* PRs that mix concerns: a tidy-up or a bulk dependency upgrade riding along with behaviour
|
|
11598
|
+
* changes, or behaviour changes in packages that have nothing to do with each other. Each half
|
|
11599
|
+
* would be easier to review, and to revert, on its own.
|
|
11600
|
+
*
|
|
11601
|
+
* The limits are judgement calls: a few formatted files or upgraded packages come with ordinary
|
|
11602
|
+
* work, so it takes enough of them to bury the change that matters.
|
|
11603
|
+
*/
|
|
11604
|
+
const MIN_TIDY_FILES = 5;
|
|
11605
|
+
const MIN_UPGRADED_PACKAGES = 10;
|
|
11606
|
+
const MIN_UNITS_PER_AREA = 3;
|
|
11607
|
+
const FILES_NAMED = 3;
|
|
11608
|
+
const SCOPE = "scope";
|
|
11609
|
+
const SCOPE_DIMENSION = {
|
|
11610
|
+
id: SCOPE,
|
|
11611
|
+
label: "Scope",
|
|
11612
|
+
kind: DimensionKind.Review,
|
|
11613
|
+
advice: "Ask whether it should be split."
|
|
11614
|
+
};
|
|
11615
|
+
const SCOPE_RUN = {
|
|
11616
|
+
name: "Scope",
|
|
11617
|
+
detail: "tidy-ups, bulk dependency upgrades and unrelated packages mixed in with behaviour changes"
|
|
11618
|
+
};
|
|
11619
|
+
const SCOPE_CHECK = {
|
|
11620
|
+
step: AnalysisStep.ScanningCode,
|
|
11621
|
+
dimensions: [SCOPE_DIMENSION],
|
|
11622
|
+
run: async ({ request }) => {
|
|
11623
|
+
const byConcern = groupByConcern(request.files);
|
|
11624
|
+
const behaviour = byConcern.get(Concern.Behaviour) ?? [];
|
|
11625
|
+
if (behaviour.length === 0) return {
|
|
11626
|
+
findings: [],
|
|
11627
|
+
checksRun: [SCOPE_RUN],
|
|
11628
|
+
notChecked: []
|
|
11629
|
+
};
|
|
11630
|
+
const tidy = byConcern.get(Concern.TidyUp) ?? [];
|
|
11631
|
+
const upgrades = await upgradedPackages(request.repoDir, request.base, request.head, byConcern.get(Concern.Dependencies) ?? []);
|
|
11632
|
+
const packages = await workspacePackages(request.repoDir, request.head);
|
|
11633
|
+
const groups = connectedGroups(areasOf(behaviour, packages), packages).filter((group) => unitsIn(group) >= MIN_UNITS_PER_AREA);
|
|
11634
|
+
const findings = [...mixedConcernsFinding(behaviour, tidy, upgrades), ...unrelatedAreasFinding(groups)];
|
|
11635
|
+
return {
|
|
11636
|
+
findings: creditedTo(SCOPE_RUN.name, findings),
|
|
11637
|
+
checksRun: [SCOPE_RUN],
|
|
11638
|
+
notChecked: []
|
|
11639
|
+
};
|
|
11640
|
+
}
|
|
11641
|
+
};
|
|
11642
|
+
function groupByConcern(files) {
|
|
11643
|
+
const groups = /* @__PURE__ */ new Map();
|
|
11644
|
+
for (const file of files) {
|
|
11645
|
+
const concern = concernOf(file);
|
|
11646
|
+
const group = groups.get(concern);
|
|
11647
|
+
if (group === void 0) groups.set(concern, [file]);
|
|
11648
|
+
else group.push(file);
|
|
11649
|
+
}
|
|
11650
|
+
return groups;
|
|
11651
|
+
}
|
|
11652
|
+
/**
|
|
11653
|
+
* Packages a lockfile already had that the PR moves to other versions. A package new to the
|
|
11654
|
+
* lockfile comes with the code that uses it, so it doesn't count; neither does a lockfile that
|
|
11655
|
+
* can't be read, which the supply-chain check reports.
|
|
11656
|
+
*/
|
|
11657
|
+
async function upgradedPackages(repoDir, base, head, lockfiles) {
|
|
11658
|
+
const readable = lockfiles.filter((file) => file.diff.status === FileChangeStatus.Modified && lockfileReaderFor(file.diff.path) !== void 0);
|
|
11659
|
+
const blobs = await readBlobs(repoDir, readable.flatMap((file) => [{
|
|
11660
|
+
commit: base,
|
|
11661
|
+
path: file.diff.path
|
|
11662
|
+
}, {
|
|
11663
|
+
commit: head,
|
|
11664
|
+
path: file.diff.path
|
|
11665
|
+
}]));
|
|
11666
|
+
const counted = readable.map((file, index) => {
|
|
11667
|
+
const reader = lockfileReaderFor(file.diff.path);
|
|
11668
|
+
const before = blobs.at(2 * index)?.toString("utf8");
|
|
11669
|
+
const after = blobs.at(2 * index + 1)?.toString("utf8");
|
|
11670
|
+
if (reader === void 0 || before === void 0 || after === void 0) return 0;
|
|
11671
|
+
try {
|
|
11672
|
+
return countUpgrades(versionsByName(reader.read(before)), versionsByName(reader.read(after)));
|
|
11673
|
+
} catch {
|
|
11674
|
+
return 0;
|
|
11675
|
+
}
|
|
11676
|
+
});
|
|
11677
|
+
return {
|
|
11678
|
+
packages: counted.reduce((sum, count) => sum + count, 0),
|
|
11679
|
+
lockfiles: readable.filter((_, index) => (counted[index] ?? 0) > 0).map((file) => file.diff.path)
|
|
11680
|
+
};
|
|
11681
|
+
}
|
|
11682
|
+
function versionsByName(packages) {
|
|
11683
|
+
const versions = /* @__PURE__ */ new Map();
|
|
11684
|
+
for (const { name, version } of packages) {
|
|
11685
|
+
const known = versions.get(name);
|
|
11686
|
+
if (known === void 0) versions.set(name, /* @__PURE__ */ new Set([version]));
|
|
11687
|
+
else known.add(version);
|
|
11688
|
+
}
|
|
11689
|
+
return versions;
|
|
11690
|
+
}
|
|
11691
|
+
function countUpgrades(before, after) {
|
|
11692
|
+
return [...after].filter(([name, versions]) => {
|
|
11693
|
+
const earlier = before.get(name);
|
|
11694
|
+
return earlier !== void 0 && [...versions].some((version) => !earlier.has(version));
|
|
11695
|
+
}).length;
|
|
11696
|
+
}
|
|
11697
|
+
function unitsIn(group) {
|
|
11698
|
+
return group.reduce((sum, area) => sum + area.units, 0);
|
|
11699
|
+
}
|
|
11700
|
+
function mixedConcernsFinding(behaviour, tidy, upgrades) {
|
|
11701
|
+
const parts = [...tidy.length >= MIN_TIDY_FILES ? [`${tidy.length} files that are only reformatted, re-commented, renamed or moved (${named(tidy)})`] : [], ...upgrades.packages >= MIN_UPGRADED_PACKAGES ? [`${upgrades.packages} package upgrades in ${upgrades.lockfiles.map(codeSpan).join(" and ")}`] : []];
|
|
11702
|
+
if (parts.length === 0) return [];
|
|
11703
|
+
const rule = {
|
|
11704
|
+
id: "scope.mixed-concerns",
|
|
11705
|
+
category: SCOPE,
|
|
11706
|
+
severity: RiskSeverity.Low,
|
|
11707
|
+
title: tidy.length >= MIN_TIDY_FILES && upgrades.packages >= MIN_UPGRADED_PACKAGES ? "Mixes a tidy-up and upgrades with behaviour changes" : tidy.length >= MIN_TIDY_FILES ? "Mixes a tidy-up with behaviour changes" : "Mixes dependency upgrades with behaviour changes",
|
|
11708
|
+
detail: `Besides behaviour changes in ${behaviour.length} ${behaviour.length === 1 ? "file" : "files"}, it has ${parts.join(", and ")}. Reviewers have to find the change that matters among the rest. Landing them separately makes each easier to review, and to revert.`
|
|
11709
|
+
};
|
|
11710
|
+
return [{
|
|
11711
|
+
ruleId: rule.id,
|
|
11712
|
+
category: rule.category,
|
|
11713
|
+
severity: rule.severity,
|
|
11714
|
+
title: rule.title,
|
|
11715
|
+
detail: rule.detail,
|
|
11716
|
+
location: null,
|
|
11717
|
+
evidence: null
|
|
11718
|
+
}];
|
|
11719
|
+
}
|
|
11720
|
+
function unrelatedAreasFinding(groups) {
|
|
11721
|
+
if (groups.length < 2) return [];
|
|
11722
|
+
const described = groups.map((group) => group.map((area) => area.root === "" ? "the repository root" : codeSpan(area.root)).join(" with ")).join("; ");
|
|
11723
|
+
return [{
|
|
11724
|
+
ruleId: "scope.unrelated-areas",
|
|
11725
|
+
category: SCOPE,
|
|
11726
|
+
severity: RiskSeverity.Low,
|
|
11727
|
+
title: `Changes ${groups.length} packages that don't use each other`,
|
|
11728
|
+
detail: `Behaviour changes in ${described}, with nothing in this PR tying them together. Each could be reviewed, released and reverted on its own.`,
|
|
11729
|
+
location: null,
|
|
11730
|
+
evidence: null
|
|
11731
|
+
}];
|
|
11732
|
+
}
|
|
11733
|
+
function named(files) {
|
|
11734
|
+
const shown = files.slice(0, FILES_NAMED).map((file) => codeSpan(file.diff.path));
|
|
11735
|
+
const rest = files.length - shown.length;
|
|
11736
|
+
return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(" and ");
|
|
11737
|
+
}
|
|
10036
11738
|
// packages/engine/src/risk/errorHandling.ts
|
|
10037
11739
|
/**
|
|
10038
11740
|
* Error handling that hides failures, in the code a PR adds: handlers that do nothing, handlers that
|
|
@@ -10465,7 +12167,7 @@ async function assessQuality({ request, scanned, config }) {
|
|
|
10465
12167
|
// packages/engine/src/risk/checks/registry.ts
|
|
10466
12168
|
const BREAKING_CHANGES_RUN = {
|
|
10467
12169
|
name: "Breaking changes",
|
|
10468
|
-
detail: "public APIs, database migrations, environment variables and config keys"
|
|
12170
|
+
detail: "public APIs, OpenAPI, GraphQL and protobuf schemas, database migrations, environment variables and config keys"
|
|
10469
12171
|
};
|
|
10470
12172
|
/**
|
|
10471
12173
|
* Every check a review runs. Their findings, runs and gaps are reported in this order, which is
|
|
@@ -10521,19 +12223,25 @@ const CHECKS$1 = [
|
|
|
10521
12223
|
},
|
|
10522
12224
|
{
|
|
10523
12225
|
step: AnalysisStep.CheckingBreakingChanges,
|
|
10524
|
-
run: async ({ request, scanned, config }) =>
|
|
10525
|
-
|
|
12226
|
+
run: async ({ request, scanned, config }) => {
|
|
12227
|
+
const breaking = await scanBreakingChanges({
|
|
10526
12228
|
repoDir: request.repoDir,
|
|
10527
12229
|
base: request.base,
|
|
10528
12230
|
head: request.head,
|
|
10529
12231
|
files: request.files.filter((file) => !isIgnored(config, file.diff.path)),
|
|
10530
12232
|
scanned,
|
|
10531
12233
|
versions: request.versions
|
|
10532
|
-
})
|
|
10533
|
-
|
|
10534
|
-
|
|
10535
|
-
|
|
12234
|
+
});
|
|
12235
|
+
return {
|
|
12236
|
+
findings: creditedTo(BREAKING_CHANGES_RUN.name, breaking.findings),
|
|
12237
|
+
checksRun: [BREAKING_CHANGES_RUN],
|
|
12238
|
+
notChecked: breaking.notChecked
|
|
12239
|
+
};
|
|
12240
|
+
}
|
|
10536
12241
|
},
|
|
12242
|
+
DOCS_DRIFT_CHECK,
|
|
12243
|
+
HOTSPOTS_CHECK,
|
|
12244
|
+
SCOPE_CHECK,
|
|
10537
12245
|
QUALITY_CHECK
|
|
10538
12246
|
];
|
|
10539
12247
|
/** The order checks run in, which the progress display follows. */
|
|
@@ -10622,6 +12330,60 @@ function coverageGaps(files, ignoredCount) {
|
|
|
10622
12330
|
function byImportance(dimensions) {
|
|
10623
12331
|
return (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || Number(isSecurityFinding(b, dimensions)) - Number(isSecurityFinding(a, dimensions)) || (a.location?.path ?? "").localeCompare(b.location?.path ?? "") || (a.location?.line ?? 0) - (b.location?.line ?? 0);
|
|
10624
12332
|
}
|
|
12333
|
+
// packages/engine/src/risk/hotspots/gitHistory.ts
|
|
12334
|
+
const RECORD = "";
|
|
12335
|
+
const FIELD = "";
|
|
12336
|
+
const LOG_FORMAT = `${RECORD}%H${FIELD}%s${FIELD}%ae${FIELD}%cI`;
|
|
12337
|
+
const PATHS_PER_COMMAND = 200;
|
|
12338
|
+
/**
|
|
12339
|
+
* Reads file history from the repository itself, for local reviews and checkouts with history.
|
|
12340
|
+
* A shallow repository, such as the depth-1 cache a hosted review fetches, has none to give.
|
|
12341
|
+
*/
|
|
12342
|
+
function gitHistoryReader(repoDir) {
|
|
12343
|
+
return async ({ paths, until, since }) => {
|
|
12344
|
+
if ((await runGit(["rev-parse", "--is-shallow-repository"], {
|
|
12345
|
+
cwd: repoDir,
|
|
12346
|
+
env: ISOLATED_CONFIG_ENV
|
|
12347
|
+
})).trim() === "true") throw new HistoryUnavailableError("the repository was fetched without its history");
|
|
12348
|
+
const histories = new Map(paths.map((path) => [path, []]));
|
|
12349
|
+
for (let start = 0; start < paths.length; start += PATHS_PER_COMMAND) {
|
|
12350
|
+
const batch = paths.slice(start, start + PATHS_PER_COMMAND);
|
|
12351
|
+
const output = await runGit([
|
|
12352
|
+
"log",
|
|
12353
|
+
until,
|
|
12354
|
+
`--since=${since.toISOString()}`,
|
|
12355
|
+
`--format=${LOG_FORMAT}`,
|
|
12356
|
+
"--name-only",
|
|
12357
|
+
"--",
|
|
12358
|
+
...batch.map((path) => `:(literal)${path}`)
|
|
12359
|
+
], {
|
|
12360
|
+
cwd: repoDir,
|
|
12361
|
+
env: ISOLATED_CONFIG_ENV
|
|
12362
|
+
});
|
|
12363
|
+
for (const { commit, paths: touched } of parseLog(output)) for (const path of touched) histories.get(path)?.push(commit);
|
|
12364
|
+
}
|
|
12365
|
+
return new Map([...histories].map(([path, commits]) => [path, {
|
|
12366
|
+
commits,
|
|
12367
|
+
total: commits.length
|
|
12368
|
+
}]));
|
|
12369
|
+
};
|
|
12370
|
+
}
|
|
12371
|
+
function parseLog(output) {
|
|
12372
|
+
return output.split(RECORD).filter((record) => record.trim() !== "").flatMap((record) => {
|
|
12373
|
+
const [header = "", ...files] = record.split("\n");
|
|
12374
|
+
const [sha, subject, author, committedAt] = header.split(FIELD);
|
|
12375
|
+
if (sha === void 0 || subject === void 0 || author === void 0 || committedAt === void 0) return [];
|
|
12376
|
+
return [{
|
|
12377
|
+
commit: {
|
|
12378
|
+
sha,
|
|
12379
|
+
subject,
|
|
12380
|
+
author,
|
|
12381
|
+
committedAt
|
|
12382
|
+
},
|
|
12383
|
+
paths: files.filter((file) => file !== "")
|
|
12384
|
+
}];
|
|
12385
|
+
});
|
|
12386
|
+
}
|
|
10625
12387
|
// packages/engine/src/syntax/similarity.ts
|
|
10626
12388
|
/**
|
|
10627
12389
|
* How alike two token sequences are, from 0 (nothing shared) to 1 (the same).
|
|
@@ -11096,7 +12858,8 @@ async function analyzeChangedFiles(repoDir, from, to, options) {
|
|
|
11096
12858
|
network: options.network,
|
|
11097
12859
|
runScanner: options.runScanner ?? runScannerProcess,
|
|
11098
12860
|
disabledChecks: new Set(options.disabledChecks),
|
|
11099
|
-
reportStep
|
|
12861
|
+
reportStep,
|
|
12862
|
+
history: options.history ?? gitHistoryReader(repoDir)
|
|
11100
12863
|
})
|
|
11101
12864
|
};
|
|
11102
12865
|
}
|
|
@@ -12152,6 +13915,18 @@ const CHECKS = [
|
|
|
12152
13915
|
when: "When a PR upgrades npm packages"
|
|
12153
13916
|
}
|
|
12154
13917
|
},
|
|
13918
|
+
{
|
|
13919
|
+
id: CheckId.Hotspots,
|
|
13920
|
+
name: "Hotspots",
|
|
13921
|
+
purpose: "Flags changed files that keep needing fixes, change very often, or had a change reverted recently",
|
|
13922
|
+
binary: null,
|
|
13923
|
+
install: null,
|
|
13924
|
+
sends: {
|
|
13925
|
+
where: "The PR's host",
|
|
13926
|
+
what: "Paths of the files a PR changes, to read their commits from the past year",
|
|
13927
|
+
when: "Reviews of a pull or merge request"
|
|
13928
|
+
}
|
|
13929
|
+
},
|
|
12155
13930
|
{
|
|
12156
13931
|
id: CheckId.FunctionMetrics,
|
|
12157
13932
|
name: "Function measures",
|
|
@@ -12873,6 +14648,111 @@ async function findMarked(api, marker) {
|
|
|
12873
14648
|
if (comments.length < 100) return void 0;
|
|
12874
14649
|
}
|
|
12875
14650
|
}
|
|
14651
|
+
// packages/providers/src/fileHistory.ts
|
|
14652
|
+
/**
|
|
14653
|
+
* Reads changed files' recent commits from a host's API, for reviews whose local repository has
|
|
14654
|
+
* only the PR's own commits. Every failure becomes a `HistoryUnavailableError`, which the review
|
|
14655
|
+
* reports as a check it couldn't run instead of failing.
|
|
14656
|
+
*/
|
|
14657
|
+
const COMMITS_PER_FILE = 100;
|
|
14658
|
+
const GITHUB_PATHS_PER_QUERY = 20;
|
|
14659
|
+
const GITLAB_CONCURRENT_REQUESTS = 6;
|
|
14660
|
+
const githubHistorySchema = z.object({
|
|
14661
|
+
totalCount: z.number(),
|
|
14662
|
+
nodes: z.array(z.object({
|
|
14663
|
+
oid: z.string(),
|
|
14664
|
+
messageHeadline: z.string(),
|
|
14665
|
+
committedDate: z.string(),
|
|
14666
|
+
author: z.object({
|
|
14667
|
+
email: z.string().nullable(),
|
|
14668
|
+
user: z.object({ login: z.string() }).nullable()
|
|
14669
|
+
}).nullable()
|
|
14670
|
+
}))
|
|
14671
|
+
});
|
|
14672
|
+
const githubResponseSchema = z.object({ repository: z.object({ object: z.record(z.string(), githubHistorySchema).nullable() }).nullable() });
|
|
14673
|
+
/** GitHub's GraphQL API answers for many files in one query; its REST API would need a request each. */
|
|
14674
|
+
async function githubFileHistory(graphql, owner, name, request) {
|
|
14675
|
+
if (graphql === void 0) throw new HistoryUnavailableError("GitHub's API for commit history needs a token");
|
|
14676
|
+
const histories = /* @__PURE__ */ new Map();
|
|
14677
|
+
for (let start = 0; start < request.paths.length; start += GITHUB_PATHS_PER_QUERY) {
|
|
14678
|
+
const paths = request.paths.slice(start, start + GITHUB_PATHS_PER_QUERY);
|
|
14679
|
+
const variables = {
|
|
14680
|
+
owner,
|
|
14681
|
+
name,
|
|
14682
|
+
oid: request.until,
|
|
14683
|
+
since: request.since.toISOString()
|
|
14684
|
+
};
|
|
14685
|
+
paths.forEach((path, index) => {
|
|
14686
|
+
variables[`p${index}`] = path;
|
|
14687
|
+
});
|
|
14688
|
+
const byAlias = (await asHistoryUnavailable(() => graphql(githubHistoryQuery(paths.length), variables, githubResponseSchema))).repository?.object;
|
|
14689
|
+
if (byAlias === null || byAlias === void 0) throw new HistoryUnavailableError("GitHub didn't find the merge base commit");
|
|
14690
|
+
paths.forEach((path, index) => {
|
|
14691
|
+
const history = byAlias[`f${index}`];
|
|
14692
|
+
if (history === void 0) return;
|
|
14693
|
+
histories.set(path, {
|
|
14694
|
+
total: history.totalCount,
|
|
14695
|
+
commits: history.nodes.map((node) => ({
|
|
14696
|
+
sha: node.oid,
|
|
14697
|
+
subject: node.messageHeadline,
|
|
14698
|
+
committedAt: node.committedDate,
|
|
14699
|
+
author: node.author?.user?.login ?? node.author?.email ?? ""
|
|
14700
|
+
}))
|
|
14701
|
+
});
|
|
14702
|
+
});
|
|
14703
|
+
}
|
|
14704
|
+
return histories;
|
|
14705
|
+
}
|
|
14706
|
+
function githubHistoryQuery(count) {
|
|
14707
|
+
const indexes = Array.from({ length: count }, (_, index) => index);
|
|
14708
|
+
return `query($owner: String!, $name: String!, $oid: GitObjectID!, $since: GitTimestamp!, ${indexes.map((index) => `$p${index}: String!`).join(", ")}) {
|
|
14709
|
+
repository(owner: $owner, name: $name) { object(oid: $oid) { ... on Commit { ${indexes.map((index) => `f${index}: history(path: $p${index}, since: $since, first: ${COMMITS_PER_FILE}) { totalCount nodes { oid messageHeadline committedDate author { email user { login } } } }`).join("\n")} } } }
|
|
14710
|
+
}`;
|
|
14711
|
+
}
|
|
14712
|
+
const gitlabCommitsSchema = z.array(z.object({
|
|
14713
|
+
id: z.string(),
|
|
14714
|
+
title: z.string(),
|
|
14715
|
+
committed_date: z.string(),
|
|
14716
|
+
author_email: z.string().nullable().optional(),
|
|
14717
|
+
author_name: z.string().nullable().optional()
|
|
14718
|
+
}));
|
|
14719
|
+
/** GitLab lists a file's commits one file at a time. */
|
|
14720
|
+
async function gitlabFileHistory(get, projectApi, request) {
|
|
14721
|
+
const histories = /* @__PURE__ */ new Map();
|
|
14722
|
+
for (let start = 0; start < request.paths.length; start += GITLAB_CONCURRENT_REQUESTS) {
|
|
14723
|
+
const batch = request.paths.slice(start, start + GITLAB_CONCURRENT_REQUESTS);
|
|
14724
|
+
const results = await Promise.all(batch.map((path) => {
|
|
14725
|
+
const query = new URLSearchParams({
|
|
14726
|
+
ref_name: request.until,
|
|
14727
|
+
path,
|
|
14728
|
+
since: request.since.toISOString(),
|
|
14729
|
+
per_page: String(COMMITS_PER_FILE)
|
|
14730
|
+
});
|
|
14731
|
+
return asHistoryUnavailable(() => get(`${projectApi}/repository/commits?${query.toString()}`, gitlabCommitsSchema));
|
|
14732
|
+
}));
|
|
14733
|
+
batch.forEach((path, index) => {
|
|
14734
|
+
const commits = (results[index] ?? []).map((commit) => ({
|
|
14735
|
+
sha: commit.id,
|
|
14736
|
+
subject: commit.title,
|
|
14737
|
+
committedAt: commit.committed_date,
|
|
14738
|
+
author: commit.author_email ?? commit.author_name ?? ""
|
|
14739
|
+
}));
|
|
14740
|
+
histories.set(path, {
|
|
14741
|
+
commits,
|
|
14742
|
+
total: commits.length
|
|
14743
|
+
});
|
|
14744
|
+
});
|
|
14745
|
+
}
|
|
14746
|
+
return histories;
|
|
14747
|
+
}
|
|
14748
|
+
async function asHistoryUnavailable(request) {
|
|
14749
|
+
try {
|
|
14750
|
+
return await request();
|
|
14751
|
+
} catch (error) {
|
|
14752
|
+
if (error instanceof HostApiError || error instanceof TypeError || error instanceof z.ZodError) throw new HistoryUnavailableError(error.message, { cause: error });
|
|
14753
|
+
throw error;
|
|
14754
|
+
}
|
|
14755
|
+
}
|
|
12876
14756
|
// packages/providers/src/stack.ts
|
|
12877
14757
|
/**
|
|
12878
14758
|
* Finds a stack by following branches, for hosts or repositories without stacks of their own.
|
|
@@ -13240,6 +15120,9 @@ var GitHubHost = class {
|
|
|
13240
15120
|
withBase: (branch) => list(`base=${encodeURIComponent(branch)}`)
|
|
13241
15121
|
};
|
|
13242
15122
|
}
|
|
15123
|
+
fetchFileHistory(request) {
|
|
15124
|
+
return githubFileHistory(this.#token === void 0 ? void 0 : (query, variables, schema) => this.#graphql(query, variables, schema), this.#ref.owner, this.#ref.repo, request);
|
|
15125
|
+
}
|
|
13243
15126
|
async #graphql(query, variables, schema) {
|
|
13244
15127
|
const url = graphqlUrl(this.#ref.webOrigin);
|
|
13245
15128
|
const response = await writeJson({
|
|
@@ -13679,6 +15562,9 @@ var GitLabHost = class {
|
|
|
13679
15562
|
defaultBranch: project.default_branch
|
|
13680
15563
|
}, this.#openMergeRequests(projectApi));
|
|
13681
15564
|
}
|
|
15565
|
+
fetchFileHistory(request) {
|
|
15566
|
+
return gitlabFileHistory((url, schema) => this.#get(url, schema), this.#projectApi(), request);
|
|
15567
|
+
}
|
|
13682
15568
|
#openMergeRequests(projectApi) {
|
|
13683
15569
|
const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE}&per_page=${MERGE_REQUESTS_PER_PAGE}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
|
|
13684
15570
|
return {
|
|
@@ -15608,7 +17494,9 @@ async function reviewLocalBranch(local, options, deps) {
|
|
|
15608
17494
|
}
|
|
15609
17495
|
async function analyzePullRequest(ref, options, deps) {
|
|
15610
17496
|
deps.reportStep(AnalysisStep.FetchingPullRequest);
|
|
15611
|
-
const
|
|
17497
|
+
const host = gitHostFor(ref, deps.tokens);
|
|
17498
|
+
const snapshot = await host.fetchPullRequest();
|
|
17499
|
+
const history = options.network ? (request) => host.fetchFileHistory(request) : offlineHistory;
|
|
15612
17500
|
const { pullRequest } = snapshot;
|
|
15613
17501
|
deps.reportStep(AnalysisStep.FetchingCommits);
|
|
15614
17502
|
return analyzeChange({
|
|
@@ -15619,11 +17507,16 @@ async function analyzePullRequest(ref, options, deps) {
|
|
|
15619
17507
|
commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
|
|
15620
17508
|
}),
|
|
15621
17509
|
pullRequest,
|
|
15622
|
-
ref
|
|
17510
|
+
ref,
|
|
17511
|
+
history
|
|
15623
17512
|
}, options, deps);
|
|
15624
17513
|
}
|
|
15625
|
-
async function
|
|
17514
|
+
async function offlineHistory() {
|
|
17515
|
+
throw new HistoryUnavailableError("offline mode: the host was not asked");
|
|
17516
|
+
}
|
|
17517
|
+
async function analyzeChange({ repoDir, pullRequest, ref, history }, options, deps) {
|
|
15626
17518
|
const { files, risk } = await analyzeChangedFiles(repoDir, pullRequest.mergeBaseSha, pullRequest.headSha, {
|
|
17519
|
+
history,
|
|
15627
17520
|
network: options.network,
|
|
15628
17521
|
disabledChecks: options.disabledChecks ?? [],
|
|
15629
17522
|
reportStep: deps.reportStep
|