Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions .github/workflows/deflake.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,26 @@ name: Deflake
on:
workflow_run:
types: [completed]
# Exclude workflows that have significant side effects, like publishing releases. It's OK to
# retry CodeQL analysis.
# Generated by `pr-checks/sync.sh` from the templates in `pr-checks/checks` and the other
# workflows listed in `pr-checks/deflake.ts`.
workflows:
- Check Expected Release Files
- Code-Scanning config CLI tests
- CodeQL action
- Manual Check - go
- "Check Expected Release Files"
- "Code-Scanning config CLI tests"
- "CodeQL action"
- "Manual Check - go"
- "PR Check - All-platform bundle"
- "PR Check - Analysis kinds"
- "PR Check - Analyze: 'ref' and 'sha' from inputs"
- "PR Check - autobuild-action"
- "PR Check - Autobuild direct tracing (custom working directory)"
- "PR Check - Autobuild working directory"
- "PR Check - autobuild-action"
- "PR Check - Build mode autobuild"
- "PR Check - Build mode manual"
- "PR Check - Build mode none"
- "PR Check - Build mode rollback"
- "PR Check - Bundle: Caching checks"
- "PR Check - Bundle: From nightly"
- "PR Check - Bundle: From toolcache"
- "PR Check - Bundle: Zstandard checks"
- "PR Check - C/C\\+\\+: autoinstalling dependencies (Linux)"
- "PR Check - C/C\\+\\+: autoinstalling dependencies is skipped (macOS)"
- "PR Check - C/C\\+\\+: disabling autoinstalling dependencies (Linux)"
Expand All @@ -37,11 +36,12 @@ on:
- "PR Check - Debug artifact upload"
- "PR Check - Debug artifacts after failure"
- "PR Check - Diagnostic export"
- "PR Check - Diagnostic export without database"
- "PR Check - Export file baseline information"
- "PR Check - Extractor ram and threads options test"
- "PR Check - Go: Custom queries"
- "PR Check - Go: diagnostic when Go is changed after init step"
- "PR Check - Go: diagnostic when `file` is not installed"
- "PR Check - Go: diagnostic when Go is changed after init step"
- "PR Check - Go: tracing with autobuilder step"
- "PR Check - Go: tracing with custom build steps"
- "PR Check - Go: tracing with legacy workflow"
Expand All @@ -56,6 +56,7 @@ on:
- "PR Check - Packaging: Config and input passed to the CLI"
- "PR Check - Packaging: Config file"
- "PR Check - Packaging: Download using registries"
- "PR Check - Per-language bundles"
- "PR Check - Proxy test"
- "PR Check - Remote config file"
- "PR Check - Resolve environment"
Expand All @@ -69,19 +70,18 @@ on:
- "PR Check - Swift analysis using autobuild"
- "PR Check - Test different uses of `upload-sarif`"
- "PR Check - Test unsetting environment variables"
- "PR Check - Upload-sarif: ref and sha from inputs"
- "PR Check - Unsupported macOS"
- "PR Check - Upload-sarif: 'ref' and 'sha' from inputs"
- "PR Check - Use a custom `checkout_path`"
- PR Checks
- Query filters tests
- Test that the workaround for python 3.12 on windows works
- "PR Checks"
- "Query filters tests"
- "Test that the workaround for python 3.12 on windows works"

