@zgeoff/chex 0.8.7 → 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 (50) hide show
  1. package/README.md +1 -1
  2. package/lefthook.yml +13 -0
  3. package/package.json +1 -1
  4. package/src/ci-plan/build-ci-plan-output.ts +1 -37
  5. package/src/ci-plan/collect-shared-checks.ts +1 -41
  6. package/src/ci-plan/find-chex-args.ts +40 -0
  7. package/src/ci-plan/parse-package-scripts.ts +36 -0
  8. package/src/workflows/collect-allowances.ts +101 -0
  9. package/src/workflows/collect-concurrency-findings.ts +1 -1
  10. package/src/workflows/collect-hook-findings.ts +13 -0
  11. package/src/workflows/collect-moved-repo-findings.ts +34 -0
  12. package/src/workflows/collect-run-commands.ts +18 -0
  13. package/src/workflows/collect-runner-labels.ts +8 -0
  14. package/src/workflows/collect-steps.ts +9 -0
  15. package/src/workflows/constants.ts +4 -0
  16. package/src/workflows/find-heavy-runner.ts +20 -0
  17. package/src/workflows/is-list.ts +4 -0
  18. package/src/workflows/parse-repo-slug.ts +7 -0
  19. package/src/workflows/pick-checked-paths.ts +33 -0
  20. package/src/workflows/pick-repo-move.ts +28 -0
  21. package/src/workflows/read-repo-slug.ts +12 -0
  22. package/src/workflows/read-repo-state.ts +57 -0
  23. package/src/workflows/rules/build-rule-finding.ts +10 -0
  24. package/src/workflows/rules/collect-condition-terms.ts +116 -0
  25. package/src/workflows/rules/collect-hook-check-findings.ts +84 -0
  26. package/src/workflows/rules/collect-main-only-job-findings.ts +123 -0
  27. package/src/workflows/rules/collect-main-run-concurrency-findings.ts +77 -0
  28. package/src/workflows/rules/collect-main-run-shape-findings.ts +161 -0
  29. package/src/workflows/rules/collect-needs.ts +13 -0
  30. package/src/workflows/rules/collect-path-filter-findings.ts +56 -0
  31. package/src/workflows/rules/collect-pr-gate-findings.ts +72 -0
  32. package/src/workflows/rules/collect-publish-findings.ts +83 -0
  33. package/src/workflows/rules/collect-release-jobs.ts +55 -0
  34. package/src/workflows/rules/collect-release-shape-findings.ts +67 -0
  35. package/src/workflows/rules/find-file-filter.ts +91 -0
  36. package/src/workflows/rules/find-image-build.ts +59 -0
  37. package/src/workflows/rules/find-job-environment.ts +9 -0
  38. package/src/workflows/rules/find-matrix-runner.ts +38 -0
  39. package/src/workflows/rules/find-shipped-build.ts +36 -0
  40. package/src/workflows/rules/is-arm-label.ts +5 -0
  41. package/src/workflows/rules/is-release-condition.ts +19 -0
  42. package/src/workflows/rules/is-shared-check-script.ts +22 -0
  43. package/src/workflows/rules/is-shared-release-workflow.ts +14 -0
  44. package/src/workflows/rules/is-workflow-call.ts +12 -0
  45. package/src/workflows/rules/types.ts +31 -0
  46. package/src/workflows/run-workflows-check.ts +60 -55
  47. package/src/workflows/to-unwrapped-command.ts +28 -0
  48. package/src/workflows/to-workflow-findings.ts +24 -0
  49. package/src/workflows/types.ts +68 -0
  50. package/src/workflows/workflow-context.ts +0 -24
package/README.md CHANGED
@@ -58,7 +58,7 @@ Run these repo checks on the branch, the pushed commits and the repo's config:
58
58
  | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
59
59
  | `lint-overrides` | an oxlint config that turns a `zgeoff/*` rule, `consistent-type-assertions` or `ban-ts-comment` off or down to a warning, a config in code (`oxlint.config.ts` or `.mts`), or a config that the last commit does not hold as a plain file or that does not parse; it reads each file or symlink named `.oxlintrc*.json` or `.oxlintrc*.jsonc`, each path a `package.json` script gives `oxlint` with `-c` or `--config`, the file each symlink reaches, and each file a config extends by a relative path | none |
60
60
  | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md), where test code covers a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
- | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
61
+ | `workflows` | nothing: it prints each fault of the shared workflow lint, and in a repo that calls the shared `checks.yml` each break of the [ci-design](https://github.com/zgeoff/skills/blob/main/skills/ci-design/SKILL.md) rules, and fails when there is one |
62
62
  | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
63
  | `uncommitted` | a file the branch changes that has an uncommitted edit, which the push does not send | none |
64
64
  | `pr-body` | a PR description with a heading, a label or a code block that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow, or a Deslop or Cold read line with a commit hash the branch lacks or a later doc change outdates ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
package/lefthook.yml CHANGED
@@ -107,6 +107,19 @@ pre-push:
107
107
  fi
108
108
  bun x --no-install diet -- bun x --no-install chex workflows {files} || status=1
109
109
  exit "$status"
110
+ # In a moved repo the workflow rules also read .github/ci.yml, package.json
111
+ # and the lefthook files, so a change to one of them runs the lint over
112
+ # every workflow and hook. actionlint reads workflows only, so these files
113
+ # get a job of their own.
114
+ - name: chex-workflow-config
115
+ files:
116
+ unset $(git rev-parse --local-env-vars); bun
117
+ node_modules/@zgeoff/chex/src/branch/read-branch-files.ts
118
+ glob:
119
+ - '.github/ci.yml'
120
+ - 'package.json'
121
+ - 'lefthook.{yml,yaml}'
122
+ run: '{clear-git-env} bun x --no-install diet -- bun x --no-install chex workflows {files}'
110
123
  # git lists the refs a push sends on the hook's stdin, and lefthook hands
111
124
  # stdin only to a job that asks for it. lefthook 2.2.2 skips a pre-push
112
125
  # job whose run substitutes no file when the checked-out branch has
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/chex",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "Run each shared docs and repo check as one subcommand, with the lefthook pre-push baseline that calls them",
5
5
  "keywords": [
6
6
  "checks",
@@ -1,4 +1,5 @@
1
1
  import { parseCIPlan } from './parse-ci-plan.ts';
2
+ import { parsePackageScripts } from './parse-package-scripts.ts';
2
3
 
3
4
  export interface CIPlanOutput {
4
5
  readonly exitCode: number;
@@ -24,43 +25,6 @@ export function buildCIPlanOutput(
24
25
  return { exitCode: 0, lines: [JSON.stringify(outcome.plan)] };
25
26
  }
26
27
 
27
- type PackageScripts =
28
- | { readonly kind: 'read'; readonly scripts: Readonly<Record<string, string>> | undefined }
29
- | { readonly kind: 'invalid'; readonly message: string };
30
-
31
- function parsePackageScripts(packageText: string | undefined): PackageScripts {
32
- if (packageText === undefined) {
33
- return { kind: 'read', scripts: undefined };
34
- }
35
-
36
- let packageJSON: unknown;
37
-
38
- try {
39
- packageJSON = JSON.parse(packageText);
40
- } catch {
41
- return { kind: 'invalid', message: 'package.json is not valid JSON; fix the syntax.' };
42
- }
43
-
44
- if (typeof packageJSON !== 'object' || packageJSON === null || !('scripts' in packageJSON)) {
45
- return { kind: 'read', scripts: {} };
46
- }
47
-
48
- const scripts = packageJSON.scripts;
49
-
50
- if (typeof scripts !== 'object' || scripts === null) {
51
- return { kind: 'read', scripts: {} };
52
- }
53
-
54
- return {
55
- kind: 'read',
56
- scripts: Object.fromEntries(
57
- Object.entries(scripts).filter(
58
- (entry): entry is [string, string] => typeof entry[1] === 'string',
59
- ),
60
- ),
61
- };
62
- }
63
-
64
28
  function buildErrorOutput(messages: readonly string[]): CIPlanOutput {
65
29
  return { exitCode: 1, lines: messages.map((message) => `::error::${escapeData(message)}`) };
66
30
  }
@@ -1,4 +1,5 @@
1
1
  import { parseChexArgs } from '../cli/parse-chex-args.ts';
2
+ import { findChexArgs } from './find-chex-args.ts';
2
3
 
3
4
  export function collectSharedChecks(command: string | undefined): readonly string[] {
4
5
  if (command === undefined) {
@@ -59,44 +60,3 @@ function splitSimpleCommands(command: string): string[][] {
59
60
 
60
61
  return commands.filter((words) => words.length > 0);
61
62
  }
62
-
63
- const chexWord = /(?:^|\/)chex$|^@zgeoff\/chex(?:@\S*)?$/u;
64
- const assignment = /^\w+=/u;
65
-
66
- // The arguments after chex when the command runs chex itself, as a path, or through bunx, npx or
67
- // bun x. A command that only mentions chex as an argument, such as echo chex, runs no check.
68
- function findChexArgs(words: readonly string[]): readonly string[] | undefined {
69
- const start = words.findIndex((word) => !assignment.test(word));
70
- const [first, second] = words.slice(start);
71
-
72
- if (start === -1 || first === undefined) {
73
- return undefined;
74
- }
75
-
76
- if (chexWord.test(first)) {
77
- return words.slice(start + 1);
78
- }
79
-
80
- const runnerLength = runnerWordCount(first, second);
81
-
82
- if (runnerLength === 0) {
83
- return undefined;
84
- }
85
-
86
- const rest = words.slice(start + runnerLength);
87
- const toolIndex = rest.findIndex((word) => !word.startsWith('-'));
88
- const tool = rest[toolIndex];
89
- const args = rest.slice(toolIndex + 1);
90
-
91
- return tool !== undefined && chexWord.test(tool) ? args : undefined;
92
- }
93
-
94
- const runners = new Set(['bunx', 'npx']);
95
-
96
- function runnerWordCount(first: string, second: string | undefined): number {
97
- if (runners.has(first)) {
98
- return 1;
99
- }
100
-
101
- return first === 'bun' && second === 'x' ? 2 : 0;
102
- }
@@ -0,0 +1,40 @@
1
+ const chexWord = /(?:^|\/)chex$|^@zgeoff\/chex(?:@\S*)?$/u;
2
+ const assignment = /^\w+=/u;
3
+
4
+ // The arguments after chex when the command runs chex itself, as a path, or through bunx, npx or
5
+ // bun x. A command that only mentions chex as an argument, such as echo chex, runs no check.
6
+ export function findChexArgs(words: readonly string[]): readonly string[] | undefined {
7
+ const start = words.findIndex((word) => !assignment.test(word));
8
+ const [first, second] = words.slice(start);
9
+
10
+ if (start === -1 || first === undefined) {
11
+ return undefined;
12
+ }
13
+
14
+ if (chexWord.test(first)) {
15
+ return words.slice(start + 1);
16
+ }
17
+
18
+ const runnerLength = runnerWordCount(first, second);
19
+
20
+ if (runnerLength === 0) {
21
+ return undefined;
22
+ }
23
+
24
+ const rest = words.slice(start + runnerLength);
25
+ const toolIndex = rest.findIndex((word) => !word.startsWith('-'));
26
+ const tool = rest[toolIndex];
27
+ const args = rest.slice(toolIndex + 1);
28
+
29
+ return tool !== undefined && chexWord.test(tool) ? args : undefined;
30
+ }
31
+
32
+ const runners = new Set(['bunx', 'npx']);
33
+
34
+ function runnerWordCount(first: string, second: string | undefined): number {
35
+ if (runners.has(first)) {
36
+ return 1;
37
+ }
38
+
39
+ return first === 'bun' && second === 'x' ? 2 : 0;
40
+ }
@@ -0,0 +1,36 @@
1
+ type PackageScripts =
2
+ | { readonly kind: 'read'; readonly scripts: Readonly<Record<string, string>> | undefined }
3
+ | { readonly kind: 'invalid'; readonly message: string };
4
+
5
+ export function parsePackageScripts(packageText: string | undefined): PackageScripts {
6
+ if (packageText === undefined) {
7
+ return { kind: 'read', scripts: undefined };
8
+ }
9
+
10
+ let packageJSON: unknown;
11
+
12
+ try {
13
+ packageJSON = JSON.parse(packageText);
14
+ } catch {
15
+ return { kind: 'invalid', message: 'package.json is not valid JSON; fix the syntax.' };
16
+ }
17
+
18
+ if (typeof packageJSON !== 'object' || packageJSON === null || !('scripts' in packageJSON)) {
19
+ return { kind: 'read', scripts: {} };
20
+ }
21
+
22
+ const scripts = packageJSON.scripts;
23
+
24
+ if (typeof scripts !== 'object' || scripts === null) {
25
+ return { kind: 'read', scripts: {} };
26
+ }
27
+
28
+ return {
29
+ kind: 'read',
30
+ scripts: Object.fromEntries(
31
+ Object.entries(scripts).filter(
32
+ (entry): entry is [string, string] => typeof entry[1] === 'string',
33
+ ),
34
+ ),
35
+ };
36
+ }
@@ -0,0 +1,101 @@
1
+ import { LineCounter, Parser } from 'yaml';
2
+ import { ruleNames } from './rules/types.ts';
3
+ import type { Allowances } from './types.ts';
4
+
5
+ const commentPattern = /^#\s*chex-allow\b(?<rest>.*)$/u;
6
+ const entryPattern = /^\s+(?<name>[\w-]+)\s*:\s*(?:\S.*)$/u;
7
+ const nameOnlyPattern = /^\s+(?<name>[\w-]+)\s*:?\s*$/u;
8
+
9
+ // A comment covers the key on its own line, or the line below when the comment stands alone. Only
10
+ // a YAML comment counts: the same text inside a value, a quoted key or a block scalar is data.
11
+ export function collectAllowances(lines: readonly string[]): Allowances {
12
+ const covered = new Set<string>();
13
+
14
+ const faults: { line: number; message: string }[] = [];
15
+
16
+ for (const comment of collectComments(lines)) {
17
+ const line = comment.line;
18
+ const rest = commentPattern.exec(comment.source)?.groups?.['rest'];
19
+
20
+ if (rest === undefined) {
21
+ continue;
22
+ }
23
+
24
+ const entry = entryPattern.exec(rest);
25
+ const name = (entry ?? nameOnlyPattern.exec(rest))?.groups?.['name'];
26
+
27
+ if (name === undefined) {
28
+ faults.push({
29
+ line,
30
+ message: `chex-allow: the comment names no rule; write # chex-allow <rule>: <reason>`,
31
+ });
32
+ } else if (!ruleNames.some((rule) => rule === name)) {
33
+ faults.push({
34
+ line,
35
+ message: `chex-allow: "${name}" is not a rule; use one of ${ruleNames.join(', ')}`,
36
+ });
37
+ } else if (entry === null) {
38
+ faults.push({
39
+ line,
40
+ message: `chex-allow: the comment for ${name} gives no reason; write # chex-allow ${name}: <reason>`,
41
+ });
42
+ } else {
43
+ covered.add(`${name}:${comment.isAlone ? line + 1 : line}`);
44
+ }
45
+ }
46
+
47
+ return { covered, faults };
48
+ }
49
+
50
+ interface YAMLComment {
51
+ readonly line: number;
52
+ readonly source: string;
53
+
54
+ // Whether nothing but spaces comes before the comment on its line.
55
+ readonly isAlone: boolean;
56
+ }
57
+
58
+ function collectComments(lines: readonly string[]): YAMLComment[] {
59
+ const comments: YAMLComment[] = [];
60
+
61
+ const lineCounter = new LineCounter();
62
+
63
+ const text = lines.join('\n');
64
+
65
+ const visit = (node: unknown): void => {
66
+ if (Array.isArray(node)) {
67
+ for (const member of node) {
68
+ visit(member);
69
+ }
70
+
71
+ return;
72
+ }
73
+
74
+ if (typeof node !== 'object' || node === null) {
75
+ return;
76
+ }
77
+
78
+ const type: unknown = Reflect.get(node, 'type');
79
+ const offset: unknown = Reflect.get(node, 'offset');
80
+ const source: unknown = Reflect.get(node, 'source');
81
+
82
+ if (type === 'comment' && typeof offset === 'number' && typeof source === 'string') {
83
+ const position = lineCounter.linePos(offset);
84
+ const before = (lines[position.line - 1] ?? '').slice(0, position.col - 1);
85
+
86
+ comments.push({ line: position.line, source, isAlone: before.trim() === '' });
87
+ }
88
+
89
+ for (const member of Object.values(node)) {
90
+ visit(member);
91
+ }
92
+ };
93
+
94
+ for (const token of new Parser((offset) => {
95
+ lineCounter.addNewLine(offset);
96
+ }).parse(text)) {
97
+ visit(token);
98
+ }
99
+
100
+ return comments;
101
+ }
@@ -2,7 +2,7 @@ import { collectExpressionReferences } from './collect-expression-references.ts'
2
2
  import { findMember } from './find-member.ts';
3
3
  import { getTopLevelLine } from './get-top-level-line.ts';
4
4
  import { pullRequestTriggers } from './pull-request-triggers.ts';
5
- import type { Job, WorkflowContext, WorkflowFinding } from './workflow-context.ts';
5
+ import type { Job, WorkflowContext, WorkflowFinding } from './types.ts';
6
6
 
7
7
  export function collectConcurrencyFindings(context: WorkflowContext): WorkflowFinding[] {
8
8
  const deployJobs = context.jobs.filter((job) => isDeployJob(job));
@@ -0,0 +1,13 @@
1
+ import { collectAllowances } from './collect-allowances.ts';
2
+ import { collectHookCheckFindings } from './rules/collect-hook-check-findings.ts';
3
+ import { toWorkflowFindings } from './to-workflow-findings.ts';
4
+ import type { HookFile, MovedRepo, WorkflowFinding } from './types.ts';
5
+
6
+ // The pre-push hook's findings, in the lefthook file that holds the hook.
7
+ export function collectHookFindings(hook: HookFile, repo: MovedRepo): WorkflowFinding[] {
8
+ return toWorkflowFindings(
9
+ collectHookCheckFindings(hook, repo),
10
+ hook.path,
11
+ collectAllowances(hook.lines),
12
+ );
13
+ }
@@ -0,0 +1,34 @@
1
+ import { collectAllowances } from './collect-allowances.ts';
2
+ import { collectMainOnlyJobFindings } from './rules/collect-main-only-job-findings.ts';
3
+ import { collectMainRunConcurrencyFindings } from './rules/collect-main-run-concurrency-findings.ts';
4
+ import { collectMainRunShapeFindings } from './rules/collect-main-run-shape-findings.ts';
5
+ import { collectPathFilterFindings } from './rules/collect-path-filter-findings.ts';
6
+ import { collectPrGateFindings } from './rules/collect-pr-gate-findings.ts';
7
+ import { collectPublishFindings } from './rules/collect-publish-findings.ts';
8
+ import { collectReleaseShapeFindings } from './rules/collect-release-shape-findings.ts';
9
+ import type { WorkflowRule } from './rules/types.ts';
10
+ import { toWorkflowFindings } from './to-workflow-findings.ts';
11
+ import type { MovedRepo, WorkflowContext, WorkflowFinding } from './types.ts';
12
+
13
+ const workflowRules: readonly WorkflowRule[] = [
14
+ collectMainOnlyJobFindings,
15
+ collectPrGateFindings,
16
+ collectMainRunConcurrencyFindings,
17
+ collectMainRunShapeFindings,
18
+ collectReleaseShapeFindings,
19
+ collectPathFilterFindings,
20
+ collectPublishFindings,
21
+ ];
22
+
23
+ // The rules of a moved repo that read one workflow file under .github/workflows/, less the findings
24
+ // that a chex-allow comment turns off, plus the faults of the comments themselves.
25
+ export function collectMovedRepoFindings(
26
+ workflow: WorkflowContext,
27
+ repo: MovedRepo,
28
+ ): WorkflowFinding[] {
29
+ return toWorkflowFindings(
30
+ workflowRules.flatMap((rule) => rule(workflow, repo)),
31
+ workflow.path,
32
+ collectAllowances(workflow.lines),
33
+ );
34
+ }
@@ -0,0 +1,18 @@
1
+ import { parseShellWords } from '../shell/parse-shell-words.ts';
2
+ import type { ShellWord } from '../shell/parse-shell-words.ts';
3
+
4
+ // Each simple command of a run, as its words after any NAME=value assignments. A new line and each
5
+ // shell operator end a command.
6
+ export function collectRunCommands(run: string): ShellWord[][] {
7
+ const commands: ShellWord[][] = [[]];
8
+
9
+ for (const word of parseShellWords(run)) {
10
+ if (word.isOperator) {
11
+ commands.push([]);
12
+ } else if (!word.isAssignment || commands.at(-1)?.length !== 0) {
13
+ commands.at(-1)?.push(word);
14
+ }
15
+ }
16
+
17
+ return commands.filter((command) => command.length > 0);
18
+ }
@@ -0,0 +1,8 @@
1
+ import { findMember } from './find-member.ts';
2
+
3
+ // The labels of a runs-on value, whether it is one label, a list or a map with labels.
4
+ export function collectRunnerLabels(runsOn: unknown): string[] {
5
+ return [runsOn, findMember(runsOn, 'labels')]
6
+ .flat()
7
+ .filter((label): label is string => typeof label === 'string');
8
+ }
@@ -0,0 +1,9 @@
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 collectSteps(job: Job): readonly unknown[] {
6
+ const steps = findMember(job.definition, 'steps');
7
+
8
+ return isList(steps) ? steps : [];
9
+ }
@@ -0,0 +1,4 @@
1
+ export const expressionOpening = `\${{`;
2
+
3
+ // The lefthook files that the hook rules read, in the order they are read.
4
+ export const hookFilePaths = ['lefthook.yml', 'lefthook.yaml'];
@@ -0,0 +1,20 @@
1
+ import { collectRunnerLabels } from './collect-runner-labels.ts';
2
+ import { expressionOpening } from './constants.ts';
3
+ import { findMember } from './find-member.ts';
4
+
5
+ // Any runner but a GitHub-hosted Ubuntu one counts as heavy: macOS, Windows, self-hosted, or a
6
+ // runner group. A runner chosen by an expression is left alone, because GitHub resolves it only
7
+ // when the job runs.
8
+ export function findHeavyRunner(runsOn: unknown): string | undefined {
9
+ if (findMember(runsOn, 'group') !== undefined) {
10
+ return 'a runner group';
11
+ }
12
+
13
+ const labels = collectRunnerLabels(runsOn);
14
+
15
+ if (labels.some((label) => label.includes(expressionOpening))) {
16
+ return undefined;
17
+ }
18
+
19
+ return labels.find((label) => !label.startsWith('ubuntu-'));
20
+ }
@@ -0,0 +1,4 @@
1
+ // Array.isArray narrows to any[], which turns the type check off for each value.
2
+ export function isList(value: unknown): value is readonly unknown[] {
3
+ return Array.isArray(value);
4
+ }
@@ -0,0 +1,7 @@
1
+ const remotePattern =
2
+ /^(?:https?:\/\/(?:[^@/]+@)?|ssh:\/\/git@|git@)github\.com[:/](?<slug>[^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/u;
3
+
4
+ // The `owner/name` of a GitHub remote URL, or undefined for any other URL.
5
+ export function parseRepoSlug(remoteURL: string): string | undefined {
6
+ return remotePattern.exec(remoteURL.trim())?.groups?.['slug'];
7
+ }
@@ -0,0 +1,33 @@
1
+ import { hookFilePaths } from './constants.ts';
2
+ import type { HookFile, RepoState } from './types.ts';
3
+
4
+ interface CheckedPaths {
5
+ readonly workflows: readonly string[];
6
+ readonly hooks: readonly HookFile[];
7
+ }
8
+
9
+ const settingsPath = '.github/ci.yml';
10
+
11
+ // No path asks for every file. In a moved repo the rules read across files, so a path that is a
12
+ // workflow, .github/ci.yml, package.json or a lefthook file asks for every workflow and hook: its
13
+ // change can break the main run or the hook that the change did not touch.
14
+ export function pickCheckedPaths(
15
+ asked: readonly string[],
16
+ workflowPaths: readonly string[],
17
+ state: RepoState,
18
+ ): CheckedPaths {
19
+ const isAll =
20
+ asked.length === 0 ||
21
+ (state.repo !== undefined &&
22
+ asked.some(
23
+ (path) =>
24
+ path === settingsPath ||
25
+ path === 'package.json' ||
26
+ path.startsWith('.github/workflows/') ||
27
+ hookFilePaths.includes(path),
28
+ ));
29
+
30
+ return isAll
31
+ ? { workflows: workflowPaths, hooks: state.hooks }
32
+ : { workflows: workflowPaths.filter((path) => asked.includes(path)), hooks: [] };
33
+ }
@@ -0,0 +1,28 @@
1
+ import { findMember } from './find-member.ts';
2
+ import type { RepoMove } from './types.ts';
3
+
4
+ const sharedChecksPattern = /^zgeoff\/tools\/\.github\/workflows\/checks\.yml(?:@.*)?$/u;
5
+ const localChecksPath = './.github/workflows/checks.yml';
6
+
7
+ // A repo that calls the shared checks.yml gets the two-workflow rules; one that doesn't keeps the
8
+ // old rules until every repo has moved. A local call counts only in zgeoff/tools itself.
9
+ export function pickRepoMove(
10
+ workflows: readonly unknown[],
11
+ repoSlug: string | undefined,
12
+ ): RepoMove {
13
+ const calls = workflows.flatMap((workflow) => {
14
+ const jobs = findMember(workflow, 'jobs');
15
+
16
+ return typeof jobs === 'object' && jobs !== null
17
+ ? Object.values(jobs).map((job: unknown) => findMember(job, 'uses'))
18
+ : [];
19
+ });
20
+
21
+ if (repoSlug === 'zgeoff/tools' && calls.includes(localChecksPath)) {
22
+ return 'tools';
23
+ }
24
+
25
+ return calls.some((uses) => typeof uses === 'string' && sharedChecksPattern.test(uses))
26
+ ? 'shared'
27
+ : 'none';
28
+ }
@@ -0,0 +1,12 @@
1
+ import type { ProgramOptions, RunProgram } from '../program/run-program.ts';
2
+ import { parseRepoSlug } from './parse-repo-slug.ts';
3
+
4
+ // The `owner/name` of the origin remote, or undefined when the repo has no origin on GitHub.
5
+ export function readRepoSlug(
6
+ runProgram: RunProgram,
7
+ options: Readonly<ProgramOptions>,
8
+ ): string | undefined {
9
+ const result = runProgram(['git', 'remote', 'get-url', 'origin'], options);
10
+
11
+ return result.exitCode === 0 ? parseRepoSlug(result.stdout) : undefined;
12
+ }
@@ -0,0 +1,57 @@
1
+ import { parseCIPlan } from '../ci-plan/parse-ci-plan.ts';
2
+ import { parsePackageScripts } from '../ci-plan/parse-package-scripts.ts';
3
+ import { hookFilePaths } from './constants.ts';
4
+ import type { HookFile, RepoMove, RepoState } from './types.ts';
5
+
6
+ interface RepoFiles {
7
+ // Every tracked path.
8
+ readonly tracked: ReadonlySet<string>;
9
+
10
+ // The text of a tracked file at HEAD.
11
+ readonly readText: (path: string) => string;
12
+ }
13
+
14
+ const settingsPath = '.github/ci.yml';
15
+
16
+ export function readRepoState(move: RepoMove, files: Readonly<RepoFiles>): RepoState {
17
+ if (move === 'none') {
18
+ return { move, repo: undefined, hooks: [] };
19
+ }
20
+
21
+ const settingsText = files.tracked.has(settingsPath) ? files.readText(settingsPath) : undefined;
22
+
23
+ const packageText = files.tracked.has('package.json')
24
+ ? files.readText('package.json')
25
+ : undefined;
26
+
27
+ const packageScripts = parsePackageScripts(packageText);
28
+ const scripts = packageScripts.kind === 'read' ? packageScripts.scripts : undefined;
29
+
30
+ return {
31
+ move,
32
+ repo: {
33
+ move,
34
+ plan:
35
+ packageScripts.kind === 'invalid'
36
+ ? { kind: 'invalid', errors: [packageScripts.message] }
37
+ : parseCIPlan({ settingsText, packageScripts: scripts }),
38
+ packageScripts: scripts,
39
+ planLines: settingsText?.split('\n') ?? [],
40
+ },
41
+ hooks: hookFilePaths
42
+ .filter((path) => files.tracked.has(path))
43
+ .map((path) => readHook(path, files.readText(path))),
44
+ };
45
+ }
46
+
47
+ function readHook(path: string, text: string): HookFile {
48
+ let document: unknown;
49
+
50
+ try {
51
+ document = Bun.YAML.parse(text);
52
+ } catch {
53
+ document = undefined;
54
+ }
55
+
56
+ return { path, lines: text.split('\n'), document };
57
+ }
@@ -0,0 +1,10 @@
1
+ import type { RuleFinding, RuleName } from './types.ts';
2
+
3
+ export function buildRuleFinding(
4
+ rule: RuleName,
5
+ line: number,
6
+ text: string,
7
+ allowAt: readonly number[],
8
+ ): RuleFinding {
9
+ return { rule, path: undefined, line, message: `${rule}: ${text}`, allowAt };
10
+ }