Skip to content

Commit 73d9b6d

Browse files
henrymercerCopilot
andcommitted
Generate the Deflake workflow list in pr-checks/sync.ts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 9ee158c commit 73d9b6d

5 files changed

Lines changed: 272 additions & 15 deletions

File tree

‎.github/workflows/deflake.yml‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,19 @@ name: Deflake
66
on:
77
workflow_run:
88
types: [completed]
9-
# Exclude workflows that have significant side effects, like publishing releases. It's OK to
10-
# retry CodeQL analysis.
9+
# Generated by `pr-checks/sync.sh` from the templates in `pr-checks/checks` and the other
10+
# workflows listed in `pr-checks/deflake.ts`.
1111
workflows:
12-
- Check Expected Release Files
13-
- Code-Scanning config CLI tests
14-
- CodeQL action
15-
- Manual Check - go
12+
- "Check Expected Release Files"
13+
- "Code-Scanning config CLI tests"
14+
- "CodeQL action"
15+
- "Manual Check - go"
1616
- "PR Check - All-platform bundle"
1717
- "PR Check - Analysis kinds"
1818
- "PR Check - Analyze: 'ref' and 'sha' from inputs"
19-
- "PR Check - autobuild-action"
2019
- "PR Check - Autobuild direct tracing (custom working directory)"
2120
- "PR Check - Autobuild working directory"
21+
- "PR Check - autobuild-action"
2222
- "PR Check - Build mode autobuild"
2323
- "PR Check - Build mode manual"
2424
- "PR Check - Build mode none"
@@ -40,8 +40,8 @@ on:
4040
- "PR Check - Export file baseline information"
4141
- "PR Check - Extractor ram and threads options test"
4242
- "PR Check - Go: Custom queries"
43-
- "PR Check - Go: diagnostic when Go is changed after init step"
4443
- "PR Check - Go: diagnostic when `file` is not installed"
44+
- "PR Check - Go: diagnostic when Go is changed after init step"
4545
- "PR Check - Go: tracing with autobuilder step"
4646
- "PR Check - Go: tracing with custom build steps"
4747
- "PR Check - Go: tracing with legacy workflow"
@@ -73,17 +73,15 @@ on:
7373
- "PR Check - Unsupported macOS"
7474
- "PR Check - Upload-sarif: 'ref' and 'sha' from inputs"
7575
- "PR Check - Use a custom `checkout_path`"
76-
- PR Checks
77-
- Query filters tests
78-
- Test that the workaround for python 3.12 on windows works
76+
- "PR Checks"
77+
- "Query filters tests"
78+
- "Test that the workaround for python 3.12 on windows works"
7979