jobs:
rerun-on-failure:
name: Rerun failed jobs
if: >-
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.run_attempt == 1 &&
(
github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt == 1 && (
github.event.workflow_run.head_branch == 'main' ||
startsWith(github.event.workflow_run.head_branch, 'releases/') ||
github.event.workflow_run.event == 'merge_group'
Expand Down
142 changes: 142 additions & 0 deletions pr-checks/deflake.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#!/usr/bin/env npx tsx

/*
Tests for `deflake.ts`.
*/

import * as assert from "node:assert/strict";
import { describe, it } from "node:test";

import { escapeWorkflowName, setWorkflowRunWorkflows } from "./deflake";

describe("escapeWorkflowName", async () => {
await it("escapes the characters that filter patterns treat as glob syntax", () => {
assert.equal(
escapeWorkflowName(
String.raw`!Name with C/C++, [a-z]?, *, ! and \ in it`,
),
String.raw`\!Name with C/C\+\+, \[a-z]\?, \*, \! and \\ in it`,
);
});

await it("leaves names without glob syntax unchanged", () => {
const name = "PR Check - Upload-sarif: 'ref' and `sha` (Linux) ]";
assert.equal(escapeWorkflowName(name), name);
});
});

describe("setWorkflowRunWorkflows", async () => {
await it("replaces the list with sorted, escaped names and leaves the rest of the workflow unchanged", () => {
const workflow = `on:
workflow_run:
types: [completed]
# A comment about the list.
workflows:
- Existing workflow
# A comment within the list.
- "Removed workflow"

jobs:
rerun:
if: |-
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.run_attempt == 1
`;
assert.equal(
setWorkflowRunWorkflows(workflow, [
"PR Check - b",
"PR Check - C/C++",
"Existing workflow",
"PR Check - a",
]),
String.raw`on:
workflow_run:
types: [completed]
# A comment about the list.
workflows:
- "Existing workflow"
- "PR Check - a"
- "PR Check - b"
- "PR Check - C/C\\+\\+"

jobs:
rerun:
if: |-
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.run_attempt == 1
`,
);
});

await it("uses single quotes only for patterns that contain double quotes and no backslashes", () => {
// These are the quotes that Prettier uses when formatting these strings.
assert.equal(
setWorkflowRunWorkflows(
"on:\n workflow_run:\n workflows:\n - Old\n",
['Upload "quoted" SARIF', `It's "quoted"`, 'C++ "quoted"'],
),
String.raw`on:
workflow_run:
workflows:
- "C\\+\\+ \"quoted\""
- 'It''s "quoted"'
- 'Upload "quoted" SARIF'
`,
);
});

await it("leaves comments and keys after the last item unchanged", () => {
const after = ` # A comment after the list.

branches: [main]
`;
assert.equal(
setWorkflowRunWorkflows(
`on:\n workflow_run:\n workflows:\n - Old\n${after}`,
["New"],
),
`on:\n workflow_run:\n workflows:\n - "New"\n${after}`,
);
});

await it("returns an up-to-date workflow unchanged", () => {
const workflow = String.raw`on:
workflow_run:
workflows:
- "C/C\\+\\+"
- "Other"
`;
assert.equal(
setWorkflowRunWorkflows(workflow, ["Other", "C/C++"]),
workflow,
);
});

await it("writes a flow sequence as a block sequence", () => {
assert.equal(
setWorkflowRunWorkflows("on:\n workflow_run:\n workflows: [Old]\n", [
"New",
]),
'on:\n workflow_run:\n workflows:\n - "New"\n',
);
});

await it("throws if the workflow isn't valid YAML", () => {
// Duplicate keys are an error in the `yaml` library, though Prettier accepts them.
assert.throws(
() =>
setWorkflowRunWorkflows(
"on:\n workflow_run:\n workflows:\n - Old\njobs: {}\njobs: {}\n",
["New"],
),
/Failed to parse the workflow: .* at line 6, column 1/,
);
});

await it("throws if the workflow has no workflow_run trigger", () => {
assert.throws(
() => setWorkflowRunWorkflows("on:\n push: {}\n", ["Other"]),
/Expected `on.workflow_run.workflows` to be a sequence/,
);
});
});
111 changes: 111 additions & 0 deletions pr-checks/deflake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import * as fs from "fs";
import * as path from "path";

import * as yaml from "yaml";

import { REPO_ROOT } from "./config";

/** The path of the workflow that reruns failed jobs in other workflows. */
const DEFLAKE_WORKFLOW_FILE = path.join(
REPO_ROOT,
".github",
"workflows",
"deflake.yml",
);

/**
* The names of workflows that `sync.ts` doesn't generate, but whose failed jobs the Deflake
* workflow should rerun.
*
* Exclude workflows that have significant side effects, like publishing releases. It's OK to retry
* CodeQL analysis.
*/
const NON_GENERATED_WORKFLOWS_TO_RERUN = [
"Check Expected Release Files",
"Code-Scanning config CLI tests",
"CodeQL action",
"PR Check - Debug artifact upload",
"PR Check - Debug artifacts after failure",
"PR Checks",
"Query filters tests",
"Test that the workaround for python 3.12 on windows works",
];

/**
* Escapes the characters in a workflow name that `on.workflow_run.workflows` would otherwise treat
* as glob syntax.
*
* @returns A pattern that matches only the workflow called `name`.
*/
export function escapeWorkflowName(name: string): string {
// These are the characters that can be escaped in GitHub Actions filter patterns. `]` is only
// special after an unescaped `[`, so it doesn't need escaping.
return name.replace(/[\\[?*+!]/g, "\\$&");
}

/**
* Replaces the items in the `on.workflow_run.workflows` list of a workflow, and any comments on
* their lines or between them, with patterns that match the workflows called `workflowNames`,
* sorted by name. The list is written as a block sequence.
*
* The whole workflow is rewritten with the `yaml` library, so any other parts that aren't
* formatted the way that library formats them are reformatted, for example by joining lines of
* folded (`>`) block scalars. Prettier, which checks the formatting of YAML files in this
* repository, formats non-empty flow mappings, and flow sequences that don't fit within 80
* columns, differently from that library, so the workflow is expected not to contain any.
*
* @param workflow The contents of the workflow file.
* @param workflowNames The names of the workflows that should trigger the workflow.
* @returns The updated contents of the workflow file.
* @throws If the workflow isn't valid YAML, or `on.workflow_run.workflows` isn't a sequence.
*/
export function setWorkflowRunWorkflows(
workflow: string,
workflowNames: string[],
): string {
const document = yaml.parseDocument(workflow);
if (document.errors.length > 0) {
throw new Error(
`Failed to parse the workflow: ${document.errors[0].message}`,
);
}
const workflows = document.getIn(["on", "workflow_run", "workflows"], true);
if (!yaml.isSeq(workflows)) {
throw new Error("Expected `on.workflow_run.workflows` to be a sequence.");
}

workflows.flow = false;
workflows.items = workflowNames
.toSorted((a, b) => a.localeCompare(b, "en"))
.map((name) => {
const pattern = escapeWorkflowName(name);
const item = new yaml.Scalar(pattern);
// Quote the pattern in the same way as Prettier, which uses single quotes for strings that
// contain `"` but no `\`, and double quotes otherwise.
item.type =
pattern.includes('"') && !pattern.includes("\\")
? yaml.Scalar.QUOTE_SINGLE
: yaml.Scalar.QUOTE_DOUBLE;
return item;
});
// These options match how Prettier formats short flow sequences, such as `[completed]`, and long
// strings.
return document.toString({ flowCollectionPadding: false, lineWidth: 0 });
}

/**
* Updates the Deflake workflow so that it reruns failed jobs in the workflows called
* `generatedWorkflowNames` and in {@link NON_GENERATED_WORKFLOWS_TO_RERUN}.
*/
export function updateDeflakeWorkflow(generatedWorkflowNames: string[]): void {
console.log(`Updating the list of workflows in '${DEFLAKE_WORKFLOW_FILE}'.`);
const workflow = fs.readFileSync(DEFLAKE_WORKFLOW_FILE, "utf8");
fs.writeFileSync(
DEFLAKE_WORKFLOW_FILE,
setWorkflowRunWorkflows(workflow, [
...generatedWorkflowNames,
...NON_GENERATED_WORKFLOWS_TO_RERUN,
]),
"utf8",
);
}
2 changes: 1 addition & 1 deletion pr-checks/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ to one of the files in this directory.

## Updating workflows

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/`.
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.

Alternatively, you can use `just`:

Expand Down
6 changes: 6 additions & 0 deletions pr-checks/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as yaml from "yaml";
import { BuiltInLanguage } from "../src/languages";

import { PR_CHECKS_DIR, REPO_ROOT } from "./config";
import { updateDeflakeWorkflow } from "./deflake";

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

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

const generatedWorkflowNames: string[] = [];
const collections: Record<
string,
Array<{
Expand Down Expand Up @@ -834,6 +836,7 @@ function main(): void {

const outputPath = path.join(OUTPUT_DIR, `__${checkName}.yml`);
writeYaml(outputPath, workflow);
generatedWorkflowNames.push(workflow.name);
}

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

const outputPath = path.join(OUTPUT_DIR, `__${collectionName}.yml`);
writeYaml(outputPath, collectionWorkflow);
generatedWorkflowNames.push(collectionWorkflow.name);
}

updateDeflakeWorkflow(generatedWorkflowNames);

console.log(
`\nDone. Wrote ${checkFiles.length} workflow file(s) to ${OUTPUT_DIR}`,
);
Expand Down
Loading