@zgeoff/chex 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +3 -2
  2. package/lefthook.yml +13 -0
  3. package/package.json +5 -2
  4. package/src/ci-plan/build-ci-plan-output.ts +36 -0
  5. package/src/ci-plan/collect-shared-checks.ts +62 -0
  6. package/src/ci-plan/find-chex-args.ts +40 -0
  7. package/src/ci-plan/parse-ci-plan.ts +299 -0
  8. package/src/ci-plan/parse-docs-checks.ts +1 -0
  9. package/src/ci-plan/parse-package-scripts.ts +36 -0
  10. package/src/ci-plan/write-ci-plan-json.ts +21 -0
  11. package/src/cli/parse-chex-args.ts +7 -2
  12. package/src/cli/run-chex.ts +2 -0
  13. package/src/cli.ts +9 -0
  14. package/src/workflows/collect-allowances.ts +101 -0
  15. package/src/workflows/collect-concurrency-findings.ts +1 -1
  16. package/src/workflows/collect-hook-findings.ts +13 -0
  17. package/src/workflows/collect-moved-repo-findings.ts +34 -0
  18. package/src/workflows/collect-run-commands.ts +18 -0
  19. package/src/workflows/collect-runner-labels.ts +8 -0
  20. package/src/workflows/collect-steps.ts +9 -0
  21. package/src/workflows/constants.ts +4 -0
  22. package/src/workflows/find-heavy-runner.ts +20 -0
  23. package/src/workflows/is-list.ts +4 -0
  24. package/src/workflows/parse-repo-slug.ts +7 -0
  25. package/src/workflows/pick-checked-paths.ts +33 -0
  26. package/src/workflows/pick-repo-move.ts +28 -0
  27. package/src/workflows/read-repo-slug.ts +12 -0
  28. package/src/workflows/read-repo-state.ts +57 -0
  29. package/src/workflows/rules/build-rule-finding.ts +10 -0
  30. package/src/workflows/rules/collect-condition-terms.ts +116 -0
  31. package/src/workflows/rules/collect-hook-check-findings.ts +84 -0
  32. package/src/workflows/rules/collect-main-only-job-findings.ts +123 -0
  33. package/src/workflows/rules/collect-main-run-concurrency-findings.ts +77 -0
  34. package/src/workflows/rules/collect-main-run-shape-findings.ts +161 -0
  35. package/src/workflows/rules/collect-needs.ts +13 -0
  36. package/src/workflows/rules/collect-path-filter-findings.ts +56 -0
  37. package/src/workflows/rules/collect-pr-gate-findings.ts +72 -0
  38. package/src/workflows/rules/collect-publish-findings.ts +83 -0
  39. package/src/workflows/rules/collect-release-jobs.ts +55 -0
  40. package/src/workflows/rules/collect-release-shape-findings.ts +67 -0
  41. package/src/workflows/rules/find-file-filter.ts +91 -0
  42. package/src/workflows/rules/find-image-build.ts +59 -0
  43. package/src/workflows/rules/find-job-environment.ts +9 -0
  44. package/src/workflows/rules/find-matrix-runner.ts +38 -0
  45. package/src/workflows/rules/find-shipped-build.ts +36 -0
  46. package/src/workflows/rules/is-arm-label.ts +5 -0
  47. package/src/workflows/rules/is-release-condition.ts +19 -0
  48. package/src/workflows/rules/is-shared-check-script.ts +22 -0
  49. package/src/workflows/rules/is-shared-release-workflow.ts +14 -0
  50. package/src/workflows/rules/is-workflow-call.ts +12 -0
  51. package/src/workflows/rules/types.ts +31 -0
  52. package/src/workflows/run-workflows-check.ts +60 -55
  53. package/src/workflows/to-unwrapped-command.ts +28 -0
  54. package/src/workflows/to-workflow-findings.ts +24 -0
  55. package/src/workflows/types.ts +68 -0
  56. package/src/workflows/workflow-context.ts +0 -24