8080
jobs:
8181
rerun-on-failure:
8282
name: Rerun failed jobs
8383
if: >-
84-
github.event.workflow_run.conclusion == 'failure' &&
85-
github.event.workflow_run.run_attempt == 1 &&
86-
(
84+
github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt == 1 && (
8785
github.event.workflow_run.head_branch == 'main' ||
8886
startsWith(github.event.workflow_run.head_branch, 'releases/') ||
8987
github.event.workflow_run.event == 'merge_group'

‎pr-checks/deflake.test.ts‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
#!/usr/bin/env npx tsx
2+
3+
/*
4+
Tests for `deflake.ts`.
5+
*/
6+
7+
import * as assert from "node:assert/strict";
8+
import { describe, it } from "node:test";
9+
10+
import { escapeWorkflowName, setWorkflowRunWorkflows } from "./deflake";
11+
12+
describe("escapeWorkflowName", async () => {
13+
await it("escapes the characters that filter patterns treat as glob syntax", () => {
14+
assert.equal(
15+
escapeWorkflowName(
16+
String.raw`!Name with C/C++, [a-z]?, *, ! and \ in it`,
17+
),
18+
String.raw`\!Name with C/C\+\+, \[a-z]\?, \*, \! and \\ in it`,
19+
);
20+
});
21+
22+
await it("leaves names without glob syntax unchanged", () => {
23+
const name = "PR Check - Upload-sarif: 'ref' and `sha` (Linux) ]";
24+
assert.equal(escapeWorkflowName(name), name);
25+
});
26+
});
27+
28+
describe("setWorkflowRunWorkflows", async () => {
29+
await it("replaces the list with sorted, escaped names and leaves the rest of the workflow unchanged", () => {
30+
const workflow = `on:
31+
workflow_run:
32+
types: [completed]
33+
# A comment about the list.
34+
workflows:
35+
- Existing workflow
36+
# A comment within the list.
37+
- "Removed workflow"
38+
39+
jobs:
40+
rerun:
41+
if: |-
42+
github.event.workflow_run.conclusion == 'failure' &&
43+
github.event.workflow_run.run_attempt == 1
44+
`;
45+
assert.equal(
46+
setWorkflowRunWorkflows(workflow, [
47+
"PR Check - b",
48+
"PR Check - C/C++",
49+
"Existing workflow",
50+
"PR Check - a",
51+
]),
52+
String.raw`on:
53+
workflow_run:
54+
types: [completed]
55+
# A comment about the list.
56+
workflows:
57+
- "Existing workflow"
58+
- "PR Check - a"
59+
- "PR Check - b"
60+
- "PR Check - C/C\\+\\+"
61+
62+
jobs:
63+
rerun:
64+
if: |-
65+
github.event.workflow_run.conclusion == 'failure' &&
66+
github.event.workflow_run.run_attempt == 1
67+
`,
68+
);
69+
});
70+
71+
await it("uses single quotes only for patterns that contain double quotes and no backslashes", () => {
72+
// These are the quotes that Prettier uses when formatting these strings.
73+
assert.equal(
74+
setWorkflowRunWorkflows(
75+
"on:\n workflow_run:\n workflows:\n - Old\n",
76+
['Upload "quoted" SARIF', `It's "quoted"`, 'C++ "quoted"'],
77+
),
78+
String.raw`on:
79+
workflow_run:
80+
workflows:
81+
- "C\\+\\+ \"quoted\""
82+
- 'It''s "quoted"'
83+
- 'Upload "quoted" SARIF'
84+
`,
85+
);
86+
});
87+
88+
await it("leaves comments and keys after the last item unchanged", () => {
89+
const after = ` # A comment after the list.
90+
91+
branches: [main]
92+
`;
93+
assert.equal(
94+
setWorkflowRunWorkflows(
95+
`on:\n workflow_run:\n workflows:\n - Old\n${after}`,
96+
["New"],
97+
),
98+
`on:\n workflow_run:\n workflows:\n - "New"\n${after}`,
99+
);
100+
});
101+
102+
await it("returns an up-to-date workflow unchanged", () => {
103+
const workflow = String.raw`on:
104+
workflow_run:
105+
workflows:
106+
- "C/C\\+\\+"
107+
- "Other"
108+
`;
109+
assert.equal(
110+
setWorkflowRunWorkflows(workflow, ["Other", "C/C++"]),
111+
workflow,
112+
);
113+
});
114+
115+
await it("writes a flow sequence as a block sequence", () => {
116+
assert.equal(
117+
setWorkflowRunWorkflows("on:\n workflow_run:\n workflows: [Old]\n", [
118+
"New",
119+
]),
120+
'on:\n workflow_run:\n workflows:\n - "New"\n',
121+
);
122+
});
123+
124+
await it("throws if the workflow isn't valid YAML", () => {
125+
// Duplicate keys are an error in the `yaml` library, though Prettier accepts them.
126+
assert.throws(
127+
() =>
128+
setWorkflowRunWorkflows(
129+
"on:\n workflow_run:\n workflows:\n - Old\njobs: {}\njobs: {}\n",
130+
["New"],
131+
),
132+
/Failed to parse the workflow: .* at line 6, column 1/,
133+
);
134+
});
135+
136+
await it("throws if the workflow has no workflow_run trigger", () => {
137+
assert.throws(
138+
() => setWorkflowRunWorkflows("on:\n push: {}\n", ["Other"]),
139+
/Expected `on.workflow_run.workflows` to be a sequence/,
140+
);
141+
});
142+
});

‎pr-checks/deflake.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import * as fs from "fs";
2+
import * as path from "path";
3+
4+
import * as yaml from "yaml";
5+
6+
import { REPO_ROOT } from "./config";
7+
8+
/** The path of the workflow that reruns failed jobs in other workflows. */
9+
const DEFLAKE_WORKFLOW_FILE = path.join(
10+
REPO_ROOT,
11+
".github",
12+
"workflows",
13+
"deflake.yml",
14+
);
15+
16+
/**
17+
* The names of workflows that `sync.ts` doesn't generate, but whose failed jobs the Deflake
18+
* workflow should rerun.
19+
*
20+
* Exclude workflows that have significant side effects, like publishing releases. It's OK to retry
21+
* CodeQL analysis.
22+
*/
23+
const NON_GENERATED_WORKFLOWS_TO_RERUN = [
24+
"Check Expected Release Files",
25+
"Code-Scanning config CLI tests",
26+
"CodeQL action",
27+
"PR Check - Debug artifact upload",
28+
"PR Check - Debug artifacts after failure",
29+
"PR Checks",
30+
"Query filters tests",
31+
"Test that the workaround for python 3.12 on windows works",
32+
];
33+
34+
/**
35+
* Escapes the characters in a workflow name that `on.workflow_run.workflows` would otherwise treat
36+
* as glob syntax.
37+
*
38+
* @returns A pattern that matches only the workflow called `name`.
39+
*/
40+
export function escapeWorkflowName(name: string): string {
41+
// These are the characters that can be escaped in GitHub Actions filter patterns. `]` is only
42+
// special after an unescaped `[`, so it doesn't need escaping.
43+
return name.replace(/[\\[?*+!]/g, "\\$&");
44+
}
45+
46+
/**
47+
* Replaces the items in the `on.workflow_run.workflows` list of a workflow, and any comments on
48+
* their lines or between them, with patterns that match the workflows called `workflowNames`,
49+
* sorted by name. The list is written as a block sequence.
50+
*
51+
* The whole workflow is rewritten with the `yaml` library, so any other parts that aren't
52+
* formatted the way that library formats them are reformatted, for example by joining lines of
53+
* folded (`>`) block scalars. Prettier, which checks the formatting of YAML files in this
54+
* repository, formats non-empty flow mappings, and flow sequences that don't fit within 80
55+
* columns, differently from that library, so the workflow is expected not to contain any.
56+
*
57+
* @param workflow The contents of the workflow file.
58+
* @param workflowNames The names of the workflows that should trigger the workflow.
59+
* @returns The updated contents of the workflow file.
60+
* @throws If the workflow isn't valid YAML, or `on.workflow_run.workflows` isn't a sequence.
61+
*/
62+
export function setWorkflowRunWorkflows(
63+
workflow: string,
64+
workflowNames: string[],
65+
): string {
66+
const document = yaml.parseDocument(workflow);
67+
if (document.errors.length > 0) {
68+
throw new Error(
69+
`Failed to parse the workflow: ${document.errors[0].message}`,
70+
);
71+
}
72+
const workflows = document.getIn(["on", "workflow_run", "workflows"], true);
73+
if (!yaml.isSeq(workflows)) {
74+
throw new Error("Expected `on.workflow_run.workflows` to be a sequence.");
75+
}
76+
77+
workflows.flow = false;
78+
workflows.items = workflowNames
79+
.toSorted((a, b) => a.localeCompare(b, "en"))
80+
.map((name) => {
81+
const pattern = escapeWorkflowName(name);
82+
const item = new yaml.Scalar(pattern);
83+
// Quote the pattern in the same way as Prettier, which uses single quotes for strings that
84+
// contain `"` but no `\`, and double quotes otherwise.
85+
item.type =
86+
pattern.includes('"') && !pattern.includes("\\")
87+
? yaml.Scalar.QUOTE_SINGLE
88+
: yaml.Scalar.QUOTE_DOUBLE;
89+
return item;
90+
});
91+
// These options match how Prettier formats short flow sequences, such as `[completed]`, and long
92+
// strings.
93+
return document.toString({ flowCollectionPadding: false, lineWidth: 0 });
94+
}
95+
96+
/**
97+
* Updates the Deflake workflow so that it reruns failed jobs in the workflows called
98+
* `generatedWorkflowNames` and in {@link NON_GENERATED_WORKFLOWS_TO_RERUN}.
99+
*/
100+
export function updateDeflakeWorkflow(generatedWorkflowNames: string[]): void {
101+
console.log(`Updating the list of workflows in '${DEFLAKE_WORKFLOW_FILE}'.`);
102+
const workflow = fs.readFileSync(DEFLAKE_WORKFLOW_FILE, "utf8");
103+
fs.writeFileSync(
104+
DEFLAKE_WORKFLOW_FILE,
105+
setWorkflowRunWorkflows(workflow, [
106+
...generatedWorkflowNames,
107+
...NON_GENERATED_WORKFLOWS_TO_RERUN,
108+
]),
109+
"utf8",
110+
);
111+
}

‎pr-checks/readme.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ to one of the files in this directory.
66

77
## Updating workflows
88

9-
Run `./sync.sh` to invoke the workflow generator and re-generate the workflow files in `.github/workflows/` based on the templates in `pr-checks/checks/`.
9+
Run `./sync.sh` to invoke the workflow generator and re-generate the workflow files in `.github/workflows/` based on the templates in `pr-checks/checks/`. This also updates the list of workflows whose failed jobs `.github/workflows/deflake.yml` reruns.
1010

1111
Alternatively, you can use `just`:
1212

‎pr-checks/sync.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import * as yaml from "yaml";
88
import { BuiltInLanguage } from "../src/languages";
99

1010
import { PR_CHECKS_DIR, REPO_ROOT } from "./config";
11+
import { updateDeflakeWorkflow } from "./deflake";
1112

1213
/**
1314
* Returns a `uses` value for `action` pinned to a commit SHA, with the
@@ -747,6 +748,7 @@ function main(): void {
747748

748749
console.log(`Found ${checkFiles.length} check specification(s).`);
749750

751+
const generatedWorkflowNames: string[] = [];
750752
const collections: Record<
751753
string,
752754
Array<{
@@ -834,6 +836,7 @@ function main(): void {
834836

835837
const outputPath = path.join(OUTPUT_DIR, `__${checkName}.yml`);
836838
writeYaml(outputPath, workflow);
839+
generatedWorkflowNames.push(workflow.name);
837840
}
838841

839842
// Write workflow files for collections.
@@ -878,8 +881,11 @@ function main(): void {
878881

879882
const outputPath = path.join(OUTPUT_DIR, `__${collectionName}.yml`);
880883
writeYaml(outputPath, collectionWorkflow);
884+
generatedWorkflowNames.push(collectionWorkflow.name);
881885
}
882886

887+
updateDeflakeWorkflow(generatedWorkflowNames);
888+
883889
console.log(
884890
`\nDone. Wrote ${checkFiles.length} workflow file(s) to ${OUTPUT_DIR}`,
885891
);

0 commit comments

Comments
 (0)