@@ -0,0 +1,123 @@
1
+ import { laneNames } from '../../ci-plan/plan-check-scripts.ts';
2
+ import { collectRunCommands } from '../collect-run-commands.ts';
3
+ import { collectRunnerLabels } from '../collect-runner-labels.ts';
4
+ import { collectSteps } from '../collect-steps.ts';
5
+ import { expressionOpening } from '../constants.ts';
6
+ import { findHeavyRunner } from '../find-heavy-runner.ts';
7
+ import { findMember } from '../find-member.ts';
8
+ import { pullRequestTriggers } from '../pull-request-triggers.ts';
9
+ import { toUnwrappedCommand } from '../to-unwrapped-command.ts';
10
+ import type { Job, WorkflowContext } from '../types.ts';
11
+ import { buildRuleFinding } from './build-rule-finding.ts';
12
+ import { findImageBuild } from './find-image-build.ts';
13
+ import { findMatrixRunner } from './find-matrix-runner.ts';
14
+ import { isARMLabel } from './is-arm-label.ts';
15
+ import type { RuleFinding } from './types.ts';
16
+
17
+ export function collectMainOnlyJobFindings(workflow: WorkflowContext): RuleFinding[] {
18
+ const trigger = pullRequestTriggers.find((name) => workflow.triggers.has(name));
19
+
20
+ if (trigger === undefined) {
21
+ return [];
22
+ }
23
+
24
+ return workflow.jobs.flatMap((job) => {
25
+ const reason = findMainOnlyReason(job);
26
+
27
+ return reason === undefined
28
+ ? []
29
+ : [
30
+ buildRuleFinding(
31
+ 'main-only-job-in-pr',
32
+ job.line,
33
+ `job ${job.id} ${reason}, in a workflow that runs on ${trigger}; move it to main.yml, or keep the work inside a test script that holds the PR's 5 minutes`,
34
+ [job.line],
35
+ ),
36
+ ];
37
+ });
38
+ }
39
+
40
+ const kvmSetupCommands = new Set(['scripts/ci/check-kvm.sh', 'scripts/open-kvm.sh', 'ci:open-kvm']);
41
+
42
+ // These print their arguments, so a path or a command name after them runs nothing.
43
+ const textCommands = new Set(['echo', 'printf']);
44
+
45
+ const vmAndSystemCommandPattern =
46
+ /^(?:qemu(?:-.+)?|firecracker|virsh|vagrant|multipass|limactl|zfs|zpool|systemctl|systemd-.+|machinectl)$/u;
47
+
48
+ function findMainOnlyReason(job: Job): string | undefined {
49
+ const runsOn = findMember(job.definition, 'runs-on');
50
+ const runner = findHeavyRunner(runsOn) ?? findArmRunner(runsOn) ?? findMatrixRunner(job);
51
+
52
+ if (runner !== undefined) {
53
+ return `runs on ${runner}, which is not an ubuntu x64 runner`;
54
+ }
55
+
56
+ const build = findImageBuild(job);
57
+
58
+ if (build !== undefined) {
59
+ return `builds an image or binary with ${build}`;
60
+ }
61
+
62
+ const commands = collectSteps(job).flatMap((step) => {
63
+ const run = findMember(step, 'run');
64
+
65
+ return typeof run === 'string'
66
+ ? collectRunCommands(run).map((words) => toUnwrappedCommand(words.map((word) => word.text)))
67
+ : [];
68
+ });
69
+
70
+ const kvm = commands
71
+ .filter(([name]) => !textCommands.has(name ?? ''))
72
+ .flat()
73
+ .find((word) => word.includes('/dev/kvm') || kvmSetupCommands.has(word));
74
+
75
+ if (kvm !== undefined) {
76
+ return `uses ${kvm}`;
77
+ }
78
+
79
+ const system = commands.find(
80
+ ([name]) => name !== undefined && vmAndSystemCommandPattern.test(name),
81
+ );
82
+
83
+ if (system?.[0] !== undefined) {
84
+ return `runs ${system[0]}, which needs a VM, ZFS or systemd`;
85
+ }
86
+
87
+ return isLaneMatrix(job, commands) ? 'is a matrix whose entries run test lanes' : undefined;
88
+ }
89
+
90
+ function findArmRunner(runsOn: unknown): string | undefined {
91
+ const labels = collectRunnerLabels(runsOn);
92
+
93
+ return labels.some((label) => label.includes(expressionOpening))
94
+ ? undefined
95
+ : labels.find((label) => isARMLabel(label));
96
+ }
97
+
98
+ const laneScripts = new Set(laneNames.map((lane) => `test:${lane}`));
99
+
100
+ function isLaneMatrix(job: Job, commands: readonly (readonly string[])[]): boolean {
101
+ const matrix = findMember(findMember(job.definition, 'strategy'), 'matrix');
102
+
103
+ if (matrix === undefined) {
104
+ return false;
105
+ }
106
+
107
+ const values = collectStrings(matrix);
108
+
109
+ return (
110
+ commands.some((words) => words.some((word) => laneScripts.has(word))) ||
111
+ values.some((value) => laneScripts.has(value) || laneNames.includes(value))
112
+ );
113
+ }
114
+
115
+ function collectStrings(value: unknown): string[] {
116
+ if (typeof value === 'string') {
117
+ return [value];
118
+ }
119
+
120
+ return typeof value === 'object' && value !== null
121
+ ? Object.values(value).flatMap((member: unknown) => collectStrings(member))
122
+ : [];
123
+ }
@@ -0,0 +1,77 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import { getTopLevelLine } from '../get-top-level-line.ts';
3
+ import type { WorkflowContext } from '../types.ts';
4
+ import { buildRuleFinding } from './build-rule-finding.ts';
5
+ import type { RuleFinding } from './types.ts';
6
+
7
+ const sharedGroup =
8
+ "github.event_name == 'push' && 'main-run-push' || format('main-run-{0}', github.run_id)";
9
+
10
+ export function collectMainRunConcurrencyFindings(workflow: WorkflowContext): RuleFinding[] {
11
+ if (!workflow.path.endsWith('/main.yml')) {
12
+ return [];
13
+ }
14
+
15
+ const concurrency = findMember(workflow.workflow, 'concurrency');
16
+ const onLine = getTopLevelLine(workflow.lines, 'on');
17
+
18
+ const concurrencyLine =
19
+ concurrency === undefined ? onLine : getTopLevelLine(workflow.lines, 'concurrency');
20
+
21
+ const allowAt = [onLine, concurrencyLine];
22
+ const group = typeof concurrency === 'string' ? concurrency : findMember(concurrency, 'group');
23
+ const queue = findMember(concurrency, 'queue');
24
+ const faults: string[] = [];
25
+
26
+ if (typeof group !== 'string' || !isSharedGroup(group)) {
27
+ faults.push(
28
+ `the group is not the shared expression; write \`group: \${{ ${sharedGroup} }}\`, so pushes queue in one group and each schedule or dispatch run gets its own`,
29
+ );
30
+ }
31
+
32
+ if (isCancelling(concurrency)) {
33
+ faults.push(
34
+ 'cancel-in-progress is not false; set it to false, since a main run is never cancelled',
35
+ );
36
+ }
37
+
38
+ if (queue === 'max') {
39
+ faults.push(
40
+ 'queue: max is set at the workflow level; remove it, since only the release job queues every run',
41
+ );
42
+ }
43
+
44
+ const workflowFindings = faults.map((fault) =>
45
+ buildRuleFinding('main-run-concurrency', concurrencyLine, fault, allowAt),
46
+ );
47
+
48
+ // A job's own group replaces the workflow's, so a job that cancels can stop a push run.
49
+ const jobFindings = workflow.jobs
50
+ .filter((job) => isCancelling(findMember(job.definition, 'concurrency')))
51
+ .map((job) =>
52
+ buildRuleFinding(
53
+ 'main-run-concurrency',
54
+ job.line,
55
+ `job ${job.id} sets a cancel-in-progress that is not false; set it to false, since a main run is never cancelled`,
56
+ [job.line],
57
+ ),
58
+ );
59
+
60
+ return [...workflowFindings, ...jobFindings];
61
+ }
62
+
63
+ const wholeExpressionPattern = /^\s*\$\{\{(?<body>.*)\}\}\s*$/su;
64
+
65
+ // A group with no `${{ }}` is text, which every event shares.
66
+ function isSharedGroup(group: string): boolean {
67
+ const body = wholeExpressionPattern.exec(group)?.groups?.['body'];
68
+
69
+ return body !== undefined && body.trim().replaceAll(/\s+/gu, ' ') === sharedGroup;
70
+ }
71
+
72
+ // A missing cancel-in-progress never cancels.
73
+ function isCancelling(concurrency: unknown): boolean {
74
+ const cancel = findMember(concurrency, 'cancel-in-progress');
75
+
76
+ return cancel !== undefined && cancel !== false && cancel !== 'false';
77
+ }
@@ -0,0 +1,161 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import { getTopLevelLine } from '../get-top-level-line.ts';
3
+ import type { Job, MovedRepo, WorkflowContext } from '../types.ts';
4
+ import { buildRuleFinding } from './build-rule-finding.ts';
5
+ import { collectNeeds } from './collect-needs.ts';
6
+ import { collectReleaseJobs } from './collect-release-jobs.ts';
7
+ import { findShippedBuild } from './find-shipped-build.ts';
8
+ import { isWorkflowCall } from './is-workflow-call.ts';
9
+ import type { RuleFinding } from './types.ts';
10
+
11
+ const settingsFile = '.github/ci.yml';
12
+
13
+ export function collectMainRunShapeFindings(
14
+ workflow: WorkflowContext,
15
+ repo: MovedRepo,
16
+ ): RuleFinding[] {
17
+ if (!workflow.path.endsWith('/main.yml')) {
18
+ return [];
19
+ }
20
+
21
+ const jobsLine = getTopLevelLine(workflow.lines, 'jobs');
22
+ const nameLine = getTopLevelLine(workflow.lines, 'name');
23
+
24
+ const checksJobs = workflow.jobs.filter((job) =>
25
+ isWorkflowCall(findMember(job.definition, 'uses'), 'checks.yml', repo.move),
26
+ );
27
+
28
+ const pickJobs = workflow.jobs.filter((job) =>
29
+ isWorkflowCall(findMember(job.definition, 'uses'), 'pick-tests.yml', repo.move),
30
+ );
31
+
32
+ const slowTests = repo.plan.kind === 'planned' ? repo.plan.plan.slowTests : {};
33
+ const faults: RuleFinding[] = [];
34
+
35
+ if (findMember(workflow.workflow, 'name') !== 'Main') {
36
+ faults.push(
37
+ buildRuleFinding(
38
+ 'main-run-shape',
39
+ nameLine,
40
+ 'the workflow is not named `Main`; set `name: Main`, which audit-fix and repo sync match',
41
+ [nameLine],
42
+ ),
43
+ );
44
+ }
45
+
46
+ if (checksJobs.length === 0) {
47
+ faults.push(
48
+ buildRuleFinding(
49
+ 'main-run-shape',
50
+ jobsLine,
51
+ 'no job calls checks.yml; add a job that calls it, so every main run repeats the fast checks',
52
+ [jobsLine],
53
+ ),
54
+ );
55
+ }
56
+
57
+ if (pickJobs.length === 0) {
58
+ faults.push(
59
+ buildRuleFinding(
60
+ 'main-run-shape',
61
+ jobsLine,
62
+ 'no job calls pick-tests.yml; add a job that calls it, so each run picks its slow tests',
63
+ [jobsLine],
64
+ ),
65
+ );
66
+ }
67
+
68
+ if (repo.plan.kind === 'invalid') {
69
+ faults.push({
70
+ ...buildRuleFinding(
71
+ 'main-run-shape',
72
+ 1,
73
+ `${settingsFile} is invalid, so its slow-tests cannot be checked: ${repo.plan.errors.join(' ')}`,
74
+ [],
75
+ ),
76
+ path: settingsFile,
77
+ });
78
+
79
+ return faults;
80
+ }
81
+
82
+ const releaseJobs = collectReleaseJobs(workflow.jobs, true);
83
+ const gateIDs = [...checksJobs, ...pickJobs].map((job) => job.id);
84
+
85
+ const gates = new Set(gateIDs);
86
+
87
+ const slowJobs = workflow.jobs.filter((job) => !gates.has(job.id) && !releaseJobs.has(job.id));
88
+
89
+ for (const job of slowJobs) {
90
+ faults.push(...collectSlowJobFindings(job, gateIDs, slowTests));
91
+ }
92
+
93
+ const jobIDs = new Set(workflow.jobs.map((job) => job.id));
94
+
95
+ for (const name of Object.keys(slowTests).filter((entry) => !jobIDs.has(entry))) {
96
+ const line =
97
+ repo.planLines.findIndex((text) =>
98
+ new RegExp(`^\\s+${RegExp.escape(name)}:`, 'u').test(text),
99
+ ) + 1;
100
+
101
+ faults.push({
102
+ ...buildRuleFinding(
103
+ 'main-run-shape',
104
+ line || 1,
105
+ `the slow-tests entry "${name}" names no job of main.yml; add the job or remove the entry`,
106
+ [],
107
+ ),
108
+ path: settingsFile,
109
+ });
110
+ }
111
+
112
+ return faults;
113
+ }
114
+
115
+ function collectSlowJobFindings(
116
+ job: Job,
117
+ gateIDs: readonly string[],
118
+ slowTests: Readonly<Record<string, unknown>>,
119
+ ): RuleFinding[] {
120
+ const needs = collectNeeds(job);
121
+ const missing = gateIDs.filter((id) => !needs.includes(id));
122
+ const entry = slowTests[job.id];
123
+ const findings: RuleFinding[] = [];
124
+
125
+ if (missing.length > 0) {
126
+ findings.push(
127
+ buildRuleFinding(
128
+ 'main-run-shape',
129
+ job.line,
130
+ `slow test ${job.id} does not need ${missing.join(' and ')}; add ${missing.length === 1 ? 'it' : 'both'} to its needs itself, since GitHub exposes the outputs of a direct need only, so it runs after the fast checks and reads the picked tests`,
131
+ [job.line],
132
+ ),
133
+ );
134
+ }
135
+
136
+ if (entry === undefined) {
137
+ findings.push(
138
+ buildRuleFinding(
139
+ 'main-run-shape',
140
+ job.line,
141
+ `slow test ${job.id} has no entry in slow-tests of ${settingsFile}; add one, as always, daily or run-when-changed`,
142
+ [job.line],
143
+ ),
144
+ );
145
+ } else if (entry !== 'always') {
146
+ const build = findShippedBuild(job);
147
+
148
+ if (build !== undefined) {
149
+ findings.push(
150
+ buildRuleFinding(
151
+ 'main-run-shape',
152
+ job.line,
153
+ `job ${job.id} builds what ships, with ${build}, so its slow-tests entry must be always; change it, so every passed run has its artefact`,
154
+ [job.line],
155
+ ),
156
+ );
157
+ }
158
+ }
159
+
160
+ return findings;
161
+ }
@@ -0,0 +1,13 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import { isList } from '../is-list.ts';
3
+ import type { Job } from '../types.ts';
4
+
5
+ export function collectNeeds(job: Job): string[] {
6
+ const needs = findMember(job.definition, 'needs');
7
+
8
+ if (typeof needs === 'string') {
9
+ return [needs];
10
+ }
11
+
12
+ return isList(needs) ? needs.filter((need): need is string => typeof need === 'string') : [];
13
+ }
@@ -0,0 +1,56 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import { getTopLevelLine } from '../get-top-level-line.ts';
3
+ import type { MovedRepo, WorkflowContext } from '../types.ts';
4
+ import { buildRuleFinding } from './build-rule-finding.ts';
5
+ import { findFileFilter } from './find-file-filter.ts';
6
+ import type { RuleFinding } from './types.ts';
7
+
8
+ export function collectPathFilterFindings(
9
+ workflow: WorkflowContext,
10
+ repo: MovedRepo,
11
+ ): RuleFinding[] {
12
+ const isPR = workflow.path.endsWith('/pr.yml');
13
+
14
+ if (!isPR && !workflow.path.endsWith('/main.yml')) {
15
+ return [];
16
+ }
17
+
18
+ const onLine = getTopLevelLine(workflow.lines, 'on');
19
+ const on = findMember(workflow.workflow, 'on');
20
+
21
+ const triggerFindings = [...workflow.triggers].flatMap((event) => {
22
+ const filter = ['paths', 'paths-ignore'].find(
23
+ (key) => findMember(findMember(on, event), key) !== undefined,
24
+ );
25
+
26
+ return filter === undefined
27
+ ? []
28
+ : [
29
+ buildRuleFinding(
30
+ 'path-filter',
31
+ onLine,
32
+ `on.${event}.${filter} filters the workflow by files; remove it, and let paths-changed.yml or pick-tests.yml skip jobs by their files`,
33
+ [onLine],
34
+ ),
35
+ ];
36
+ });
37
+
38
+ const jobFindings = isPR
39
+ ? workflow.jobs.flatMap((job) => {
40
+ const filter = findFileFilter(job, repo.move);
41
+
42
+ return filter === undefined
43
+ ? []
44
+ : [
45
+ buildRuleFinding(
46
+ 'path-filter',
47
+ job.line,
48
+ `job ${job.id} skips on its files with ${filter}; call paths-changed.yml instead, so every repo skips the same way`,
49
+ [job.line],
50
+ ),
51
+ ];
52
+ })
53
+ : [];
54
+
55
+ return [...triggerFindings, ...jobFindings];
56
+ }
@@ -0,0 +1,72 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import { getTopLevelLine } from '../get-top-level-line.ts';
3
+ import type { MovedRepo, WorkflowContext } from '../types.ts';
4
+ import { buildRuleFinding } from './build-rule-finding.ts';
5
+ import { collectConditionTerms } from './collect-condition-terms.ts';
6
+ import { collectNeeds } from './collect-needs.ts';
7
+ import { isWorkflowCall } from './is-workflow-call.ts';
8
+ import type { RuleFinding } from './types.ts';
9
+
10
+ export function collectPrGateFindings(workflow: WorkflowContext, repo: MovedRepo): RuleFinding[] {
11
+ if (!workflow.path.endsWith('/pr.yml')) {
12
+ return [];
13
+ }
14
+
15
+ const jobsLine = getTopLevelLine(workflow.lines, 'jobs');
16
+ const checks = workflow.jobs.find((job) => job.id === 'checks');
17
+ const gate = workflow.jobs.find((job) => job.id === 'pr');
18
+ const faults: { line: number; text: string }[] = [];
19
+
20
+ if (
21
+ checks === undefined ||
22
+ !isWorkflowCall(findMember(checks.definition, 'uses'), 'checks.yml', repo.move)
23
+ ) {
24
+ faults.push({
25
+ line: checks?.line ?? jobsLine,
26
+ text: 'no job `checks` calls checks.yml; add `checks: { uses: zgeoff/tools/.github/workflows/checks.yml@<sha> }`',
27
+ });
28
+ }
29
+
30
+ if (
31
+ gate === undefined ||
32
+ !isWorkflowCall(findMember(gate.definition, 'uses'), 'pr-gate.yml', repo.move)
33
+ ) {
34
+ faults.push({
35
+ line: gate?.line ?? jobsLine,
36
+ text: 'no job `pr` calls pr-gate.yml; add it, since the ruleset requires `pr / checks`',
37
+ });
38
+ } else {
39
+ const needs = collectNeeds(gate);
40
+ const missing = workflow.jobs.filter((job) => job !== gate && !needs.includes(job.id));
41
+ const terms = collectConditionTerms(findMember(gate.definition, 'if'));
42
+ const needsInput = findMember(findMember(gate.definition, 'with'), 'needs');
43
+
44
+ if (missing.length > 0) {
45
+ faults.push({
46
+ line: gate.line,
47
+ text: `job \`pr\` does not need ${missing.map((job) => job.id).join(', ')}; list every other job in its needs, so a failure or a skip there reaches the gate`,
48
+ });
49
+ }
50
+
51
+ if (terms?.length !== 1 || terms[0] !== 'always()') {
52
+ faults.push({
53
+ line: gate.line,
54
+ text: 'job `pr` has no `if: always()` alone, so a failed job skips the gate instead of failing it, or another term skips it after one; set `if: always()`',
55
+ });
56
+ }
57
+
58
+ if (
59
+ typeof needsInput !== 'string' ||
60
+ needsInput.replaceAll(/\s+/gu, '') !== `\${{toJSON(needs)}}`
61
+ ) {
62
+ faults.push({
63
+ line: gate.line,
64
+ text: `job \`pr\` does not pass \`needs: \${{ toJSON(needs) }}\` to pr-gate.yml; pass it in \`with\`, so the gate reads every result`,
65
+ });
66
+ }
67
+ }
68
+
69
+ return faults.map((fault) =>
70
+ buildRuleFinding('pr-gate-missing', fault.line, fault.text, [fault.line]),
71
+ );
72
+ }
@@ -0,0 +1,83 @@
1
+ import { collectRunCommands } from '../collect-run-commands.ts';
2
+ import { collectSteps } from '../collect-steps.ts';
3
+ import { findMember } from '../find-member.ts';
4
+ import { toUnwrappedCommand } from '../to-unwrapped-command.ts';
5
+ import type { Job, MovedRepo, RepoMove, WorkflowContext } from '../types.ts';
6
+ import { buildRuleFinding } from './build-rule-finding.ts';
7
+ import { collectReleaseJobs } from './collect-release-jobs.ts';
8
+ import { isSharedReleaseWorkflow } from './is-shared-release-workflow.ts';
9
+ import { isWorkflowCall } from './is-workflow-call.ts';
10
+ import type { RuleFinding } from './types.ts';
11
+
12
+ export function collectPublishFindings(workflow: WorkflowContext, repo: MovedRepo): RuleFinding[] {
13
+ if (isSharedReleaseWorkflow(workflow, repo.move)) {
14
+ return [];
15
+ }
16
+
17
+ const releaseJobs = collectReleaseJobs(workflow.jobs, workflow.path.endsWith('/main.yml'));
18
+
19
+ return workflow.jobs
20
+ .filter((job) => !releaseJobs.has(job.id))
21
+ .flatMap((job) => {
22
+ const publish = findPublish(job, repo.move);
23
+
24
+ return publish === undefined
25
+ ? []
26
+ : [
27
+ buildRuleFinding(
28
+ 'publish-outside-release',
29
+ job.line,
30
+ `job ${job.id} publishes with ${publish}, outside the release job; move the publish into the release job of main.yml`,
31
+ [job.line],
32
+ ),
33
+ ];
34
+ });
35
+ }
36
+
37
+ function findPublish(job: Job, move: RepoMove): string | undefined {
38
+ if (isWorkflowCall(findMember(job.definition, 'uses'), 'npm-publish.yml', move)) {
39
+ return 'npm-publish.yml';
40
+ }
41
+
42
+ return collectSteps(job)
43
+ .flatMap((step) => {
44
+ const run = findMember(step, 'run');
45
+
46
+ return typeof run === 'string' ? collectRunCommands(run) : [];
47
+ })
48
+ .map((words) => findPublishCommand(words.map((word) => word.text)))
49
+ .find((command) => command !== undefined);
50
+ }
51
+
52
+ const publishers = new Set(['npm', 'bun', 'pnpm', 'changeset']);
53
+
54
+ // A publisher starts the command, or follows npx, bunx or bun x. A word further on, as in
55
+ // `echo npm publish`, is text.
56
+ function findPublishCommand(words: readonly string[]): string | undefined {
57
+ const command = toUnwrappedCommand(words);
58
+ const runnerLength = countRunnerWords(command);
59
+ const launched = runnerLength === 0 ? command : dropLeadingOptions(command.slice(runnerLength));
60
+ const [publisher, ...rest] = launched;
61
+
62
+ return publisher !== undefined &&
63
+ publishers.has(publisher) &&
64
+ rest.find((word) => !word.startsWith('-')) === 'publish'
65
+ ? `${publisher} publish`
66
+ : undefined;
67
+ }
68
+
69
+ function countRunnerWords(command: readonly string[]): number {
70
+ const [first, second] = command;
71
+
72
+ if (first === 'npx' || first === 'bunx') {
73
+ return 1;
74
+ }
75
+
76
+ return first === 'bun' && second === 'x' ? 2 : 0;
77
+ }
78
+
79
+ function dropLeadingOptions(words: readonly string[]): string[] {
80
+ const index = words.findIndex((word) => !word.startsWith('-'));
81
+
82
+ return index === -1 ? [] : words.slice(index);
83
+ }
@@ -0,0 +1,55 @@
1
+ import { findMember } from '../find-member.ts';
2
+ import type { Job } from '../types.ts';
3
+ import { collectConditionTerms } from './collect-condition-terms.ts';
4
+ import { collectNeeds } from './collect-needs.ts';
5
+ import { findJobEnvironment } from './find-job-environment.ts';
6
+
7
+ // The jobs of a release: each job in the release environment, and each job that needs one and runs
8
+ // only when the release succeeded. In main.yml the job `release` counts too, because a job that
9
+ // calls a shared workflow can't set an environment.
10
+ export function collectReleaseJobs(jobs: readonly Job[], isMainRun: boolean): Set<string> {
11
+ const releaseJobs = new Set(
12
+ jobs
13
+ .filter((job) => findJobEnvironment(job) === 'release' || (isMainRun && job.id === 'release'))
14
+ .map((job) => job.id),
15
+ );
16
+
17
+ let hasGrown = true;
18
+
19
+ while (hasGrown) {
20
+ hasGrown = false;
21
+
22
+ for (const job of jobs) {
23
+ if (!releaseJobs.has(job.id) && isFollowingRelease(job, releaseJobs)) {
24
+ releaseJobs.add(job.id);
25
+
26
+ hasGrown = true;
27
+ }
28
+ }
29
+ }
30
+
31
+ return releaseJobs;
32
+ }
33
+
34
+ const statusFunctionPattern = /\b(?:always|cancelled|failure)\s*\(/iu;
35
+
36
+ // A job that needs a release job runs after the release succeeded, unless its condition names a
37
+ // status function, such as always(), which also runs it after a failed or skipped release. Then it
38
+ // must say that the release it needs succeeded.
39
+ function isFollowingRelease(job: Job, releaseJobs: ReadonlySet<string>): boolean {
40
+ const needed = collectNeeds(job).filter((need) => releaseJobs.has(need));
41
+
42
+ if (needed.length === 0) {
43
+ return false;
44
+ }
45
+
46
+ const condition = findMember(job.definition, 'if');
47
+
48
+ if (typeof condition !== 'string' || !statusFunctionPattern.test(condition)) {
49
+ return true;
50
+ }
51
+
52
+ const terms = collectConditionTerms(condition);
53
+
54
+ return needed.some((need) => terms?.includes(`needs.${need}.result=='success'`) === true);
55
+ }