diff --git a/.github/CI.md b/.github/CI.md index 07ed246986..43829554e8 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -1019,3 +1019,22 @@ rebuilt without it. Live proof is recorded under [Activation and observation](#activation-and-observation) as it is observed. The complete [release-candidate gate](RELEASING.md) remains required before tagging a release. + +## Forgejo + +`tools/cli/scripts/forgejo-port/` turns these workflows into the ones Forgejo's runner runs. It +is applied once, when the repository moves to Forgejo, and changes no workflow here until then; +the cut-over adds one condition, to the `publish` job of `publish-packages.yml`, so that it +publishes nothing once Forgejo is the source. The unit tests of `@tale/cli` run the port over +these workflows. They fail a change when the generator crashes on a workflow, when +`declared-checks.yml` no longer lists the `CI ready (…)` checks the workflows define (a change +that adds, renames or removes one runs `bun tools/cli/scripts/forgejo-port.ts checks --write`), +when a composite action or a script the port names is renamed or removed, or when `e2e.yml` or +`sast.yml` stops carrying the tier it is generated for. + +On Forgejo a pull request owes what a batch of the merge train (a push to `mq/**`) owes, the +whole suite, so that a failure shows on the pull request and not in the train. A workflow whose +`tier` says `fast` owes this document's pull request tier instead, except that Security is not +path-scoped and runs on every pull request. The +[README](../tools/cli/scripts/forgejo-port/README.md) says what the port does and what stays on +GitHub; `bun tools/cli/scripts/forgejo-port.ts report` shows it on the workflows as they are. diff --git a/tools/cli/scripts/forgejo-port.test.ts b/tools/cli/scripts/forgejo-port.test.ts new file mode 100644 index 0000000000..8730bcc4d7 --- /dev/null +++ b/tools/cli/scripts/forgejo-port.test.ts @@ -0,0 +1,543 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + DECLARED_CHECKS, + README, + compare, + declaredChecksText, + describe as describeGenerated, + main, + mirrorProblems, + readDeclaredChecks, + readSources, + runnerCheck, + writeGenerated, + type Io, +} from './forgejo-port'; +import { generate } from './forgejo-port/generate'; +import { planGithubEdits } from './forgejo-port/github-edits'; +import { MANIFEST, type Manifest } from './forgejo-port/manifest'; +import { pinnedRunner } from './forgejo-port/runner'; +import type { Problem } from './forgejo-port/validate'; + +const ROOT = fileURLToPath(new URL('../../../', import.meta.url)); +const SHA = 'a'.repeat(40); + +const temporary: string[] = []; + +afterEach(() => { + for (const directory of temporary.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); + +function scratch(): string { + const directory = mkdtempSync(join(tmpdir(), 'forgejo-port-test-')); + temporary.push(directory); + return directory; +} + +function put(root: string, path: string, text: string): void { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), text); +} + +/** A workflow the runner reads: the second job needs the first. */ +const PROBE = `name: Probe +on: + push: +jobs: + first: + runs-on: ubuntu-latest + steps: + - run: echo first + second: + needs: [first] + runs-on: ubuntu-latest + steps: + - run: echo second +`; + +const CHECKS = `name: Checks +on: + merge_group: + pull_request: +jobs: + lint: + runs-on: ubuntu-latest + steps: + - run: echo lint + format: + name: Format + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@${SHA} + with: + persist-credentials: false + fetch-depth: 2 + - name: Refuse links that do not land + run: bun run lint:links + ci-ready: + name: CI ready (Checks) + needs: [lint, format] + if: always() && (github.event_name == 'pull_request' || github.event_name == 'merge_group') + runs-on: ubuntu-latest + steps: + - name: Checkout verdict policy + uses: actions/checkout@${SHA} + - name: Evaluate native workflow + uses: ./.github/actions/ci-ready +`; + +const PUBLISH = `name: Publish packages +on: + workflow_dispatch: +jobs: + publish: + name: Publish \${{ matrix.package }} + runs-on: ubuntu-latest + steps: + - run: echo publish +`; + +const SMALL: Manifest = { + tier: 'full', + registry: { host: 'git.example.test', tokenSecret: 'CI_PACKAGES_TOKEN' }, + githubApiTokenSecret: 'CI_GITHUB_TOKEN', + labels: ['ubuntu-latest'], + composites: [], + scripts: [], + workflows: { 'publish-packages.yml': { kind: 'github', why: 'stays' } }, + githubEdits: [ + { + file: 'publish-packages.yml', + find: ' publish:\n name: Publish ${{ matrix.package }}\n', + replace: + " publish:\n name: Publish ${{ matrix.package }}\n if: vars.TALE_SOURCE != 'forgejo'\n", + why: 'it publishes nothing once Forgejo is the source', + }, + ], +}; + +function repository(): string { + const root = scratch(); + put(root, '.github/workflows/checks.yml', CHECKS); + put(root, '.github/workflows/publish-packages.yml', PUBLISH); + put(root, README, '| Mirrors | `actions/checkout` |\n'); + return root; +} + +function run(root: string, ...argv: string[]) { + const out: string[] = []; + const err: string[] = []; + const io: Io = { + cwd: root, + out: (line) => out.push(line), + err: (line) => err.push(line), + }; + const code = main(['--root', root, ...argv], io, SMALL); + return { code, out, err }; +} + +describe('readSources', () => { + test('reads the workflows, the composite actions and the files the manifest names', () => { + const root = repository(); + put(root, '.github/actions/setup-turbo/action.yml', 'name: x\n'); + put(root, '.github/actions/notes.md', 'not an action\n'); + put(root, '.github/workflows/readme.md', 'not a workflow\n'); + put(root, '.github/scripts/pull.sh', '#!/bin/sh\n'); + const sources = readSources(root, { + ...SMALL, + scripts: [{ from: '.github/scripts/pull.sh', to: 'x', edits: [] }], + }); + expect([...sources.workflows.keys()].toSorted()).toEqual([ + 'checks.yml', + 'publish-packages.yml', + ]); + expect([...sources.actions.keys()]).toEqual(['setup-turbo']); + expect([...sources.files.keys()]).toEqual(['.github/scripts/pull.sh']); + }); + + test('reads nothing from a repository that has no .github', () => { + const sources = readSources(scratch(), SMALL); + expect(sources.workflows.size).toBe(0); + expect(sources.actions.size).toBe(0); + }); +}); + +describe('describe, compare and writeGenerated', () => { + test('say what the port did, and what is on disk against it', () => { + const root = repository(); + const generated = generate(readSources(root, SMALL), SMALL); + const lines = describeGenerated(generated); + expect(lines.join('\n')).toContain( + 'checks.yml: ported; a pull request owes what a batch owes', + ); + expect(lines.join('\n')).toContain('publish-packages.yml: github; stays'); + expect(lines).toContain(' Checks / CI ready (Checks)'); + expect(lines).toContain('Problems: 0'); + + expect([...compare(root, generated).files]).toEqual([ + ['.forgejo/workflows/checks.yml', 'new'], + ]); + writeGenerated(root, generated); + expect( + compare(root, generated).files.get('.forgejo/workflows/checks.yml'), + ).toBe('same'); + put(root, '.forgejo/workflows/checks.yml', 'name: edited\n'); + put(root, '.forgejo/workflows/old.yml', 'name: old\n'); + const after = compare(root, generated); + expect(after.files.get('.forgejo/workflows/checks.yml')).toBe('changed'); + expect(after.stale).toEqual(['.forgejo/workflows/old.yml']); + writeGenerated(root, generated, after.stale); + expect(existsSync(join(root, '.forgejo/workflows/old.yml'))).toBe(false); + }); +}); + +describe('the command line', () => { + test('report prints the plan and succeeds', () => { + const { code, out } = run(repository(), 'report'); + expect(code).toBe(0); + expect(out.join('\n')).toContain('checks.yml: ported'); + }); + + test('checks prints the declared checks, and writes them on request', () => { + const root = repository(); + expect(run(root, 'checks').out.join('\n')).toContain( + 'Checks / CI ready (Checks)', + ); + expect(run(root, 'checks', '--write').out).toEqual([ + `wrote ${DECLARED_CHECKS}`, + ]); + expect(readDeclaredChecks(root)).toEqual(['Checks / CI ready (Checks)']); + expect(readFileSync(join(root, DECLARED_CHECKS), 'utf8')).toBe( + declaredChecksText(['Checks / CI ready (Checks)']), + ); + }); + + test('check fails until the declared checks are the generated ones', () => { + const root = repository(); + const missing = run(root, 'check'); + expect(missing.code).toBe(1); + expect(missing.err.join('\n')).toContain('is not what the port generates'); + run(root, 'checks', '--write'); + const fine = run(root, 'check'); + expect(fine.code).toBe(0); + expect(fine.out).toEqual(['ok: 1 files, 1 checks']); + put(root, DECLARED_CHECKS, '- Something else\n'); + expect(run(root, 'check').code).toBe(1); + }); + + test('check also fails on a declared-checks.yml whose header has drifted, not only its list', () => { + const root = repository(); + run(root, 'checks', '--write'); + const text = readFileSync(join(root, DECLARED_CHECKS), 'utf8'); + expect(text).toContain('deployments/tale/merge-train/pr/repositories.yml'); + put(root, DECLARED_CHECKS, text.replace('merge-train', 'train')); + const drifted = run(root, 'check'); + expect(drifted.code).toBe(1); + expect(drifted.err.join('\n')).toContain('is not what the port generates'); + }); + + test('check fails on an action the README does not list among the mirrors', () => { + const root = repository(); + run(root, 'checks', '--write'); + expect(run(root, 'check').code).toBe(0); + put(root, README, '| Mirrors | `actions/setup-node` |\n'); + const unlisted = run(root, 'check'); + expect(unlisted.code).toBe(1); + expect(unlisted.err.join('\n')).toContain( + 'does not list `actions/checkout`', + ); + rmSync(join(root, README)); + expect(run(root, 'check').err.join('\n')).toContain('is missing'); + }); + + test('check says when an edit of a workflow that stays has lost its place', () => { + const root = repository(); + run(root, 'checks', '--write'); + put( + root, + '.github/workflows/publish-packages.yml', + 'name: Publish packages\non:\n push:\njobs: {}\n', + ); + const { code, err } = run(root, 'check'); + expect(code).toBe(1); + expect(err.join('\n')).toContain('holds the lines of the edit nowhere'); + }); + + test('generate compares the link check with the merge base with main, and check fails when its step is no longer the one the rule finds', () => { + const root = repository(); + const generated = generate(readSources(root, SMALL), SMALL); + const text = generated.files.get('.forgejo/workflows/checks.yml') ?? ''; + expect(text).toContain('LINT_LINKS_BASE="$base" bun run lint:links'); + expect(text).toContain('git merge-base HEAD origin/main'); + expect(text).toContain('fetch-depth: 0'); + expect(text).not.toContain('fetch-depth: 2'); + run(root, 'checks', '--write'); + expect(run(root, 'check').code).toBe(0); + + // the step is edited, so the rule finds nothing to change: the file would keep `HEAD^1` and a shallow checkout + put( + root, + '.github/workflows/checks.yml', + CHECKS.replace( + 'run: bun run lint:links', + 'run: bun run lint:links --verbose', + ), + ); + const lost = run(root, 'check'); + expect(lost.code).toBe(1); + expect(lost.err.join('\n')).toContain( + 'the step `run: bun run lint:links` after a checkout is gone', + ); + expect( + generate(readSources(root, SMALL), SMALL).files.get( + '.forgejo/workflows/checks.yml', + ), + ).toContain('fetch-depth: 2'); + expect(run(root, 'report').code).toBe(0); + }); + + test('check fails on a local action the port leaves as the GitHub copy, and says which', () => { + const root = repository(); + run(root, 'checks', '--write'); + expect(run(root, 'check').code).toBe(0); + put( + root, + '.github/workflows/checks.yml', + CHECKS.replace( + ' - run: echo lint\n', + ' - uses: ./.github/actions/brand-new\n', + ), + ); + const unported = run(root, 'check'); + expect(unported.code).toBe(1); + expect(unported.err.join('\n')).toContain( + '`./.github/actions/brand-new` is not ported', + ); + expect(run(root, 'report').code).toBe(0); + }); + + test('generate is a dry run until --write, and refuses a port with problems', () => { + const root = repository(); + const dry = run(root, 'generate'); + expect(dry.code).toBe(0); + expect(dry.out).toContain('new .forgejo/workflows/checks.yml'); + expect(dry.out.at(-1)).toContain('dry run'); + expect(existsSync(join(root, '.forgejo'))).toBe(false); + + const out = scratch(); + expect(run(root, 'generate', '--write', '--out', out).code).toBe(0); + expect(existsSync(join(out, '.forgejo/workflows/checks.yml'))).toBe(true); + expect(existsSync(join(root, '.forgejo'))).toBe(false); + + put( + root, + '.github/workflows/checks.yml', + CHECKS.replace('ubuntu-latest', 'macos-latest'), + ); + const refused = run(root, 'generate', '--write'); + expect(refused.code).toBe(1); + expect(refused.err.join('\n')).toContain('not generating'); + }); + + test('generate --write refuses to overwrite or delete what it may not have made, unless forced', () => { + const root = repository(); + const out = scratch(); + const path = '.forgejo/workflows/checks.yml'; + expect(run(root, 'generate', '--write', '--out', out).code).toBe(0); + expect(run(root, 'generate', '--write', '--out', out).code).toBe(0); + + put(out, path, 'name: edited by hand\n'); + put(out, '.forgejo/workflows/renovate.yml', 'name: renovate\n'); + const refused = run(root, 'generate', '--write', '--out', out); + expect(refused.code).toBe(1); + expect(refused.out).toContain(`changed ${path}`); + expect(refused.out).toContain('stale .forgejo/workflows/renovate.yml'); + expect(refused.err.join('\n')).toContain('pass --force'); + expect(readFileSync(join(out, path), 'utf8')).toBe( + 'name: edited by hand\n', + ); + expect(existsSync(join(out, '.forgejo/workflows/renovate.yml'))).toBe(true); + expect(run(root, 'generate', '--out', out).code).toBe(0); + + const forced = run(root, 'generate', '--write', '--force', '--out', out); + expect(forced.code).toBe(0); + expect(readFileSync(join(out, path), 'utf8')).toContain('name: Checks'); + expect(existsSync(join(out, '.forgejo/workflows/renovate.yml'))).toBe( + false, + ); + }); + + test('github shows the edit and makes it, once', () => { + const root = repository(); + const dry = run(root, 'github'); + expect(dry.out[0]).toContain( + 'pending .github/workflows/publish-packages.yml', + ); + expect( + readFileSync( + join(root, '.github/workflows/publish-packages.yml'), + 'utf8', + ), + ).toBe(PUBLISH); + expect(run(root, 'github', '--write').out.at(-1)).toBe('wrote 1 files'); + expect( + readFileSync( + join(root, '.github/workflows/publish-packages.yml'), + 'utf8', + ), + ).toContain(" if: vars.TALE_SOURCE != 'forgejo'\n"); + const again = run(root, 'github', '--write'); + expect(again.out[0]).toContain('applied'); + expect(again.out.at(-1)).toBe('wrote 0 files'); + }); + + test("a tier of the command line replaces the manifest's, and only fast and full are tiers", () => { + const root = repository(); + expect(run(root, 'report', '--tier', 'fast').out.join('\n')).toContain( + 'checks.yml: ported; a pull request owes the fast tier', + ); + expect(run(root, 'report').out.join('\n')).toContain( + 'checks.yml: ported; a pull request owes what a batch owes', + ); + expect(run(root, 'report', '--tier', 'half').code).toBe(2); + }); + + test('refuses what it does not know', () => { + const root = repository(); + expect(run(root, 'nonsense').code).toBe(2); + expect(run(root, 'report', 'extra').code).toBe(2); + const bad = run(root, '--no-such-flag'); + expect(bad.code).toBe(2); + expect(bad.err.length).toBe(1); + }); +}); + +describe("Tale's own workflows", () => { + const sources = readSources(ROOT); + + test('are ported without the port failing, and the checks the merge train declares are the ones listed', () => { + const generated = generate(sources); + expect(generated.checks.length).toBeGreaterThan(0); + expect( + generated.checks, + 'declared-checks.yml is stale: run `bun tools/cli/scripts/forgejo-port.ts checks --write`', + ).toEqual(readDeclaredChecks(ROOT) ?? []); + for (const path of generated.files.keys()) + expect(path.startsWith('.forgejo/')).toBe(true); + }); + + test('are ported in both tiers, with the same checks', () => { + const fast = generate(sources, { ...MANIFEST, tier: 'fast' }); + const full = generate(sources, { ...MANIFEST, tier: 'full' }); + expect(fast.checks).toEqual(full.checks); + expect(fast.files.size).toBe(full.files.size); + expect(fast.files.get('.forgejo/workflows/e2e.yml')).not.toBe( + full.files.get('.forgejo/workflows/e2e.yml'), + ); + expect(fast.files.get('.forgejo/workflows/sast.yml')).toContain( + 'CI_TIER: fast', + ); + expect(full.files.get('.forgejo/workflows/sast.yml')).toContain( + 'CI_TIER: full', + ); + }); + + test('say what Forgejo would refuse, without holding a workflow edited today to a port applied at the cut-over', () => { + const generated = generate(sources); + const edits = planGithubEdits(sources.workflows, MANIFEST); + for (const problem of [...generated.problems, ...edits.problems]) + console.warn( + `forgejo-port: ${problem.file} ${problem.at}: ${problem.message}`, + ); + for (const warning of generated.report.warnings) + console.warn( + `forgejo-port: ${warning.file} ${warning.at}: ${warning.detail}`, + ); + expect(generated.outcomes.length).toBe(sources.workflows.size); + }); + + test('are described in the README, one row for each that does not move', () => { + const readme = readFileSync( + join(ROOT, 'tools/cli/scripts/forgejo-port/README.md'), + 'utf8', + ); + for (const file of Object.keys(MANIFEST.workflows)) + expect(readme, file).toContain(`\`${file}\``); + for (const edit of MANIFEST.githubEdits) + expect(readme, edit.file).toContain(`\`${edit.file}\``); + }); + + test('say which actions the README does not list among the mirrors, without holding a workflow edited today to it', () => { + for (const problem of mirrorProblems(ROOT, generate(sources))) + console.warn( + `forgejo-port: ${problem.file} ${problem.at}: ${problem.message}`, + ); + expect(existsSync(join(ROOT, README))).toBe(true); + }); + + test('is either ported or given a reason, and the files the manifest names exist', () => { + const generated = generate(sources); + expect( + generated.outcomes.map((outcome) => outcome.file).toSorted(), + ).toEqual([...sources.workflows.keys()].toSorted()); + for (const outcome of generated.outcomes) { + if (outcome.plan.kind === 'port') continue; + expect(outcome.plan.why.length).toBeGreaterThan(20); + expect(generated.files.has(`.forgejo/workflows/${outcome.file}`)).toBe( + false, + ); + } + for (const name of MANIFEST.composites) + expect(sources.actions.has(name)).toBe(true); + for (const script of MANIFEST.scripts) + expect(sources.files.has(script.from)).toBe(true); + }); + + test('are read by the pinned forgejo-runner, and a broken file is not', async () => { + const runner = + process.env.FORGEJO_RUNNER ?? + (await pinnedRunner( + join(tmpdir(), `forgejo-port-runner-${process.getuid?.() ?? 'user'}`), + )); + if (runner === undefined) { + console.warn( + 'forgejo-port: no forgejo-runner to check against (set FORGEJO_RUNNER, or run on linux/amd64)', + ); + return; + } + const generated = generate(sources); + for (const problem of runnerCheck(runner, generated)) + console.warn( + `forgejo-port: the pinned runner: ${problem.at}: ${problem.message}`, + ); + + // The instrument can fail: a key the schema does not know, and a job that needs a job that is + // not there. The probes are a workflow of their own, so that no edit of a workflow under + // `.github/` changes what they prove. + const probe = '.forgejo/workflows/probe.yml'; + const planned = (text: string): Problem[] => + runnerCheck(runner, { + ...generated, + files: new Map([[probe, text]]), + }).filter((problem) => problem.at === probe); + expect(planned(PROBE)).toEqual([]); + expect(planned(PROBE.replace('runs-on:', 'runs-onn:'))).not.toEqual([]); + expect( + planned(PROBE.replace('needs: [first]', 'needs: [nowhere]')), + ).not.toEqual([]); + }, 120_000); +}); diff --git a/tools/cli/scripts/forgejo-port.ts b/tools/cli/scripts/forgejo-port.ts new file mode 100644 index 0000000000..e445b4a42d --- /dev/null +++ b/tools/cli/scripts/forgejo-port.ts @@ -0,0 +1,461 @@ +#!/usr/bin/env bun +/** + * Port Tale's GitHub Actions to Forgejo. + * + * bun tools/cli/scripts/forgejo-port.ts report what the port does to each file + * bun tools/cli/scripts/forgejo-port.ts check port in memory and fail on a problem, a rule that found nothing to change, a local action left as GitHub's, or a README that lacks a mirror + * bun tools/cli/scripts/forgejo-port.ts generate [--write [--force]] the files of `.forgejo/` (the cut-over) + * bun tools/cli/scripts/forgejo-port.ts checks [--write] the checks the merge train declares + * bun tools/cli/scripts/forgejo-port.ts github [--write] the edits GitHub's copies of the workflows that stay need + * + * `--root ` names the repository (default: the checkout this file is in), `--out ` + * where `generate --write` puts the files (default: the root) and `--runner ` makes + * `check` hold every generated file to that forgejo-runner. `generate --write` overwrites a file + * that differs and deletes a file of the generated directories it does not produce, so it refuses + * both unless `--force` is given. The port is a function of the files under `.github/`; + * `forgejo-port/README.md` says what it does and why. + */ + +import { spawnSync } from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; + +import { parse, stringify } from 'yaml'; + +import { + WORKFLOW_DIR, + generate, + type Generated, + type Sources, +} from './forgejo-port/generate'; +import { planGithubEdits } from './forgejo-port/github-edits'; +import { MANIFEST, type Manifest } from './forgejo-port/manifest'; +import type { Problem } from './forgejo-port/validate'; + +/** The checks the merge train waits for, as the port generates them. */ +export const DECLARED_CHECKS = + 'tools/cli/scripts/forgejo-port/declared-checks.yml'; + +/** The README that lists what the node must hold, among it the actions it mirrors. */ +export const README = 'tools/cli/scripts/forgejo-port/README.md'; + +/** The directories the generator owns under the repository root. */ +const GENERATED_DIRS = [ + '.forgejo/workflows', + '.forgejo/actions', + '.forgejo/scripts', +]; + +const YAML_FILE = /\.ya?ml$/; + +function textOf(path: string): string | undefined { + return existsSync(path) ? readFileSync(path, 'utf8') : undefined; +} + +/** Everything the port reads, from a checkout. */ +export function readSources( + root: string, + manifest: Manifest = MANIFEST, +): Sources { + const workflows = new Map(); + const workflowDir = join(root, '.github/workflows'); + for (const name of existsSync(workflowDir) ? readdirSync(workflowDir) : []) { + if (YAML_FILE.test(name)) + workflows.set(name, readFileSync(join(workflowDir, name), 'utf8')); + } + const actions = new Map(); + const actionDir = join(root, '.github/actions'); + for (const entry of existsSync(actionDir) + ? readdirSync(actionDir, { withFileTypes: true }) + : []) { + if (!entry.isDirectory()) continue; + const text = + textOf(join(actionDir, entry.name, 'action.yml')) ?? + textOf(join(actionDir, entry.name, 'action.yaml')); + if (text !== undefined) actions.set(entry.name, text); + } + const files = new Map(); + for (const script of manifest.scripts) { + const text = textOf(join(root, script.from)); + if (text !== undefined) files.set(script.from, text); + } + return { workflows, actions, files }; +} + +function countBy(items: readonly T[], key: (item: T) => string): string { + const counts = new Map(); + for (const item of items) + counts.set(key(item), (counts.get(key(item)) ?? 0) + 1); + return [...counts] + .toSorted(([a], [b]) => a.localeCompare(b)) + .map(([name, count]) => `${name} ${count}`) + .join(', '); +} + +function problemLine(problem: Problem): string { + return `${problem.file}${problem.at ? ` ${problem.at}` : ''}: ${problem.message}`; +} + +/** What the port did, for a person: one line per workflow, then the checks, then the problems. */ +export function describe(generated: Generated): string[] { + const lines: string[] = ['Workflows']; + for (const outcome of generated.outcomes) { + const { plan } = outcome; + if (plan.kind === 'port') { + const gone = [...outcome.removed.keys()]; + lines.push( + ` ${outcome.file}: ported; a pull request owes ${outcome.tier === 'fast' ? 'the fast tier' : 'what a batch owes'}; on ${outcome.events.join(', ') || 'nothing'}; ${outcome.jobs.length} jobs` + + (gone.length > 0 + ? `, ${gone.length} removed (${gone.join(', ')})` + : ''), + ); + const changes = generated.report.changes.filter( + (change) => change.file === outcome.file, + ); + if (changes.length > 0) + lines.push(` ${countBy(changes, (change) => change.rule)}`); + } else { + lines.push(` ${outcome.file}: ${plan.kind}; ${plan.why}`); + } + } + lines.push('', 'Checks the merge train declares'); + for (const check of generated.checks) lines.push(` ${check}`); + lines.push('', 'Actions the node mirrors'); + for (const [name, refs] of generated.actions) + lines.push(` ${name}: ${refs.map((ref) => ref.slice(0, 12)).join(', ')}`); + if (generated.report.warnings.length > 0) { + lines.push('', 'Warnings'); + for (const warning of generated.report.warnings) + lines.push(` ${warning.file} ${warning.at}: ${warning.detail}`); + } + lines.push('', `Problems: ${generated.problems.length}`); + for (const problem of generated.problems) + lines.push(` ${problemLine(problem)}`); + return lines; +} + +export type FileState = 'new' | 'changed' | 'same'; + +/** Each generated file against the one on disk, and the generated-looking files that no longer come out. */ +export function compare( + root: string, + generated: Generated, +): { files: Map; stale: string[] } { + const files = new Map(); + for (const [path, text] of generated.files) { + const current = textOf(join(root, path)); + files.set( + path, + current === undefined ? 'new' : current === text ? 'same' : 'changed', + ); + } + const stale: string[] = []; + const walk = (directory: string): void => { + const absolute = join(root, directory); + if (!existsSync(absolute)) return; + for (const entry of readdirSync(absolute, { withFileTypes: true })) { + const path = `${directory}/${entry.name}`; + if (entry.isDirectory()) walk(path); + else if (!generated.files.has(path)) stale.push(path); + } + }; + for (const directory of GENERATED_DIRS) walk(directory); + return { files, stale: stale.toSorted() }; +} + +/** + * Write the generated files, and remove `stale`: every file of the generator's directories that + * this run does not produce, whoever made it. + */ +export function writeGenerated( + out: string, + generated: Generated, + stale: readonly string[] = [], +): void { + for (const [path, text] of generated.files) { + mkdirSync(dirname(join(out, path)), { recursive: true }); + writeFileSync(join(out, path), text); + } + for (const path of stale) rmSync(join(out, path), { force: true }); +} + +const CHECKS_HEADER = `# The checks the merge train waits for on tale/tale, one per workflow: the +# readiness job of each ported workflow, as Forgejo names its status. The ops +# repository declares them in deployments/tale/merge-train/pr/repositories.yml. +# Generated: bun tools/cli/scripts/forgejo-port.ts checks --write +`; + +export function declaredChecksText(checks: readonly string[]): string { + return CHECKS_HEADER + stringify(checks, { lineWidth: 0 }); +} + +export function readDeclaredChecks(root: string): string[] | undefined { + const text = textOf(join(root, DECLARED_CHECKS)); + if (text === undefined) return undefined; + const value: unknown = parse(text); + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : []; +} + +/** + * Hold the generated files to Forgejo's own runner: `validate` reads every workflow and + * action against the runner's schema, and `exec --list` plans every workflow (resolves + * `needs`, expands matrices), so a file that parses and cannot be planned fails here. + */ +export function runnerCheck(runner: string, generated: Generated): Problem[] { + const problems: Problem[] = []; + const directory = mkdtempSync(join(tmpdir(), 'forgejo-port-')); + try { + writeGenerated(directory, generated); + const fail = (at: string, message: string): void => { + problems.push({ file: '.forgejo', at, message }); + }; + for (const [path] of generated.files) { + const kind = path.startsWith(`${WORKFLOW_DIR}/`) + ? '--workflow' + : path.endsWith('/action.yml') + ? '--action' + : undefined; + if (kind === undefined) continue; + const checked = spawnSync( + runner, + ['validate', kind, '--path', join(directory, path)], + { encoding: 'utf8' }, + ); + if (checked.error) { + fail(path, checked.error.message); + return problems; + } + if (checked.status !== 0) + fail(path, `validate: ${checked.stdout}${checked.stderr}`.trim()); + } + for (const [path] of generated.files) { + if (!path.startsWith(`${WORKFLOW_DIR}/`)) continue; + const planned = spawnSync( + runner, + ['exec', '--list', '--directory', directory, '--workflows', path], + { encoding: 'utf8' }, + ); + if (planned.status !== 0) + fail(path, `exec --list: ${planned.stdout}${planned.stderr}`.trim()); + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } + return problems; +} + +/** The warnings of the port that leave a generated file wrong, which `check` fails on. */ +const CHECKED_WARNINGS: ReadonlySet = new Set([ + 'anchor', + 'local-action-unported', +]); + +/** + * A rule of the port finds the text it changes by what the workflow says. When that text is + * gone the rule leaves the file as it is and says so as an `anchor` warning, which the unit + * tests only print: the generated file then keeps what the rule exists to change (a retired + * page that goes unseen, a batch that lints one commit). A local action the port does not + * generate is left as a call to the GitHub copy, which the port itself calls GitHub-only + * (`local-action-unported`). `check`, the first step of the cut-over, fails on each. + */ +function ruleProblems(generated: Generated): Problem[] { + return generated.report.warnings + .filter((warning) => CHECKED_WARNINGS.has(warning.rule)) + .map((warning) => ({ + file: warning.file, + at: warning.at, + message: warning.detail, + })); +} + +/** + * Each external action the generated files use against the README's `Mirrors` row: the node + * resolves `uses:` at its own mirrors, so an action the README does not list is one nobody was + * told to mirror. + */ +export function mirrorProblems(root: string, generated: Generated): Problem[] { + const text = textOf(join(root, README)); + if (text === undefined) + return [ + { file: README, at: '', message: 'is missing: it lists the mirrors' }, + ]; + const row = /\| Mirrors[^\n]*\n/.exec(text)?.[0] ?? ''; + const named = new Set( + [...row.matchAll(/`([a-z0-9-]+\/[a-z0-9._-]+)`/g)].map((match) => match[1]), + ); + return [...generated.actions.keys()] + .filter((name) => !named.has(name)) + .map((name) => ({ + file: README, + at: 'Mirrors', + message: `does not list \`${name}\`, an action the generated workflows use: the node must mirror it`, + })); +} + +export interface Io { + readonly cwd: string; + readonly out: (line: string) => void; + readonly err: (line: string) => void; +} + +const OPTIONS = { + root: { type: 'string' }, + out: { type: 'string' }, + runner: { type: 'string' }, + tier: { type: 'string' }, + write: { type: 'boolean' }, + force: { type: 'boolean' }, +} as const; + +function parseCommandLine(argv: readonly string[]) { + const { values, positionals } = parseArgs({ + args: [...argv], + options: OPTIONS, + allowPositionals: true, + }); + return { values, command: positionals[0] ?? 'report', extra: positionals[1] }; +} + +/** The command line. Returns the exit code. */ +export function main( + argv: readonly string[], + io: Io, + declared: Manifest = MANIFEST, +): number { + let parsed: ReturnType; + try { + parsed = parseCommandLine(argv); + } catch (error) { + io.err(error instanceof Error ? error.message : String(error)); + return 2; + } + const { command } = parsed; + const tier = parsed.values.tier ?? declared.tier; + if (tier !== 'fast' && tier !== 'full') { + io.err(`--tier is fast or full, not ${tier}`); + return 2; + } + const manifest: Manifest = { ...declared, tier }; + if (parsed.extra !== undefined) { + io.err(`unexpected argument ${parsed.extra}`); + return 2; + } + const root = resolve(io.cwd, parsed.values.root ?? defaultRoot()); + const generated = generate(readSources(root, manifest), manifest); + + if (command === 'report') { + for (const line of describe(generated)) io.out(line); + return 0; + } + + if (command === 'checks') { + const text = declaredChecksText(generated.checks); + if (parsed.values.write) { + mkdirSync(dirname(join(root, DECLARED_CHECKS)), { recursive: true }); + writeFileSync(join(root, DECLARED_CHECKS), text); + io.out(`wrote ${DECLARED_CHECKS}`); + } else io.out(text.trimEnd()); + return 0; + } + + if (command === 'check') { + const problems = [ + ...generated.problems, + ...planGithubEdits(readSources(root, manifest).workflows, manifest) + .problems, + ]; + problems.push(...ruleProblems(generated)); + problems.push(...mirrorProblems(root, generated)); + if (parsed.values.runner) + problems.push(...runnerCheck(parsed.values.runner, generated)); + if ( + textOf(join(root, DECLARED_CHECKS)) !== + declaredChecksText(generated.checks) + ) + problems.push({ + file: DECLARED_CHECKS, + at: '', + message: `is not what the port generates (the checks are ${generated.checks.join('; ')}); run \`bun tools/cli/scripts/forgejo-port.ts checks --write\``, + }); + for (const problem of problems) io.err(problemLine(problem)); + io.out( + problems.length === 0 + ? `ok: ${generated.files.size} files, ${generated.checks.length} checks` + : `${problems.length} problems`, + ); + return problems.length === 0 ? 0 : 1; + } + + if (command === 'generate') { + if (generated.problems.length > 0) { + for (const problem of generated.problems) io.err(problemLine(problem)); + io.err('not generating: the port reports problems'); + return 1; + } + const out = resolve(io.cwd, parsed.values.out ?? root); + const { files, stale } = compare(out, generated); + for (const [path, state] of files) io.out(`${state.padEnd(7)} ${path}`); + for (const path of stale) io.out(`stale ${path}`); + if (parsed.values.write) { + const changed = [...files].filter(([, state]) => state === 'changed'); + if ((changed.length > 0 || stale.length > 0) && !parsed.values.force) { + io.err( + `not writing: ${changed.length} files would be overwritten and ${stale.length} deleted, and the generator did not make them all; read the list above and pass --force to do it`, + ); + return 1; + } + writeGenerated(out, generated, stale); + io.out(`wrote ${generated.files.size} files to ${out}`); + } else io.out('dry run: add --write to write them'); + return 0; + } + + if (command === 'github') { + const { outcomes, problems } = planGithubEdits( + readSources(root, manifest).workflows, + manifest, + ); + for (const problem of problems) io.err(problemLine(problem)); + if (problems.length > 0) return 1; + for (const { path, edit, state } of outcomes) + io.out(`${state.padEnd(7)} ${path}: ${edit.why}`); + const last = new Map(outcomes.map((outcome) => [outcome.path, outcome])); + if (parsed.values.write) { + for (const [path, outcome] of last) + if (outcome.state === 'pending') + writeFileSync(join(root, path), outcome.text); + io.out( + `wrote ${[...last.values()].filter((o) => o.state === 'pending').length} files`, + ); + } else io.out('dry run: add --write to write them'); + return 0; + } + + io.err(`unknown command ${command}`); + return 2; +} + +function defaultRoot(): string { + return resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); +} + +if (import.meta.main) { + process.exitCode = main(process.argv.slice(2), { + cwd: process.cwd(), + out: (line) => console.log(line), + err: (line) => console.error(line), + }); +} diff --git a/tools/cli/scripts/forgejo-port/README.md b/tools/cli/scripts/forgejo-port/README.md new file mode 100644 index 0000000000..4fbe9ff42a --- /dev/null +++ b/tools/cli/scripts/forgejo-port/README.md @@ -0,0 +1,180 @@ +# Forgejo port + +Turns the workflows under `.github/` into the ones Forgejo's runner runs under `.forgejo/`. +It is a function of text: the files go in, the generated files, the checks the merge train +declares and the list of what Forgejo would refuse come out. No workflow under `.github/` is +changed until the cut-over, which adds one condition to one of them (`github --write`, below). + +The unit tests of `@tale/cli` run the port over the workflows as they are today. They fail a +change when the generator crashes on a workflow, when `declared-checks.yml` no longer lists the +checks the port generates (`checks --write` rewrites it), when a composite action or a script the +manifest names is renamed or removed, when `e2e.yml` or `sast.yml` stops carrying the tier it is +generated for, and when this README lacks a row for a workflow or an edit the manifest lists. +What Forgejo would refuse in a workflow, an action the node's mirror list below lacks, a rule +that no longer finds the text it changes (its `anchor` warning) and a local action the port does +not generate (its `local-action-unported` warning) are printed as warnings, so that a workflow +edited today is not held to a port applied later; `check` fails on all four. The rule that finds +nothing leaves its file as the GitHub workflow has it, so a ported file would then lack what the +rule exists to change, and a local action left as it is stays a call to the GitHub copy, which +the port itself calls GitHub-only. + +The port is applied once, at the cut-over. After that `.forgejo/workflows/` is edited by hand +and the generator is not run again. Until then it stays current with `.github/` by being +re-run, which is why it names no job or step that Tale edits daily: a workflow is ported by +rules that find what to change from what it says. + +## Commands + +```sh +bun tools/cli/scripts/forgejo-port.ts report # what the port does to each file +bun tools/cli/scripts/forgejo-port.ts check # fail on a problem, a rule with nothing to change, a local action left as GitHub's, a stale declared-checks.yml +bun tools/cli/scripts/forgejo-port.ts check --runner PATH # also hold every file to a forgejo-runner +bun tools/cli/scripts/forgejo-port.ts generate [--write] # the files of .forgejo/ (the cut-over); --force to overwrite what differs +bun tools/cli/scripts/forgejo-port.ts checks [--write] # the checks the merge train declares +bun tools/cli/scripts/forgejo-port.ts github [--write] # the edits GitHub's copies of the workflows that stay need +``` + +`--root DIR` names another checkout and `--out DIR` another place to write to. + +`generate --write` overwrites a generated file whose contents differ and deletes any file in +`.forgejo/workflows`, `.forgejo/actions` and `.forgejo/scripts` that it does not generate, a +hand-written one included. The dry run lists them as `changed` and `stale`, and `--write` refuses +until `--force` is given. + +## What it does + +| Where | What | Why | +| --- | --- | --- | +| Triggers | `merge_group` and `repository_dispatch` are removed; `push` runs for `mq/**` with no `paths`; `pull_request` loses the types Forgejo has no event for | Forgejo fires neither event, and a batch of the merge train is a push to `mq/-`. A new branch has no "before" to compare paths with | +| Release candidate | the `candidate-source` and `candidate-gate` jobs, `run-name`, and every condition on them | the candidate runs are GitHub's dispatch, which only the release lane on GitHub receives | +| Conditions | folded by what the port knows (the events the workflow has, the jobs it lost, the size of a matrix); a job or step that can never run is removed; a condition that called `always()`, `cancelled()`, `failure()` or `success()` still calls one when it folds to true | Forgejo evaluates `if` on the runner, so a skipped job still takes a runner; an `if:` that calls no status function waits for its `needs` to succeed | +| Merge group | `github.event_name == 'merge_group'` reads `push` | a batch is a push, and the only pushes a ported workflow has are batches | +| Scope | the `ci-scope` step is replaced by what it answers for the tier (below); Security runs on every pull request | the answer is a function of the event, and the files a pull request touches need GitHub's API | +| Readiness | each `CI ready (…)` job runs `forgejo-port/ready.ts`, which hands the needs to Tale's own policy (`../ci-ready.ts`) as a pull request or as a merge group, by the tier | the check the merge train reads is the one the merge queue read | +| Services | `services:` become `docker run` steps on the loopback address; a service's `credentials` and `volumes` are not carried over and are reported as warnings | a runner in host mode never starts them | +| Matrix | `strategy.job-total` is written as the number; rows whose runner the pool does not serve are removed | the runner leaves `job-total` empty, and a label it does not serve falls back to a Docker image instead of waiting | +| Actions | each external action is kept, replaced, dropped or refused from one table (`actions.ts`) | the node mirrors every action a workflow pins; the artifact actions have Forgejo forks; the runner cache is per instance | +| Registry | CI images go to `git.tale.dev` with the token of the secret `CI_PACKAGES_TOKEN`; BuildKit's `type=gha` cache becomes a registry cache written by batches | the job token can log in but cannot push a package | +| Link check | `lint:links` runs with `LINT_LINKS_BASE` set to the merge base with main, and the Format job fetches the whole history | GitHub checks a pull request out as a merge commit, so `HEAD^1` is the base there; a Forgejo run checks out the pull request's head and a batch is one commit per pull request, so `HEAD^1` would hide a page retired in an earlier commit | +| Release feed | `GITHUB_TOKEN` handed to a build becomes the secret `CI_GITHUB_TOKEN` | the web site's release feed calls api.github.com, which does not know Forgejo's token | +| Publisher | `publish-packages.yml` pushes to the Forgejo repository and runs on a `v*.*.*` tag as well | the push mirror makes GitHub's refs exactly Forgejo's, so snapshots and pins must be made there | + +The rules are in `rules.ts`, `scope.ts`, `triggers.ts`, `actions.ts`, `cache.ts` and +`workflow-rules.ts`; the folder is `expression.ts` and `workflow.ts`; `manifest.ts` is the +one place that names a workflow, a label, a secret or a file. + +## Tiers + +A batch of the merge train, a push to `mq/**`, owes every job of every workflow. What a pull +request owes is the tier, set for all workflows by `tier` in `manifest.ts` and for one by the +`tier` of its plan; `--tier` replaces it for one run of the command. + +| Tier | A pull request owes | Why | +| --- | --- | --- | +| `full` (the manifest's) | what a batch owes | a failure shows on the pull request, where its author is, and not in the train, where it costs a rebuild of the batch | +| `fast` | Checks' fast lanes, Commitlint, SAST and Security; Build, E2E, CLI and the backend integration check read as skipped | GitHub's pull request tier, which CI.md describes | + +Both tiers hand each `CI ready (…)` job to Tale's own policy; `full` as a merge group, `fast` as +a pull request. + +| Per day | `full` | `fast` | +| --- | --- | --- | +| Pull request pushes (about 108; 122 or 28 runner-minutes each) | 220 runner-hours | 50 runner-hours | +| Batches (about 40; 122 runner-minutes each) | 81 runner-hours | 81 runner-hours | +| Runners busy on average | 12.5 | 5.5 | + +The minutes are medians of GitHub's runs without the CLI's macOS and Windows legs (19 +runner-minutes, which stay on GitHub), and they include Turbo cache hits that a runner on the +node does not get (the cache is per instance). A node of 48 threads runs 12 four-CPU runners +at full speed. Measure on the soak before the tier is chosen for the repository, and move a +workflow to `fast` with its own `tier` when the pool saturates. + +## What the node must hold + +| Of | What the generated workflows need | +| --- | --- | +| Mirrors (the instance resolves `uses:` at itself) | `actions/checkout`, `actions/setup-node`, `aquasecurity/trivy-action`, `astral-sh/setup-uv`, `docker/bake-action`, `docker/build-push-action`, `docker/login-action`, `docker/setup-buildx-action`, `forgejo/download-artifact`, `forgejo/upload-artifact`, `oven-sh/setup-bun`; and the pins those actions resolve before a job starts: `aquasecurity/setup-trivy`, `actions/cache` | +| Runner labels | `ubuntu-latest` and `ubuntu-24.04`, in host mode | +| Runner image | Bun, Node, git, jq, Docker with buildx and compose, and passwordless `sudo` for the runner's user; 4 CPUs, 16 GiB of memory (Type check gives Node a 6 GiB heap) and 80 GiB of disk (Build reclaims space down to 40 GiB free before it pulls the images) | +| Secrets of the repository | `CI_PACKAGES_TOKEN`, a token that may write packages (the job's own token logs in to the registry but cannot push), and `CI_GITHUB_TOKEN`, a read-only GitHub token for the web site's release feed | +| Registry | `git.tale.dev`, where CI images are pushed under `tale/tale/` | + +`report` prints the actions the generated files use; `check` holds the Mirrors row to them. + +## What stays on GitHub + +| File | Plan | Reason | +| --- | --- | --- | +| `release.yml` | github | the release lane: its jobs and runs are what the release adopter reads, it builds arm64 images, signs the macOS and Windows binaries and creates the GitHub release | +| `release-candidate-source.yml`, `release-candidate-receipt.yml` | github | reusable workflows of the candidate dispatch, which only GitHub can send | +| `scorecard.yml` | github | OpenSSF Scorecard publishes with GitHub's OIDC identity | +| `load.yml` | github | a manual load test GitHub-hosted runners serve as it is | +| `workspace-upgrade.yml` | github | upgrades a workspace from the published releases, resolved through GitHub's release API | +| `issue-labeler.yml` | later | labels issues with GitHub's REST API; Forgejo's labels API takes ids | +| `cleanup-pr-images.yml` | later | deletes a closed pull request's image tags through GHCR's API | +| `sandbox-incus-e2e.yml` | later | builds an Incus node with a ZFS pool on the runner, which needs a virtual machine | +| `cli.yml` | port | ported without its manual `release` job and without the macOS and Windows rows | + +`github` prints the one edit GitHub's own copies need: `publish-packages.yml` publishes +nothing while the repository variable `TALE_SOURCE` is `forgejo`, because the mirror deletes +a ref only GitHub made. + +## Checks + +`declared-checks.yml` lists the checks the merge train waits for, one `CI ready (…)` per +workflow. `check` fails when it differs from what the port generates; `checks --write` +rewrites it. + +`check --runner PATH` runs `forgejo-runner validate` on every generated workflow and action +and `forgejo-runner exec --list` on every workflow, so a file that parses but cannot be +planned fails too. The tests run it when `FORGEJO_RUNNER` names a binary, or on linux/amd64 +by downloading the pinned build (`runner.ts`: version 13.2.0, the digest the ops repository +pins for the node) into a directory only the user can use; a download that fails or does not match +the digest is reported. A problem the port or the runner reports about the workflows as they are +today is printed as a warning by the tests, so that a workflow edited today is not held to a port +applied later. + +`forgejo-runner` is a Linux binary. On a workstation that is not Linux, `FORGEJO_RUNNER` may +name a script that runs the same version from its container image (the version, not the +pinned bytes), with the scratch directory shared at the same path: + +```sh +#!/bin/sh +exec docker run --rm -v "$TMPDIR:$TMPDIR" --entrypoint /bin/forgejo-runner \ + code.forgejo.org/forgejo/runner:13.2.0 "$@" +``` + +Set `TMPDIR` to a directory the container engine shares. Give the script to `check --runner`, +or set `FORGEJO_RUNNER` to it for the tests. Without a runner the test says so and skips the +check. + +## What the port leaves as it is + +| What | On Forgejo | Why it stays | +| --- | --- | --- | +| `continue-on-error: true` on the job of an advisory scan (Build's `vulnerability-scan`) | the server ignores it, so a failing scan is a red context of its own | `ci-ready.ts` reads that job as advisory, a success or a failure, so `CI ready (Build)` stays green and the merge train, which waits for the seven checks only, never reads the scan | +| `$GITHUB_STEP_SUMMARY` | Forgejo 15.0.9 discards the summary | the readiness job prints its verdict table to the job log | +| SARIF uploads to the Security tab | dropped with `github/codeql-action/upload-sarif`: Forgejo has no code scanning | a job that already retains the SARIF as an artifact keeps doing so | +| Comments that describe GitHub's behaviour | carried through unchanged | they are read and tidied by hand in the cut-over commit | + +## Changing the port + +1. Find what the rule has to recognise in the workflow itself (a job id Tale's readiness table + lists, a label the pool serves, one exact line) and nothing else. +2. Say what was done in the report and what was not found in `warnings`; a rule that finds + nothing to do does nothing. A rule whose text is gone says so with `rule: 'anchor'`, which + `check` fails on. +3. Test it on a small workflow, then on the real ones with `report`. +4. Run `check --runner` before the cut-over. + +## Cut-over + +1. `check --runner PATH` is clean: no problem in the generated files, no rule without the text + it changes, no local action left as GitHub's, `declared-checks.yml` is current and the + Mirrors row lists every action the files use. +2. `generate --write` in a branch of the Forgejo repository; read the diff, in particular the + comments that describe GitHub's behaviour. +3. `github --write` in a branch of the GitHub repository, merged before the push mirror is + switched on; set the repository variable `TALE_SOURCE` to `forgejo` when it is. +4. The ops repository's `docs/guides/tale-cutover.md` has the rest: the accounts, the + secrets, the merge train's declaration and the order. diff --git a/tools/cli/scripts/forgejo-port/actions.test.ts b/tools/cli/scripts/forgejo-port/actions.test.ts new file mode 100644 index 0000000000..0041d67395 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/actions.test.ts @@ -0,0 +1,272 @@ +import { describe, expect, test } from 'bun:test'; + +import { + ACTIONS, + DOWNLOAD_ARTIFACT, + UPLOAD_ARTIFACT, + externalActions, + registryLogin, + replaceText, + rewriteActions, + rewriteLocalActions, +} from './actions'; +import { portWorkflow } from './port'; +import { emptyReport, readWorkflow } from './workflow'; + +const SHA = 'a'.repeat(40); + +function run(source: string, rules: Parameters[3]) { + const report = emptyReport(); + const result = portWorkflow(source, 'w.yml', report, rules); + return { ...result, report }; +} + +const wf = (steps: string, extra = '') => `name: W +on: + pull_request: +${extra}jobs: + a: + runs-on: ubuntu-latest + steps: +${steps}`; + +describe('the action table', () => { + test('pins the Forgejo artifact forks by full commit', () => { + expect(UPLOAD_ARTIFACT.sha).toMatch(/^[0-9a-f]{40}$/); + expect(DOWNLOAD_ARTIFACT.sha).toMatch(/^[0-9a-f]{40}$/); + expect(ACTIONS.get('forgejo/upload-artifact')).toEqual({ kind: 'keep' }); + expect(ACTIONS.get('actions/upload-artifact')).toEqual({ + kind: 'replace', + to: UPLOAD_ARTIFACT, + }); + }); + + test('knows every external action Tale uses today', () => { + // every external action the workflows used when the table was written + for (const name of [ + 'actions/checkout', + 'actions/upload-artifact', + 'actions/download-artifact', + 'actions/cache', + 'actions/cache/restore', + 'actions/cache/save', + 'actions/setup-node', + 'actions/github-script', + 'oven-sh/setup-bun', + 'astral-sh/setup-uv', + 'docker/setup-buildx-action', + 'docker/build-push-action', + 'docker/bake-action', + 'docker/login-action', + 'aquasecurity/trivy-action', + 'dorny/paths-filter', + 'github/codeql-action/upload-sarif', + 'ossf/scorecard-action', + ]) + expect(ACTIONS.has(name), name).toBe(true); + }); +}); + +describe('rewriteActions', () => { + test('uses the artifact forks and says why, keeping the pin comment honest', () => { + const { text, report } = run( + wf(` - uses: actions/upload-artifact@${SHA} # v7 + with: + name: x + - uses: actions/download-artifact@${SHA} # v8 + with: + name: x +`), + { rules: [rewriteActions] }, + ); + expect(text).toContain( + `uses: forgejo/upload-artifact@${UPLOAD_ARTIFACT.sha} # v5, patched for Forgejo`, + ); + expect(text).toContain( + `uses: forgejo/download-artifact@${DOWNLOAD_ARTIFACT.sha} # v7, patched for Forgejo`, + ); + expect( + report.changes.filter((change) => change.rule === 'action-replaced'), + ).toHaveLength(2); + }); + + test('removes cache steps and what they said, so a save that waited for a miss goes too', () => { + const { text } = run( + wf(` - id: bun-cache + uses: actions/cache/restore@${SHA} # v5 + with: + path: ~/.bun + key: k + - run: echo install + - if: steps.bun-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@${SHA} # v5 + with: + path: ~/.bun + key: k + - if: steps.bun-cache.outputs.cache-hit == 'true' + run: echo hit +`), + { rules: [rewriteActions] }, + ); + expect(text).not.toContain('actions/cache'); + expect(text).toContain('echo install'); + expect(text).not.toContain('echo hit'); + expect(text).not.toContain('cache-hit'); + }); + + test('keeps the cache facts of one job inside that job', () => { + const { text } = run( + `name: W +on: + pull_request: +jobs: + a: + runs-on: ubuntu-latest + steps: + - id: cache + uses: actions/cache@${SHA} + - if: steps.cache.outputs.cache-hit == 'true' + run: echo a-hit + b: + runs-on: ubuntu-latest + steps: + - id: cache + run: echo make + - if: steps.cache.outputs.cache-hit == 'true' + run: echo b-hit +`, + { rules: [rewriteActions] }, + ); + expect(text).not.toContain('a-hit'); + expect(text).toContain('b-hit'); + }); + + test('removes the SARIF upload', () => { + const { text } = run( + wf(` - uses: github/codeql-action/upload-sarif@${SHA} # v4 + with: + sarif_file: x.sarif + - run: echo done +`), + { rules: [rewriteActions] }, + ); + expect(text).not.toContain('codeql'); + expect(text).toContain('echo done'); + }); + + test('warns about an action it does not know and about one that cannot work', () => { + const { report, text } = run( + wf(` - uses: someone/new-action@${SHA} + - uses: actions/github-script@${SHA} + with: + script: return 1 +`), + { rules: [rewriteActions] }, + ); + expect(report.warnings.map((warning) => warning.rule).sort()).toEqual([ + 'action-unportable', + 'unknown-action', + ]); + expect(text).toContain('someone/new-action'); + }); + + test('leaves local and docker steps to their own rules', () => { + const { report } = run( + wf(` - uses: ./.github/actions/x + - uses: docker://alpine:3 +`), + { rules: [rewriteActions] }, + ); + expect(report.warnings).toEqual([]); + }); +}); + +describe('rewriteLocalActions', () => { + const rule = rewriteLocalActions({ + composites: ['setup-turbo'], + scripts: [], + }); + + test('uses the Forgejo copy of a ported composite and flags one that is GitHub-only', () => { + const { text, report } = run( + wf(` - uses: ./.github/actions/setup-turbo + - uses: ./.github/actions/ci-scope +`), + { rules: [rule] }, + ); + expect(text).toContain('uses: ./.forgejo/actions/setup-turbo'); + expect(text).toContain('uses: ./.github/actions/ci-scope'); + expect(report.warnings.map((warning) => warning.rule)).toEqual([ + 'local-action-unported', + ]); + }); +}); + +describe('registryLogin', () => { + test('logs in to Forgejo with the package token, and names the registry', () => { + const { text } = run( + `name: B +on: + pull_request: +env: + REGISTRY: ghcr.io +jobs: + a: + runs-on: ubuntu-latest + steps: + - uses: docker/login-action@${SHA} # v4 + with: + registry: \${{ env.REGISTRY }} + username: \${{ github.actor }} + password: \${{ secrets.GITHUB_TOKEN }} + - uses: docker/login-action@${SHA} # v4 + with: + registry: docker.io + username: me + password: \${{ secrets.HUB }} +`, + { + rules: [ + registryLogin({ + host: 'git.tale.dev', + tokenSecret: 'CI_PACKAGES_TOKEN', + }), + ], + }, + ); + expect(text).toContain('REGISTRY: git.tale.dev'); + expect(text).toContain('password: ${{ secrets.CI_PACKAGES_TOKEN }}'); + expect(text).toContain('password: ${{ secrets.HUB }}'); + }); +}); + +describe('externalActions and replaceText', () => { + test('lists the actions a document uses, with the refs it pins', () => { + const doc = readWorkflow( + wf(` - uses: actions/checkout@${SHA} + - uses: ./.github/actions/x + - uses: docker://alpine:3 +`), + 'w.yml', + ); + expect(externalActions(doc)).toEqual([ + { name: 'actions/checkout', ref: SHA }, + ]); + }); + + test('replaces text everywhere, and counts the strings it changed', () => { + const doc = readWorkflow( + wf( + ' - run: bash .github/scripts/x.sh && echo .github/scripts/x.sh\n', + ), + 'w.yml', + ); + expect( + replaceText(doc, '.github/scripts/x.sh', '.forgejo/scripts/x.sh'), + ).toBe(1); + expect(replaceText(doc, 'nothing here', 'x')).toBe(0); + expect(doc.toString()).toContain( + 'bash .forgejo/scripts/x.sh && echo .forgejo/scripts/x.sh', + ); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/actions.ts b/tools/cli/scripts/forgejo-port/actions.ts new file mode 100644 index 0000000000..83bbcf54a1 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/actions.ts @@ -0,0 +1,303 @@ +/** + * What each action a workflow uses becomes on Forgejo. + * + * `uses: owner/repo@sha` is resolved by the runner against the instance's own + * `owner/repo` (a pull mirror, `DEFAULT_ACTIONS_URL = self`), so an action that + * works unchanged needs nothing but its mirror. The ones that do not are named + * here, each with why, so a reviewer reads the whole list in one place. + */ + +import { Scalar, YAMLMap, isMap, visit } from 'yaml'; +import type { Document } from 'yaml'; + +import { jobKnowledge, type Rule } from './context'; +import { parseUses, stepLists, stringOf } from './workflow'; + +/** + * Forgejo's own builds of the artifact actions. The upstream v4+ clients refuse every + * server that is not github.com (`isGhes()`); these are upstream's v5 and v7 with that + * check removed, at the commits Forgejo tags (code.forgejo.org/forgejo/upload-artifact + * `v5`, code.forgejo.org/forgejo/download-artifact `v7`). The upload is pinned at `v5` and + * not at `branch-v6`: the v6 client drops the padding of the signature in the signed URL, + * and the server refuses the upload. + */ +export const UPLOAD_ARTIFACT = { + name: 'forgejo/upload-artifact', + sha: 'cb8afe72b42edc798abfb8fcb556cf660d894245', + comment: ' v5, patched for Forgejo', +} as const; +export const DOWNLOAD_ARTIFACT = { + name: 'forgejo/download-artifact', + sha: '769f970437aa3291b13f35dc23fc87967d7fb19f', + comment: ' v7, patched for Forgejo', +} as const; + +export type ActionDisposition = + /** Works as it is, from its pull mirror. */ + | { readonly kind: 'keep' } + /** Another action does the same on Forgejo. */ + | { + readonly kind: 'replace'; + readonly to: typeof UPLOAD_ARTIFACT | typeof DOWNLOAD_ARTIFACT; + } + /** The step is removed, and says why. */ + | { readonly kind: 'drop'; readonly why: string } + /** It cannot work on Forgejo: a workflow that still has it is not ported. */ + | { readonly kind: 'unportable'; readonly why: string }; + +const CACHE_WHY = + "the runner's cache is per instance and the instance is deleted with its job: a restore always misses and a save only spends time"; + +export const ACTIONS: ReadonlyMap = new Map< + string, + ActionDisposition +>([ + ['actions/checkout', { kind: 'keep' }], + ['actions/setup-node', { kind: 'keep' }], + ['oven-sh/setup-bun', { kind: 'keep' }], + ['astral-sh/setup-uv', { kind: 'keep' }], + ['docker/setup-buildx-action', { kind: 'keep' }], + ['docker/setup-qemu-action', { kind: 'keep' }], + ['docker/build-push-action', { kind: 'keep' }], + ['docker/bake-action', { kind: 'keep' }], + ['docker/login-action', { kind: 'keep' }], + ['aquasecurity/trivy-action', { kind: 'keep' }], + ['dorny/paths-filter', { kind: 'keep' }], + [UPLOAD_ARTIFACT.name, { kind: 'keep' }], + [DOWNLOAD_ARTIFACT.name, { kind: 'keep' }], + ['actions/upload-artifact', { kind: 'replace', to: UPLOAD_ARTIFACT }], + ['actions/download-artifact', { kind: 'replace', to: DOWNLOAD_ARTIFACT }], + ['actions/cache', { kind: 'drop', why: CACHE_WHY }], + ['actions/cache/restore', { kind: 'drop', why: CACHE_WHY }], + ['actions/cache/save', { kind: 'drop', why: CACHE_WHY }], + [ + 'github/codeql-action/upload-sarif', + { + kind: 'drop', + why: 'it feeds GitHub code scanning, which Forgejo does not have', + }, + ], + [ + 'actions/github-script', + { + kind: 'unportable', + why: "it calls GitHub's REST API, whose shapes Forgejo's API does not share", + }, + ], + [ + 'ossf/scorecard-action', + { + kind: 'unportable', + why: 'it publishes to GitHub and needs its OIDC identity', + }, + ], +]); + +export interface ExternalAction { + readonly name: string; + readonly ref: string; +} + +/** Every external action a document uses, with the ref it pins. */ +export function externalActions( + doc: Parameters[0], +): ExternalAction[] { + const found: ExternalAction[] = []; + for (const { steps } of stepLists(doc)) { + for (const step of steps.items) { + const uses = isMap(step) ? stringOf(step.get('uses')) : undefined; + const parsed = uses === undefined ? undefined : parseUses(uses); + if (parsed?.kind === 'remote') + found.push({ name: parsed.name, ref: parsed.ref }); + } + } + return found; +} + +function usesOf(step: unknown): string | undefined { + return isMap(step) ? stringOf(step.get('uses')) : undefined; +} + +/** Rewrite, remove or flag every step by what its action becomes. */ +export const rewriteActions: Rule = (doc, context) => { + const { file, report, knowledge } = context; + for (const { at, steps } of stepLists(doc)) { + for (let index = steps.items.length - 1; index >= 0; index -= 1) { + const step = steps.items[index]; + const uses = usesOf(step); + if (!isMap(step) || uses === undefined) continue; + const parsed = parseUses(uses); + if (parsed.kind !== 'remote') continue; + const disposition = ACTIONS.get(parsed.name); + const where = `${at}.steps[${index}]`; + if (!disposition) { + report.warnings.push({ + file, + at: where, + rule: 'unknown-action', + detail: `\`${parsed.name}\` is not in the port's action table: add it, and its pull mirror`, + }); + continue; + } + if (disposition.kind === 'keep') continue; + if (disposition.kind === 'replace') { + const node = step.get('uses', true); + const next = `${disposition.to.name}@${disposition.to.sha}`; + if (node instanceof Scalar) { + node.value = next; + node.comment = disposition.to.comment; + } else step.set('uses', next); + report.changes.push({ + file, + at: where, + rule: 'action-replaced', + detail: `\`${parsed.name}\` is \`${disposition.to.name}\`: upstream's refuses a Forgejo server`, + }); + continue; + } + if (disposition.kind === 'unportable') { + report.warnings.push({ + file, + at: where, + rule: 'action-unportable', + detail: `\`${parsed.name}\`: ${disposition.why}`, + }); + continue; + } + const id = stringOf(step.get('id')); + steps.items.splice(index, 1); + if (id !== undefined) { + const owner = at.startsWith('jobs.') + ? jobKnowledge(knowledge, at.slice('jobs.'.length)).absent + : knowledge.absent; + owner.push(`steps.${id}.outputs`); + } + report.changes.push({ + file, + at: where, + rule: 'action-dropped', + detail: `removed \`${parsed.name}\`: ${disposition.why}`, + }); + } + } +}; + +// --- where the registry and the helpers live ---------------------------------- + +/** What a job or composite that this port also generates is called, by the name GitHub knows it. */ +export interface PortedPaths { + /** Local composite actions that are generated too: `setup-turbo`. */ + readonly composites: readonly string[]; + /** Repository files copied with the same text edits: `.github/scripts/pull-ci-images.sh`. */ + readonly scripts: readonly string[]; +} + +const GITHUB_ACTIONS_DIR = './.github/actions/'; +const FORGEJO_ACTIONS_DIR = './.forgejo/actions/'; + +/** + * A local composite action that is generated for Forgejo too is used from its + * Forgejo copy; one that is not ported is flagged where it is still used. + */ +export function rewriteLocalActions(paths: PortedPaths): Rule { + return (doc, context) => { + const { file, report } = context; + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + const uses = usesOf(step); + if ( + !isMap(step) || + uses === undefined || + !uses.startsWith(GITHUB_ACTIONS_DIR) + ) + continue; + const name = uses.slice(GITHUB_ACTIONS_DIR.length).replace(/\/$/, ''); + const where = `${at}.steps[${index}]`; + if (paths.composites.includes(name)) { + step.set('uses', `${FORGEJO_ACTIONS_DIR}${name}`); + report.changes.push({ + file, + at: where, + rule: 'local-action', + detail: `\`${uses}\` is generated for Forgejo as \`${FORGEJO_ACTIONS_DIR}${name}\``, + }); + } else { + report.warnings.push({ + file, + at: where, + rule: 'local-action-unported', + detail: `\`${uses}\` is not ported: it is GitHub-only`, + }); + } + } + } + }; +} + +/** Replace a text in every scalar string of a document; returns how many strings changed. */ +export function replaceText(doc: Document, from: string, to: string): number { + let count = 0; + visit(doc, { + Scalar(_key, node) { + if (typeof node.value === 'string' && node.value.includes(from)) { + node.value = node.value.replaceAll(from, to); + count += 1; + } + }, + }); + return count; +} + +export interface Registry { + /** The registry that holds CI images on Forgejo: `git.tale.dev`. */ + readonly host: string; + /** The secret that holds the package token of the CI user. */ + readonly tokenSecret: string; +} + +const GITHUB_REGISTRY = 'ghcr.io'; + +/** + * CI images are pushed to and pulled from Forgejo's registry, with the token of a + * user who may write packages: the job's own token can log in but not push. + */ +export function registryLogin(registry: Registry): Rule { + return (doc, context) => { + const { file, report } = context; + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + if (!usesOf(step)?.startsWith('docker/login-action@') || !isMap(step)) + continue; + const inputs = step.get('with'); + if (!isMap(inputs)) continue; + const target = stringOf(inputs.get('registry')); + if ( + target === undefined || + !(target.includes('env.REGISTRY') || target === GITHUB_REGISTRY) + ) + continue; + inputs.set('password', `\${{ secrets.${registry.tokenSecret} }}`); + report.changes.push({ + file, + at: `${at}.steps[${index}]`, + rule: 'registry-login', + detail: `logs in with \`secrets.${registry.tokenSecret}\`: the job token cannot push packages`, + }); + } + } + const env = + doc.contents instanceof YAMLMap ? doc.contents.get('env') : undefined; + if ( + env instanceof YAMLMap && + stringOf(env.get('REGISTRY')) === GITHUB_REGISTRY + ) { + env.set('REGISTRY', registry.host); + report.changes.push({ + file, + at: 'env.REGISTRY', + rule: 'registry-host', + detail: `\`${GITHUB_REGISTRY}\` is \`${registry.host}\``, + }); + } + }; +} diff --git a/tools/cli/scripts/forgejo-port/cache.ts b/tools/cli/scripts/forgejo-port/cache.ts new file mode 100644 index 0000000000..6d009f19fd --- /dev/null +++ b/tools/cli/scripts/forgejo-port/cache.ts @@ -0,0 +1,88 @@ +/** + * BuildKit's layer cache on Forgejo. + * + * GitHub's `type=gha` cache talks to the runner's cache service; on Forgejo that + * service is per instance (the instance is deleted with its job) and the exporter + * reaches out to api.github.com for the cache's bookkeeping. The cache that works + * is a registry cache in Forgejo's own registry. The build job already reads one + * (`...-buildcache:amd64`, which release.yml writes); here the build job also + * writes it, for a push of the merge train only: a pull request never writes a + * cache another run reads. + * + * The site images (web, docs, ui-docs) and the database image the integration job + * builds have no registry login before their cache step, which a registry cache + * needs, so they build without a layer cache. A login step before the cache would + * give them one. + */ + +import { isMap, isScalar } from 'yaml'; +import type { YAMLMap } from 'yaml'; + +import type { Rule } from './context'; +import { stepLists, stringOf } from './workflow'; + +const GHA = 'type=gha'; + +/** `cache-to` the build job wrote to GitHub's cache from main, as it is written today. */ +const BUILD_CACHE_TO = + /^\$\{\{\s*github\.event_name == 'push' && github\.ref == 'refs\/heads\/main' && format\('type=gha,scope=\{0\},mode=max,ghtoken=\{1\},repository=\{2\}', matrix\.service, secrets\.GITHUB_TOKEN, github\.repository\) \|\| ''\s*\}\}$/; + +const REGISTRY_CACHE_TO = + "${{ github.event_name == 'push' && format('type=registry,ref={0}/{1}/tale-{2}-buildcache:amd64,mode=max,ignore-error=true,compression=zstd', env.REGISTRY, github.repository, matrix.service) || '' }}"; + +const CACHE_KEYS = ['cache-from', 'cache-to', 'set'] as const; + +/** Lines of a scalar that do not mention the GitHub cache; `undefined` when none are left. */ +function withoutGha(text: string): string | undefined { + const kept = text.split('\n').filter((line) => !line.includes(GHA)); + const joined = kept.join('\n'); + return joined.trim() === '' + ? undefined + : joined.endsWith('\n') || !text.endsWith('\n') + ? joined + : `${joined}\n`; +} + +export const buildCache: Rule = (doc, context) => { + const { file, report } = context; + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + if (!isMap(step)) continue; + const inputs = step.get('with'); + if (!isMap(inputs)) continue; + for (const key of CACHE_KEYS) { + const text = stringOf(inputs.get(key)); + if (text === undefined || !text.includes(GHA)) continue; + const where = `${at}.steps[${index}].with.${key}`; + if (key === 'cache-to' && BUILD_CACHE_TO.test(text.trim())) { + setValue(inputs, key, REGISTRY_CACHE_TO); + report.changes.push({ + file, + at: where, + rule: 'build-cache', + detail: + 'the main-only GitHub cache export is a registry cache export for the merge train', + }); + continue; + } + const left = withoutGha(text); + if (left === undefined) inputs.delete(key); + else setValue(inputs, key, left); + report.changes.push({ + file, + at: where, + rule: 'build-cache', + detail: + 'removed the `type=gha` cache: the runner cache is per instance', + }); + } + } + } +}; + +/** Write a new text into an input, keeping the scalar's style (block or plain) where it has one. */ +function setValue(inputs: YAMLMap, key: string, value: string): void { + const node = inputs.get(key, true); + if (isScalar(node)) node.value = value; + else inputs.set(key, value); +} diff --git a/tools/cli/scripts/forgejo-port/context.ts b/tools/cli/scripts/forgejo-port/context.ts new file mode 100644 index 0000000000..b76192aa5d --- /dev/null +++ b/tools/cli/scripts/forgejo-port/context.ts @@ -0,0 +1,113 @@ +/** + * What the pipeline knows about a workflow while it is ported, and the shape of a + * rule. Kept apart from the pipeline so the rules and the pipeline can both + * import it. + */ + +import type { Document } from 'yaml'; + +import type { Conditional, Facts, Scalar } from './expression'; +import type { JobResult, RemovedJob } from './ready'; +import type { Report } from './workflow'; + +/** What is known about a workflow while it is ported; rules add to it. */ +export interface Knowledge { + /** Context paths with a known value: `needs.pr-scope.result` is `'success'`. */ + readonly values: Map; + /** Context paths (and below) that do not exist on Forgejo. */ + readonly absent: string[]; + /** The strings a context path can be: the events the generated workflow has. */ + readonly oneOf: Map; + /** Context paths whose value depends on the event: a scope output is 'false' for a pull request. */ + readonly conditional: Map; + /** Strings that mean another when a path is compared with them: a batch is a push. */ + readonly aliases: Map>; + /** What holds inside one job only, by job id: the size of its matrix, what its own steps report. */ + readonly jobs: Map; +} + +/** What is known inside one job. */ +export interface JobKnowledge { + readonly values: Map; + readonly absent: string[]; + readonly conditional: Map; +} + +export function newKnowledge(): Knowledge { + return { + values: new Map(), + absent: [], + oneOf: new Map(), + conditional: new Map(), + aliases: new Map(), + jobs: new Map(), + }; +} + +export function factsOf(knowledge: Knowledge): Facts { + return { + values: knowledge.values, + absent: knowledge.absent, + oneOf: knowledge.oneOf, + conditional: knowledge.conditional, + aliases: knowledge.aliases, + }; +} + +/** The facts that hold inside each job only, as the folder wants them. */ +export function jobFactsOf(knowledge: Knowledge): Map { + return new Map( + [...knowledge.jobs].map(([id, facts]) => [ + id, + { + values: facts.values, + absent: facts.absent, + conditional: facts.conditional, + } satisfies Facts, + ]), + ); +} + +/** The mutable facts of one job, made when first asked for. */ +export function jobKnowledge(knowledge: Knowledge, id: string): JobKnowledge { + const existing = knowledge.jobs.get(id); + if (existing) return existing; + const made: JobKnowledge = { + values: new Map(), + absent: [], + conditional: new Map(), + }; + knowledge.jobs.set(id, made); + return made; +} + +export type { JobResult, Tier } from './ready'; + +/** What a job would have reported to the jobs that need it, by the kind of run. */ +export type EventResults = RemovedJob; + +export const SKIPPED: JobResult = { result: 'skipped', outputs: {} }; + +export interface PortContext { + /** The file name under `.github/workflows`: `checks.yml`. */ + readonly file: string; + readonly report: Report; + readonly knowledge: Knowledge; + /** The jobs removed so far, with why. */ + readonly removed: Map; + /** + * What a removed job would have reported, where it is not simply skipped: the readiness + * policy judges the GitHub workflow's jobs, so a scope job that ran on a pull request + * and was folded away is handed its result and outputs back. + */ + readonly results: Map; +} + +/** A rule changes the document, and may teach the pipeline something. */ +export type Rule = (doc: Document, context: PortContext) => void; + +/** What a job that left the workflow is for the jobs that needed it: skipped, with no outputs. */ +export function learnRemoval(knowledge: Knowledge, id: string): void { + knowledge.values.set(`needs.${id}.result`, 'skipped'); + knowledge.absent.push(`needs.${id}.outputs`); +} diff --git a/tools/cli/scripts/forgejo-port/declared-checks.yml b/tools/cli/scripts/forgejo-port/declared-checks.yml new file mode 100644 index 0000000000..a123a7aef0 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/declared-checks.yml @@ -0,0 +1,11 @@ +# The checks the merge train waits for on tale/tale, one per workflow: the +# readiness job of each ported workflow, as Forgejo names its status. The ops +# repository declares them in deployments/tale/merge-train/pr/repositories.yml. +# Generated: bun tools/cli/scripts/forgejo-port.ts checks --write +- Build / CI ready (Build) +- CLI / CI ready (CLI) +- Checks / CI ready (Checks) +- Commitlint / CI ready (Commitlint) +- E2E / CI ready (E2E) +- SAST / CI ready (SAST) +- Security / CI ready (Security) diff --git a/tools/cli/scripts/forgejo-port/expression.test.ts b/tools/cli/scripts/forgejo-port/expression.test.ts new file mode 100644 index 0000000000..96d86d3302 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/expression.test.ts @@ -0,0 +1,491 @@ +import { describe, expect, test } from 'bun:test'; + +import { + ExpressionError, + contextPath, + foldTemplate, + hasStatusFunction, + keepStatusFunction, + parseExpression, + parseTemplate, + printExpression, + simplify, + truthy, + type Facts, +} from './expression'; + +const print = (source: string) => printExpression(parseExpression(source)); + +/** What a Forgejo run knows about a workflow whose candidate jobs were left out. */ +const forgejo: Facts = { + values: new Map([ + ['needs.candidate-source.result', 'skipped'], + ['needs.candidate-gate.result', 'skipped'], + ]), + absent: [ + 'github.event.client_payload', + 'github.event.merge_group', + 'needs.candidate-source.outputs', + ], + oneOf: new Map([['github.event_name', ['pull_request', 'push']]]), +}; + +function fold(source: string, mode: 'condition' | 'value' = 'condition') { + return printExpression(simplify(parseExpression(source), forgejo, mode)); +} + +describe('parseExpression and printExpression', () => { + test('keep contexts, indexing, wildcards and calls', () => { + expect(print('github.event.pull_request.head.repo.fork')).toBe( + 'github.event.pull_request.head.repo.fork', + ); + expect(print("matrix['service'].name")).toBe("matrix['service'].name"); + expect(print('needs.*.result')).toBe('needs.*.result'); + expect( + print('contains(fromJSON(needs.scope.outputs.services), matrix.service)'), + ).toBe('contains(fromJSON(needs.scope.outputs.services), matrix.service)'); + expect(print('hashFiles( "a" )'.replace('"a"', "'a'"))).toBe( + "hashFiles('a')", + ); + }); + + test('read names with hyphens as one name', () => { + expect( + contextPath( + parseExpression('needs.candidate-source.outputs.candidate_sha'), + ), + ).toBe('needs.candidate-source.outputs.candidate_sha'); + }); + + test('read GitHub literals', () => { + expect(parseExpression('true')).toEqual({ kind: 'literal', value: true }); + expect(parseExpression('null')).toEqual({ kind: 'literal', value: null }); + expect(parseExpression('42')).toEqual({ kind: 'literal', value: 42 }); + expect(parseExpression('-1.5e2')).toEqual({ kind: 'literal', value: -150 }); + expect(parseExpression('0x10')).toEqual({ kind: 'literal', value: 16 }); + expect(parseExpression("'it''s'")).toEqual({ + kind: 'literal', + value: "it's", + }); + expect(print("'it''s'")).toBe("'it''s'"); + }); + + test('read every escaped quote of a string, and any name it is given', () => { + expect(parseExpression("'a''b''c'")).toEqual({ + kind: 'literal', + value: "a'b'c", + }); + expect(print("'a''b''c'")).toBe("'a''b''c'"); + expect(print('someNewContext.value[otherName]')).toBe( + 'someNewContext.value[otherName]', + ); + }); + + test('give && more weight than ||, and ! more than both', () => { + expect(parseExpression('a || b && c')).toEqual({ + kind: 'binary', + op: '||', + left: { kind: 'ident', name: 'a' }, + right: { + kind: 'binary', + op: '&&', + left: { kind: 'ident', name: 'b' }, + right: { kind: 'ident', name: 'c' }, + }, + }); + expect(print('(a || b) && c')).toBe('(a || b) && c'); + expect(print('a || (b && c)')).toBe('a || b && c'); + expect(print('!(a && b)')).toBe('!(a && b)'); + expect(print('!a && b')).toBe('!a && b'); + expect(print("a == 'x' && b != 'y'")).toBe("a == 'x' && b != 'y'"); + }); + + test('keep a right-hand group of the same operator', () => { + expect(print('a && (b && c)')).toBe('a && (b && c)'); + expect(print('a && b && c')).toBe('a && b && c'); + }); + + test('round-trip every shape the workflows use', () => { + const sources = [ + "!cancelled() && (((github.event_name == 'repository_dispatch') && needs.candidate-source.result == 'success') || ((github.event_name != 'repository_dispatch') && needs.candidate-source.result == 'skipped'))", + "github.event_name == 'pull_request' && !startsWith(github.head_ref, 'dependabot/')", + "always() && (github.event_name == 'pull_request' || github.event_name == 'merge_group')", + "(needs.integration-scope.result != 'success' || needs.integration-scope.outputs.run == 'true')", + "github.event_name == 'push' && github.ref == 'refs/heads/main'", + "format('type=gha,scope={0},mode=max,ghtoken={1},repository={2}', matrix.service, secrets.GITHUB_TOKEN, github.repository)", + ]; + for (const source of sources) { + const once = print(source); + expect(print(once)).toBe(once); + expect(parseExpression(once)).toEqual(parseExpression(source)); + } + }); + + test('refuse what is not an expression', () => { + expect(() => parseExpression('a == ')).toThrow(ExpressionError); + expect(() => parseExpression("'open")).toThrow('Unterminated string'); + expect(() => parseExpression('a b')).toThrow('Unexpected token'); + expect(() => parseExpression('a @ b')).toThrow('Unexpected character'); + expect(() => parseExpression('f(a,')).toThrow(ExpressionError); + expect(() => parseExpression('(a')).toThrow('Expected ")"'); + }); +}); + +describe('contextPath', () => { + test('is undefined for a computed lookup', () => { + expect(contextPath(parseExpression('a[b]'))).toBeUndefined(); + expect(contextPath(parseExpression('f(a).b'))).toBeUndefined(); + expect(contextPath(parseExpression("a['b'].c"))).toBe('a.b.c'); + }); +}); + +describe('status functions', () => { + const parse = parseExpression; + + test('are found wherever an expression calls one, in any case', () => { + for (const source of [ + 'always()', + '!cancelled()', + 'success() && a', + "a == 'x' || FAILURE()", + 'contains(github.ref, always())', + 'a[always()]', + ]) + expect(hasStatusFunction(parse(source)), source).toBe(true); + for (const source of [ + 'a', + "github.event_name == 'push'", + 'contains(github.ref, x)', + ]) + expect(hasStatusFunction(parse(source)), source).toBe(false); + }); + + test('are put back when a fold left none, and only then', () => { + const keep = (original: string, folded: string) => + printExpression(keepStatusFunction(parse(original), parse(folded))); + expect(keep('always() || a', 'true')).toBe('always()'); + expect(keep('always() || a', 'b')).toBe('always() && b'); + expect(keep('always() || a', 'b || c')).toBe('always() && (b || c)'); + expect(keep('always() && a', 'false')).toBe('false'); + expect(keep('always() && a', '!cancelled()')).toBe('!cancelled()'); + expect(keep('a || b', 'true')).toBe('true'); + }); +}); + +describe('truthy', () => { + test('follows GitHub: only false, 0, NaN, empty and null are falsy', () => { + expect([false, 0, '', null, Number.NaN].some(truthy)).toBe(false); + expect([true, 1, 'false', 'x', -1].every(truthy)).toBe(true); + }); +}); + +describe('simplify', () => { + test('decides the candidate conditions of a ported workflow', () => { + expect( + fold( + "!cancelled() && (((github.event_name == 'repository_dispatch') && needs.candidate-source.result == 'success') || ((github.event_name != 'repository_dispatch') && needs.candidate-source.result == 'skipped'))", + ), + ).toBe('!cancelled()'); + }); + + test('keeps the conditions that are not about candidates', () => { + expect( + fold( + "!cancelled() && (((github.event_name == 'repository_dispatch') && needs.candidate-source.result == 'success') || ((github.event_name != 'repository_dispatch') && needs.candidate-source.result == 'skipped')) && (github.event.pull_request.draft != true)", + ), + ).toBe('!cancelled() && github.event.pull_request.draft != true'); + }); + + test('folds what it knows around a name it does not know', () => { + expect( + fold("someNewContext.value || github.event_name == 'merge_group'"), + ).toBe('someNewContext.value'); + }); + + test('drops the merge-group half of the readiness gate', () => { + expect( + fold( + "always() && (github.event_name == 'pull_request' || github.event_name == 'merge_group')", + ), + ).toBe("always() && github.event_name == 'pull_request'"); + }); + + test('follows value semantics of && and || in a value', () => { + expect( + fold("github.event_name == 'repository_dispatch' && 1 || 0", 'value'), + ).toBe('0'); + expect( + fold( + "github.event_name == 'repository_dispatch' && format('candidate-{0}', github.event.client_payload.candidate_sha) || github.ref", + 'value', + ), + ).toBe('github.ref'); + }); + + test('does not drop an operand a value would still show', () => { + expect(fold('x && true', 'value')).toBe('x && true'); + expect(fold('x && true', 'condition')).toBe('x'); + expect(fold('x || true', 'condition')).toBe('true'); + expect(fold('x || false', 'condition')).toBe('x'); + expect(fold('x && false', 'condition')).toBe('false'); + expect(fold('x || false', 'value')).toBe('x || false'); + }); + + test('reads an absent context as null', () => { + expect(fold('github.event.client_payload.candidate_sha', 'value')).toBe( + 'null', + ); + expect(fold('needs.candidate-source.outputs.candidate_sha', 'value')).toBe( + 'null', + ); + expect(fold("github.event.merge_group.base_sha == ''", 'value')).toBe( + 'true', + ); + }); + + test('compares strings without regard to case, as GitHub does', () => { + const facts: Facts = { values: new Map([['x', 'Skipped']]) }; + expect( + printExpression(simplify(parseExpression("x == 'skipped'"), facts)), + ).toBe('true'); + expect( + printExpression(simplify(parseExpression("x != 'skipped'"), facts)), + ).toBe('false'); + }); + + test('compares different types by their numbers, as GitHub does', () => { + const facts: Facts = { values: new Map([['x', 1]]) }; + const folded = (source: string) => + printExpression(simplify(parseExpression(source), facts)); + expect(folded("x == '1'")).toBe('true'); + expect(folded("x == 'one'")).toBe('false'); + expect(folded("null == ''")).toBe('true'); + expect(folded('true == 1')).toBe('true'); + expect(folded("false == ''")).toBe('true'); + expect(folded("'abc' == 0")).toBe('false'); + expect(folded("'abc' != 0")).toBe('true'); + }); + + test('decides only what the declared events settle', () => { + expect(fold("github.event_name == 'pull_request'")).toBe( + "github.event_name == 'pull_request'", + ); + expect(fold("github.event_name != 'push'")).toBe( + "github.event_name != 'push'", + ); + expect(fold("github.event_name == 'schedule'")).toBe('false'); + const single: Facts = { + oneOf: new Map([['github.event_name', ['push']]]), + }; + const folded = (source: string) => + printExpression(simplify(parseExpression(source), single)); + expect(folded("github.event_name == 'PUSH'")).toBe('true'); + expect(folded("'push' != github.event_name")).toBe('false'); + expect(folded("github.event_name == 'pull_request'")).toBe('false'); + }); + + test('negates a decided operand', () => { + expect(fold("!(github.event_name == 'merge_group')")).toBe('true'); + expect(fold("!(github.event_name != 'merge_group')")).toBe('false'); + }); + + test('simplifies inside calls and indexes', () => { + expect( + fold( + "contains(fromJSON(needs.x.outputs.y), github.event_name == 'merge_group' && 'a' || 'b')", + 'value', + ), + ).toBe("contains(fromJSON(needs.x.outputs.y), 'b')"); + }); +}); + +describe('conditional values', () => { + const pullRequest = parseExpression("github.event_name == 'pull_request'"); + const scoped: Facts = { + oneOf: new Map([['github.event_name', ['pull_request', 'push']]]), + conditional: new Map([ + // A queue-only scope: 'false' for a pull request, 'true' for a batch. + [ + 'needs.scope.outputs.run', + { when: pullRequest, ifTrue: 'false', ifFalse: 'true' }, + ], + // An output a pull request leaves unset. + [ + 'needs.scope.outputs.changes', + { when: pullRequest, ifTrue: '', ifFalse: '["web"]' }, + ], + ]), + }; + const read = (source: string, mode: 'condition' | 'value' = 'condition') => + printExpression(simplify(parseExpression(source), scoped, mode)); + + test('a comparison says what the condition says', () => { + expect(read("needs.scope.outputs.run == 'true'")).toBe( + "github.event_name != 'pull_request'", + ); + expect(read("needs.scope.outputs.run != 'true'")).toBe( + "github.event_name == 'pull_request'", + ); + expect(read("'false' == needs.scope.outputs.run")).toBe( + "github.event_name == 'pull_request'", + ); + expect(read("needs.scope.outputs.run == 'TRUE'")).toBe( + "github.event_name != 'pull_request'", + ); + expect(read("needs.scope.outputs.run == 'maybe'")).toBe('false'); + expect(read("needs.scope.outputs.changes == ''")).toBe( + "github.event_name == 'pull_request'", + ); + }); + + test('a value is read as the condition picks it', () => { + expect(read('needs.scope.outputs.run', 'value')).toBe( + "github.event_name == 'pull_request' && 'false' || 'true'", + ); + expect(read('needs.scope.outputs.changes', 'value')).toBe( + "github.event_name != 'pull_request' && '[\"web\"]' || ''", + ); + }); + + test('a truthiness needs only the branches that are not empty', () => { + expect(read('needs.scope.outputs.run')).toBe('true'); + expect(read('needs.scope.outputs.changes')).toBe( + "github.event_name != 'pull_request'", + ); + }); + + test('a run of one kind decides it', () => { + const batch: Facts = { + ...scoped, + oneOf: new Map([['github.event_name', ['push']]]), + }; + const foldBatch = (source: string) => + printExpression(simplify(parseExpression(source), batch)); + expect(foldBatch("needs.scope.outputs.run == 'true'")).toBe('true'); + expect(foldBatch('needs.scope.outputs.changes')).toBe('\'["web"]\''); + }); + + test('a condition and its negation fold together', () => { + expect( + read( + "github.event_name != 'pull_request' || (needs.scope.outputs.run == 'true' && needs.scope.outputs.run == 'true')", + ), + ).toBe("github.event_name != 'pull_request'"); + expect( + read( + "github.event_name == 'pull_request' || needs.scope.outputs.run == 'false'", + ), + ).toBe("github.event_name == 'pull_request'"); + expect( + read( + "needs.scope.outputs.run == 'true' || github.event_name == 'pull_request'", + ), + ).toBe('true'); + expect( + read( + "needs.scope.outputs.run == 'true' && github.event_name == 'pull_request'", + ), + ).toBe('false'); + }); + + test('refuse a value with no branch that can be read back', () => { + const facts: Facts = { + conditional: new Map([ + ['x.y', { when: pullRequest, ifTrue: '', ifFalse: null }], + ]), + }; + expect(() => simplify(parseExpression('x.y'), facts, 'value')).toThrow( + ExpressionError, + ); + }); +}); + +describe('aliases', () => { + const facts: Facts = { + aliases: new Map([ + ['github.event_name', new Map([['merge_group', 'push']])], + ]), + oneOf: new Map([['github.event_name', ['pull_request', 'push']]]), + }; + const read = (source: string) => + printExpression(simplify(parseExpression(source), facts)); + + test('a batch is a push', () => { + expect(read("github.event_name == 'merge_group'")).toBe( + "github.event_name == 'push'", + ); + expect(read("'Merge_Group' != github.event_name")).toBe( + "'push' != github.event_name", + ); + expect(read("github.event_name != 'pull_request'")).toBe( + "github.event_name != 'pull_request'", + ); + }); + + test('a workflow that only has pushes decides it', () => { + const only: Facts = { + ...facts, + oneOf: new Map([['github.event_name', ['push']]]), + }; + expect( + printExpression( + simplify(parseExpression("github.event_name == 'merge_group'"), only), + ), + ).toBe('true'); + }); +}); + +describe('templates', () => { + test('split text from holes, and a quoted }} stays in its string', () => { + expect(parseTemplate("a ${{ x }} b ${{ format('}}', y) }}")).toEqual([ + { kind: 'text', text: 'a ' }, + { kind: 'expr', expr: parseExpression('x') }, + { kind: 'text', text: ' b ' }, + { kind: 'expr', expr: parseExpression("format('}}', y)") }, + ]); + expect(() => parseTemplate('${{ x')).toThrow('Unterminated'); + }); + + test('a single hole that folds becomes a typed constant', () => { + expect( + foldTemplate( + "${{ github.event_name == 'repository_dispatch' && 1 || 0 }}", + forgejo, + ), + ).toEqual({ kind: 'constant', value: 0 }); + expect( + foldTemplate( + '${{ needs.candidate-source.outputs.candidate_sha }}', + forgejo, + ), + ).toEqual({ + kind: 'constant', + value: null, + }); + }); + + test('holes inside text are written back as text', () => { + expect( + foldTemplate( + "${{ github.workflow }}-${{ github.event_name == 'repository_dispatch' && 'c' || github.ref }}", + forgejo, + ), + ).toEqual({ + kind: 'text', + text: '${{ github.workflow }}-${{ github.ref }}', + }); + expect( + foldTemplate('pre-${{ needs.candidate-source.result }}-post', forgejo), + ).toEqual({ + kind: 'text', + text: 'pre-skipped-post', + }); + }); + + test('a template without holes is its own text', () => { + expect(foldTemplate('plain text', forgejo)).toEqual({ + kind: 'text', + text: 'plain text', + }); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/expression.ts b/tools/cli/scripts/forgejo-port/expression.ts new file mode 100644 index 0000000000..bd476fad7d --- /dev/null +++ b/tools/cli/scripts/forgejo-port/expression.ts @@ -0,0 +1,842 @@ +/** + * GitHub Actions expressions (`${{ … }}` and bare `if:` conditions): a parser, a + * printer and a constant folder. + * + * The Forgejo port rewrites workflows that were written for GitHub. Where an event + * can never happen on Forgejo (`repository_dispatch`, `merge_group`) or a job is + * left out (`candidate-source`), the conditions that mention them are decided at + * generation time instead of being carried into a file somebody has to maintain. + * That takes real expressions, not text substitution: a condition such as + * `!cancelled() && (((github.event_name == 'repository_dispatch') && …) || …)` has + * to come out as the shorter condition it means. + * + * Nothing here knows about workflows. The folder follows GitHub's semantics for + * what it folds (`&&` and `||` return an operand, strings compare without regard + * to case, `''`, `0`, `null` and `false` are falsy) and leaves everything else + * alone, so an expression it does not understand is carried through unchanged + * rather than guessed at. + * + * GitHub's own package, `@actions/expressions` (0.3.61), does not serve here, for three + * reasons. Its parser refuses an expression that names a context or a function it was not + * given beforehand, so one new name would stop the whole condition from being folded, where + * this parser folds what it knows and keeps the rest. Its lexer decodes only the first `''` of + * a string literal (`'a''b''c'` reads as `a'b''c`), and the folder compares string literals. + * And it has a parser and an evaluator but no printer and no partial evaluation (its evaluator + * reads a value it was not given as null, not as unknown, so it cannot leave the undecided part + * of a condition in place), so the folder and the printer below would stay, behind an adapter + * from its token-bearing tree to the folder's. The lexer and parser are the smallest part of + * this file. Revisit when its parser takes names it was not given and its lexer decodes every + * escape. + */ + +export type Scalar = null | boolean | number | string; + +export type BinaryOp = '&&' | '||' | '==' | '!=' | '<' | '<=' | '>' | '>='; + +export type Expr = + | { readonly kind: 'literal'; readonly value: Scalar } + | { readonly kind: 'ident'; readonly name: string } + | { + readonly kind: 'member'; + readonly object: Expr; + readonly property: string; + } + | { readonly kind: 'index'; readonly object: Expr; readonly index: Expr } + | { readonly kind: 'wildcard'; readonly object: Expr } + | { + readonly kind: 'call'; + readonly name: string; + readonly args: readonly Expr[]; + } + | { readonly kind: 'not'; readonly operand: Expr } + | { + readonly kind: 'binary'; + readonly op: BinaryOp; + readonly left: Expr; + readonly right: Expr; + }; + +export class ExpressionError extends Error { + constructor( + message: string, + readonly source: string, + readonly position: number, + ) { + super(`${message} at ${position} in: ${source}`); + this.name = 'ExpressionError'; + } +} + +type Token = + | { readonly type: 'literal'; readonly value: Scalar; readonly at: number } + | { readonly type: 'name'; readonly value: string; readonly at: number } + | { readonly type: 'punct'; readonly value: string; readonly at: number } + | { readonly type: 'end'; readonly at: number }; + +const NAME_START = /[A-Za-z_]/; +const NAME_PART = /[A-Za-z0-9_-]/; +const NUMBER = /^-?(?:0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/; + +function tokenize(source: string): Token[] { + const tokens: Token[] = []; + let at = 0; + while (at < source.length) { + const char = source.charAt(at); + if (/\s/.test(char)) { + at += 1; + continue; + } + if (char === "'") { + let value = ''; + let next = at + 1; + for (;;) { + if (next >= source.length) + throw new ExpressionError('Unterminated string', source, at); + const current = source.charAt(next); + if (current === "'") { + if (source.charAt(next + 1) === "'") { + value += "'"; + next += 2; + continue; + } + next += 1; + break; + } + value += current; + next += 1; + } + tokens.push({ type: 'literal', value, at }); + at = next; + continue; + } + const numeric = + char === '-' || /\d/.test(char) ? NUMBER.exec(source.slice(at)) : null; + if (numeric) { + tokens.push({ type: 'literal', value: Number(numeric[0]), at }); + at += numeric[0].length; + continue; + } + if (NAME_START.test(char)) { + let next = at + 1; + while (next < source.length && NAME_PART.test(source.charAt(next))) + next += 1; + tokens.push({ type: 'name', value: source.slice(at, next), at }); + at = next; + continue; + } + const pair = source.slice(at, at + 2); + if (['&&', '||', '==', '!=', '<=', '>='].includes(pair)) { + tokens.push({ type: 'punct', value: pair, at }); + at += 2; + continue; + } + if ('()[].,!<>*'.includes(char)) { + tokens.push({ type: 'punct', value: char, at }); + at += 1; + continue; + } + throw new ExpressionError( + `Unexpected character ${JSON.stringify(char)}`, + source, + at, + ); + } + tokens.push({ type: 'end', at: source.length }); + return tokens; +} + +/** Parse one expression, without the `${{ }}` around it. */ +export function parseExpression(source: string): Expr { + const tokens = tokenize(source); + let index = 0; + const peek = (): Token => tokens[index] ?? { type: 'end', at: source.length }; + const take = (): Token => { + const token = peek(); + index += 1; + return token; + }; + const isPunct = (value: string): boolean => { + const token = peek(); + return token.type === 'punct' && token.value === value; + }; + const expect = (value: string): void => { + const token = take(); + if (token.type !== 'punct' || token.value !== value) + throw new ExpressionError( + `Expected ${JSON.stringify(value)}`, + source, + token.at, + ); + }; + + const parseOr = (): Expr => { + let left = parseAnd(); + while (isPunct('||')) { + take(); + left = { kind: 'binary', op: '||', left, right: parseAnd() }; + } + return left; + }; + const parseAnd = (): Expr => { + let left = parseEquality(); + while (isPunct('&&')) { + take(); + left = { kind: 'binary', op: '&&', left, right: parseEquality() }; + } + return left; + }; + const takeOperator = (allowed: readonly BinaryOp[]): BinaryOp | undefined => { + const token = peek(); + if (token.type !== 'punct') return undefined; + const found = allowed.find((candidate) => candidate === token.value); + if (found !== undefined) take(); + return found; + }; + const parseEquality = (): Expr => { + let left = parseRelation(); + for ( + let op = takeOperator(['==', '!=']); + op; + op = takeOperator(['==', '!=']) + ) { + left = { kind: 'binary', op, left, right: parseRelation() }; + } + return left; + }; + const parseRelation = (): Expr => { + let left = parseUnary(); + const relations: readonly BinaryOp[] = ['<=', '>=', '<', '>']; + for (let op = takeOperator(relations); op; op = takeOperator(relations)) { + left = { kind: 'binary', op, left, right: parseUnary() }; + } + return left; + }; + const parseUnary = (): Expr => { + if (isPunct('!')) { + take(); + return { kind: 'not', operand: parseUnary() }; + } + return parsePostfix(); + }; + const parsePostfix = (): Expr => { + let node = parsePrimary(); + for (;;) { + if (isPunct('.')) { + take(); + const next = take(); + if (next.type === 'punct' && next.value === '*') { + node = { kind: 'wildcard', object: node }; + } else if (next.type === 'name') { + node = { kind: 'member', object: node, property: next.value }; + } else if (next.type === 'literal' && typeof next.value === 'number') { + // `a.0` is not valid GitHub syntax, but `needs.x.outputs.1` style names exist. + node = { kind: 'member', object: node, property: String(next.value) }; + } else + throw new ExpressionError( + 'Expected a property name', + source, + next.at, + ); + continue; + } + if (isPunct('[')) { + take(); + const inner = parseOr(); + expect(']'); + node = { kind: 'index', object: node, index: inner }; + continue; + } + return node; + } + }; + const parsePrimary = (): Expr => { + const token = take(); + if (token.type === 'literal') + return { kind: 'literal', value: token.value }; + if (token.type === 'punct' && token.value === '(') { + const inner = parseOr(); + expect(')'); + return inner; + } + if (token.type === 'name') { + if (isPunct('(')) { + take(); + const args: Expr[] = []; + if (!isPunct(')')) { + args.push(parseOr()); + while (isPunct(',')) { + take(); + args.push(parseOr()); + } + } + expect(')'); + return { kind: 'call', name: token.value, args }; + } + if (token.value === 'true') return { kind: 'literal', value: true }; + if (token.value === 'false') return { kind: 'literal', value: false }; + if (token.value === 'null') return { kind: 'literal', value: null }; + return { kind: 'ident', name: token.value }; + } + throw new ExpressionError('Unexpected token', source, token.at); + }; + + const result = parseOr(); + const rest = peek(); + if (rest.type !== 'end') + throw new ExpressionError('Unexpected token', source, rest.at); + return result; +} + +const PRECEDENCE: Record = { + '||': 1, + '&&': 2, + '==': 3, + '!=': 3, + '<': 4, + '<=': 4, + '>': 4, + '>=': 4, +}; +const NOT_PRECEDENCE = 5; +const ATOM_PRECEDENCE = 6; + +function precedenceOf(node: Expr): number { + if (node.kind === 'binary') return PRECEDENCE[node.op] ?? ATOM_PRECEDENCE; + if (node.kind === 'not') return NOT_PRECEDENCE; + return ATOM_PRECEDENCE; +} + +function printScalar(value: Scalar): string { + if (value === null) return 'null'; + if (typeof value === 'string') return `'${value.replaceAll("'", "''")}'`; + return String(value); +} + +/** The shortest text that parses back to the same tree. */ +export function printExpression(node: Expr): string { + switch (node.kind) { + case 'literal': + return printScalar(node.value); + case 'ident': + return node.name; + case 'member': + return `${printExpression(node.object)}.${node.property}`; + case 'index': + return `${printExpression(node.object)}[${printExpression(node.index)}]`; + case 'wildcard': + return `${printExpression(node.object)}.*`; + case 'call': + return `${node.name}(${node.args.map(printExpression).join(', ')})`; + case 'not': { + const inner = printExpression(node.operand); + return precedenceOf(node.operand) < NOT_PRECEDENCE + ? `!(${inner})` + : `!${inner}`; + } + case 'binary': { + const precedence = precedenceOf(node); + const left = printExpression(node.left); + const right = printExpression(node.right); + const leftText = + precedenceOf(node.left) < precedence ? `(${left})` : left; + const rightText = + precedenceOf(node.right) <= precedence ? `(${right})` : right; + return `${leftText} ${node.op} ${rightText}`; + } + } +} + +/** + * The dotted path of a plain context lookup (`github.event_name`, + * `needs.build.outputs['sha']`), or `undefined` when the lookup is computed. + */ +export function contextPath(node: Expr): string | undefined { + switch (node.kind) { + case 'ident': + return node.name; + case 'member': { + const parent = contextPath(node.object); + return parent === undefined ? undefined : `${parent}.${node.property}`; + } + case 'index': { + if (node.index.kind !== 'literal' || typeof node.index.value !== 'string') + return undefined; + const parent = contextPath(node.object); + return parent === undefined ? undefined : `${parent}.${node.index.value}`; + } + default: + return undefined; + } +} + +/** What the generator knows about the run a workflow will have on Forgejo. */ +export interface Facts { + /** Context paths with a known value: `needs.candidate-source.result` is `'skipped'`. */ + readonly values?: ReadonlyMap; + /** + * Context paths (and everything below them) that do not exist on Forgejo, so a + * lookup yields `null`: `github.event.client_payload` has no payload there. + */ + readonly absent?: readonly string[]; + /** + * The strings a path can be, when it can only be one of a few: a workflow that + * declares `push` and `pull_request` can only run as `github.event_name` of + * either, so a comparison with `merge_group` is decided. + */ + readonly oneOf?: ReadonlyMap; + /** + * Paths whose value depends on a condition that only holds, or not, when the run + * starts: a scope output is `'false'` for a pull request and `''` for a batch. + */ + readonly conditional?: ReadonlyMap; + /** + * Strings that mean another string when a path is compared with them, lowercase: + * a batch of the merge train is a push here, so `github.event_name == 'merge_group'` + * asks whether this run is one. + */ + readonly aliases?: ReadonlyMap>; +} + +/** A value that is `ifTrue` when `when` holds and `ifFalse` when it does not. */ +export interface Conditional { + readonly when: Expr; + readonly ifTrue: Scalar; + readonly ifFalse: Scalar; +} + +/** Where the result is read: a condition only needs a truthiness, a value is kept as it is. */ +export type Mode = 'condition' | 'value'; + +export function truthy(value: Scalar): boolean { + if (value === null || value === false || value === '') return false; + if (typeof value === 'number') return !(value === 0 || Number.isNaN(value)); + return true; +} + +/** GitHub's number for a value of another type: null is 0, true 1, '' 0, a JSON number itself, the rest NaN. */ +function toNumber(value: Scalar): number { + if (value === null) return 0; + if (typeof value === 'number') return value; + if (typeof value === 'boolean') return value ? 1 : 0; + if (value === '') return 0; + return /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) + ? Number(value) + : Number.NaN; +} + +/** GitHub's `==`: strings without regard to case, other types by their numbers. */ +function looseEquals(a: Scalar, b: Scalar): boolean { + if (typeof a === 'string' && typeof b === 'string') + return a.toLowerCase() === b.toLowerCase(); + if (a === null && b === null) return true; + if (typeof a === typeof b) return a === b; + return toNumber(a) === toNumber(b); +} + +function lookup( + node: Expr, + facts: Facts, +): { found: true; value: Scalar } | { found: false } { + const path = contextPath(node); + if (path === undefined) return { found: false }; + const known = facts.values?.get(path); + if (known !== undefined) return { found: true, value: known }; + for (const prefix of facts.absent ?? []) + if (path === prefix || path.startsWith(`${prefix}.`)) + return { found: true, value: null }; + return { found: false }; +} + +function isLiteral(node: Expr): node is Extract { + return node.kind === 'literal'; +} + +/** + * Fold what the facts decide and nothing else. `condition` mode may also drop an + * operand whose value a truthiness test would never see (`x && true` is `x`). + */ +export function simplify(node: Expr, facts: Facts, mode: Mode = 'value'): Expr { + switch (node.kind) { + case 'literal': + return node; + case 'ident': + case 'member': + case 'index': { + const resolved = lookup(node, facts); + if (resolved.found) return { kind: 'literal', value: resolved.value }; + const conditional = conditionalAt(node, facts); + if (conditional) return conditionalNode(conditional, facts, mode); + if (node.kind === 'ident') return node; + return { + ...node, + object: simplify(node.object, facts, 'value'), + ...(node.kind === 'index' + ? { index: simplify(node.index, facts, 'value') } + : {}), + } as Expr; + } + case 'wildcard': + return { + kind: 'wildcard', + object: simplify(node.object, facts, 'value'), + }; + case 'call': + return { + ...node, + args: node.args.map((arg) => simplify(arg, facts, 'value')), + }; + case 'not': { + const operand = simplify(node.operand, facts, 'condition'); + if (isLiteral(operand)) + return { kind: 'literal', value: !truthy(operand.value) }; + return { kind: 'not', operand }; + } + case 'binary': + return simplifyBinary(node, facts, mode); + } +} + +function literalOf(value: Scalar): Expr { + return { kind: 'literal', value }; +} + +/** Whether an expression is a boolean whatever its operands are. */ +function isBoolean(node: Expr): boolean { + switch (node.kind) { + case 'literal': + return typeof node.value === 'boolean'; + case 'not': + return true; + case 'binary': + return node.op === '&&' || node.op === '||' + ? isBoolean(node.left) && isBoolean(node.right) + : true; + case 'call': + return ['contains', 'startswith', 'endswith'].includes( + node.name.toLowerCase(), + ); + default: + return false; + } +} + +/** `!node`, written the shortest way: `!(a == b)` is `a != b`. */ +function notOf(node: Expr): Expr { + if (isLiteral(node)) return literalOf(!truthy(node.value)); + if (node.kind === 'not' && isBoolean(node.operand)) return node.operand; + if (node.kind === 'binary' && (node.op === '==' || node.op === '!=')) + return { ...node, op: node.op === '==' ? '!=' : '==' }; + return { kind: 'not', operand: node }; +} + +function conditionalAt(node: Expr, facts: Facts): Conditional | undefined { + const path = contextPath(node); + return path === undefined ? undefined : facts.conditional?.get(path); +} + +/** A conditional path read as a value (`when && ifTrue || ifFalse`) or as a truthiness. */ +function conditionalNode( + conditional: Conditional, + facts: Facts, + mode: Mode, +): Expr { + const { ifTrue, ifFalse } = conditional; + const when = simplify(conditional.when, facts, 'condition'); + if (isLiteral(when)) return literalOf(truthy(when.value) ? ifTrue : ifFalse); + if (ifTrue === ifFalse) return literalOf(ifTrue); + if (mode === 'condition') { + const [yes, no] = [truthy(ifTrue), truthy(ifFalse)]; + if (yes && no) return literalOf(true); + if (!yes && !no) return literalOf(false); + return yes ? when : notOf(when); + } + if (truthy(ifTrue)) + return { + kind: 'binary', + op: '||', + left: { kind: 'binary', op: '&&', left: when, right: literalOf(ifTrue) }, + right: literalOf(ifFalse), + }; + if (truthy(ifFalse)) + return { + kind: 'binary', + op: '||', + left: { + kind: 'binary', + op: '&&', + left: notOf(when), + right: literalOf(ifFalse), + }, + right: literalOf(ifTrue), + }; + throw new ExpressionError( + 'A conditional value needs one branch that is not false, null, 0 or empty', + printExpression(conditional.when), + 0, + ); +} + +/** A comparison of a conditional path with a literal: what the condition says about it. */ +function compareConditional( + node: Extract, + facts: Facts, +): Expr | undefined { + const decide = (pathSide: Expr, otherSide: Expr): Expr | undefined => { + if (lookup(pathSide, facts).found) return undefined; + const conditional = conditionalAt(pathSide, facts); + if (!conditional) return undefined; + const other = simplify(otherSide, facts, 'value'); + if (!isLiteral(other)) return undefined; + const when = simplify(conditional.when, facts, 'condition'); + const [yes, no] = [ + looseEquals(conditional.ifTrue, other.value), + looseEquals(conditional.ifFalse, other.value), + ]; + let equal: Expr; + if (isLiteral(when)) equal = literalOf(truthy(when.value) ? yes : no); + else if (yes === no) equal = literalOf(yes); + else equal = yes ? when : notOf(when); + return node.op === '==' ? equal : notOf(equal); + }; + return decide(node.left, node.right) ?? decide(node.right, node.left); +} + +/** The literal a path is compared with, in the words this run uses for it. */ +function aliasLiteral(pathSide: Expr, literalSide: Expr, facts: Facts): Expr { + const path = contextPath(pathSide); + const table = path === undefined ? undefined : facts.aliases?.get(path); + if ( + !table || + !isLiteral(literalSide) || + typeof literalSide.value !== 'string' + ) + return literalSide; + const renamed = table.get(literalSide.value.toLowerCase()); + return renamed === undefined ? literalSide : literalOf(renamed); +} + +/** What a comparison of a path with a string is, when the path can only be one of a few strings. */ +function decidedByOneOf( + left: Expr, + right: Expr, + facts: Facts, +): boolean | undefined { + const path = contextPath(left); + if ( + path === undefined || + !isLiteral(right) || + typeof right.value !== 'string' + ) + return undefined; + const allowed = facts.oneOf?.get(path); + if (allowed === undefined) return undefined; + const wanted = right.value.toLowerCase(); + const listed = allowed.some((entry) => entry.toLowerCase() === wanted); + if (!listed) return false; + return allowed.length === 1 ? true : undefined; +} + +function simplifyBinary( + node: Extract, + facts: Facts, + mode: Mode, +): Expr { + const { op } = node; + if (op === '&&' || op === '||') { + const left = simplify( + node.left, + facts, + 'condition' === mode ? 'condition' : 'value', + ); + if (isLiteral(left)) { + const decided = truthy(left.value); + if (op === '&&') + return decided ? simplify(node.right, facts, mode) : left; + return decided ? left : simplify(node.right, facts, mode); + } + const right = simplify(node.right, facts, mode); + if (mode === 'condition' && isLiteral(right)) { + const decided = truthy(right.value); + if (op === '&&') + return decided ? left : { kind: 'literal', value: false }; + return decided ? { kind: 'literal', value: true } : left; + } + // `p && p` and `p || p` are `p`; `p || !p` always holds and `p && !p` never does. + if (sameExpression(left, right)) return left; + if ( + isBoolean(left) && + isBoolean(right) && + sameExpression(notOf(left), right) + ) + return literalOf(op === '||'); + return { kind: 'binary', op, left, right }; + } + if (op === '==' || op === '!=') { + const conditional = compareConditional(node, facts); + if (conditional) return conditional; + } + let left = simplify(node.left, facts, 'value'); + let right = simplify(node.right, facts, 'value'); + if (op === '==' || op === '!=') { + const [leftPath, rightPath] = [left, right]; + left = aliasLiteral(rightPath, left, facts); + right = aliasLiteral(leftPath, right, facts); + if (isLiteral(left) && isLiteral(right)) { + const equal = looseEquals(left.value, right.value); + return { kind: 'literal', value: op === '==' ? equal : !equal }; + } + const decided = + decidedByOneOf(left, right, facts) ?? decidedByOneOf(right, left, facts); + if (decided !== undefined) + return { kind: 'literal', value: op === '==' ? decided : !decided }; + } + return { kind: 'binary', op, left, right }; +} + +const STATUS_FUNCTIONS = new Set(['always', 'cancelled', 'failure', 'success']); + +/** Whether an expression calls a status check function: `always()`, `cancelled()`, `failure()` or `success()`. */ +export function hasStatusFunction(node: Expr): boolean { + switch (node.kind) { + case 'literal': + case 'ident': + return false; + case 'member': + case 'wildcard': + return hasStatusFunction(node.object); + case 'index': + return hasStatusFunction(node.object) || hasStatusFunction(node.index); + case 'call': + return ( + STATUS_FUNCTIONS.has(node.name.toLowerCase()) || + node.args.some(hasStatusFunction) + ); + case 'not': + return hasStatusFunction(node.operand); + case 'binary': + return hasStatusFunction(node.left) || hasStatusFunction(node.right); + } +} + +/** + * GitHub and Forgejo put `success() &&` in front of an `if:` that calls no status function, + * so the job or step is skipped once something it needs has failed. A condition that called + * one and folds to something that calls none (`always() || github.event_name == 'push'` in a + * workflow that only pushes is true, and `true` is a condition that waits for success) would + * change when it runs, so the status function is put back: `always()` for a condition that + * holds, `always() && ` for one that still depends on something. A condition that + * is false is false whatever the status. + */ +export function keepStatusFunction(original: Expr, folded: Expr): Expr { + if (!hasStatusFunction(original) || hasStatusFunction(folded)) return folded; + if (isLiteral(folded) && !truthy(folded.value)) return folded; + const always: Expr = { kind: 'call', name: 'always', args: [] }; + if (isLiteral(folded)) return always; + return { kind: 'binary', op: '&&', left: always, right: folded }; +} + +/** A string value with `${{ }}` holes. */ +export type TemplatePart = + | { readonly kind: 'text'; readonly text: string } + | { readonly kind: 'expr'; readonly expr: Expr }; + +/** Split `a ${{ x }} b` into its text and its expressions. */ +export function parseTemplate(source: string): TemplatePart[] { + const parts: TemplatePart[] = []; + let at = 0; + for (;;) { + const open = source.indexOf('${{', at); + if (open === -1) { + if (at < source.length) + parts.push({ kind: 'text', text: source.slice(at) }); + return parts; + } + if (open > at) parts.push({ kind: 'text', text: source.slice(at, open) }); + const close = findClose(source, open + 3); + if (close === -1) + throw new ExpressionError('Unterminated ${{', source, open); + parts.push({ + kind: 'expr', + expr: parseExpression(source.slice(open + 3, close)), + }); + at = close + 2; + } +} + +/** The `}}` that ends a hole, skipping any that sits inside a string literal. */ +function findClose(source: string, from: number): number { + let inString = false; + for (let at = from; at < source.length; at += 1) { + const char = source.charAt(at); + if (char === "'") inString = !inString; + else if (!inString && char === '}' && source.charAt(at + 1) === '}') + return at; + } + return -1; +} + +/** The text of a literal when it is written into a larger string. */ +function interpolate(value: Scalar): string { + if (value === null) return ''; + return String(value); +} + +export type TemplateResult = + /** The template is one expression that folded to a constant: use the typed value. */ + | { readonly kind: 'constant'; readonly value: Scalar } + | { readonly kind: 'text'; readonly text: string }; + +/** + * Fold every hole of a template. A template that is a single hole and folds to a + * constant becomes that constant, so `fetch-depth: ${{ a && 1 || 0 }}` can end as the + * number `0`; anything else is returned as text, with the holes that did not fold + * printed back. + */ +export function foldTemplate( + source: string, + facts: Facts, + mode: Mode = 'value', +): TemplateResult { + const parts = parseTemplate(source).map((part) => + part.kind === 'expr' + ? { kind: 'expr' as const, expr: simplify(part.expr, facts, mode) } + : part, + ); + const only = parts.length === 1 ? parts[0] : undefined; + if (only?.kind === 'expr' && isLiteral(only.expr)) + return { kind: 'constant', value: only.expr.value }; + const text = parts + .map((part) => { + if (part.kind === 'text') return part.text; + if (isLiteral(part.expr)) return interpolate(part.expr.value); + return `\${{ ${printExpression(part.expr)} }}`; + }) + .join(''); + return { kind: 'text', text }; +} + +/** Whether a string holds an expression at all. */ +export function hasExpression(source: string): boolean { + return source.includes('${{'); +} + +/** The operands of a chain of `&&`, outermost first: `a && (b && c)` is `[a, b, c]`. */ +export function conjuncts(node: Expr): Expr[] { + if (node.kind === 'binary' && node.op === '&&') + return [...conjuncts(node.left), ...conjuncts(node.right)]; + return [node]; +} + +/** `&&` of the operands, or `undefined` for none (always true). */ +export function allOf(nodes: readonly Expr[]): Expr | undefined { + return nodes.reduce( + (left, right) => + left === undefined ? right : { kind: 'binary', op: '&&', left, right }, + undefined, + ); +} + +/** Whether two expressions are the same tree, whatever their spacing. */ +export function sameExpression(a: Expr, b: Expr): boolean { + return printExpression(a) === printExpression(b); +} diff --git a/tools/cli/scripts/forgejo-port/generate.test.ts b/tools/cli/scripts/forgejo-port/generate.test.ts new file mode 100644 index 0000000000..008f18a4e9 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/generate.test.ts @@ -0,0 +1,324 @@ +import { describe, expect, test } from 'bun:test'; + +import { generate } from './generate'; +import type { Manifest } from './manifest'; + +const SHA = 'a'.repeat(40); + +const SCRIPT = '.github/scripts/pull.sh'; + +/** A manifest of its own, so that no rule of the port is held back by what the real one names. */ +const MANIFEST: Manifest = { + tier: 'full', + registry: { host: 'git.example.test', tokenSecret: 'CI_PACKAGES_TOKEN' }, + githubApiTokenSecret: 'CI_GITHUB_TOKEN', + labels: ['ubuntu-latest'], + composites: ['setup-turbo'], + scripts: [{ from: SCRIPT, to: '.forgejo/scripts/pull.sh', edits: [] }], + workflows: {}, + githubEdits: [], +}; + +const COMPOSITE = `name: Setup turbo +runs: + using: composite + steps: + - run: echo turbo + shell: bash +`; + +/** One job on a runner the pool serves, with the steps given. */ +const job = (id: string, steps: string, more = ''): string => ` + ${id}: + runs-on: ubuntu-latest +${more} steps: +${steps}`; + +const workflow = (jobs: string, more = ''): string => + `name: W +on: + pull_request: +${more}jobs:${jobs}`; + +interface Row { + /** The rules that must have changed something, by the name they report. */ + readonly rules: readonly string[]; + /** Text the generated workflow must hold, for a rule that reports nothing. */ + readonly text?: readonly string[]; + readonly file?: string; + readonly source: string; + readonly manifest?: Partial; +} + +/** + * A workflow in which each rule of the port has something to change. A rule that is dropped + * from the generator changes nothing, says nothing and warns of nothing, so the only thing + * that shows it is gone is that its change is missing from the report. + */ +const ROWS: Record = { + dropJobs: { + rules: ['job-dropped'], + source: workflow( + job('keep', ' - run: echo keep\n') + + job('gone', ' - run: echo gone\n'), + ), + manifest: { + workflows: { + 'w.yml': { + kind: 'port', + dropJobs: [{ id: 'gone', why: 'the node cannot run it' }], + }, + }, + }, + }, + services: { + rules: ['services'], + source: workflow( + job( + 'db', + ' - run: echo db\n', + ' services:\n postgres:\n image: postgres:18\n ports:\n - 5432:5432\n', + ), + ), + }, + environment: { + rules: ['environment'], + source: workflow( + job( + 'deploy', + ' - run: echo deploy\n', + ' environment: production\n', + ), + ), + }, + matrixTotals: { + rules: [], + text: ['--shard=${{ matrix.shard }}/3'], + source: workflow( + job( + 'test', + ' - run: bun test --shard=${{ matrix.shard }}/${{ strategy.job-total }}\n', + ' strategy:\n matrix:\n shard: [1, 2, 3]\n', + ), + ), + }, + ciScope: { + rules: ['scope-job'], + source: `name: E2E +on: + merge_group: + pull_request: +jobs: + pr-scope: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + outputs: + run: \${{ steps.scope.outputs.run }} + steps: + - uses: actions/checkout@${SHA} + with: + sparse-checkout: | + /.github/actions/ci-scope/action.yml + - id: scope + uses: ./.github/actions/ci-scope + with: + filter: e2e + queue-only: 'true' + suite: + needs: [pr-scope] + if: needs.pr-scope.outputs.run == 'true' + runs-on: ubuntu-latest + steps: + - run: echo suite +`, + }, + queueOnlyJobs: { + rules: ['queue-only'], + file: 'checks.yml', + source: `name: Checks +on: + merge_group: + pull_request: +jobs: + build: + if: github.event_name != 'pull_request' && !cancelled() + runs-on: ubuntu-latest + steps: + - run: echo build +`, + }, + dropForeignRows: { + rules: ['matrix-row'], + source: workflow(` + build: + runs-on: \${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-latest + - os: macos-latest + steps: + - run: echo build +`), + }, + readyJob: { + rules: ['ready'], + source: workflow( + job('lint', ' - run: echo lint\n') + + ` + ci-ready: + name: CI ready (W) + needs: [lint] + if: always() + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@${SHA} +`, + ), + }, + rewriteActions: { + rules: ['action-replaced'], + source: workflow( + job('upload', ` - uses: actions/upload-artifact@${SHA}\n`), + ), + }, + buildCache: { + rules: ['build-cache'], + source: workflow( + job( + 'image', + ` - uses: docker/build-push-action@${SHA}\n with:\n cache-from: type=gha,scope=web\n`, + ), + ), + }, + registryLogin: { + rules: ['registry-login', 'registry-host'], + source: workflow( + job( + 'login', + ` - uses: docker/login-action@${SHA}\n with:\n registry: \${{ env.REGISTRY }}\n`, + ), + 'env:\n REGISTRY: ghcr.io\n', + ), + }, + rewriteLocalActions: { + rules: ['local-action'], + source: workflow( + job('setup', ' - uses: ./.github/actions/setup-turbo\n'), + ), + }, + movePaths: { + rules: ['path'], + source: workflow(job('pull', ` - run: ${SCRIPT}\n`)), + }, + runUrls: { + rules: ['run-url'], + source: workflow( + job( + 'link', + ' - run: echo ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\n', + ), + ), + }, + batchEvent: { + rules: ['batch-event'], + file: 'build.yml', + source: workflow( + job( + 'changes', + ' - run: |\n if [ "$EVENT_NAME" = merge_group ]; then\n echo all\n fi\n', + ), + ), + }, + commitlintBatch: { + rules: ['commitlint-batch'], + file: 'commitlint.yml', + source: workflow( + job('commitlint', ' - run: bunx commitlint --last --verbose\n'), + ), + }, + lintLinksBase: { + rules: ['lint-links-base'], + file: 'checks.yml', + source: workflow( + job( + 'format', + ` - uses: actions/checkout@${SHA}\n with:\n fetch-depth: 2\n - run: bun run lint:links\n`, + ), + ), + }, + publishRemote: { + rules: ['publish-remote'], + file: 'publish-packages.yml', + source: workflow( + job( + 'publish', + ' - run: |\n REMOTE="https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"\n echo "github:${GITHUB_REPOSITORY}#dist/ui"\n', + ), + ), + }, + publishOnTag: { + rules: ['publish-on-tag'], + file: 'publish-packages.yml', + source: `name: Publish packages +on: + push: + branches: + - main + workflow_dispatch: + inputs: + release_tag: + required: false + type: string +jobs: + publish: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@${SHA} + - name: Resolve snapshot tag + id: tag + env: + REF: \${{ github.ref }} + RELEASE_TAG: \${{ inputs.release_tag }} + SOURCE_SHA: \${{ inputs.source_sha }} + run: echo "$REF" +`, + }, + githubApiToken: { + rules: ['github-api-token'], + source: workflow( + job( + 'build', + ' - run: bunx turbo run build\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n', + ), + ), + }, + ownPath: { + rules: ['own-path'], + source: workflow( + job('lint', ' - run: echo lint\n'), + " paths:\n - '.github/workflows/w.yml'\n", + ), + }, +}; + +describe('the rules a workflow is ported by', () => { + for (const [name, row] of Object.entries(ROWS)) + test(`${name} is run by the generator`, () => { + const file = row.file ?? 'w.yml'; + const generated = generate( + { + workflows: new Map([[file, row.source]]), + actions: new Map([['setup-turbo', COMPOSITE]]), + files: new Map([[SCRIPT, '#!/bin/sh\n']]), + }, + { ...MANIFEST, ...row.manifest }, + ); + const changed = generated.report.changes.map((change) => change.rule); + for (const rule of row.rules) expect(changed, rule).toContain(rule); + const text = generated.files.get(`.forgejo/workflows/${file}`) ?? ''; + for (const fragment of row.text ?? []) + expect(text, fragment).toContain(fragment); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/generate.ts b/tools/cli/scripts/forgejo-port/generate.ts new file mode 100644 index 0000000000..b6cb24b19c --- /dev/null +++ b/tools/cli/scripts/forgejo-port/generate.ts @@ -0,0 +1,240 @@ +/** + * Generate `.forgejo/` from `.github/`: the whole port, as a function of text. + * + * Nothing here reads a disk or a network: the sources go in as strings and the files + * come out as strings, with what was done said once in the report and what Forgejo + * would refuse said in `problems`. The command line (`../forgejo-port.ts`) is the + * only thing that touches files. + */ + +import { isMap } from 'yaml'; + +import { + externalActions, + registryLogin, + rewriteActions, + rewriteLocalActions, +} from './actions'; +import { buildCache } from './cache'; +import type { Rule, Tier } from './context'; +import { + MANIFEST, + planFor, + tierOf, + type Manifest, + type Plan, +} from './manifest'; +import { portAction, portWorkflow } from './port'; +import { defaultRules } from './rules'; +import { validateAction, validateWorkflow, type Problem } from './validate'; +import { + emptyReport, + jobOf, + readWorkflow, + stringOf, + type Report, +} from './workflow'; +import { + batchEvent, + commitlintBatch, + dropForeignRows, + dropJobs, + githubApiToken, + lintLinksBase, + movePaths, + ownPath, + publishOnTag, + publishRemote, + readyJob, + recordRemoved, + runUrls, +} from './workflow-rules'; + +export interface Sources { + /** `.github/workflows/` by file name. */ + readonly workflows: ReadonlyMap; + /** `.github/actions//action.yml` by action name. */ + readonly actions: ReadonlyMap; + /** Other repository files the generated workflows use, by path. */ + readonly files: ReadonlyMap; +} + +export interface WorkflowOutcome { + readonly file: string; + readonly plan: Plan; + /** The generated jobs, when it was ported. */ + readonly jobs: readonly string[]; + /** The jobs of the GitHub file that are not in the generated one, with why. */ + readonly removed: ReadonlyMap; + readonly events: readonly string[]; + /** What a pull request owes of it. */ + readonly tier?: Tier; +} + +export interface Generated { + /** Repository path to text. */ + readonly files: ReadonlyMap; + readonly outcomes: readonly WorkflowOutcome[]; + /** ` / ` of every readiness job: what the merge train reads. */ + readonly checks: readonly string[]; + readonly report: Report; + /** What Forgejo would refuse in the files above. Empty when the port is sound. */ + readonly problems: readonly Problem[]; + /** The external actions the files use, by `owner/name`, with the refs they pin: what the node must mirror. */ + readonly actions: ReadonlyMap; +} + +export const WORKFLOW_DIR = '.forgejo/workflows'; +const ACTION_DIR = '.forgejo/actions'; + +const HEADER = (from: string): string => + `# Generated by tools/cli/scripts/forgejo-port from ${from}.\n` + + '# Once Tale is built on Forgejo this is the file to edit, by hand: the generator is for the cut-over.\n'; + +/** The rules every ported workflow goes through, in order. */ +function rulesFor( + plan: Extract, + manifest: Manifest, +): Rule[] { + const moves = manifest.scripts.map((script) => ({ + from: script.from, + to: script.to, + })); + return [ + dropJobs(plan.dropJobs ?? []), + ...defaultRules(tierOf(manifest, plan)), + dropForeignRows(manifest.labels), + readyJob(tierOf(manifest, plan)), + rewriteActions, + buildCache, + registryLogin(manifest.registry), + rewriteLocalActions({ + composites: manifest.composites, + scripts: manifest.scripts.map((script) => script.from), + }), + movePaths(moves), + runUrls, + batchEvent, + commitlintBatch, + lintLinksBase, + publishRemote, + publishOnTag, + githubApiToken(manifest.githubApiTokenSecret), + ownPath, + ]; +} + +export function generate( + sources: Sources, + manifest: Manifest = MANIFEST, +): Generated { + const files = new Map(); + const report = emptyReport(); + const problems: Problem[] = []; + const outcomes: WorkflowOutcome[] = []; + const checks: string[] = []; + + for (const [file, source] of [...sources.workflows].toSorted(([a], [b]) => + a.localeCompare(b), + )) { + const plan = planFor(manifest, file); + if (plan.kind !== 'port') { + outcomes.push({ file, plan, jobs: [], removed: new Map(), events: [] }); + continue; + } + const ported = portWorkflow(source, file, report, { + rules: rulesFor(plan, manifest), + after: [recordRemoved], + triggers: { dropEvents: plan.dropEvents ?? [] }, + }); + const path = `${WORKFLOW_DIR}/${file}`; + const text = HEADER(`.github/workflows/${file}`) + ported.text; + files.set(path, text); + outcomes.push({ + file, + plan, + jobs: ported.jobs, + removed: ported.removed, + events: ported.events, + tier: tierOf(manifest, plan), + }); + problems.push(...validateWorkflow(text, path, { labels: manifest.labels })); + const doc = readWorkflow(ported.text, file); + const name = isMap(doc.contents) + ? stringOf(doc.contents.get('name')) + : undefined; + const ready = jobOf(doc, 'ci-ready'); + const readyName = ready && stringOf(ready.get('name')); + if (name !== undefined && readyName !== undefined) + checks.push(`${name} / ${readyName}`); + } + + for (const name of manifest.composites) { + const source = sources.actions.get(name); + if (source === undefined) { + problems.push({ + file: `.github/actions/${name}/action.yml`, + at: '', + message: 'is named by the manifest and does not exist', + }); + continue; + } + const path = `${ACTION_DIR}/${name}/action.yml`; + const text = + HEADER(`.github/actions/${name}/action.yml`) + + portAction(source, path, report, [rewriteActions]); + files.set(path, text); + problems.push(...validateAction(text, path)); + } + + for (const script of manifest.scripts) { + const source = sources.files.get(script.from); + if (source === undefined) { + problems.push({ + file: script.from, + at: '', + message: 'is named by the manifest and does not exist', + }); + continue; + } + let text = source; + for (const edit of script.edits) { + if (!text.includes(edit.find)) { + problems.push({ + file: script.from, + at: '', + message: `the line \`${edit.find}\` is gone: the copy would still say GHCR`, + }); + continue; + } + text = text.replaceAll(edit.find, edit.replace); + } + files.set(script.to, text); + } + + return { + files, + outcomes, + checks: checks.toSorted(), + report, + problems, + actions: usedActions(files), + }; +} + +/** The external actions of the generated workflows and composite actions. */ +function usedActions( + files: ReadonlyMap, +): Map { + const found = new Map>(); + for (const [path, text] of files) { + if (!path.endsWith('.yml')) continue; + for (const { name, ref } of externalActions(readWorkflow(text, path))) + found.set(name, (found.get(name) ?? new Set()).add(ref)); + } + return new Map( + [...found] + .toSorted(([a], [b]) => a.localeCompare(b)) + .map(([name, refs]) => [name, [...refs].toSorted()]), + ); +} diff --git a/tools/cli/scripts/forgejo-port/github-edits.test.ts b/tools/cli/scripts/forgejo-port/github-edits.test.ts new file mode 100644 index 0000000000..17955cd114 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/github-edits.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, test } from 'bun:test'; + +import { planGithubEdits } from './github-edits'; +import type { GithubEdit } from './manifest'; + +const edit = (find: string, replace: string): GithubEdit => ({ + file: 'a.yml', + find, + replace, + why: 'a reason', +}); + +describe('planGithubEdits', () => { + test('plans an edit once, and says when it is made', () => { + const workflows = new Map([['a.yml', 'one\ntwo\n']]); + const manifest = { githubEdits: [edit('two\n', 'two\nthree\n')] }; + const first = planGithubEdits(workflows, manifest); + expect(first.problems).toEqual([]); + expect(first.outcomes[0]?.state).toBe('pending'); + expect(first.outcomes[0]?.text).toBe('one\ntwo\nthree\n'); + const second = planGithubEdits( + new Map([['a.yml', first.outcomes[0]?.text ?? '']]), + manifest, + ); + expect(second.outcomes[0]?.state).toBe('applied'); + expect(second.outcomes[0]?.text).toBe('one\ntwo\nthree\n'); + }); + + test('applies the edits of one file one after the other', () => { + const workflows = new Map([['a.yml', 'a\nb\n']]); + const { outcomes } = planGithubEdits(workflows, { + githubEdits: [edit('a\n', 'A\n'), edit('b\n', 'B\n')], + }); + expect(outcomes.map((outcome) => outcome.text)).toEqual([ + 'A\nb\n', + 'A\nB\n', + ]); + }); + + test('refuses an anchor that is gone, one that is ambiguous and a file that is not there', () => { + const manifest = { githubEdits: [edit('x\n', 'y\n')] }; + const gone = planGithubEdits(new Map([['a.yml', 'a\n']]), manifest); + expect(gone.problems[0]?.message).toContain('nowhere'); + const twice = planGithubEdits(new Map([['a.yml', 'x\nx\n']]), manifest); + expect(twice.problems[0]?.message).toContain('2 times'); + const missing = planGithubEdits(new Map(), manifest); + expect(missing.problems[0]?.message).toBe('does not exist'); + expect(gone.outcomes).toEqual([]); + }); + + test('writes the replacement as it is, whatever characters it holds', () => { + const { outcomes } = planGithubEdits(new Map([['a.yml', 'x\n']]), { + githubEdits: [edit('x\n', '$& $1 ${{ vars.A }}\n')], + }); + expect(outcomes[0]?.text).toBe('$& $1 ${{ vars.A }}\n'); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/github-edits.ts b/tools/cli/scripts/forgejo-port/github-edits.ts new file mode 100644 index 0000000000..01a42a8ac3 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/github-edits.ts @@ -0,0 +1,59 @@ +/** + * What GitHub's own copies of the workflows that stay need once Forgejo is the source. + * + * The release lane stays on GitHub, and a few of its workflows do something that + * Forgejo's push mirror would undo: the mirror makes GitHub's refs exactly Forgejo's, + * so a branch or a tag that only GitHub made is deleted at the next sync. Each edit + * here is a text change anchored on the exact lines it expects, applied by the + * cut-over and by nothing before it; before that the files are not touched. + */ + +import type { GithubEdit, Manifest } from './manifest'; +import type { Problem } from './validate'; + +export type EditState = 'pending' | 'applied'; + +export interface EditOutcome { + readonly path: string; + readonly edit: GithubEdit; + readonly state: EditState; + /** The file once the edit is made; unchanged when it already is. */ + readonly text: string; +} + +const WORKFLOWS = '.github/workflows'; + +/** Each edit against the file it names: pending, already made, or impossible. */ +export function planGithubEdits( + workflows: ReadonlyMap, + manifest: Pick, +): { outcomes: EditOutcome[]; problems: Problem[] } { + const outcomes: EditOutcome[] = []; + const problems: Problem[] = []; + const current = new Map(workflows); + for (const edit of manifest.githubEdits) { + const path = `${WORKFLOWS}/${edit.file}`; + const text = current.get(edit.file); + if (text === undefined) { + problems.push({ file: path, at: '', message: 'does not exist' }); + continue; + } + if (text.includes(edit.replace)) { + outcomes.push({ path, edit, state: 'applied', text }); + continue; + } + const found = text.split(edit.find).length - 1; + if (found !== 1) { + problems.push({ + file: path, + at: '', + message: `holds the lines of the edit ${found === 0 ? 'nowhere' : `${found} times`}: ${edit.why}`, + }); + continue; + } + const edited = text.replace(edit.find, () => edit.replace); + current.set(edit.file, edited); + outcomes.push({ path, edit, state: 'pending', text: edited }); + } + return { outcomes, problems }; +} diff --git a/tools/cli/scripts/forgejo-port/manifest.ts b/tools/cli/scripts/forgejo-port/manifest.ts new file mode 100644 index 0000000000..f7c3088ce8 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/manifest.ts @@ -0,0 +1,169 @@ +/** + * What the port decides about each file, in one place a reviewer can read. + * + * Nothing here lists a job or a step of a workflow that Tale edits every day: a + * workflow is ported unless it is named below, and what is done to it is found by the + * rules from what it says. This file names the few files that stay on GitHub or wait, + * and the facts of the node the port is for. + */ + +import type { Registry } from './actions'; +import type { Tier } from './context'; + +export type Plan = + /** Ported to `.forgejo/workflows`, with whatever its entry adds. */ + | { + readonly kind: 'port'; + /** What a pull request owes of this workflow, where it is not what the manifest says. */ + readonly tier?: Tier; + /** Jobs that cannot run on Forgejo even though the workflow can, with why. */ + readonly dropJobs?: readonly { + readonly id: string; + readonly why: string; + }[]; + /** Events that make no sense on Forgejo even though it fires them, with why. */ + readonly dropEvents?: readonly { + readonly name: string; + readonly why: string; + }[]; + } + /** Stays on GitHub on purpose: the release lane and what only GitHub can serve. */ + | { readonly kind: 'github'; readonly why: string } + /** Not ported yet: a follow-up with a named reason. */ + | { readonly kind: 'later'; readonly why: string }; + +/** A change to a workflow that stays on GitHub, made by the cut-over and by nothing before it. */ +export interface GithubEdit { + /** The file under `.github/workflows`. */ + readonly file: string; + /** The exact text to find, once. */ + readonly find: string; + readonly replace: string; + readonly why: string; +} + +export interface Manifest { + /** + * What a pull request owes: `full` is what a batch owes, so that a failure shows on the pull + * request and not in the train; `fast` is GitHub's pull request tier. A workflow may say + * otherwise in its own plan, so the heavy suites can move onto pull requests one at a time. + */ + readonly tier: Tier; + /** The registry CI images are pushed to, and the secret that holds the package token. */ + readonly registry: Registry; + /** + * The secret that holds a GitHub token for the calls a build makes to api.github.com (the + * web site's release feed): the job's own token is Forgejo's and means nothing there. A name + * may not start with FORGEJO_, GITEA_ or GITHUB_ (models/secret/secret.go). + */ + readonly githubApiTokenSecret: string; + /** The runner labels the pool serves: a `runs-on` outside them does not queue, it falls back to Docker. */ + readonly labels: readonly string[]; + /** Local composite actions that are generated for Forgejo too. */ + readonly composites: readonly string[]; + /** Files copied beside the workflows, with the text edits Forgejo needs. */ + readonly scripts: readonly { + readonly from: string; + readonly to: string; + readonly edits: readonly { + readonly find: string; + readonly replace: string; + }[]; + }[]; + /** What happens to each file of `.github/workflows`; one that is not named is ported. */ + readonly workflows: Readonly>; + /** What GitHub's own copies need once Forgejo is the source. */ + readonly githubEdits: readonly GithubEdit[]; +} + +const RELEASE_LANE = + 'the release lane stays on GitHub: Ops binds its jobs and its runs, it builds arm64 images, signs the macOS and Windows binaries and creates the GitHub release'; + +export const MANIFEST: Manifest = { + tier: 'full', + registry: { host: 'git.tale.dev', tokenSecret: 'CI_PACKAGES_TOKEN' }, + githubApiTokenSecret: 'CI_GITHUB_TOKEN', + labels: ['ubuntu-latest', 'ubuntu-24.04'], + composites: ['setup-turbo'], + scripts: [ + { + from: '.github/scripts/pull-ci-images.sh', + to: '.forgejo/scripts/pull-ci-images.sh', + edits: [ + { + find: '^ghcr\\.io/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$', + replace: + '^(ghcr\\.io|git\\.tale\\.dev)/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$', + }, + ], + }, + ], + githubEdits: [ + { + file: 'publish-packages.yml', + find: ' publish:\n name: Publish ${{ matrix.package }}\n', + replace: + " publish:\n name: Publish ${{ matrix.package }}\n # Forgejo publishes the snapshots and its push mirror carries them to GitHub, which\n # deletes any ref Forgejo does not hold: a snapshot made here would not stay.\n if: vars.TALE_SOURCE != 'forgejo'\n", + why: 'the release lane still dispatches this workflow on GitHub, and it must publish nothing once Forgejo is the source', + }, + ], + workflows: { + 'cli.yml': { + kind: 'port', + dropEvents: [ + { + name: 'workflow_dispatch', + why: 'it builds the binaries of a release tag, to attach them to a GitHub release; releases are made on GitHub', + }, + ], + dropJobs: [ + { + id: 'release', + why: 'its manual publication uploads to a GitHub release with `gh`; releases are made on GitHub', + }, + ], + }, + 'release.yml': { kind: 'github', why: RELEASE_LANE }, + 'release-candidate-source.yml': { + kind: 'github', + why: 'a reusable workflow of the candidate dispatch, which only GitHub can send', + }, + 'release-candidate-receipt.yml': { + kind: 'github', + why: 'a reusable workflow of the candidate dispatch, which only GitHub can send', + }, + 'scorecard.yml': { + kind: 'github', + why: "OpenSSF Scorecard publishes to GitHub with GitHub's OIDC identity", + }, + 'load.yml': { + kind: 'github', + why: 'a manual load test of the whole stack, which GitHub-hosted runners serve as they are', + }, + 'workspace-upgrade.yml': { + kind: 'github', + why: "it upgrades a workspace from the published releases, which it resolves through GitHub's release API and pulls from GHCR", + }, + 'sandbox-incus-e2e.yml': { + kind: 'later', + why: 'it builds an Incus node with a ZFS pool on the runner, which needs a runner that is a virtual machine; the pool serves system containers', + }, + 'issue-labeler.yml': { + kind: 'later', + why: "it labels issues with github-script and GitHub's REST API; Forgejo's labels API takes ids, not names", + }, + 'cleanup-pr-images.yml': { + kind: 'later', + why: "it deletes a closed pull request's image tags through GHCR's API; Forgejo's registry needs its own cleanup (a package cleanup rule of the organization, or the package API with a token)", + }, + }, +}; + +export function planFor(manifest: Manifest, file: string): Plan { + return manifest.workflows[file] ?? { kind: 'port' }; +} + +/** What a pull request owes of a ported workflow. */ +export function tierOf(manifest: Manifest, plan: Plan): Tier { + return plan.kind === 'port' && plan.tier ? plan.tier : manifest.tier; +} diff --git a/tools/cli/scripts/forgejo-port/port.ts b/tools/cli/scripts/forgejo-port/port.ts new file mode 100644 index 0000000000..328516fd1e --- /dev/null +++ b/tools/cli/scripts/forgejo-port/port.ts @@ -0,0 +1,148 @@ +/** + * Port one workflow: the pipeline. + * + * The same few steps run for every workflow, in this order, and a rule that finds + * nothing to do does nothing: + * + * 1. the triggers say which events the generated file can receive; + * 2. structural rules remove what exists only for GitHub (scope discovery, + * candidate validation) and rewrite what Forgejo does differently; + * 3. every condition and value is folded by what is now known, and jobs that can + * never run are removed, which makes them a fact for the jobs that needed + * them, until nothing changes. + * + * What the pipeline does not touch is carried through as it was written. + */ + +import { + factsOf, + jobFactsOf, + learnRemoval, + newKnowledge, + type PortContext, + type Rule, +} from './context'; +import { DEFAULT_RULES, learnEmptyOutputs } from './rules'; +import { rewriteTriggers, type TriggerOptions } from './triggers'; +import { + emptyReport, + foldAction, + foldWorkflow, + jobIds, + readWorkflow, + removeJobs, + writeWorkflow, + type Report, + type Workflow, +} from './workflow'; + +export interface PortOptions { + readonly triggers?: Partial; + /** Rules that run before folding, in order. */ + readonly rules?: readonly Rule[]; + /** Rules that run once folding is done, in order. */ + readonly after?: readonly Rule[]; +} + +export interface PortedWorkflow { + readonly text: string; + readonly jobs: readonly string[]; + readonly removed: ReadonlyMap; + readonly events: readonly string[]; +} + +export function portWorkflow( + source: string, + file: string, + report: Report = emptyReport(), + options: PortOptions = {}, +): PortedWorkflow { + const doc: Workflow = readWorkflow(source, file); + const knowledge = newKnowledge(); + const removed = new Map(); + const context: PortContext = { + file, + report, + knowledge, + removed, + results: new Map(), + }; + + const triggers = rewriteTriggers(doc, { file, ...options.triggers }, report); + knowledge.oneOf.set('github.event_name', [...triggers.events]); + // A batch of the merge train is a push here: what GitHub asks of a merge group, a run asks + // of its push, and the only pushes the workflow has are the batches. + if (triggers.validatedInQueue) + knowledge.aliases.set( + 'github.event_name', + new Map([['merge_group', 'push']]), + ); + // Forgejo has no draft to skip for and no event when one is marked ready, so a pull + // request runs whatever its title says; the merge train itself refuses a work in progress. + knowledge.values.set('github.event.pull_request.draft', false); + knowledge.absent.push( + 'github.event.client_payload', + 'github.event.merge_group', + 'inputs.candidate_sha', + 'github.event.inputs.candidate_sha', + ); + + for (const rule of options.rules ?? DEFAULT_RULES) rule(doc, context); + + // A removed job is a fact for the jobs that needed it, and an empty output is a fact for + // the jobs that read it: fold until neither teaches anything new. + for (let round = 0; round < 32; round += 1) { + const dead = foldWorkflow(doc, { + file, + facts: factsOf(knowledge), + jobFacts: jobFactsOf(knowledge), + report, + }); + const learned = learnEmptyOutputs(doc, context); + if (dead.length === 0 && !learned) break; + removeJobs(doc, dead); + for (const id of dead) { + removed.set(id, 'its condition can never hold on Forgejo'); + learnRemoval(knowledge, id); + report.changes.push({ + file, + at: `jobs.${id}`, + rule: 'job-removed', + detail: 'removed: it can never run on Forgejo', + }); + } + } + + for (const rule of options.after ?? []) rule(doc, context); + + return { + text: writeWorkflow(doc), + jobs: jobIds(doc), + removed, + events: triggers.events, + }; +} + +/** + * Port a composite action: its steps go through the rules given, and are folded by what + * those rules learned. An action has no events or jobs of its own to decide. + */ +export function portAction( + source: string, + file: string, + report: Report, + rules: readonly Rule[], +): string { + const doc = readWorkflow(source, file); + const knowledge = newKnowledge(); + const context: PortContext = { + file, + report, + knowledge, + removed: new Map(), + results: new Map(), + }; + for (const rule of rules) rule(doc, context); + foldAction(doc, { file, facts: factsOf(knowledge), report }); + return writeWorkflow(doc); +} diff --git a/tools/cli/scripts/forgejo-port/ready.test.ts b/tools/cli/scripts/forgejo-port/ready.test.ts new file mode 100644 index 0000000000..ff2549b91f --- /dev/null +++ b/tools/cli/scripts/forgejo-port/ready.test.ts @@ -0,0 +1,421 @@ +import { describe, expect, test } from 'bun:test'; + +import { + BUILD_SERVICES, + CHECKS_MERGE_QUEUE_ONLY, + CI_JOBS, + COMPOSE_SERVICES, +} from '../ci-ready'; +import { + judgeReadiness, + parseRemoved, + readInput, + renderVerdict, + type JobResult, + type ReadyInput, + type RemovedJob, +} from './ready'; + +const A = 'a'.repeat(40); +const B = 'b'.repeat(40); + +type Workflow = keyof typeof CI_JOBS; +type Job = { result: string; outputs: Record }; + +const skipped: Job = { result: 'skipped', outputs: {} }; +const wasSkipped: JobResult = { result: 'skipped', outputs: {} }; +/** A job the port took out that neither kind of run would have run. */ +const neverRan: RemovedJob = { pull_request: wasSkipped, push: wasSkipped }; + +/** The workflows whose heavy suites only a batch runs: a pull request's scope says so and nothing else runs. */ +const QUEUE_ONLY = new Set(['build', 'e2e', 'cli']); + +/** What the port took out of each workflow, and what each job would have said. */ +function removedFor(workflow: Workflow): Record { + const gone: Record = { + 'candidate-source': neverRan, + 'candidate-gate': neverRan, + }; + if (workflow === 'cli') gone.release = neverRan; + if (QUEUE_ONLY.has(workflow)) + gone['pr-scope'] = { + pull_request: { + result: 'success', + outputs: { run: 'false', full: 'false' }, + }, + push: wasSkipped, + }; + if (workflow === 'security') + gone['pr-scope'] = { + pull_request: { + result: 'success', + outputs: { run: 'true', full: 'true' }, + }, + push: wasSkipped, + }; + return gone; +} + +/** A fully green batch of one workflow, as `toJSON(needs)` of its ready job on Forgejo. */ +function greenBatch(workflow: Workflow): Record { + const needs: Record = {}; + for (const id of CI_JOBS[workflow]) { + if (id in removedFor(workflow)) continue; + needs[id] = { result: 'success', outputs: {} }; + } + if (needs['integration-scope']) + needs['integration-scope'].outputs = { run: 'true' }; + if (workflow === 'e2e') + needs.scope = { + result: 'success', + outputs: { platform: 'true', static_services: '["web","docs"]' }, + }; + if (workflow === 'build') { + needs['smoke-test-fork'] = skipped; + needs['image-validate-fork'] = skipped; + needs.changes = { + result: 'success', + outputs: { + services: JSON.stringify(BUILD_SERVICES), + scannable_services: JSON.stringify(COMPOSE_SERVICES), + ci_tests: 'true', + stack: 'true', + storybook: 'true', + }, + }; + } + return needs; +} + +/** A pull request's tier: the fast lanes ran, and the heavy suites are held for the batch. */ +function greenPullRequest(workflow: Workflow): Record { + const needs: Record = {}; + for (const id of CI_JOBS[workflow]) { + if (id in removedFor(workflow)) continue; + needs[id] = QUEUE_ONLY.has(workflow) + ? skipped + : { result: 'success', outputs: {} }; + } + if (workflow === 'checks') { + for (const id of [...CHECKS_MERGE_QUEUE_ONLY, 'backend-integration']) + needs[id] = skipped; + needs['integration-scope'] = { + result: 'success', + outputs: { run: 'false' }, + }; + } + return needs; +} + +function pullRequest(overrides: Record = {}) { + return { + pull_request: { + title: 'feat(cli): something', + base: { sha: A }, + head: { sha: B, repo: { fork: false } }, + changed_files: 3, + ...overrides, + }, + }; +} + +function onPullRequest( + workflow: Workflow, + extra: Partial = {}, +): ReadyInput { + return { + workflow, + needs: greenPullRequest(workflow), + tier: 'fast', + removed: removedFor(workflow), + event: 'pull_request', + payload: pullRequest(), + sha: B, + ...extra, + }; +} + +function onBatch( + workflow: Workflow, + extra: Partial = {}, +): ReadyInput { + return { + workflow, + needs: greenBatch(workflow), + tier: 'fast', + removed: removedFor(workflow), + event: 'push', + payload: { before: '0'.repeat(40), after: B }, + sha: B, + ...extra, + }; +} + +const WORKFLOWS = Object.keys(CI_JOBS) as Workflow[]; + +describe('judgeReadiness', () => { + for (const workflow of WORKFLOWS) { + test(`${workflow}: a green pull request is ready at its own tier`, () => { + const verdict = judgeReadiness(onPullRequest(workflow)); + expect(verdict.reasons).toEqual([]); + expect(verdict.passed).toBe(true); + }); + + test(`${workflow}: a green batch is ready at full scope`, () => { + const verdict = judgeReadiness(onBatch(workflow)); + expect(verdict.reasons).toEqual([]); + expect(verdict.passed).toBe(true); + }); + + test(`${workflow}: a batch that skipped a job it owes is held`, () => { + for (const id of Object.keys(greenBatch(workflow))) { + const needs = greenBatch(workflow); + const job = needs[id]; + if (!job || job.result === 'skipped') continue; + for (const result of ['failure', 'cancelled', 'skipped', '']) { + job.result = result; + if (id === 'vulnerability-scan' && result === 'failure') continue; + expect( + judgeReadiness(onBatch(workflow, { needs })).passed, + `${id}/${result}`, + ).toBe(false); + } + } + }); + + test(`${workflow}: a job that is neither there nor removed by the port holds it`, () => { + for (const id of Object.keys(greenBatch(workflow))) { + const needs = greenBatch(workflow); + delete needs[id]; + expect( + judgeReadiness(onBatch(workflow, { needs })).passed, + `missing ${id}`, + ).toBe(false); + } + }); + + test(`${workflow}: a job nobody classified holds it`, () => { + const needs = greenBatch(workflow); + needs['new-unclassified-proof'] = { result: 'success', outputs: {} }; + expect(judgeReadiness(onBatch(workflow, { needs })).passed).toBe(false); + }); + } + + for (const workflow of WORKFLOWS) { + test(`${workflow}: a pull request of the full tier owes what a batch owes`, () => { + const verdict = judgeReadiness( + onPullRequest(workflow, { tier: 'full', needs: greenBatch(workflow) }), + ); + expect(verdict.reasons).toEqual([]); + expect(verdict.passed).toBe(true); + }); + + test(`${workflow}: a pull request of the full tier is held for a job a batch would not skip`, () => { + for (const id of Object.keys(greenBatch(workflow))) { + const needs = greenBatch(workflow); + const job = needs[id]; + if (!job || job.result === 'skipped') continue; + job.result = 'skipped'; + expect( + judgeReadiness(onPullRequest(workflow, { tier: 'full', needs })) + .passed, + `${id}`, + ).toBe(false); + } + }); + } + + test('a pull request of the fast tier is held for a suite it ran, and one of the full tier for a suite it skipped', () => { + const fast = judgeReadiness( + onPullRequest('checks', { needs: greenBatch('checks') }), + ); + expect(fast.passed).toBe(false); + const full = judgeReadiness( + onPullRequest('checks', { + tier: 'full', + needs: greenPullRequest('checks'), + }), + ); + expect(full.passed).toBe(false); + }); + + test('a pull request that ran a suite held for the batch is held', () => { + const needs = greenPullRequest('checks'); + needs.build = { result: 'success', outputs: {} }; + expect(judgeReadiness(onPullRequest('checks', { needs })).passed).toBe( + false, + ); + const queued = greenPullRequest('e2e'); + queued.e2e = { result: 'success', outputs: {} }; + expect(judgeReadiness(onPullRequest('e2e', { needs: queued })).passed).toBe( + false, + ); + }); + + test('a pull request that failed a lane it owes is held', () => { + const needs = greenPullRequest('checks'); + needs.lint = { result: 'failure', outputs: {} }; + expect(judgeReadiness(onPullRequest('checks', { needs })).passed).toBe( + false, + ); + }); + + test('does not hold a work-in-progress pull request: the merge train does', () => { + for (const title of ['WIP: x', '[WIP] x']) { + expect( + judgeReadiness( + onPullRequest('commitlint', { + payload: pullRequest({ title, draft: true }), + }), + ).passed, + ).toBe(true); + } + }); + + test('a pull request from a fork is held with the way out', () => { + const verdict = judgeReadiness( + onPullRequest('commitlint', { + payload: pullRequest({ head: { sha: B, repo: { fork: true } } }), + }), + ); + expect(verdict.passed).toBe(false); + expect(verdict.reasons[0]).toContain('a maintainer pushes the branch'); + }); + + test('an event it cannot describe is held, and so is a pull request with no commits named', () => { + expect( + judgeReadiness(onBatch('sast', { event: 'schedule' })).reasons[0], + ).toContain('only defined for'); + expect( + judgeReadiness( + onPullRequest('sast', { payload: { pull_request: { title: 'x' } } }), + ).passed, + ).toBe(false); + expect(judgeReadiness(onBatch('sast', { needs: [] })).passed).toBe(false); + }); + + test('a batch that is not the commit checked out is held', () => { + const verdict = judgeReadiness( + onBatch('sast', { payload: { before: A, after: B }, sha: A }), + ); + expect(verdict.passed).toBe(false); + }); + + test('does not hand a job the port never removed to the policy as skipped', () => { + const needs = greenBatch('cli'); + delete needs.build; + const verdict = judgeReadiness( + onBatch('cli', { + needs, + removed: { + ...removedFor('cli'), + build: neverRan, + }, + }), + ); + // `build` is a job the policy wants to have succeeded: skipping it is a refusal, not a pass + expect(verdict.passed).toBe(false); + }); +}); + +describe('parseRemoved', () => { + const one = JSON.stringify({ + 'pr-scope': { + pull_request: { result: 'success', outputs: { run: 'false' } }, + push: { result: 'skipped', outputs: {} }, + }, + }); + + test('reads what the generator recorded', () => { + expect(parseRemoved(one)).toEqual({ + 'pr-scope': { + pull_request: { result: 'success', outputs: { run: 'false' } }, + push: { result: 'skipped', outputs: {} }, + }, + }); + expect(parseRemoved('')).toEqual({}); + }); + + test('refuses what is not a result', () => { + expect(() => parseRemoved('[]')).toThrow('not an object'); + expect(() => parseRemoved('{"x":{}}')).toThrow( + 'CI_PORT_REMOVED.x.pull_request is not a job result', + ); + expect(() => + parseRemoved( + '{"x":{"pull_request":{"result":"failure","outputs":{}},"push":{"result":"skipped","outputs":{}}}}', + ), + ).toThrow('not a job result'); + expect(() => + parseRemoved( + '{"x":{"pull_request":{"result":"success","outputs":{"a":1}},"push":{"result":"skipped","outputs":{}}}}', + ), + ).toThrow('not a job result'); + }); +}); + +describe('readInput', () => { + const env = { + CI_WORKFLOW: 'sast', + CI_TIER: 'fast', + CI_NEEDS: '{"sast":{"result":"success","outputs":{}}}', + CI_PORT_REMOVED: '{}', + GITHUB_EVENT_NAME: 'push', + GITHUB_EVENT_PATH: '/tmp/event.json', + GITHUB_SHA: B, + }; + + test('takes the job environment and the runner event file', () => { + const read = (path: string) => + path === '/tmp/event.json' ? '{"before":"x","after":"y"}' : ''; + expect(readInput(env, read)).toEqual({ + workflow: 'sast', + tier: 'fast', + needs: { sast: { result: 'success', outputs: {} } }, + removed: {}, + event: 'push', + payload: { before: 'x', after: 'y' }, + sha: B, + }); + }); + + test('refuses a tier it does not know', () => { + expect(() => readInput({ ...env, CI_TIER: 'half' }, () => '{}')).toThrow( + 'CI_TIER is neither fast nor full', + ); + expect(() => readInput({ ...env, CI_TIER: undefined }, () => '{}')).toThrow( + 'CI_TIER is not set', + ); + }); + + test('names what is missing', () => { + expect(() => + readInput({ ...env, CI_NEEDS: undefined }, () => '{}'), + ).toThrow('CI_NEEDS is not set'); + expect(() => readInput({ ...env, GITHUB_SHA: '' }, () => '{}')).toThrow( + 'GITHUB_SHA is not set', + ); + }); + + test('has no removed jobs when the port removed none', () => { + expect( + readInput({ ...env, CI_PORT_REMOVED: undefined }, () => '{}').removed, + ).toEqual({}); + }); +}); + +describe('renderVerdict', () => { + test('prints a table, and the reasons when held', () => { + const held = renderVerdict({ + passed: false, + reasons: ['sast: expected success, got failure'], + jobs: [{ job: 'sast', result: 'failure', policy: 'required' }], + }); + expect(held).toContain('CI readiness: held'); + expect(held).toContain('sast'); + expect(held).toContain(' - sast: expected success, got failure'); + expect(renderVerdict({ passed: true, reasons: [], jobs: [] })).toBe( + 'CI readiness: passed', + ); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/ready.ts b/tools/cli/scripts/forgejo-port/ready.ts new file mode 100644 index 0000000000..3e7634400a --- /dev/null +++ b/tools/cli/scripts/forgejo-port/ready.ts @@ -0,0 +1,258 @@ +/** + * The verdict a ported workflow's `CI ready (…)` job gives. + * + * On GitHub that job evaluates the workflow's `needs` with Tale's own policy + * (`../ci-ready.ts`) in a `github-script` step, against a pull request or a merge + * group. On Forgejo there is neither the API nor the merge group: a batch of the merge + * train, which is a push to `mq/**`, is what the policy calls a merge group, and so is a + * pull request that owes what a batch owes (the `full` tier). A pull request of the + * `fast` tier is a pull request. The policy itself is not copied or changed: + * this describes the Forgejo run in the words it knows, and hands it the jobs the + * port left out as what they would have reported, which the generator recorded. + * + * Run as a script it reads the job's environment and the runner's event file, so + * the generated job is a checkout and one command. + */ + +import { readFileSync } from 'node:fs'; + +import { CI_JOBS, evaluateReadiness } from '../ci-ready'; + +const ZEROS = '0'.repeat(40); +const SHA = /^[a-f0-9]{40}$/; + +/** + * What a pull request owes. `fast` is GitHub's pull request tier: the fast lanes, with the + * heavy suites held for the batch. `full` is the batch's own scope, so that a failure shows + * on the pull request and not in the train. + */ +export type Tier = 'fast' | 'full'; + +/** What a job reports to the jobs that need it. */ +export interface JobResult { + readonly result: 'success' | 'skipped'; + readonly outputs: Readonly>; +} + +/** What a job the port left out would have reported, by the kind of run. */ +export interface RemovedJob { + readonly pull_request: JobResult; + readonly push: JobResult; +} + +export interface ReadyInput { + /** The workflow's stem: `checks`. */ + readonly workflow: string; + /** `toJSON(needs)` of the ready job. */ + readonly needs: unknown; + /** What a pull request owes of this workflow. */ + readonly tier: Tier; + /** The jobs of the GitHub workflow the port left out, by id. */ + readonly removed: Readonly>; + /** `github.event_name`. */ + readonly event: string; + /** The runner's event payload. */ + readonly payload: unknown; + /** `github.sha`. */ + readonly sha: string; +} + +export interface Verdict { + readonly passed: boolean; + readonly reasons: readonly string[]; + readonly jobs: readonly { job: string; result: string; policy: string }[]; +} + +function record(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? Object.fromEntries(Object.entries(value)) + : undefined; +} + +function held(reason: string): Verdict { + return { passed: false, reasons: [reason], jobs: [] }; +} + +type Described = + | { + readonly kind: 'pull_request'; + readonly base: string; + readonly head: string; + readonly changed: number; + } + | { + readonly kind: 'push'; + readonly base: string; + readonly head: string; + }; + +/** What the run is, in the policy's words: a pull request, or a batch with a base and a head. */ +function describe( + event: string, + payload: unknown, + sha: string, +): Described | Verdict { + const body = record(payload); + if (event === 'pull_request') { + const pull = record(body?.pull_request); + const head = record(pull?.head); + const base = record(pull?.base); + if (record(head?.repo)?.fork === true) + return held( + 'A pull request from a fork is not validated here: a maintainer pushes the branch to the repository', + ); + const headSha = head?.sha; + const baseSha = base?.sha; + if (typeof headSha !== 'string' || typeof baseSha !== 'string') + return held('The pull request event names no base and head commit'); + const changed = pull?.changed_files; + return { + kind: 'pull_request', + base: baseSha, + head: headSha, + changed: + typeof changed === 'number' && Number.isSafeInteger(changed) + ? changed + : 0, + }; + } + if (event === 'push') { + const after = typeof body?.after === 'string' ? body.after : sha; + const before = typeof body?.before === 'string' ? body.before : ZEROS; + return { + kind: 'push', + base: SHA.test(before) ? before : ZEROS, + head: after, + }; + } + return held('Readiness is only defined for pull_request and push'); +} + +export function judgeReadiness(input: ReadyInput): Verdict { + const what = describe(input.event, input.payload, input.sha); + if ('passed' in what) return what; + const needs = record(input.needs); + if (!needs) return held('Native needs must be an object'); + const known: readonly string[] = Object.hasOwn(CI_JOBS, input.workflow) + ? CI_JOBS[input.workflow as keyof typeof CI_JOBS] + : []; + // A pull request that owes what a batch owes is judged as the merge group the policy knows. + const batch = what.kind === 'push' || input.tier === 'full'; + const filled: Record = { ...needs }; + for (const [id, removed] of Object.entries(input.removed)) { + if (known.includes(id) && !(id in filled)) + filled[id] = removed[batch ? 'push' : 'pull_request']; + } + // A work in progress is held by the merge train, not here: Forgejo raises no event when + // one is marked ready, so a hold would stay on a pull request that is ready. + return evaluateReadiness({ + workflow: input.workflow, + ...(batch + ? { + event: 'merge_group', + payload: { + merge_group: { base_sha: what.base, head_sha: what.head }, + }, + } + : { + event: 'pull_request', + payload: { + pull_request: { + base: { sha: what.base }, + head: { sha: what.head, repo: { fork: false } }, + changed_files: what.kind === 'pull_request' ? what.changed : 0, + draft: false, + }, + }, + }), + needs: filled, + source: input.sha, + }); +} + +function jobResult(value: unknown, where: string): JobResult { + const job = record(value); + const outputs = record(job?.outputs); + if ( + !job || + !outputs || + (job.result !== 'success' && job.result !== 'skipped') || + Object.values(outputs).some((output) => typeof output !== 'string') + ) + throw new Error(`${where} is not a job result`); + return { + result: job.result, + outputs: Object.fromEntries( + Object.entries(outputs).map(([name, output]) => [name, String(output)]), + ), + }; +} + +/** `CI_PORT_REMOVED`: the jobs the port left out, as the generator recorded them. */ +export function parseRemoved(text: string): Record { + const parsed: unknown = text === '' ? {} : JSON.parse(text); + const jobs = record(parsed); + if (!jobs) throw new Error('CI_PORT_REMOVED is not an object'); + return Object.fromEntries( + Object.entries(jobs).map(([id, value]) => { + const kinds = record(value); + return [ + id, + { + pull_request: jobResult( + kinds?.pull_request, + `CI_PORT_REMOVED.${id}.pull_request`, + ), + push: jobResult(kinds?.push, `CI_PORT_REMOVED.${id}.push`), + }, + ]; + }), + ); +} + +/** The job's environment and the runner's files, as `judgeReadiness` wants them. */ +export function readInput( + env: Readonly>, + read: (path: string) => string = (path) => readFileSync(path, 'utf8'), +): ReadyInput { + const required = (name: string): string => { + const value = env[name]; + if (value === undefined || value === '') + throw new Error(`${name} is not set`); + return value; + }; + const tier = required('CI_TIER'); + if (tier !== 'fast' && tier !== 'full') + throw new Error('CI_TIER is neither fast nor full'); + return { + workflow: required('CI_WORKFLOW'), + tier, + needs: JSON.parse(required('CI_NEEDS')) as unknown, + removed: parseRemoved((env.CI_PORT_REMOVED ?? '').trim()), + event: required('GITHUB_EVENT_NAME'), + payload: JSON.parse(read(required('GITHUB_EVENT_PATH'))) as unknown, + sha: required('GITHUB_SHA'), + }; +} + +/** Print the verdict as the GitHub version does: a table and, when held, the reasons. */ +export function renderVerdict(verdict: Verdict): string { + const rows = verdict.jobs.map( + (job) => `${job.job.padEnd(24)} ${job.result.padEnd(10)} ${job.policy}`, + ); + const head = verdict.passed ? 'CI readiness: passed' : 'CI readiness: held'; + return [ + head, + ...rows, + ...verdict.reasons.map((reason) => ` - ${reason}`), + ].join('\n'); +} + +if (import.meta.main) { + const verdict = judgeReadiness(readInput(process.env)); + console.log(renderVerdict(verdict)); + if (!verdict.passed) { + console.log(`::error::${verdict.reasons.join('; ')}`); + process.exit(1); + } +} diff --git a/tools/cli/scripts/forgejo-port/rules.test.ts b/tools/cli/scripts/forgejo-port/rules.test.ts new file mode 100644 index 0000000000..cc93820965 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/rules.test.ts @@ -0,0 +1,217 @@ +import { describe, expect, test } from 'bun:test'; + +import { portWorkflow } from './port'; +import { emptyReport } from './workflow'; + +/** Port a workflow with the default rules and return the text and the report. */ +function port(source: string, file = 'w.yml') { + const report = emptyReport(); + const result = portWorkflow(source, file, report); + return { ...result, report }; +} + +const RUNS = ` runs-on: ubuntu-latest\n`; + +describe('servicesToDockerRun', () => { + const JOB = (services: string) => `name: W +on: + pull_request: +jobs: + test: +${RUNS} services: +${services} + steps: + - name: Checkout + uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +`; + + test('starts a service with docker run on the loopback address, before the checkout', () => { + const { text, report } = port( + JOB(` bgutil: + image: mirror.gcr.io/brainicism/bgutil-ytdlp-pot-provider:1.3.1 + ports: + - 4416:4416`), + ); + expect(text).not.toContain('services:'); + expect(text.indexOf('Start the bgutil service')).toBeLessThan( + text.indexOf('Checkout'), + ); + expect(text).toContain("docker run -d --name 'service-bgutil'"); + expect(text).toContain('-p 127.0.0.1:4416:4416'); + expect(text).toContain( + "'docker.io/brainicism/bgutil-ytdlp-pot-provider:1.3.1'", + ); + expect(text).not.toContain('docker inspect'); + expect(report.changes.some((change) => change.rule === 'services')).toBe( + true, + ); + }); + + test('waits for the health check the options define, and passes env by name', () => { + const { text } = port( + JOB(` postgres: + image: postgres:16 + env: + POSTGRES_USER: tale + POSTGRES_PASSWORD: \${{ secrets.DB_PASSWORD }} + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U tale -d tale_app" + --health-interval 10s`), + ); + expect(text).toContain('POSTGRES_PASSWORD: ${{ secrets.DB_PASSWORD }}'); + expect(text).toContain('-e POSTGRES_USER'); + expect(text).toContain( + '--health-cmd "pg_isready -U tale -d tale_app" --health-interval 10s', + ); + expect(text).toContain( + "docker inspect --format '{{.State.Health.Status}}'", + ); + expect(text).not.toMatch(/-e POSTGRES_USER=/); + }); + + test('says when a port has no fixed host port, and when credentials are not carried over', () => { + const { text, report } = port( + JOB(` db: + image: postgres:16 + ports: + - 5432 + credentials: + username: x + password: y`), + ); + expect(text).not.toContain('-p '); + expect(report.warnings.map((warning) => warning.rule).sort()).toEqual([ + 'service-credentials', + 'service-port', + ]); + }); + + test('says when the volumes of a service are not carried over', () => { + const { text, report } = port( + JOB(` db: + image: postgres:16 + volumes: + - /tmp/data:/var/lib/postgresql/data + options: --user 1000 --memory 2g`), + ); + expect(text).not.toContain('/tmp/data'); + expect(text).toContain('--user 1000 --memory 2g'); + expect(report.warnings.map((warning) => warning.rule)).toEqual([ + 'service-volumes', + ]); + }); +}); + +describe('matrixTotals', () => { + test('writes the size of a plain matrix where the job asks the runner for it', () => { + const { text } = port(`name: E2E +on: + pull_request: +jobs: + e2e: +${RUNS} strategy: + matrix: + shard: [1, 2, 3, 4] + steps: + - run: bunx playwright test --shard=\${{ matrix.shard }}/\${{ strategy.job-total }} +`); + expect(text).toContain('--shard=${{ matrix.shard }}/4'); + }); + + test('leaves a matrix that something decides at run time', () => { + const { text } = port(`name: B +on: + pull_request: +jobs: + scan: +${RUNS} strategy: + matrix: + service: \${{ fromJSON(needs.changes.outputs.services) }} + steps: + - run: echo \${{ strategy.job-total }} +`); + expect(text).toContain('${{ strategy.job-total }}'); + }); +}); + +describe('dropEnvironments', () => { + test('removes an environment and says so', () => { + const { text, report } = port(`name: S +on: + pull_request: +jobs: + scan: + environment: production +${RUNS} steps: + - run: scan +`); + expect(text).not.toContain('environment'); + expect(report.changes.map((change) => change.rule)).toContain( + 'environment', + ); + }); +}); + +describe('the pipeline', () => { + test('folds what an empty job output decides', () => { + const { text } = port(`name: Build +on: + merge_group: + repository_dispatch: + types: [release-candidate] + pull_request: +jobs: + candidate-source: + if: github.event_name == 'repository_dispatch' + uses: ./.github/workflows/release-candidate-source.yml + changes: + needs: candidate-source + if: needs.candidate-source.result == 'skipped' +${RUNS} outputs: + candidate_sha: \${{ needs.candidate-source.outputs.candidate_sha }} + steps: + - run: echo changes + build: + needs: changes +${RUNS} steps: + - uses: actions/checkout@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + with: + ref: \${{ needs.changes.outputs.candidate_sha }} + persist-credentials: false + - name: Candidate only + if: needs.changes.outputs.candidate_sha != '' + run: echo candidate + candidate-gate: + needs: [changes, build] + if: always() && needs.changes.outputs.candidate_sha != '' +${RUNS} steps: + - run: echo gate +`); + expect(text).not.toContain('candidate-source'); + expect(text).not.toContain('candidate-gate'); + expect(text).not.toContain('Candidate only'); + expect(text).not.toContain('ref:'); + expect(text).toContain('persist-credentials: false'); + }); + + test('is the identity on a workflow with nothing to port', () => { + const source = `name: Plain + +on: + schedule: + - cron: '0 3 * * 2' + workflow_dispatch: + +jobs: + scan: + runs-on: ubuntu-latest + steps: + - run: echo scan +`; + const { text, report } = port(source); + expect(report.changes).toEqual([]); + expect(text).toBe(source); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/rules.ts b/tools/cli/scripts/forgejo-port/rules.ts new file mode 100644 index 0000000000..614150cc41 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/rules.ts @@ -0,0 +1,282 @@ +/** + * The structural rules of the port: what exists only for GitHub is removed, and + * what Forgejo's runner does differently is written the way it does it. + * + * Each rule is a function of the document that says what it did in the report. A + * rule that finds nothing to do does nothing, so a workflow someone changes + * tomorrow either still matches or is carried through as it is. + */ + +import { Scalar, YAMLMap, isMap, isScalar, isSeq } from 'yaml'; +import type { Document } from 'yaml'; + +import { + jobKnowledge, + type PortContext, + type Rule, + type Tier, +} from './context'; +import { ciScope, queueOnlyJobs } from './scope'; +import { jobIds, jobOf, stepsOf, stringOf } from './workflow'; + +// --- services ----------------------------------------------------------------- + +/** Registries a job used for convenience on GitHub that the node serves under another name. */ +const IMAGE_HOSTS: ReadonlyMap = new Map([ + ['mirror.gcr.io/', 'docker.io/'], +]); + +function localImage(image: string): string { + for (const [from, to] of IMAGE_HOSTS) + if (image.startsWith(from)) return to + image.slice(from.length); + return image; +} + +function sequenceStrings(node: unknown): string[] { + if (!isSeq(node)) return []; + return node.items.flatMap((item) => { + const text = isScalar(item) ? String(item.value) : undefined; + return text === undefined ? [] : [text]; + }); +} + +function shellQuote(text: string): string { + return `'${text.replaceAll("'", "'\\''")}'`; +} + +/** `5432:5432` or `127.0.0.1:5432:5432` becomes a loopback publish; a bare container port is refused. */ +function publishPort(entry: string): string | undefined { + const parts = entry.split(':'); + if ( + parts.length === 2 && + parts.every((part) => /^\d+(\/(tcp|udp))?$/.test(part)) + ) + return `127.0.0.1:${entry}`; + if (parts.length === 3 && parts[0] === '127.0.0.1') return entry; + return undefined; +} + +function startScript( + name: string, + image: string, + ports: readonly string[], + envNames: readonly string[], + options: string | undefined, + command: string | undefined, +): string { + const container = `service-${name}`; + const lines = [ + 'set -euo pipefail', + `docker run -d --name ${shellQuote(container)} \\`, + ...ports.map((port) => ` -p ${port} \\`), + ...envNames.map((env) => ` -e ${env} \\`), + ...(options ? [` ${options} \\`] : []), + ` ${shellQuote(image)}${command ? ` ${command}` : ''}`, + ]; + if (options?.includes('--health-cmd')) { + lines.push( + 'for _ in $(seq 1 90); do', + ` status=$(docker inspect --format '{{.State.Health.Status}}' ${shellQuote(container)})`, + ' [ "$status" = healthy ] && exit 0', + ' if [ "$status" = unhealthy ]; then', + ` docker logs ${shellQuote(container)}`, + ' exit 1', + ' fi', + ' sleep 2', + 'done', + `echo "::error::service ${name} never became healthy"`, + `docker logs ${shellQuote(container)}`, + 'exit 1', + ); + } + return `${lines.join('\n')}\n`; +} + +/** + * Forgejo's runner never starts `services:` for a job that runs on a host + * (label `:host`), so a service becomes the `docker run` it stands for, published + * on the loopback address where the job's steps already look for it, and waited + * for when its options define a health check. The step goes first, so that the + * service is up before any step needs it. + * Nothing removes the container: the runner's instance is deleted with the job. + */ +const servicesToDockerRun: Rule = (doc, context) => { + const { file, report } = context; + for (const id of jobIds(doc)) { + const job = jobOf(doc, id); + const services = job?.get('services'); + if (!job || !isMap(services)) continue; + const steps = stepsOf(job); + if (!steps) continue; + const created: YAMLMap[] = []; + for (const entry of services.items) { + const name = stringOf(entry.key); + const spec = entry.value; + if (name === undefined || !isMap(spec)) continue; + const image = stringOf(spec.get('image')); + if (image === undefined) continue; + if (spec.has('credentials')) + report.warnings.push({ + file, + at: `jobs.${id}.services.${name}`, + rule: 'service-credentials', + detail: 'a registry login for a service is not carried over', + }); + if (spec.has('volumes')) + report.warnings.push({ + file, + at: `jobs.${id}.services.${name}`, + rule: 'service-volumes', + detail: + 'the volumes of a service are not carried over: it starts with none', + }); + const ports = sequenceStrings(spec.get('ports')).map((entryPort) => ({ + entry: entryPort, + publish: publishPort(entryPort), + })); + for (const port of ports) + if (!port.publish) + report.warnings.push({ + file, + at: `jobs.${id}.services.${name}`, + rule: 'service-port', + detail: `port \`${port.entry}\` has no fixed host port: not published`, + }); + const env = spec.get('env'); + const envPairs = isMap(env) + ? env.items.flatMap((pair) => { + const key = stringOf(pair.key); + return key === undefined ? [] : [{ key, value: pair.value }]; + }) + : []; + const options = stringOf(spec.get('options')) + ?.replace(/\s+/g, ' ') + .trim(); + const command = stringOf(spec.get('cmd')); + const step = new YAMLMap(); + step.set('name', `Start the ${name} service`); + if (envPairs.length > 0) { + const stepEnv = new YAMLMap(); + for (const pair of envPairs) stepEnv.set(pair.key, pair.value); + step.set('env', stepEnv); + } + const run = new Scalar( + startScript( + name, + localImage(image), + ports.flatMap((port) => (port.publish ? [port.publish] : [])), + envPairs.map((pair) => pair.key), + options, + command, + ), + ); + run.type = Scalar.BLOCK_LITERAL; + step.set('run', run); + created.push(step); + } + steps.items.unshift(...created); + job.delete('services'); + report.changes.push({ + file, + at: `jobs.${id}`, + rule: 'services', + detail: `${created.length} service${created.length === 1 ? '' : 's'} started with docker run: the host-mode runner does not start \`services:\``, + }); + } +}; + +// --- the size of a matrix ----------------------------------------------------- + +/** The number of jobs a plain matrix makes, or `undefined` when something decides it at run time. */ +function matrixSize(job: YAMLMap): number | undefined { + const strategy = job.get('strategy'); + const matrix = isMap(strategy) ? strategy.get('matrix') : undefined; + if (!isMap(matrix)) return undefined; + let total = 1; + for (const pair of matrix.items) { + const key = stringOf(pair.key); + if (key === 'include' || key === 'exclude') return undefined; + if (!isSeq(pair.value)) return undefined; + total *= pair.value.items.length; + } + return total; +} + +/** + * The runner never fills `strategy.job-total` (nor `job-index`), so a job that + * passes `--shard=N/${{ strategy.job-total }}` would pass `--shard=N/`. The size + * of a plain matrix is known when the file is generated. + */ +const matrixTotals: Rule = (doc, context) => { + for (const id of jobIds(doc)) { + const job = jobOf(doc, id); + const size = job && matrixSize(job); + if (size !== undefined) + jobKnowledge(context.knowledge, id).values.set( + 'strategy.job-total', + size, + ); + } +}; + +// --- what has no meaning on Forgejo ------------------------------------------ + +/** Deployment environments do not exist on Forgejo and the server drops the key. */ +const dropEnvironments: Rule = (doc, context) => { + const { file, report } = context; + for (const id of jobIds(doc)) { + if (jobOf(doc, id)?.delete('environment')) + report.changes.push({ + file, + at: `jobs.${id}`, + rule: 'environment', + detail: + 'removed `environment:` (the server ignores it and Forgejo has no deployment environments)', + }); + } +}; + +// --- facts a job leaves behind ------------------------------------------------ + +/** + * An output that is the empty string says nothing whether its job ran or not, so + * the jobs that read it can be folded: build.yml's `changes` job exports the + * release candidate's SHA, which is empty without candidates. + */ +export function learnEmptyOutputs( + doc: Document, + context: PortContext, +): boolean { + let learned = false; + for (const id of jobIds(doc)) { + const job = jobOf(doc, id); + const outputs = job?.get('outputs'); + if (!isMap(outputs)) continue; + for (const pair of outputs.items) { + const name = stringOf(pair.key); + const value = isScalar(pair.value) ? pair.value.value : undefined; + if (name === undefined || value !== '') continue; + const path = `needs.${id}.outputs.${name}`; + if (context.knowledge.values.get(path) === '') continue; + context.knowledge.values.set(path, ''); + learned = true; + } + } + return learned; +} + +/** The rules every workflow goes through, in order. */ +export function defaultRules(tier: Tier): Rule[] { + return [ + ciScope(tier), + queueOnlyJobs(tier), + servicesToDockerRun, + matrixTotals, + dropEnvironments, + ]; +} + +/** What a pull request owes unless a manifest says otherwise. */ +const DEFAULT_TIER: Tier = 'full'; + +export const DEFAULT_RULES: readonly Rule[] = defaultRules(DEFAULT_TIER); diff --git a/tools/cli/scripts/forgejo-port/runner.test.ts b/tools/cli/scripts/forgejo-port/runner.test.ts new file mode 100644 index 0000000000..a79e0675ff --- /dev/null +++ b/tools/cli/scripts/forgejo-port/runner.test.ts @@ -0,0 +1,191 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { RUNNER, pinnedRunner } from './runner'; + +const LINUX = { os: 'linux', arch: 'x64' }; +const temporary: string[] = []; + +afterEach(() => { + for (const directory of temporary.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); + +function cache(): string { + const directory = mkdtempSync(join(tmpdir(), 'forgejo-runner-test-')); + temporary.push(directory); + return directory; +} + +/** What the work says through `console.warn`, so that a test can read it. */ +async function warned( + work: () => Promise, +): Promise<{ result: T; warnings: string }> { + const original = console.warn; + const warnings: string[] = []; + console.warn = (...args: unknown[]) => { + warnings.push(args.join(' ')); + }; + try { + return { result: await work(), warnings: warnings.join('\n') }; + } finally { + console.warn = original; + } +} + +/** A download whose bytes hash to the pin: the test pins its own digest for the fake binary. */ +const BYTES = new TextEncoder().encode('not really a runner'); + +describe('pinnedRunner', () => { + test('pins the amd64 build of the version ops runs', () => { + expect(RUNNER.version).toBe('13.2.0'); + expect(RUNNER.linuxAmd64Sha256).toMatch(/^[0-9a-f]{64}$/); + }); + + test('has nothing to give on a platform the pin does not cover', async () => { + let asked = false; + const get = (() => { + asked = true; + return Promise.reject(new Error('never')); + }) as unknown as typeof fetch; + expect( + await pinnedRunner(cache(), { os: 'darwin', arch: 'arm64' }, get), + ).toBeUndefined(); + expect( + await pinnedRunner(cache(), { os: 'linux', arch: 'arm64' }, get), + ).toBeUndefined(); + expect(asked).toBe(false); + }); + + test('refuses a download that is not the pinned binary, and says so', async () => { + const directory = cache(); + const get = (() => + Promise.resolve(new Response(BYTES))) as unknown as typeof fetch; + const { result, warnings } = await warned(() => + pinnedRunner(directory, LINUX, get), + ); + expect(result).toBeUndefined(); + expect(warnings).toContain('not the pinned runner'); + expect(createHash('sha256').update(BYTES).digest('hex')).not.toBe( + RUNNER.linuxAmd64Sha256, + ); + }); + + test('says why when the download fails, by status or by error', async () => { + const refused = (() => + Promise.resolve( + new Response('', { status: 503 }), + )) as unknown as typeof fetch; + const status = await warned(() => pinnedRunner(cache(), LINUX, refused)); + expect(status.result).toBeUndefined(); + expect(status.warnings).toContain('answered 503'); + const failing = (() => + Promise.reject(new Error('offline'))) as unknown as typeof fetch; + const error = await warned(() => pinnedRunner(cache(), LINUX, failing)); + expect(error.result).toBeUndefined(); + expect(error.warnings).toContain('offline'); + }); + + // Windows has no owners and no mode bits to read, and creating a link there needs a privilege. + test.skipIf(process.platform === 'win32')( + 'takes nothing from a cache another user could write to, or a link', + async () => { + let asked = false; + const get = (() => { + asked = true; + return Promise.resolve(new Response(BYTES)); + }) as unknown as typeof fetch; + const open = cache(); + chmodSync(open, 0o755); + const shared = await warned(() => pinnedRunner(open, LINUX, get)); + expect(shared.result).toBeUndefined(); + expect(shared.warnings).toContain('only this user can use'); + + const target = cache(); + const link = join(cache(), 'link'); + symlinkSync(target, link); + const linked = await warned(() => pinnedRunner(link, LINUX, get)); + expect(linked.result).toBeUndefined(); + expect(linked.warnings).toContain('only this user can use'); + expect(asked).toBe(false); + }, + ); + + test('downloads the binary once and checks it against the digest', async () => { + const directory = cache(); + const digest = createHash('sha256').update(BYTES).digest('hex'); + let fetched = 0; + const get = (() => { + fetched += 1; + return Promise.resolve(new Response(BYTES)); + }) as unknown as typeof fetch; + const path = await pinnedRunner(directory, LINUX, get, digest); + expect(path).toBe( + join(directory, `forgejo-runner-${RUNNER.version}-linux-amd64`), + ); + expect(await pinnedRunner(directory, LINUX, get, digest)).toBe(path); + expect(fetched).toBe(1); + }); + + // Windows files have no executable bit to read. + test.skipIf(process.platform === 'win32')( + 'makes the downloaded binary executable', + async () => { + const digest = createHash('sha256').update(BYTES).digest('hex'); + const get = (() => + Promise.resolve(new Response(BYTES))) as unknown as typeof fetch; + const path = await pinnedRunner(cache(), LINUX, get, digest); + expect(statSync(path ?? '').mode & 0o111).not.toBe(0); + }, + ); + + test('reads no mode bits where there are no users to own a directory, as on Windows', async () => { + // Windows reports every directory as writable by the group and by others. + const open = cache(); + chmodSync(open, 0o777); + const digest = createHash('sha256').update(BYTES).digest('hex'); + const get = (() => + Promise.resolve(new Response(BYTES))) as unknown as typeof fetch; + const getuid = process.getuid; + process.getuid = undefined as unknown as typeof process.getuid; + try { + expect(await pinnedRunner(open, LINUX, get, digest)).toBe( + join(open, `forgejo-runner-${RUNNER.version}-linux-amd64`), + ); + } finally { + process.getuid = getuid; + } + }); + + test('reuses a binary it already holds, and replaces one that is not the pin', async () => { + const directory = cache(); + const path = join( + directory, + `forgejo-runner-${RUNNER.version}-linux-amd64`, + ); + // a binary of the wrong digest is not trusted: it is fetched again, and the fetch fails here + writeFileSync(path, BYTES); + const get = (() => + Promise.resolve( + new Response('', { status: 404 }), + )) as unknown as typeof fetch; + const { result, warnings } = await warned(() => + pinnedRunner(directory, LINUX, get), + ); + expect(result).toBeUndefined(); + expect(warnings).toContain('answered 404'); + expect(readFileSync(path)).toEqual(Buffer.from(BYTES)); + expect(statSync(path).size).toBe(BYTES.length); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/runner.ts b/tools/cli/scripts/forgejo-port/runner.ts new file mode 100644 index 0000000000..74211d4a8d --- /dev/null +++ b/tools/cli/scripts/forgejo-port/runner.ts @@ -0,0 +1,108 @@ +/** + * The forgejo-runner the port is held to. + * + * `forgejo-runner validate` reads a workflow against the runner's schema and + * `forgejo-runner exec --list` plans it, so a file that passes both is one the node's + * runner reads. The version is the one the ops repository pins for the node + * (`FORGEJO_RUNNER_VERSION` and `FORGEJO_RUNNER_LINUX_AMD64_SHA256` in its + * `scripts/pins.yml`); the cut-over compares the two. + */ + +import { createHash } from 'node:crypto'; +import { chmod, lstat, mkdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +export const RUNNER = { + version: '13.2.0', + /** SHA-256 of `forgejo-runner--linux-amd64`. */ + linuxAmd64Sha256: + 'fadaec897f5e6641c363f87ecaf75f866f99c81b7097ec6b433e4c48123fcad1', +} as const; + +function sha256(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +function warn(message: string): void { + console.warn(`forgejo-port: ${message}`); +} + +/** + * The cache holds a binary that is executed by path after its digest is checked, so no one + * else may write to it: it is the caller's own directory, closed to the group and to others, + * and not a link. A shared, predictable path under the temporary directory is refused. + * Windows has no `getuid`, and its directories report the mode bits of every user and ignore + * the mode given to `mkdir`, so there only the directory itself is checked. + */ +async function ownDirectory(path: string): Promise { + try { + await mkdir(path, { recursive: true, mode: 0o700 }); + const found = await lstat(path); + const uid = process.getuid?.(); + if ( + found.isDirectory() && + (uid === undefined || (found.uid === uid && (found.mode & 0o077) === 0)) + ) + return true; + warn( + `${path} is not a directory of this user that only this user can use: the pinned runner is not taken from it`, + ); + } catch (error) { + warn( + `could not prepare ${path} for the pinned runner: ${error instanceof Error ? error.message : String(error)}`, + ); + } + return false; +} + +/** + * The pinned binary, downloaded once into `cache` and checked against its digest. + * Only the linux/amd64 build is pinned, so on another platform this is `undefined` + * and a caller points `FORGEJO_RUNNER` at a binary it can run. Anything that keeps the + * pinned binary from being used says so, and the result is `undefined`. + */ +export async function pinnedRunner( + cache: string, + platform: { os: string; arch: string } = { + os: process.platform, + arch: process.arch, + }, + get: typeof fetch = fetch, + digest: string = RUNNER.linuxAmd64Sha256, +): Promise { + if (platform.os !== 'linux' || platform.arch !== 'x64') return undefined; + if (!(await ownDirectory(cache))) return undefined; + const path = join(cache, `forgejo-runner-${RUNNER.version}-linux-amd64`); + const held = await readFile(path).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + }); + if (held !== undefined && sha256(held) === digest) return path; + try { + const response = await get( + `https://code.forgejo.org/forgejo/runner/releases/download/v${RUNNER.version}/forgejo-runner-${RUNNER.version}-linux-amd64`, + { signal: AbortSignal.timeout(60_000) }, + ); + if (!response.ok) { + warn( + `could not download the pinned runner: the server answered ${response.status}`, + ); + return undefined; + } + const bytes = new Uint8Array(await response.arrayBuffer()); + if (sha256(bytes) !== digest) { + warn( + 'the download is not the pinned runner: its digest is not the one pinned', + ); + return undefined; + } + await writeFile(path, bytes); + await chmod(path, 0o755); + return path; + } catch (error) { + warn( + `could not download the pinned runner: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } +} diff --git a/tools/cli/scripts/forgejo-port/scope.test.ts b/tools/cli/scripts/forgejo-port/scope.test.ts new file mode 100644 index 0000000000..e46e0c82d6 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/scope.test.ts @@ -0,0 +1,355 @@ +import { describe, expect, test } from 'bun:test'; + +import { BUILD_FILTERS } from '../ci-ready'; +import type { Tier } from './context'; +import { portWorkflow } from './port'; +import { defaultRules } from './rules'; +import { emptyReport } from './workflow'; + +function port(source: string, file = 'w.yml', tier: Tier = 'fast') { + const report = emptyReport(); + const result = portWorkflow(source, file, report, { + rules: defaultRules(tier), + }); + return { ...result, report }; +} + +const RUNS = ` runs-on: ubuntu-latest\n`; +const SHA = 'a'.repeat(40); + +/** The pure job every queue-only workflow starts with, as Tale writes it. */ +const scopeJob = ( + filter: string, + queueOnly: boolean, + outputs: string[], + condition: string | null = "github.event_name == 'pull_request'", +) => ` + pr-scope: + name: PR scope +${condition === null ? '' : ` if: ${condition}\n`}${RUNS} outputs: +${outputs.map((name) => ` ${name}: \${{ steps.scope.outputs.${name} }}`).join('\n')} + steps: + - uses: actions/checkout@${SHA} + with: + sparse-checkout: | + /.github/actions/ci-scope/action.yml + - id: scope + uses: ./.github/actions/ci-scope + with: + filter: ${filter}${queueOnly ? "\n queue-only: 'true'" : ''} +`; + +describe('a job that only asks for the scope', () => { + const E2E = `name: E2E +on: + merge_group: + pull_request: + branches: [main] + workflow_dispatch: +jobs:${scopeJob('e2e', true, ['run', 'full', 'platform', 'web', 'changes'])} + scope: + needs: [pr-scope] + name: E2E scope + if: >- + !cancelled() && + (github.event_name != 'pull_request' || + (needs.pr-scope.result == 'success' && needs.pr-scope.outputs.run == 'true')) +${RUNS} steps: + - name: Decide + env: + PLATFORM: \${{ needs.pr-scope.outputs.platform }} + FULL: \${{ needs.pr-scope.outputs.full }} + CHANGES: \${{ needs.pr-scope.outputs.changes }} + run: echo "$PLATFORM $WEB" +`; + + test('is removed, and what reads it asks about the event instead', () => { + const { text, jobs, removed } = port(E2E); + expect(jobs).toEqual(['scope']); + expect(removed.get('pr-scope')).toContain('scope'); + expect(text).not.toContain('pr-scope'); + // a pull request owes nothing of a queue-only suite, a batch and a dispatch owe it all + expect(text).toContain( + 'if: "!cancelled() && github.event_name != \'pull_request\'"', + ); + // the job runs for pull requests only, so its outputs are empty for every other run + expect(text).toContain( + "FULL: ${{ github.event_name == 'pull_request' && 'false' || '' }}", + ); + // and what the scope never sets is empty for pull requests too + expect(text).toContain("PLATFORM: ''"); + expect(text).toContain("CHANGES: ''"); + expect(text).not.toContain('needs:'); + }); + + test('hands the readiness policy what the job would have said, for each kind of run', () => { + const report = emptyReport(); + const context: { results?: Map } = {}; + const ported = portWorkflow(E2E, 'e2e.yml', report, { + rules: defaultRules('fast'), + after: [ + (_doc, ctx) => { + context.results = ctx.results; + }, + ], + }); + expect(ported.removed.has('pr-scope')).toBe(true); + expect(context.results?.get('pr-scope')).toEqual({ + pull_request: { + result: 'success', + outputs: { + run: 'false', + full: 'false', + platform: '', + web: '', + changes: '', + }, + }, + push: { + result: 'skipped', + outputs: { + run: '', + full: '', + platform: '', + web: '', + changes: '', + }, + }, + }); + }); + + test('a Build scope that also runs for a batch names every service', () => { + const { text } = port(`name: Build +on: + merge_group: + pull_request: +jobs:${scopeJob('build', true, ['changes', 'ci_tests'], null)} + changes: + needs: [pr-scope] +${RUNS} steps: + - env: + PR_CHANGES: \${{ needs.pr-scope.outputs.changes }} + PR_CI_TESTS: \${{ needs.pr-scope.outputs.ci_tests }} + run: echo "$PR_CHANGES" +`); + const all = JSON.stringify( + BUILD_FILTERS.filter((name) => name !== 'image_inputs'), + ); + expect(text).toContain( + `PR_CHANGES: \${{ github.event_name != 'pull_request' && '${all}' || '' }}`, + ); + expect(text).toContain( + "PR_CI_TESTS: ${{ github.event_name != 'pull_request' && 'true' || '' }}", + ); + }); + + test('without queue-only, a pull request owes everything too', () => { + const { text, removed } = port(`name: Security +on: + merge_group: + pull_request: +jobs:${scopeJob('security', false, ['run', 'full'])} + scan: + needs: [pr-scope] + if: >- + github.event_name != 'pull_request' || + (needs.pr-scope.result == 'success' && needs.pr-scope.outputs.run == 'true') +${RUNS} steps: + - run: echo scan +`); + expect(removed.has('pr-scope')).toBe(true); + expect(text).not.toContain('if:'); + expect(text).not.toContain('needs:'); + }); +}); + +describe('a scope step in a job that does other work', () => { + const INTEGRATION = `name: Checks +on: + merge_group: + pull_request: +jobs: + integration-scope: +${RUNS} outputs: + run: \${{ steps.complete.outputs.run || steps.decide.outputs.run }} + steps: + - name: Require complete integration + if: github.event_name != 'pull_request' + id: complete + run: echo 'run=true' >> "$GITHUB_OUTPUT" + - name: Checkout + if: github.event_name == 'pull_request' + uses: actions/checkout@${SHA} + with: + sparse-checkout: | + /.github/actions/ci-scope/action.yml + /.github/ci-scope.yml + - name: Decide + id: decide + if: github.event_name == 'pull_request' + uses: ./.github/actions/ci-scope + with: + filter: integration + queue-only: 'true' +`; + + test('is removed with the checkout that fetched it, and the job output says what it said', () => { + const { text, jobs, report } = port(INTEGRATION); + expect(jobs).toEqual(['integration-scope']); + expect(text).toContain('Require complete integration'); + expect(text).not.toContain('ci-scope'); + expect(text).not.toContain('Checkout'); + // a pull request reports 'false', anything else the other step's 'true' + expect(text).toContain( + "run: ${{ steps.complete.outputs.run || (github.event_name == 'pull_request' && 'false' || '') }}", + ); + expect(report.changes.filter((c) => c.rule === 'scope-step')).toHaveLength( + 2, + ); + }); + + test('leaves a step that only skips an upload for pull requests alone', () => { + const { text } = port(`name: CLI +on: + merge_group: + pull_request: +jobs: + build: +${RUNS} steps: + - name: Upload artifact + if: github.event_name != 'pull_request' + run: echo upload +`); + expect(text).toContain("if: github.event_name != 'pull_request'"); + }); +}); + +describe('a scope step the port cannot read', () => { + test('is left, with a warning, when something other than the event decides whether it runs', () => { + const { text, report } = port(`name: W +on: + pull_request: +jobs: + scope: +${RUNS} steps: + - id: decide + if: github.event_name == 'pull_request' && inputs.go + uses: ./.github/actions/ci-scope + with: + filter: build + queue-only: 'true' +`); + expect(text).toContain('./.github/actions/ci-scope'); + expect(report.warnings.some((warning) => warning.rule === 'scope')).toBe( + true, + ); + }); + + test('is left, with a warning, when it has no id to read its outputs by', () => { + const { text, report } = port(`name: W +on: + pull_request: +jobs: + scope: +${RUNS} steps: + - uses: ./.github/actions/ci-scope + with: + filter: build +`); + expect(text).toContain('./.github/actions/ci-scope'); + expect(report.warnings).toHaveLength(1); + }); +}); + +describe('the full tier', () => { + const E2E = `name: E2E +on: + merge_group: + pull_request: +jobs:${scopeJob('e2e', true, ['run', 'full'])} + scope: + needs: [pr-scope] + if: >- + !cancelled() && + (github.event_name != 'pull_request' || + (needs.pr-scope.result == 'success' && needs.pr-scope.outputs.run == 'true')) +${RUNS} steps: + - env: + FULL: \${{ needs.pr-scope.outputs.full }} + run: echo "$FULL" +`; + + test('a pull request owes the suite a batch owes, and the scope job answers so', () => { + const { text } = port(E2E, 'e2e.yml', 'full'); + expect(text).toContain('if: "!cancelled()"'); + expect(text).toContain( + "FULL: ${{ github.event_name == 'pull_request' && 'true' || '' }}", + ); + expect(port(E2E, 'e2e.yml', 'fast').text).toContain( + "github.event_name != 'pull_request'", + ); + }); + + test('hands the readiness policy the scope a pull request really had', () => { + const seen: Record = {}; + portWorkflow(E2E, 'e2e.yml', emptyReport(), { + rules: defaultRules('full'), + after: [ + (_doc, context) => { + seen.pr = context.results.get('pr-scope'); + }, + ], + }); + expect(seen.pr).toEqual({ + pull_request: { + result: 'success', + outputs: { run: 'true', full: 'true' }, + }, + push: { result: 'skipped', outputs: { run: '', full: '' } }, + }); + }); +}); + +describe('queueOnlyJobs', () => { + const CHECKS = (file: string, tier: Tier) => + port( + `name: Checks +on: + merge_group: + pull_request: +jobs: + build: + if: >- + github.event_name != 'pull_request' && + !cancelled() && + needs.x.result == 'success' +${RUNS} steps: + - run: echo build + lint: + if: github.event_name != 'pull_request' +${RUNS} steps: + - run: echo lint +`, + file, + tier, + ); + + test('lets a pull request of the full tier run the suites the merge queue alone ran', () => { + const { text } = CHECKS('checks.yml', 'full'); + expect(text).toContain( + 'if: "!cancelled() && needs.x.result == \'success\'"', + ); + }); + + test('touches only the jobs Tale lists as queue-only, only in checks.yml, and not in the fast tier', () => { + expect(CHECKS('checks.yml', 'full').text).toContain( + "if: github.event_name != 'pull_request'", + ); + expect(CHECKS('build.yml', 'full').text).toContain( + "github.event_name != 'pull_request' &&", + ); + expect(CHECKS('checks.yml', 'fast').text).toContain( + "github.event_name != 'pull_request' &&", + ); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/scope.ts b/tools/cli/scripts/forgejo-port/scope.ts new file mode 100644 index 0000000000..e8cdc3ff74 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/scope.ts @@ -0,0 +1,359 @@ +/** + * The scope of a run: which suites a pull request owes and which only a batch of the + * merge train does. + * + * On GitHub a `ci-scope` step answers that. The heavy suites (Build, E2E, CLI, the + * backend integration check) pass `queue-only: 'true'`: a pull request owes nothing + * and reports so without looking at its files, the merge queue's group owes everything. + * Security passes nothing and decides from the pull request's paths. The answers are + * a function of the event, so the port does not run the step: it teaches the folder + * what each output is for a pull request and for anything else, and the conditions that + * read it fold into conditions on the event. + * + * What a pull request owes is the tier. `fast` keeps GitHub's: the fast lanes, and the + * heavy suites held for the batch. `full` makes a pull request owe what a batch owes, so + * that a failure shows on the pull request and not in the train. + * + * The one thing it does not carry over is Security's path filter: Security runs on + * every pull request, which costs a few runner-minutes for two lockfile scans. + */ + +import { isMap, isScalar } from 'yaml'; + +import { + BUILD_FILTERS, + CHECKS_MERGE_QUEUE_ONLY, + E2E_SERVICES, + buildScope, + e2eScope, +} from '../ci-ready'; +import { + jobKnowledge, + type EventResults, + type JobResult, + type Knowledge, + type Rule, + type Tier, +} from './context'; +import { + ExpressionError, + allOf, + conjuncts, + contextPath, + parseExpression, + parseTemplate, + sameExpression, +} from './expression'; +import { + conditionOf, + editCondition, + foldCondition, + jobIds, + jobOf, + removeJobs, + stepsOf, + stringOf, +} from './workflow'; + +const CI_SCOPE_ACTION = '/actions/ci-scope'; + +/** Every output the scope action declares. */ +const OUTPUTS = [ + 'run', + 'full', + 'changes', + 'ci_tests', + 'storybook', + 'platform', + 'web', + 'docs', +] as const; + +type Event = 'pull_request' | 'push'; +const EVENTS: readonly Event[] = ['pull_request', 'push']; + +/** `push` stands for every event that is not a pull request: a batch, a schedule, a dispatch. */ +const PULL_REQUEST = parseExpression("github.event_name == 'pull_request'"); + +function usesOf(step: unknown): string | undefined { + return isMap(step) ? stringOf(step.get('uses')) : undefined; +} + +function isScopeStep(step: unknown): boolean { + return usesOf(step)?.includes(CI_SCOPE_ACTION) === true; +} + +/** A checkout that only fetches the scope action and its policy. */ +function isScopeCheckout(step: unknown): boolean { + if (!isMap(step) || !usesOf(step)?.startsWith('actions/checkout@')) + return false; + const inputs = step.get('with'); + const sparse = isMap(inputs) + ? stringOf(inputs.get('sparse-checkout')) + : undefined; + return sparse?.includes('ci-scope/action.yml') === true; +} + +function inputText(inputs: unknown, name: string): string | undefined { + if (!isMap(inputs)) return undefined; + const node = inputs.get(name, true); + const value = isScalar(node) ? node.value : node; + return value === null || value === undefined ? undefined : String(value); +} + +/** What the scope action answers when the run owes everything. */ +function fullOutputs(filter: string): Record { + const outputs: Record = { run: 'true', full: 'true' }; + if (filter === 'build') + Object.assign( + outputs, + buildScope( + Object.fromEntries(BUILD_FILTERS.map((name) => [name, 'true'])), + true, + ), + ); + if (filter === 'e2e') + Object.assign( + outputs, + e2eScope( + Object.fromEntries(E2E_SERVICES.map((name) => [name, 'true'])), + true, + ), + ); + return outputs; +} + +/** What it answers for each kind of run. */ +function scopeOutputs( + filter: string, + queueOnly: boolean, + tier: Tier, +): Record> { + const full = fullOutputs(filter); + return { + pull_request: + queueOnly && tier === 'fast' ? { run: 'false', full: 'false' } : full, + push: full, + }; +} + +/** Whether something with this condition runs for this kind of run; `undefined` when more than the event decides. */ +function ranOn( + condition: string | undefined, + event: Event, +): boolean | undefined { + if (condition === undefined) return true; + try { + const outcome = foldCondition(condition, { + values: new Map([['github.event_name', event]]), + }); + if (outcome.kind === 'always') return true; + if (outcome.kind === 'never') return false; + return undefined; + } catch (error) { + if (error instanceof ExpressionError) return undefined; + throw error; + } +} + +/** Teach the folder a path that holds one string for a pull request and another for anything else. */ +function teach( + knowledge: { + values: Knowledge['values']; + conditional: Knowledge['conditional']; + }, + path: string, + values: Record, +): void { + if (values.pull_request === values.push) + knowledge.values.set(path, values.push); + else + knowledge.conditional.set(path, { + when: PULL_REQUEST, + ifTrue: values.pull_request, + ifFalse: values.push, + }); +} + +/** The step output a job output passes on: `${{ steps.scope.outputs.run }}`. */ +function stepOutputPath(value: unknown): string | undefined { + const text = stringOf(value); + if (text === undefined) return undefined; + try { + const parts = parseTemplate(text); + const only = parts.length === 1 ? parts[0] : undefined; + if (only?.kind !== 'expr') return undefined; + const path = contextPath(only.expr); + return path?.startsWith('steps.') ? path : undefined; + } catch (error) { + if (error instanceof ExpressionError) return undefined; + throw error; + } +} + +export function ciScope(tier: Tier): Rule { + return (doc, context) => { + const { file, report, knowledge, removed, results } = context; + const warn = (at: string, detail: string): void => { + report.warnings.push({ file, at, rule: 'scope', detail }); + }; + + for (const id of jobIds(doc)) { + const job = jobOf(doc, id); + const steps = job && stepsOf(job); + if (!job || !steps) continue; + const scoping = steps.items.filter(isScopeStep); + if (scoping.length === 0) continue; + const at = `jobs.${id}`; + const inJob = jobKnowledge(knowledge, id); + + // What each scope step reports where it runs, by the path a later step or job reads. + const reported = new Map>(); + let understood = true; + for (const step of scoping) { + if (!isMap(step)) continue; + const stepId = stringOf(step.get('id')); + const inputs = step.get('with'); + const filter = inputText(inputs, 'filter'); + if (stepId === undefined || filter === undefined) { + warn(at, 'a scope step with no id or no filter: left as it is'); + understood = false; + continue; + } + const queueOnly = inputText(inputs, 'queue-only') === 'true'; + const answers = scopeOutputs(filter, queueOnly, tier); + const ran = EVENTS.map((event) => ranOn(conditionOf(step), event)); + if (ran.some((value) => value === undefined)) { + warn( + at, + `the scope step \`${stepId}\` runs on more than the event decides: left as it is`, + ); + understood = false; + continue; + } + for (const name of OUTPUTS) { + const values = Object.fromEntries( + EVENTS.map((event, index) => [ + event, + ran[index] ? (answers[event][name] ?? '') : '', + ]), + ) as Record; + reported.set(`steps.${stepId}.outputs.${name}`, values); + teach(inJob, `steps.${stepId}.outputs.${name}`, values); + } + } + if (!understood) continue; + + const pure = steps.items.every( + (step) => + (isScopeStep(step) || isScopeCheckout(step)) && + isMap(step) && + conditionOf(step) === undefined, + ); + if (!pure) { + for (let index = steps.items.length - 1; index >= 0; index -= 1) { + const step = steps.items[index]; + if (!isScopeStep(step) && !isScopeCheckout(step)) continue; + steps.items.splice(index, 1); + report.changes.push({ + file, + at: `${at}.steps[${index}]`, + rule: 'scope-step', + detail: + 'removed: what the step answers is a function of the event, so the conditions that read it say so', + }); + } + continue; + } + + // A job that only asks for the scope: its result and outputs are functions of the event too. + const jobRan = EVENTS.map((event) => ranOn(conditionOf(job), event)); + if (jobRan.some((value) => value === undefined)) { + warn( + at, + 'a scope job that runs on more than the event decides: left as it is', + ); + continue; + } + const declared = job.get('outputs'); + const outputPaths = new Map(); + if (isMap(declared)) { + for (const pair of declared.items) { + const name = stringOf(pair.key); + const path = stepOutputPath(pair.value); + if (name !== undefined && path !== undefined && reported.has(path)) + outputPaths.set(name, path); + } + } + const perEvent = Object.fromEntries( + EVENTS.map((event, index): [Event, JobResult] => { + const outputs: Record = {}; + for (const [name, path] of outputPaths) + outputs[name] = jobRan[index] + ? (reported.get(path)?.[event] ?? '') + : ''; + return [ + event, + { result: jobRan[index] ? 'success' : 'skipped', outputs }, + ]; + }), + ) as unknown as EventResults; + teach(knowledge, `needs.${id}.result`, { + pull_request: perEvent.pull_request.result, + push: perEvent.push.result, + }); + for (const name of outputPaths.keys()) + teach(knowledge, `needs.${id}.outputs.${name}`, { + pull_request: perEvent.pull_request.outputs[name] ?? '', + push: perEvent.push.outputs[name] ?? '', + }); + knowledge.jobs.delete(id); + removeJobs(doc, [id]); + removed.set( + id, + 'scope: what it reports is a function of the event, so the jobs that read it say so', + ); + results.set(id, perEvent); + report.changes.push({ + file, + at, + rule: 'scope-job', + detail: + 'removed: a pull request owes only what is not held for the merge train, a batch owes everything', + }); + } + }; +} + +const NOT_PULL_REQUEST = parseExpression("github.event_name != 'pull_request'"); + +/** + * GitHub keeps the heavy suites of Checks for the merge queue: their jobs carry + * `github.event_name != 'pull_request'`. When a pull request owes what a batch owes, that + * condition goes. The jobs are the ones Tale's own readiness policy lists + * (`CHECKS_MERGE_QUEUE_ONLY`), which its tests already hold to the workflow. + */ +export function queueOnlyJobs(tier: Tier): Rule { + return (doc, context) => { + if (tier !== 'full' || context.file !== 'checks.yml') return; + for (const id of CHECKS_MERGE_QUEUE_ONLY) { + const job = jobOf(doc, id); + if (!job) continue; + const changed = editCondition(job, (expression) => + allOf( + conjuncts(expression).filter( + (part) => !sameExpression(part, NOT_PULL_REQUEST), + ), + ), + ); + if (changed) + context.report.changes.push({ + file: context.file, + at: `jobs.${id}`, + rule: 'queue-only', + detail: + 'no longer held back for pull requests: they owe what a batch owes', + }); + } + }; +} diff --git a/tools/cli/scripts/forgejo-port/triggers.test.ts b/tools/cli/scripts/forgejo-port/triggers.test.ts new file mode 100644 index 0000000000..12536d662a --- /dev/null +++ b/tools/cli/scripts/forgejo-port/triggers.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, test } from 'bun:test'; + +import { rewriteTriggers } from './triggers'; +import { emptyReport, readWorkflow, writeWorkflow } from './workflow'; + +function rewrite( + on: string, + options: { + keepMainPush?: boolean; + dropEvents?: { name: string; why: string }[]; + } = {}, +) { + const doc = readWorkflow( + `name: W\n${on}\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: x\n`, + 'w.yml', + ); + const report = emptyReport(); + const result = rewriteTriggers(doc, { file: 'w.yml', ...options }, report); + const written = writeWorkflow(doc); + return { result, report, written }; +} + +describe('rewriteTriggers', () => { + test('drops what Forgejo never fires and adds the train, as for commitlint.yml', () => { + const { result, written } = rewrite(`on: + merge_group: + types: [checks_requested] + repository_dispatch: + types: [release-candidate] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - main + push: + branches: + - main +`); + expect(result.events).toEqual(['pull_request', 'push']); + expect(result.validatedInQueue).toBe(true); + expect(written).not.toContain('merge_group'); + expect(written).not.toContain('repository_dispatch'); + expect(written).not.toContain('ready_for_review'); + expect(written).toContain('types: [opened, synchronize, reopened]'); + expect(written).toMatch(/push:\n {4}branches: \['mq\/\*\*'\]/); + expect(written).toContain('- main'); + }); + + test('adds a push for the train to a workflow that had only the merge queue, as e2e.yml', () => { + const { result, written } = rewrite(`on: + merge_group: + types: [checks_requested] + repository_dispatch: + types: [release-candidate] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + schedule: + - cron: '30 2 * * *' + workflow_dispatch: +`); + expect(result.events).toEqual([ + 'pull_request', + 'schedule', + 'workflow_dispatch', + 'push', + ]); + expect(written).toContain("branches: ['mq/**']"); + expect(written).toContain("cron: '30 2 * * *'"); + }); + + test('takes the paths off a push, since a new branch has no files to compare', () => { + const { written } = rewrite(`on: + pull_request: + branches: [main] + push: + branches: [main] + paths: + - 'services/**' + - 'bun.lock' + merge_group: +`); + expect(written).not.toContain('paths'); + expect(written).not.toContain('services/**'); + expect(written).toContain("branches: ['mq/**']"); + }); + + test('removes a workflow_dispatch that exists for release candidates, as build.yml', () => { + const { result, written } = rewrite(`on: + merge_group: + workflow_dispatch: + inputs: + candidate_sha: + description: 'Release candidate' + required: true + type: string + repository_dispatch: + types: [release-candidate] +`); + expect(result.events).toEqual(['push']); + expect(written).not.toContain('workflow_dispatch'); + expect(written).not.toContain('candidate_sha'); + }); + + test('drops an event the plan says makes no sense here, and says why', () => { + const { result, written, report } = rewrite( + `on: + workflow_dispatch: + inputs: + release_tag: + required: true + pull_request: +`, + { + dropEvents: [ + { + name: 'workflow_dispatch', + why: 'it attaches binaries to a release', + }, + ], + }, + ); + expect(result.events).toEqual(['pull_request']); + expect(written).not.toContain('workflow_dispatch'); + expect(report.changes.map((change) => change.rule)).toContain( + 'trigger-dropped', + ); + expect( + report.changes.find((change) => change.rule === 'trigger-dropped') + ?.detail, + ).toContain('it attaches binaries to a release'); + }); + + test('keeps a manual dispatch with other inputs', () => { + const { result } = rewrite(`on: + merge_group: + workflow_dispatch: + inputs: + profile: + type: string +`); + expect(result.events).toEqual(['workflow_dispatch', 'push']); + }); + + test('leaves a publisher alone: a push to main is what it is for', () => { + const { result, written } = rewrite(`on: + push: + branches: [main] + paths: ['packages/ui/**'] + workflow_dispatch: + inputs: + release_tag: + required: false +`); + expect(result.validatedInQueue).toBe(false); + expect(result.events).toEqual(['push', 'workflow_dispatch']); + expect(written).toContain("paths: ['packages/ui/**']"); + expect(written).not.toContain('mq/'); + }); + + test('keeps the default branch too when the workflow publishes after a merge', () => { + const { written } = rewrite( + `on: + push: + branches: [main] + merge_group: +`, + { keepMainPush: true }, + ); + expect(written).toContain("branches: [main, 'mq/**']"); + }); + + test('reads the scalar and list forms of on', () => { + expect(rewrite('on: push').result.events).toEqual(['push']); + expect(rewrite('on: [push, pull_request]').result.events).toEqual([ + 'push', + 'pull_request', + ]); + expect(rewrite('on: [merge_group, pull_request]').result.events).toEqual([ + 'pull_request', + 'push', + ]); + }); + + test('says what it did', () => { + const { report } = rewrite(`on: + merge_group: + repository_dispatch: + pull_request: + types: [opened, ready_for_review] +`); + expect(report.changes.map((change) => change.rule)).toEqual([ + 'trigger-dead', + 'trigger-dead', + 'trigger-type', + 'trigger-train', + ]); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/triggers.ts b/tools/cli/scripts/forgejo-port/triggers.ts new file mode 100644 index 0000000000..de69aee76b --- /dev/null +++ b/tools/cli/scripts/forgejo-port/triggers.ts @@ -0,0 +1,183 @@ +/** + * The `on:` block of a ported workflow. + * + * Forgejo fires `push`, `pull_request`, `schedule`, `workflow_dispatch`, `release` + * and a handful more. It never fires `merge_group`, `repository_dispatch`, + * `workflow_run` or `branch_protection_rule`, and a workflow that lists them is + * accepted without a word and simply never runs on them. So the generated file + * says what it will really do: those events are gone, and a workflow that GitHub + * validated in its merge queue is validated on Forgejo by the merge train, whose + * batches are pushes to `mq/**`. + */ + +import { Scalar, YAMLMap, YAMLSeq, isMap, isSeq } from 'yaml'; +import type { Document } from 'yaml'; + +import { + emptyReport, + rootOf, + stringOf, + type Change, + type Report, +} from './workflow'; + +/** Events GitHub fires and Forgejo 15 never does: a trigger on one is dead. */ +export const NEVER_FIRED = [ + 'merge_group', + 'repository_dispatch', + 'workflow_run', + 'branch_protection_rule', +] as const; + +/** Pull request activities Forgejo has no event for (it has no drafts and no queue). */ +const UNSUPPORTED_PULL_REQUEST_TYPES = [ + 'ready_for_review', + 'converted_to_draft', + 'auto_merge_enabled', + 'auto_merge_disabled', + 'enqueued', + 'dequeued', + 'locked', + 'unlocked', +] as const; + +/** The branches the merge train pushes a batch to (tools/merge-train: `mq/-`). */ +const TRAIN_BRANCHES = 'mq/**'; + +export interface TriggerOptions { + readonly file: string; + /** Events the workflow has on GitHub and does not have here, with why. */ + readonly dropEvents?: readonly { + readonly name: string; + readonly why: string; + }[]; + /** Whether the workflow keeps running for a push to the default branch, as a publisher does. */ + readonly keepMainPush?: boolean; +} + +export interface TriggerResult { + /** The events the generated workflow is triggered by: what `github.event_name` can be. */ + readonly events: readonly string[]; + /** Whether the workflow was validated by GitHub's merge queue. */ + readonly validatedInQueue: boolean; +} + +/** A flow sequence of branch names; a glob is quoted, since `*` is YAML's alias sign. */ +export function flowSequence(values: readonly string[]): YAMLSeq { + const seq = new YAMLSeq(); + seq.flow = true; + for (const value of values) { + const node = new Scalar(value); + if (/[*?[\]{}!]/.test(value)) node.type = Scalar.QUOTE_SINGLE; + seq.add(node); + } + return seq; +} + +/** `on: push`, `on: [push, pull_request]` and the mapping form, all as a mapping. */ +function normalize(doc: Document): YAMLMap { + const root = rootOf(doc); + const current = root.get('on'); + if (isMap(current)) return current; + const events = new YAMLMap(); + const single = stringOf(current); + const names = + single !== undefined + ? [single] + : isSeq(current) + ? current.items.map((item) => stringOf(item)) + : []; + for (const name of names) if (name !== undefined) events.set(name, null); + root.set('on', events); + return events; +} + +/** + * Rewrite a workflow's triggers for Forgejo. Returns the events the result can + * receive, from which every condition on `github.event_name` is decided. + */ +export function rewriteTriggers( + doc: Document, + options: TriggerOptions, + report: Report = emptyReport(), +): TriggerResult { + const { file } = options; + const events = normalize(doc); + const note = (rule: string, detail: string): void => { + const change: Change = { file, at: 'on', rule, detail }; + report.changes.push(change); + }; + + const validatedInQueue = events.has('merge_group'); + for (const name of NEVER_FIRED) { + if (events.delete(name)) + note('trigger-dead', `removed \`${name}\`: Forgejo never fires it`); + } + + const pull = events.get('pull_request'); + if (isMap(pull)) { + const types = pull.get('types'); + if (isSeq(types)) { + for (let index = types.items.length - 1; index >= 0; index -= 1) { + const type = stringOf(types.items[index]); + if ( + type !== undefined && + (UNSUPPORTED_PULL_REQUEST_TYPES as readonly string[]).includes(type) + ) { + types.items.splice(index, 1); + note( + 'trigger-type', + `removed pull_request type \`${type}\`: Forgejo has no such activity`, + ); + } + } + if (types.items.length === 0) pull.delete('types'); + } + } + + if (validatedInQueue) { + const existing = events.get('push'); + const push = isMap(existing) ? existing : new YAMLMap(); + const branches = options.keepMainPush + ? ['main', TRAIN_BRANCHES] + : [TRAIN_BRANCHES]; + const before = isMap(existing) ? JSON.stringify(existing.toJSON()) : 'none'; + // A batch is a branch that did not exist a moment ago: `paths` has no files to compare. + push.delete('paths'); + push.delete('paths-ignore'); + push.delete('branches-ignore'); + if (!options.keepMainPush) push.delete('tags'); + push.set('branches', flowSequence(branches)); + events.set('push', push); + const after = JSON.stringify(push.toJSON()); + if (before !== after) + note( + 'trigger-train', + `\`push\` now runs for ${branches.map((b) => `\`${b}\``).join(' and ')}, the merge train's batches${options.keepMainPush ? ' and the default branch' : ''}`, + ); + } + + for (const { name, why } of options.dropEvents ?? []) { + if (events.delete(name)) + note('trigger-dropped', `removed \`${name}\`: ${why}`); + } + + const dispatch = events.get('workflow_dispatch'); + if (isMap(dispatch)) { + const inputs = dispatch.get('inputs'); + if (isMap(inputs) && inputs.has('candidate_sha')) { + // A dispatch that exists to validate a release candidate has nothing to do here. + events.delete('workflow_dispatch'); + note( + 'trigger-candidate', + 'removed `workflow_dispatch`: its only input was the release candidate', + ); + } + } + + const names = events.items.flatMap((pair) => { + const name = stringOf(pair.key); + return name === undefined ? [] : [name]; + }); + return { events: names, validatedInQueue }; +} diff --git a/tools/cli/scripts/forgejo-port/validate.ts b/tools/cli/scripts/forgejo-port/validate.ts new file mode 100644 index 0000000000..9593b39254 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/validate.ts @@ -0,0 +1,393 @@ +/** + * Is a generated workflow something Forgejo will accept and run? + * + * Two kinds of answer. Forgejo's own parser (`forgejo-runner validate`) checks the + * keys of a file against a schema, and it is the final word: `FORGEJO_RUNNER=` + * makes the tests run it over every generated file. This validator is what runs + * without that Linux binary: the same key sets (read from the runner's + * `act/schema/workflow_schema.json`, which is identical in the server's runner 12.10.2 + * and the node's 13.2.0), and the things the schema cannot say and the server and runner + * do differently: a label the pool does not serve, a step the server cannot decode, a + * trigger that never fires. + */ + +import { isMap, isScalar, isSeq } from 'yaml'; +import type { Document, YAMLMap } from 'yaml'; + +import { ACTIONS, externalActions } from './actions'; +import { parseExpression, ExpressionError } from './expression'; +import { NEVER_FIRED } from './triggers'; +import { + jobIds, + jobOf, + needsOf, + readWorkflow, + stepLists, + stepsOf, + stringOf, +} from './workflow'; + +export interface Problem { + readonly file: string; + readonly at: string; + readonly message: string; +} + +const WORKFLOW_KEYS = new Set([ + 'on', + 'name', + 'run-name', + 'description', + 'enable-email-notifications', + 'enable-openid-connect', + 'defaults', + 'env', + 'permissions', + 'concurrency', + 'jobs', +]); + +const JOB_KEYS = new Set([ + 'name', + 'needs', + 'if', + 'strategy', + 'runs-on', + 'timeout-minutes', + 'cancel-timeout-minutes', + 'continue-on-error', + 'container', + 'services', + 'env', + 'environment', + 'permissions', + 'concurrency', + 'outputs', + 'defaults', + 'steps', + 'enable-openid-connect', +]); + +const RUN_STEP_KEYS = new Set([ + 'name', + 'id', + 'if', + 'timeout-minutes', + 'run', + 'continue-on-error', + 'env', + 'working-directory', + 'shell', +]); + +const USES_STEP_KEYS = new Set([ + 'name', + 'id', + 'if', + 'continue-on-error', + 'timeout-minutes', + 'uses', + 'with', + 'env', +]); + +const PERMISSION_SCOPES = new Set([ + 'actions', + 'attestations', + 'checks', + 'contents', + 'deployments', + 'discussions', + 'id-token', + 'issues', + 'packages', + 'pages', + 'pull-requests', + 'repository-projects', + 'security-events', + 'statuses', +]); + +/** Keys of an action's `runs:` for a composite action. */ +const ACTION_KEYS = new Set([ + 'name', + 'description', + 'inputs', + 'runs', + 'outputs', +]); + +function keysOf(map: YAMLMap): string[] { + return map.items.flatMap((pair) => { + const key = stringOf(pair.key); + return key === undefined ? [] : [key]; + }); +} + +function expressionOf(text: string): string | undefined { + const trimmed = text.trim(); + const wrapped = trimmed.match(/^\$\{\{([\s\S]*)\}\}$/); + return wrapped ? wrapped[1] : trimmed.includes('${{') ? undefined : trimmed; +} + +/** The runner each row of a job's matrix names under `key`. */ +function matrixRunners(job: YAMLMap, key: string): string[] { + const strategy = job.get('strategy'); + const matrix = isMap(strategy) ? strategy.get('matrix') : undefined; + const include = isMap(matrix) ? matrix.get('include') : undefined; + const direct = isMap(matrix) ? matrix.get(key) : undefined; + const rows = isSeq(include) + ? include.items.flatMap((row) => + isMap(row) ? [stringOf(row.get(key))] : [], + ) + : []; + const listed = isSeq(direct) + ? direct.items.map((item) => stringOf(item)) + : []; + return [...rows, ...listed].flatMap((runner) => + runner === undefined ? [] : [runner], + ); +} + +function checkExpressions( + doc: Document, + file: string, + problems: Problem[], +): void { + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + if (!isMap(step)) continue; + const condition = stringOf(step.get('if')); + if (condition !== undefined) { + const expression = expressionOf(condition); + try { + if (expression !== undefined) parseExpression(expression); + } catch (error) { + if (!(error instanceof ExpressionError)) throw error; + problems.push({ + file, + at: `${at}.steps[${index}].if`, + message: error.message, + }); + } + } + const cont = step.get('continue-on-error'); + if (typeof cont === 'string' && cont.includes('${{')) + problems.push({ + file, + at: `${at}.steps[${index}].continue-on-error`, + message: + "an expression here fails the server's decoder (the field is a boolean)", + }); + } + } +} + +export interface ValidateOptions { + /** The runner labels the pool serves. */ + readonly labels: readonly string[]; +} + +/** The problems of one generated workflow. */ +export function validateWorkflow( + source: string, + file: string, + options: ValidateOptions, +): Problem[] { + const problems: Problem[] = []; + const doc = readWorkflow(source, file); + const root = doc.contents; + if (!isMap(root)) return [{ file, at: '', message: 'not a mapping' }]; + for (const key of keysOf(root)) + if (!WORKFLOW_KEYS.has(key)) + problems.push({ + file, + at: key, + message: 'Forgejo rejects this workflow key', + }); + + const on = root.get('on'); + const events = isMap(on) + ? keysOf(on) + : isScalar(on) || typeof on === 'string' + ? [stringOf(on) ?? ''] + : isSeq(on) + ? on.items.map((item) => stringOf(item) ?? '') + : []; + for (const event of events) + if ((NEVER_FIRED as readonly string[]).includes(event)) + problems.push({ + file, + at: `on.${event}`, + message: 'Forgejo never fires this event', + }); + + const permissions = root.get('permissions'); + if (isMap(permissions)) + for (const scope of keysOf(permissions)) + if (!PERMISSION_SCOPES.has(scope)) + problems.push({ + file, + at: `permissions.${scope}`, + message: 'Forgejo rejects this permission scope', + }); + + const ids = jobIds(doc); + for (const id of ids) { + const job = jobOf(doc, id); + if (!job) continue; + const at = `jobs.${id}`; + for (const key of keysOf(job)) + if (!JOB_KEYS.has(key)) + problems.push({ + file, + at: `${at}.${key}`, + message: 'Forgejo rejects this job key', + }); + for (const need of needsOf(job)) + if (!ids.includes(need)) + problems.push({ + file, + at: `${at}.needs`, + message: `needs \`${need}\`, which is not a job: the run would fail at creation`, + }); + if (job.has('services')) + problems.push({ + file, + at: `${at}.services`, + message: 'a host-mode runner never starts services', + }); + if (job.has('uses')) + problems.push({ + file, + at: `${at}.uses`, + message: 'a reusable workflow call is not generated', + }); + const runsOn = stringOf(job.get('runs-on')); + const matrixKey = runsOn?.match( + /^\$\{\{\s*matrix\.([A-Za-z0-9_-]+)\s*\}\}$/, + )?.[1]; + if (runsOn === undefined) + problems.push({ + file, + at: `${at}.runs-on`, + message: 'is not one plain label', + }); + else if (matrixKey !== undefined) { + for (const runner of matrixRunners(job, matrixKey)) + if (!options.labels.includes(runner)) + problems.push({ + file, + at: `${at}.runs-on`, + message: `a matrix row runs on \`${runner}\`, which the pool does not serve`, + }); + } else if (runsOn.includes('${{')) + problems.push({ + file, + at: `${at}.runs-on`, + message: 'the label of a job must be known when the file is generated', + }); + else if (!options.labels.includes(runsOn)) + problems.push({ + file, + at: `${at}.runs-on`, + message: `\`${runsOn}\` is not a label the pool serves: the runner would run it in a Docker image instead of queueing`, + }); + const steps = stepsOf(job); + if (!steps) + problems.push({ file, at: `${at}.steps`, message: 'has no steps' }); + } + + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + if (!isMap(step)) continue; + const where = `${at}.steps[${index}]`; + const uses = step.has('uses'); + const allowed = uses ? USES_STEP_KEYS : RUN_STEP_KEYS; + if (uses && step.has('run')) + problems.push({ + file, + at: where, + message: 'a step cannot have both uses and run', + }); + for (const key of keysOf(step)) + if (!allowed.has(key) && !(key === 'run' && !uses)) + problems.push({ + file, + at: `${where}.${key}`, + message: 'Forgejo rejects this step key', + }); + const shell = stringOf(step.get('shell')); + if ( + shell !== undefined && + !shell.includes('{0}') && + !['bash', 'sh', 'pwsh', 'python', 'node', 'cmd', 'powershell'].includes( + shell, + ) + ) + problems.push({ + file, + at: `${where}.shell`, + message: 'a custom shell without {0} runs nothing', + }); + } + } + + for (const action of externalActions(doc)) { + const disposition = ACTIONS.get(action.name); + if (!disposition) + problems.push({ + file, + at: 'uses', + message: `\`${action.name}\` is not in the action table`, + }); + else if (disposition.kind === 'drop' || disposition.kind === 'unportable') + problems.push({ + file, + at: 'uses', + message: `\`${action.name}\` cannot run on Forgejo: ${disposition.why}`, + }); + else if (disposition.kind === 'replace') + problems.push({ + file, + at: 'uses', + message: `\`${action.name}\` must be \`${disposition.to.name}\``, + }); + else if (!/^[0-9a-f]{40}$/.test(action.ref)) + problems.push({ + file, + at: 'uses', + message: `\`${action.name}@${action.ref}\` is not pinned by a full commit SHA`, + }); + } + + checkExpressions(doc, file, problems); + return problems; +} + +/** The problems of one generated composite action. */ +export function validateAction(source: string, file: string): Problem[] { + const problems: Problem[] = []; + const doc = readWorkflow(source, file); + const root = doc.contents; + if (!isMap(root)) return [{ file, at: '', message: 'not a mapping' }]; + for (const key of keysOf(root)) + if (!ACTION_KEYS.has(key)) + problems.push({ file, at: key, message: 'not a key of an action file' }); + for (const action of externalActions(doc)) { + const disposition = ACTIONS.get(action.name); + if ( + !disposition || + disposition.kind === 'drop' || + disposition.kind === 'unportable' || + disposition.kind === 'replace' + ) + problems.push({ + file, + at: 'runs.steps', + message: `\`${action.name}\` is not usable on Forgejo as it is`, + }); + } + checkExpressions(doc, file, problems); + return problems; +} diff --git a/tools/cli/scripts/forgejo-port/workflow-rules.test.ts b/tools/cli/scripts/forgejo-port/workflow-rules.test.ts new file mode 100644 index 0000000000..019049a564 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/workflow-rules.test.ts @@ -0,0 +1,619 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { parse } from 'yaml'; + +import { buildCache } from './cache'; +import type { Rule } from './context'; +import { portWorkflow } from './port'; +import { emptyReport } from './workflow'; +import { + batchEvent, + commitlintBatch, + dropForeignRows, + dropJobs, + githubApiToken, + lintLinksBase, + movePaths, + ownPath, + publishOnTag, + publishRemote, + readyJob, + recordRemoved, + runUrls, +} from './workflow-rules'; + +const SHA = 'a'.repeat(40); + +function run( + source: string, + rules: readonly Rule[], + file = 'w.yml', + after: readonly Rule[] = [], +) { + const report = emptyReport(); + const result = portWorkflow(source, file, report, { rules, after }); + return { ...result, report }; +} + +describe('readyJob', () => { + const SOURCE = `name: Checks +on: + merge_group: + pull_request: +jobs: + candidate-source: + if: github.event_name == 'repository_dispatch' + uses: ./.github/workflows/release-candidate-source.yml + lint: + needs: candidate-source + runs-on: ubuntu-latest + steps: + - run: echo lint + ci-ready: + name: CI ready (Checks) + if: always() && (github.event_name == 'pull_request' || github.event_name == 'merge_group') + needs: [candidate-source, lint] + runs-on: ubuntu-latest + timeout-minutes: 3 + permissions: + contents: read + steps: + - name: Checkout verdict policy + uses: actions/checkout@${SHA} # v6 + with: + persist-credentials: false + sparse-checkout: | + /.github/actions/ci-ready/action.yml + /tools/cli/scripts/ci-ready.ts + sparse-checkout-cone-mode: false + - name: Evaluate native workflow + uses: ./.github/actions/ci-ready + with: + workflow: checks + jobs: \${{ toJSON(needs) }} +`; + + test("judges the needs with Tale's policy, for a pull request and for a batch", () => { + const { text, jobs } = run(SOURCE, [readyJob('fast')], 'checks.yml', [ + recordRemoved, + ]); + expect(jobs).toEqual(['lint', 'ci-ready']); + expect(text).toContain( + "if: always() && (github.event_name == 'pull_request' || github.event_name == 'push')", + ); + expect(text).toContain('needs: [lint]'); + expect(text).toContain('CI_WORKFLOW: checks'); + expect(text).toContain('CI_TIER: fast'); + expect(text).toContain('CI_NEEDS: ${{ toJSON(needs) }}'); + expect(text).toContain('run: bun tools/cli/scripts/forgejo-port/ready.ts'); + expect(text).toContain(`uses: actions/checkout@${SHA} # v6`); + expect(text).not.toContain('permissions'); + expect(text).not.toContain('ci-ready/action.yml'); + }); + + test('says which jobs of the GitHub workflow are gone, and what each would have reported', () => { + const { text } = run(SOURCE, [readyJob('fast')], 'checks.yml', [ + recordRemoved, + ]); + const recorded = /CI_PORT_REMOVED: \|\n([\s\S]*?)\n\s*run:/.exec(text); + expect(JSON.parse(recorded?.[1] ?? 'null')).toEqual({ + 'candidate-source': { + pull_request: { result: 'skipped', outputs: {} }, + push: { result: 'skipped', outputs: {} }, + }, + }); + }); + + test('leaves a job it does not recognise alone, and says when it cannot rewrite', () => { + const odd = `name: X +on: + pull_request: +jobs: + ci-ready: + name: Something else + runs-on: ubuntu-latest + steps: + - run: echo +`; + expect(run(odd, [readyJob('fast')]).text).toContain('Something else'); + const noCheckout = SOURCE.replace( + / {6}- name: Checkout verdict policy[\s\S]*?cone-mode: false\n/, + '', + ); + expect( + run(noCheckout, [readyJob('fast')], 'checks.yml').report.warnings.map( + (w) => w.rule, + ), + ).toEqual(['ready']); + }); +}); + +describe('dropJobs', () => { + test('removes a job the port cannot run and lets the jobs that needed it see it skipped', () => { + const { text, removed } = run( + `name: CLI +on: + pull_request: +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: echo build + release: + needs: build + runs-on: ubuntu-latest + steps: + - run: gh release upload + after: + needs: [build, release] + if: always() && needs.release.result == 'skipped' + runs-on: ubuntu-latest + steps: + - run: echo after +`, + [dropJobs([{ id: 'release', why: 'uses gh' }])], + ); + expect(text).not.toContain('gh release'); + expect(text).toContain('needs: [build]'); + expect(text).toContain('if: always()'); + expect(removed.get('release')).toBe('uses gh'); + }); +}); + +describe('dropForeignRows', () => { + const CLI = `name: CLI +on: + pull_request: +jobs: + build: + runs-on: \${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-latest + platform: linux + - os: macos-latest + platform: macos + - os: windows-latest + platform: windows + - os: ubuntu-latest + platform: linux-arm64 + steps: + - run: echo \${{ matrix.platform }} +`; + + test('removes the rows whose runner the pool does not have', () => { + const { text, report } = run(CLI, [ + dropForeignRows(['ubuntu-latest', 'ubuntu-24.04']), + ]); + expect(text).toContain('platform: linux'); + expect(text).toContain('platform: linux-arm64'); + expect(text).not.toContain('macos'); + expect(text).not.toContain('windows'); + expect( + report.changes.filter((change) => change.rule === 'matrix-row'), + ).toHaveLength(2); + }); + + test('leaves a job with a plain label alone', () => { + const { report } = run(CLI.replace('${{ matrix.os }}', 'ubuntu-latest'), [ + dropForeignRows(['ubuntu-latest']), + ]); + expect(report.changes).toEqual([]); + }); +}); + +describe('commitlintBatch', () => { + const SCRIPT = `name: Commitlint +on: + pull_request: +jobs: + commitlint: + runs-on: ubuntu-latest + steps: + - run: | + if [ -z "$PUSH_BEFORE" ]; then + bunx commitlint --last --verbose + fi +`; + + test('lints every commit of a batch, not the last one', () => { + const { text } = run(SCRIPT, [commitlintBatch], 'commitlint.yml'); + expect(text).toContain( + 'bunx commitlint --from "$(git merge-base "$PUSH_SHA" origin/main)" --to "$PUSH_SHA" --verbose', + ); + expect(text).not.toContain('--last'); + }); + + test('says when the line it anchors on is gone, and only touches commitlint.yml', () => { + const gone = run( + SCRIPT.replace('--last', '--changed'), + [commitlintBatch], + 'commitlint.yml', + ); + expect(gone.report.warnings.map((warning) => warning.rule)).toEqual([ + 'anchor', + ]); + expect(run(SCRIPT, [commitlintBatch], 'other.yml').text).toContain( + '--last', + ); + }); +}); + +describe('lintLinksBase', () => { + const SOURCE = `name: Checks +on: + pull_request: +jobs: + format: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@${SHA} # v6 + with: + persist-credentials: false + # lint:links compares a change with HEAD^1 (a pull request's merge + # commit has the base branch as its first parent). + fetch-depth: 2 + - name: Refuse links that do not land + run: bun run lint:links +`; + + const roots: string[] = []; + afterEach(() => { + for (const root of roots.splice(0)) + rmSync(root, { recursive: true, force: true }); + }); + + /** A repository with the commits a Forgejo run sees: main, and a branch of two commits off it. */ + function repository() { + const root = mkdtempSync(join(tmpdir(), 'forgejo-port-links-')); + roots.push(root); + const config = join(root, 'gitconfig'); + writeFileSync(config, ''); + const env = { + ...Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => !name.startsWith('GIT_'), + ), + ), + GIT_CONFIG_GLOBAL: config, + GIT_CONFIG_NOSYSTEM: '1', + }; + const work = join(root, 'work'); + const git = (...args: string[]): string => { + const result = spawnSync( + 'git', + [ + '-c', + 'user.name=Fixture', + '-c', + 'user.email=f@example.invalid', + ...args, + ], + { cwd: work, env, encoding: 'utf8' }, + ); + if (result.status !== 0) + throw new Error(`git ${args.join(' ')}: ${result.stderr}`); + return result.stdout.trim(); + }; + spawnSync('git', ['init', '--quiet', '--initial-branch', 'main', work], { + env, + }); + const commit = (name: string): string => { + writeFileSync(join(work, name), `${name}\n`); + git('add', '--all'); + git('commit', '--quiet', '-m', name); + return git('rev-parse', 'HEAD'); + }; + return { work, env, git, commit }; + } + + test('compares a change with the merge base with main, with the history to find it', () => { + const { text, report } = run(SOURCE, [lintLinksBase], 'checks.yml'); + expect(text).toContain('fetch-depth: 0'); + expect(text).not.toContain('fetch-depth: 2'); + expect(text).not.toContain('HEAD^1'); + expect(text).toContain('LINT_LINKS_BASE="$base" bun run lint:links'); + expect(report.changes.map((change) => change.rule)).toEqual([ + 'lint-links-base', + ]); + }); + + test('gives the commit a pull request of two commits, or a batch of two, branched from', () => { + const { text } = run(SOURCE, [lintLinksBase], 'checks.yml'); + const steps = ( + parse(text) as { jobs: { format: { steps: { run?: string }[] } } } + ).jobs.format.steps; + const script = steps[1]?.run ?? ''; + // What the step runs, with lint:links itself replaced by what it would be given. + const probe = script.replace( + 'bun run lint:links', + `sh -c 'printf %s "$LINT_LINKS_BASE"'`, + ); + expect(probe).not.toBe(script); + + const { work, env, git, commit } = repository(); + const main = commit('main.txt'); + git('update-ref', 'refs/remotes/origin/main', main); + git('checkout', '--quiet', '-b', 'change'); + const first = commit('first.txt'); + commit('second.txt'); + const result = spawnSync('bash', ['-e', '-c', probe], { + cwd: work, + env: { ...env, GITHUB_ACTIONS: 'true' }, + encoding: 'utf8', + }); + expect(result.status).toBe(0); + // `HEAD^1` is the first commit, which hides what that commit retired. + expect(git('rev-parse', 'HEAD^1')).toBe(first); + expect(result.stdout).toBe(main); + }); + + test('fails the step when there is no merge base to compare with', () => { + const { text } = run(SOURCE, [lintLinksBase], 'checks.yml'); + const script = + (parse(text) as { jobs: { format: { steps: { run?: string }[] } } }).jobs + .format.steps[1]?.run ?? ''; + const { work, env, commit } = repository(); + commit('main.txt'); + const result = spawnSync( + 'bash', + ['-e', '-c', script.replace('bun run lint:links', 'echo ran')], + { cwd: work, env, encoding: 'utf8' }, + ); + expect(result.status).not.toBe(0); + expect(result.stdout).not.toContain('ran'); + }); + + test('adds the history and the base where the checkout has no inputs, and says when the step is gone', () => { + const bare = run( + SOURCE.replace(/ {8}with:[\s\S]*?fetch-depth: 2\n/, ''), + [lintLinksBase], + 'checks.yml', + ); + expect(bare.text).toContain('fetch-depth: 0'); + const gone = run( + SOURCE.replace('bun run lint:links', 'bun run lint:conflicts'), + [lintLinksBase], + 'checks.yml', + ); + expect(gone.report.warnings.map((warning) => warning.rule)).toEqual([ + 'anchor', + ]); + expect(run(SOURCE, [lintLinksBase], 'other.yml').text).toContain( + 'fetch-depth: 2', + ); + }); +}); + +describe('publishRemote', () => { + test('pushes to the Forgejo repository and prints the GitHub spec', () => { + const { text } = run( + `name: Publish +on: + workflow_dispatch: +jobs: + publish: + runs-on: ubuntu-latest + steps: + - run: | + REMOTE="https://x-access-token:\${GITHUB_TOKEN}@github.com/\${GITHUB_REPOSITORY}.git" + echo "github:\${GITHUB_REPOSITORY}#dist/ui" +`, + [publishRemote], + 'publish-packages.yml', + ); + expect(text).toContain( + '@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git', + ); + expect(text).toContain('github:tale-project/tale#dist/ui'); + expect(text).not.toContain('github.com'); + }); + + test('warns twice when both anchors are gone', () => { + const { report } = run( + `name: P\non:\n push:\njobs:\n publish:\n runs-on: ubuntu-latest\n steps:\n - run: echo\n`, + [publishRemote], + 'publish-packages.yml', + ); + expect(report.warnings).toHaveLength(2); + }); +}); + +describe('publishOnTag', () => { + const PUBLISH = `name: Publish packages +on: + push: + branches: + - main + paths: + - 'packages/ui/**' + workflow_dispatch: + inputs: + release_tag: + required: false + type: string +jobs: + publish: + name: Publish + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@${SHA} + with: + persist-credentials: false + - name: Resolve snapshot tag + id: tag + env: + REF: \${{ github.ref }} + RELEASE_TAG: \${{ inputs.release_tag }} + SOURCE_SHA: \${{ inputs.source_sha }} + run: echo "$REF" +`; + + test("a release tag pins the snapshots from main's tooling and the tag's commit", () => { + const { text, report } = run( + PUBLISH, + [publishOnTag], + 'publish-packages.yml', + ); + // the branch and path filters still hold for main; a tag is matched on its own + expect(text).toContain("tags: ['v*.*.*']"); + expect(text).toContain( + '# A release tag pins the snapshot of its own commit.', + ); + expect(text).toContain( + "ref: ${{ startsWith(github.ref, 'refs/tags/') && 'main' || '' }}", + ); + expect(text).toContain( + "REF: ${{ startsWith(github.ref, 'refs/tags/') && 'refs/heads/main' || github.ref }}", + ); + expect(text).toContain( + "RELEASE_TAG: ${{ inputs.release_tag || startsWith(github.ref, 'refs/tags/') && github.ref_name || '' }}", + ); + expect(text).toContain( + "SOURCE_SHA: ${{ inputs.source_sha || startsWith(github.ref, 'refs/tags/') && github.sha || '' }}", + ); + expect(report.changes.map((change) => change.rule)).toEqual([ + 'publish-on-tag', + ]); + }); + + test('says when the publisher is not the one it knows, and leaves it alone', () => { + const odd = PUBLISH.replace( + 'REF: ${{ github.ref }}', + 'REF: refs/heads/main', + ); + const { text, report } = run(odd, [publishOnTag], 'publish-packages.yml'); + expect(text).not.toContain('tags:'); + expect(report.warnings.map((warning) => warning.rule)).toEqual(['anchor']); + expect(run(PUBLISH, [publishOnTag], 'other.yml').text).not.toContain( + 'tags:', + ); + }); +}); + +describe('small text rules', () => { + test('run URLs use the run number', () => { + const { text } = run( + `name: B\non:\n push:\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: echo \${{ github.server_url }}/\${{ github.repository }}/actions/runs/\${{ github.run_id }}\n`, + [runUrls], + ); + expect(text).toContain('/actions/runs/${{ github.run_number }}'); + }); + + test('the service matrix tells a batch by its push', () => { + const source = `name: Build +on: + pull_request: +jobs: + changes: + runs-on: ubuntu-latest + steps: + - run: | + if [ -n "$CANDIDATE_SHA" ] || [ "$EVENT_NAME" = merge_group ] || [ "$FULL_SCOPE" = true ]; then + echo all + fi +`; + const { text, report } = run(source, [batchEvent], 'build.yml'); + expect(text).toContain('[ "$EVENT_NAME" = push ]'); + expect(text).not.toContain('merge_group'); + expect(report.changes.map((change) => change.rule)).toEqual([ + 'batch-event', + ]); + // another workflow's script is not touched, and a moved anchor is said + expect(run(source, [batchEvent], 'e2e.yml').text).toContain('merge_group'); + expect( + run( + source.replace('= merge_group', '= merge'), + [batchEvent], + 'build.yml', + ).report.warnings.map((warning) => warning.rule), + ).toEqual(['anchor']); + }); + + test('a build that feeds the release feed takes a GitHub token, a publisher keeps the job token', () => { + const source = `name: B +on: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - run: bunx turbo run build + env: + GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }} + - run: bun publish.ts + env: + GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }} +`; + const { text } = run(source, [githubApiToken('CI_GITHUB_TOKEN')]); + expect(text).toContain('GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}'); + expect(text.match(/secrets\.GITHUB_TOKEN/g)).toHaveLength(1); + }); + + test('a workflow names its own copy, and moved paths are written once', () => { + const { text } = run( + `name: P\non:\n push:\n paths:\n - '.github/workflows/w.yml'\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: bash .github/scripts/x.sh\n`, + [ + ownPath, + movePaths([ + { from: '.github/scripts/x.sh', to: '.forgejo/scripts/x.sh' }, + ]), + ], + ); + expect(text).toContain("'.forgejo/workflows/w.yml'"); + expect(text).toContain('bash .forgejo/scripts/x.sh'); + }); +}); + +describe('buildCache', () => { + const BUILD = `name: Build +on: + merge_group: + pull_request: +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: docker/build-push-action@${SHA} + with: + cache-from: | + type=gha,scope=\${{ matrix.service }} + type=registry,ref=\${{ env.REGISTRY }}/\${{ github.repository }}/tale-\${{ matrix.service }}-buildcache:amd64 + cache-to: \${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && format('type=gha,scope={0},mode=max,ghtoken={1},repository={2}', matrix.service, secrets.GITHUB_TOKEN, github.repository) || '' }} + - uses: docker/bake-action@${SHA} + with: + set: | + *.cache-from=type=gha,scope=web + \${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && format('*.cache-to=type=gha,scope=web,mode=max,ghtoken={0},repository={1}', secrets.GITHUB_TOKEN, github.repository) || '' }} + provenance: false + - uses: docker/build-push-action@${SHA} + with: + cache-from: type=gha,scope=db +`; + + test('keeps the registry cache the build already reads and writes it for the merge train only', () => { + const { text } = run(BUILD, [buildCache]); + expect(text).not.toContain('type=gha'); + expect(text).toContain( + 'type=registry,ref=${{ env.REGISTRY }}/${{ github.repository }}/tale-${{ matrix.service }}-buildcache:amd64', + ); + expect(text).toContain( + "cache-to: ${{ github.event_name == 'push' && format('type=registry,ref={0}/{1}/tale-{2}-buildcache:amd64,mode=max,ignore-error=true,compression=zstd', env.REGISTRY, github.repository, matrix.service) || '' }}", + ); + }); + + test('builds the site images and the database image without a layer cache', () => { + const { text } = run(BUILD, [buildCache]); + expect(text).not.toContain('scope=web'); + expect(text).not.toContain('scope=db'); + expect(text).toContain('provenance: false'); + expect(text).not.toMatch(/set:\s*\n\s*\n/); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/workflow-rules.ts b/tools/cli/scripts/forgejo-port/workflow-rules.ts new file mode 100644 index 0000000000..d958703755 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/workflow-rules.ts @@ -0,0 +1,507 @@ +/** + * The rules that know a workflow or a job by name: the readiness job the merge + * train reads, jobs and matrix rows that cannot run on the node, and the few + * lines of a script that must say something else on Forgejo. + * + * Each is anchored on something Tale already holds still (a job id its readiness + * table lists, a label the pool serves) or on one exact line it says out loud, and + * says when that anchor is gone, so a workflow edited tomorrow is reported, not + * carried through wrong. + */ + +import { Pair, Scalar, YAMLMap, YAMLSeq, isMap, isScalar, isSeq } from 'yaml'; +import type { Document } from 'yaml'; + +import { replaceText } from './actions'; +import { + SKIPPED, + learnRemoval, + type EventResults, + type PortContext, + type Rule, + type Tier, +} from './context'; +import { flowSequence } from './triggers'; +import { + jobIds, + jobOf, + jobsOf, + removeJobs, + rootOf, + stepLists, + stepsOf, + stringOf, +} from './workflow'; + +function literal(text: string): Scalar { + const node = new Scalar(text); + node.type = Scalar.BLOCK_LITERAL; + return node; +} + +/** The pull request and the batch of the merge train are the two events a verdict is given for. */ +const READY_CONDITION = + "always() && (github.event_name == 'pull_request' || github.event_name == 'push')"; + +const READY_STEP = 'Evaluate native workflow'; + +/** + * `CI ready (X)`: the one check the merge train reads. It runs after every other job + * whatever their result and judges them with Tale's own policy (see ready.ts): a + * checkout of the policy and one command, where GitHub's version needs its API. + */ +export function readyJob(tier: Tier): Rule { + return (doc, context) => { + const job = jobOf(doc, 'ci-ready'); + const name = job && stringOf(job.get('name')); + if (!job || name === undefined || !name.startsWith('CI ready (')) return; + const checkout = stepsOf(job)?.items.find( + (step) => + isMap(step) && + stringOf(step.get('uses'))?.startsWith('actions/checkout@'), + ); + const pinned = isMap(checkout) ? checkout.get('uses', true) : undefined; + if (!(pinned instanceof Scalar)) { + context.report.warnings.push({ + file: context.file, + at: 'jobs.ci-ready', + rule: 'ready', + detail: 'has no pinned checkout to copy: left as it is', + }); + return; + } + const stem = context.file.replace(/\.ya?ml$/, ''); + const verdict = new YAMLMap(); + verdict.set('name', 'Checkout verdict policy'); + verdict.set('uses', pinned.clone()); + const withInputs = new YAMLMap(); + withInputs.set('persist-credentials', false); + withInputs.set( + 'sparse-checkout', + literal( + '/tools/cli/scripts/ci-ready.ts\n/tools/cli/scripts/forgejo-port/ready.ts\n', + ), + ); + withInputs.set('sparse-checkout-cone-mode', false); + verdict.set('with', withInputs); + + const evaluate = new YAMLMap(); + evaluate.set('name', READY_STEP); + const env = new YAMLMap(); + env.set('CI_WORKFLOW', stem); + env.set('CI_NEEDS', '${{ toJSON(needs) }}'); + env.set('CI_TIER', tier); + env.set('CI_PORT_REMOVED', ''); + evaluate.set('env', env); + evaluate.set('run', 'bun tools/cli/scripts/forgejo-port/ready.ts'); + + const others = jobIds(doc).filter((id) => id !== 'ci-ready'); + const ready = new YAMLMap(); + ready.set('name', name); + ready.set('needs', flowSequence(others)); + ready.set('if', READY_CONDITION); + ready.set('runs-on', job.get('runs-on') ?? 'ubuntu-latest'); + ready.set('timeout-minutes', job.get('timeout-minutes') ?? 3); + const steps = new YAMLSeq(); + steps.add(verdict); + steps.add(evaluate); + ready.set('steps', steps); + jobsOf(doc).set('ci-ready', ready); + context.report.changes.push({ + file: context.file, + at: 'jobs.ci-ready', + rule: 'ready', + detail: + "rewritten: one command judges the needs with Tale's readiness policy, for a pull request and for a batch alike", + }); + }; +} + +/** + * After folding: say which jobs of the GitHub workflow are gone and what each would have + * reported, so the policy, which judges the GitHub workflow's jobs, finds them where it + * expects them: skipped, or a scope job's success with its outputs. + */ +export const recordRemoved: Rule = (doc, context) => { + const job = jobOf(doc, 'ci-ready'); + const steps = job && stepsOf(job); + if (!steps) return; + const removed: Record = {}; + for (const id of [...context.removed.keys()].toSorted()) + removed[id] = context.results.get(id) ?? { + pull_request: SKIPPED, + push: SKIPPED, + }; + for (const step of steps.items) { + if (!isMap(step) || stringOf(step.get('name')) !== READY_STEP) continue; + const env = step.get('env'); + if (isMap(env)) + env.set( + 'CI_PORT_REMOVED', + literal(`${JSON.stringify(removed, null, 2)}\n`), + ); + } +}; + +/** A job the port leaves out for a reason it can name: the jobs that needed it see it skipped. */ +export function dropJobs(jobs: readonly { id: string; why: string }[]): Rule { + return (doc, context) => { + for (const { id, why } of jobs) { + if (!jobOf(doc, id)) continue; + removeJobs(doc, [id]); + context.removed.set(id, why); + learnRemoval(context.knowledge, id); + context.report.changes.push({ + file: context.file, + at: `jobs.${id}`, + rule: 'job-dropped', + detail: `removed: ${why}`, + }); + } + }; +} + +/** + * A job whose `runs-on` is a matrix key names its runner in every row. The pool serves + * the labels it is given, and a job that names any other does not wait for one: the + * runner falls back to a Docker image and runs it there. So a row whose runner the + * pool does not have is a row that must not exist. + */ +export function dropForeignRows(labels: readonly string[]): Rule { + return (doc, context) => { + for (const id of jobIds(doc)) { + const job = jobOf(doc, id); + const runsOn = job && stringOf(job.get('runs-on')); + const key = runsOn?.match( + /^\$\{\{\s*matrix\.([A-Za-z0-9_-]+)\s*\}\}$/, + )?.[1]; + const strategy = job?.get('strategy'); + const matrix = isMap(strategy) ? strategy.get('matrix') : undefined; + const include = isMap(matrix) ? matrix.get('include') : undefined; + if (key === undefined || !isSeq(include)) continue; + for (let index = include.items.length - 1; index >= 0; index -= 1) { + const row = include.items[index]; + const runner = isMap(row) ? stringOf(row.get(key)) : undefined; + if (runner === undefined || labels.includes(runner)) continue; + const named = isMap(row) + ? (stringOf(row.get('platform')) ?? + stringOf(row.get('name')) ?? + runner) + : runner; + include.items.splice(index, 1); + context.report.changes.push({ + file: context.file, + at: `jobs.${id}.strategy.matrix.include[${index}]`, + rule: 'matrix-row', + detail: `removed the \`${named}\` row: the pool has no \`${runner}\` runner`, + }); + } + } + }; +} + +/** + * A batch is a new branch, so the push has no "before" to lint from: the last commit + * only would be linted. The commits a batch adds are the ones since it left main. + */ +export const commitlintBatch: Rule = (doc, context) => { + if (context.file !== 'commitlint.yml') return; + const from = 'bunx commitlint --last --verbose'; + const to = + 'bunx commitlint --from "$(git merge-base "$PUSH_SHA" origin/main)" --to "$PUSH_SHA" --verbose'; + if (replaceText(doc, from, to) === 0) + context.report.warnings.push({ + file: context.file, + at: 'jobs.commitlint', + rule: 'anchor', + detail: `the line \`${from}\` is gone: a batch's commits are no longer all linted`, + }); + else + context.report.changes.push({ + file: context.file, + at: 'jobs.commitlint', + rule: 'commitlint-batch', + detail: + 'a push of a new branch lints every commit since main, not only the last', + }); +}; + +const LINT_LINKS = 'bun run lint:links'; + +/** + * `lint:links` holds a change to the pages it retires by comparing the tree with the commit + * the change branched from. Under GitHub Actions it takes `HEAD^1`, which is that commit only + * because GitHub checks a pull request out as a merge commit whose first parent is the base + * branch. Here a pull request is checked out as its own head and a batch is a branch of one + * squash commit per pull request, so `HEAD^1` is the previous commit of the pull request or + * of the batch: a page retired without a redirect in any earlier commit would never be seen. + * The base is the merge base with main, which needs the history down to it. + */ +export const lintLinksBase: Rule = (doc, context) => { + if (context.file !== 'checks.yml') return; + const { file, report } = context; + for (const { at, steps } of stepLists(doc)) { + const index = steps.items.findIndex( + (step) => isMap(step) && stringOf(step.get('run'))?.trim() === LINT_LINKS, + ); + const lint = steps.items[index]; + if (!isMap(lint)) continue; + const checkout = steps.items + .slice(0, index) + .findLast( + (step) => + isMap(step) && + stringOf(step.get('uses'))?.startsWith('actions/checkout@'), + ); + if (!isMap(checkout)) break; + + const comment = + ' lint:links compares a change with the commit it branched from, the merge base with main:\n' + + ' a pull request is checked out as its own head here, and a batch is one commit per pull request,\n' + + ' so a page retired without a redirect in an earlier commit is only seen from the whole history.'; + const existing = checkout.get('with'); + const inputs = isMap(existing) ? existing : new YAMLMap(); + if (!isMap(existing)) checkout.set('with', inputs); + const depth = inputs.items.find( + (pair) => stringOf(pair.key) === 'fetch-depth', + ); + const key = isScalar(depth?.key) ? depth.key : new Scalar('fetch-depth'); + key.commentBefore = comment; + if (depth) depth.value = new Scalar(0); + else inputs.items.push(new Pair(key, new Scalar(0))); + + lint.set( + 'run', + literal( + `base="$(git merge-base HEAD origin/main)"\nLINT_LINKS_BASE="$base" ${LINT_LINKS}\n`, + ), + ); + report.changes.push({ + file, + at: `${at}.steps[${index}]`, + rule: 'lint-links-base', + detail: + 'compares a change with the merge base with main: a pull request is checked out as its own head, not as a merge commit', + }); + return; + } + report.warnings.push({ + file, + at: 'jobs', + rule: 'anchor', + detail: `the step \`run: ${LINT_LINKS}\` after a checkout is gone: a retired page may no longer be caught`, + }); +}; + +/** + * Build's service matrix names a batch by its event, `merge_group`, to build everything for + * it. A batch is a push here, and the only pushes the workflow has are batches. + */ +export const batchEvent: Rule = (doc, context) => { + if (context.file !== 'build.yml') return; + const from = '[ "$EVENT_NAME" = merge_group ]'; + const to = '[ "$EVENT_NAME" = push ]'; + if (replaceText(doc, from, to) === 0) + context.report.warnings.push({ + file: context.file, + at: 'jobs.changes', + rule: 'anchor', + detail: `the line \`${from}\` is gone: a batch may no longer build every service`, + }); + else + context.report.changes.push({ + file: context.file, + at: 'jobs.changes', + rule: 'batch-event', + detail: 'the service matrix tells a batch by its push, not a merge group', + }); +}; + +/** Run URLs on Forgejo carry the run's number in the repository, not its database id. */ +export const runUrls: Rule = (doc, context) => { + const count = replaceText( + doc, + '/actions/runs/${{ github.run_id }}', + '/actions/runs/${{ github.run_number }}', + ); + if (count > 0) + context.report.changes.push({ + file: context.file, + at: '', + rule: 'run-url', + detail: `${count} run URL${count === 1 ? '' : 's'} use github.run_number: Forgejo's URLs count runs per repository`, + }); +}; + +/** Text a script or a workflow says about where it lives, in the places Forgejo keeps them. */ +export function movePaths( + moves: readonly { from: string; to: string }[], +): Rule { + return (doc: Document, context: PortContext) => { + for (const { from, to } of moves) { + const count = replaceText(doc, from, to); + if (count > 0) + context.report.changes.push({ + file: context.file, + at: '', + rule: 'path', + detail: `\`${from}\` is \`${to}\` in ${count} place${count === 1 ? '' : 's'}`, + }); + } + }; +} + +/** + * The package publisher pushes `dist/*` branches and package tags to the repository it + * runs in, with the job's token. It names GitHub as the host, and prints the spec a + * consumer installs from, which is GitHub's whatever the repository is called here. + */ +export const publishRemote: Rule = (doc, context) => { + if (context.file !== 'publish-packages.yml') return; + const edits = [ + { + from: 'https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git', + to: 'https://x-access-token:${GITHUB_TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git', + detail: 'pushes to the Forgejo repository it runs in', + }, + { + from: 'github:${GITHUB_REPOSITORY}#', + to: 'github:tale-project/tale#', + detail: 'prints the GitHub spec consumers install from: the mirror', + }, + ]; + for (const edit of edits) { + if (replaceText(doc, edit.from, edit.to) > 0) + context.report.changes.push({ + file: context.file, + at: 'jobs.publish', + rule: 'publish-remote', + detail: edit.detail, + }); + else + context.report.warnings.push({ + file: context.file, + at: 'jobs.publish', + rule: 'anchor', + detail: `the text \`${edit.from}\` is gone: the publisher would ${edit.detail.replace('pushes', 'push').replace('prints', 'print')} wrongly`, + }); + } +}; + +const ON_TAG = "startsWith(github.ref, 'refs/tags/')"; + +/** + * The release lane stays on GitHub, but the tags it releases are pushed to Forgejo, so the + * package snapshots pinned for a release are made where the tag is: Forgejo's refs are what + * the push mirror makes GitHub's, and it deletes any ref Forgejo does not hold. A tag run + * does what the dispatch of `release_tag` and `source_sha` does on GitHub: the tooling is + * main's, the source is the tag's commit. + */ +export const publishOnTag: Rule = (doc, context) => { + if (context.file !== 'publish-packages.yml') return; + const { file, report } = context; + const missing = (at: string, what: string): void => { + report.warnings.push({ + file, + at, + rule: 'anchor', + detail: `${what} is not as the port expects: a release tag does not pin the package snapshots`, + }); + }; + + const events = rootOf(doc).get('on'); + const push = isMap(events) ? events.get('push') : undefined; + const job = jobOf(doc, 'publish'); + const steps = job && stepsOf(job); + const checkout = steps?.items.find( + (step) => + isMap(step) && + stringOf(step.get('uses'))?.startsWith('actions/checkout@') && + stringOf(step.get('name')) === 'Checkout', + ); + const resolve = steps?.items.find( + (step) => isMap(step) && stringOf(step.get('id')) === 'tag', + ); + const env = isMap(resolve) ? resolve.get('env') : undefined; + if ( + !isMap(push) || + !isMap(checkout) || + !isMap(env) || + stringOf(env.get('REF')) !== '${{ github.ref }}' || + stringOf(env.get('RELEASE_TAG')) !== '${{ inputs.release_tag }}' || + stringOf(env.get('SOURCE_SHA')) !== '${{ inputs.source_sha }}' + ) { + missing('on.push', 'the publisher'); + return; + } + + const tagsKey = new Scalar('tags'); + tagsKey.commentBefore = ' A release tag pins the snapshot of its own commit.'; + push.items.push(new Pair(tagsKey, flowSequence(['v*.*.*']))); + const inputs = checkout.get('with'); + if (isMap(inputs)) inputs.set('ref', `\${{ ${ON_TAG} && 'main' || '' }}`); + else { + const added = new YAMLMap(); + added.set('ref', `\${{ ${ON_TAG} && 'main' || '' }}`); + checkout.set('with', added); + } + env.set('REF', `\${{ ${ON_TAG} && 'refs/heads/main' || github.ref }}`); + env.set( + 'RELEASE_TAG', + `\${{ inputs.release_tag || ${ON_TAG} && github.ref_name || '' }}`, + ); + env.set( + 'SOURCE_SHA', + `\${{ inputs.source_sha || ${ON_TAG} && github.sha || '' }}`, + ); + report.changes.push({ + file, + at: 'jobs.publish', + rule: 'publish-on-tag', + detail: + "a release tag pushed to Forgejo pins the package snapshots, from main's tooling and the tag's commit", + }); +}; + +/** + * A step that builds with turbo hands the job's token to the web site's release feed, + * which calls api.github.com with it. The job's token on Forgejo is Forgejo's own: sent + * to GitHub it is a bad credential, and GitHub answers a bad credential with a refusal + * where it answers no credential with a rate limit. The feed needs a GitHub token of its own. + */ +export function githubApiToken(secret: string): Rule { + return (doc, context) => { + for (const { at, steps } of stepLists(doc)) { + for (const [index, step] of steps.items.entries()) { + if (!isMap(step) || !stringOf(step.get('run'))?.includes('turbo run')) + continue; + const env = step.get('env'); + if ( + !isMap(env) || + stringOf(env.get('GITHUB_TOKEN')) !== '${{ secrets.GITHUB_TOKEN }}' + ) + continue; + env.set('GITHUB_TOKEN', `\${{ secrets.${secret} }}`); + context.report.changes.push({ + file: context.file, + at: `${at}.steps[${index}].env.GITHUB_TOKEN`, + rule: 'github-api-token', + detail: `a build's release feed calls api.github.com: it takes \`secrets.${secret}\`, not Forgejo's job token`, + }); + } + } + }; +} + +/** A workflow that names its own file in a trigger path names the Forgejo copy. */ +export const ownPath: Rule = (doc, context) => { + const from = `.github/workflows/${context.file}`; + const count = replaceText(doc, from, `.forgejo/workflows/${context.file}`); + if (count > 0) + context.report.changes.push({ + file: context.file, + at: 'on', + rule: 'own-path', + detail: `\`${from}\` is its Forgejo copy in ${count} place${count === 1 ? '' : 's'}`, + }); +}; diff --git a/tools/cli/scripts/forgejo-port/workflow.test.ts b/tools/cli/scripts/forgejo-port/workflow.test.ts new file mode 100644 index 0000000000..27a3c08119 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/workflow.test.ts @@ -0,0 +1,451 @@ +import { describe, expect, test } from 'bun:test'; + +import type { Facts } from './expression'; +import { + emptyReport, + foldCondition, + foldWorkflow, + jobIds, + jobOf, + needsOf, + readWorkflow, + removeJobs, + setNeeds, + stepsOf, + writeWorkflow, + WorkflowError, +} from './workflow'; + +/** Tale's commitlint.yml as it is today, trimmed to the shapes the port meets. */ +const COMMITLINT = `name: Commitlint + +run-name: \${{ github.event_name == 'repository_dispatch' && format('Release candidate {0}', github.event.client_payload.candidate_sha) || '' }} + +on: + merge_group: + types: [checks_requested] + repository_dispatch: + types: [release-candidate] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - main + +concurrency: + group: \${{ github.workflow }}-\${{ github.event_name == 'repository_dispatch' && format('candidate-{0}', github.event.client_payload.candidate_sha) || github.ref }} + cancel-in-progress: \${{ github.event_name != 'repository_dispatch' }} + +jobs: + # Only candidates need remote source validation; ordinary jobs keep their event SHA. + candidate-source: + if: >- + github.event_name == 'repository_dispatch' + name: Candidate source + uses: ./.github/workflows/release-candidate-source.yml + with: + candidate: \${{ github.event_name == 'repository_dispatch' }} + candidate_sha: \${{ github.event.client_payload.candidate_sha }} + + commitlint: + needs: candidate-source + name: Lint commits + if: >- + !cancelled() && + (((github.event_name == 'repository_dispatch') && + needs.candidate-source.result == 'success') || + ((github.event_name != 'repository_dispatch') && + needs.candidate-source.result == 'skipped')) && + (github.event.pull_request.draft != true) + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + ref: \${{ needs.candidate-source.outputs.candidate_sha }} + fetch-depth: \${{ github.event_name == 'repository_dispatch' && 1 || 0 }} + filter: blob:none + - name: Run commitlint + env: + EVENT_NAME: \${{ github.event_name }} + CANDIDATE_SHA: \${{ needs.candidate-source.outputs.candidate_sha }} + run: | + if [ "$EVENT_NAME" = "repository_dispatch" ]; then + echo candidate + fi +`; + +const facts: Facts = { + values: new Map([['needs.candidate-source.result', 'skipped']]), + absent: ['github.event.client_payload', 'needs.candidate-source.outputs'], + oneOf: new Map([['github.event_name', ['pull_request', 'push']]]), +}; + +function fold(source: string, folding: Facts = facts) { + const doc = readWorkflow(source, 'commitlint.yml'); + const report = emptyReport(); + const dead = foldWorkflow(doc, { + file: 'commitlint.yml', + facts: folding, + report, + }); + return { doc, report, dead }; +} + +describe('readWorkflow and writeWorkflow', () => { + test('refuse what is not a workflow', () => { + expect(() => readWorkflow('a: [', 'x.yml')).toThrow(WorkflowError); + expect(() => readWorkflow('- a\n- b\n', 'x.yml')).toThrow('not a mapping'); + expect(() => readWorkflow('name: x\n', 'x.yml').toString()).not.toThrow(); + }); + + test('expand an anchor that another job uses, so removing the first job is safe', () => { + const source = `jobs: + a: + runs-on: ubuntu-latest + steps: + - name: Reclaim + run: &reclaim | + df -h / + b: + runs-on: ubuntu-latest + steps: + - name: Reclaim + run: *reclaim +`; + const doc = readWorkflow(source, 'x.yml'); + removeJobs(doc, ['a']); + const written = writeWorkflow(doc); + expect(written).not.toContain('&reclaim'); + expect(written).not.toContain('*reclaim'); + expect(written).toContain('df -h /'); + expect(jobIds(doc)).toEqual(['b']); + }); + + test('drop the inputs of an action that came to nothing, and the `with` that held them', () => { + const { doc } = fold(`jobs: + a: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: \${{ needs.candidate-source.outputs.candidate_sha }} + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: \${{ needs.candidate-source.outputs.candidate_sha }} + fetch-depth: 0 +`); + expect(writeWorkflow(doc)).toBe(`jobs: + a: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + fetch-depth: 0 +`); + }); + + test('leave no blank line after `jobs:` when the first job is removed', () => { + const doc = readWorkflow( + `jobs: + a: + runs-on: ubuntu-latest + + # about b + b: + runs-on: ubuntu-latest +`, + 'x.yml', + ); + removeJobs(doc, ['a']); + expect(writeWorkflow(doc)).toBe( + `jobs: + # about b + b: + runs-on: ubuntu-latest +`, + ); + }); + + test('hand the comment above a removed run-name to the key that follows', () => { + const { doc } = fold(`name: X + +# What this workflow is for. +run-name: \${{ github.event_name == 'repository_dispatch' && 'candidate' || '' }} + +on: + push: +jobs: + a: + runs-on: ubuntu-latest + steps: + - run: echo +`); + expect(writeWorkflow(doc)).toBe(`name: X + +# What this workflow is for. +on: + push: +jobs: + a: + runs-on: ubuntu-latest + steps: + - run: echo +`); + }); + + test('keep comments and the style of text it does not change', () => { + const { doc } = fold(COMMITLINT); + const written = writeWorkflow(doc); + expect(written).toContain('# v6'); + expect(written).toContain( + 'if [ "$EVENT_NAME" = "repository_dispatch" ]; then', + ); + expect(written).toContain('run: |'); + }); +}); + +describe('needs', () => { + test('read one name or a list, and write a list back', () => { + const doc = readWorkflow( + `jobs: + a: { runs-on: x } + b: { needs: a, runs-on: x } + c: { needs: [a, b], runs-on: x } +`, + 'x.yml', + ); + const [b, c] = [jobOf(doc, 'b'), jobOf(doc, 'c')]; + expect(b && needsOf(b)).toEqual(['a']); + expect(c && needsOf(c)).toEqual(['a', 'b']); + if (c) setNeeds(c, ['b']); + removeJobs(doc, ['a']); + expect(writeWorkflow(doc)).not.toContain('needs: a'); + expect(b && needsOf(b)).toEqual([]); + expect(c && needsOf(c)).toEqual(['b']); + }); +}); + +describe('foldCondition', () => { + test('decides, simplifies, or leaves a condition alone', () => { + expect(foldCondition("github.event_name == 'merge_group'", facts)).toEqual({ + kind: 'never', + }); + expect(foldCondition("github.event_name != 'merge_group'", facts)).toEqual({ + kind: 'always', + }); + expect( + foldCondition("always() && github.event_name == 'pull_request'", facts), + ).toEqual({ + kind: 'unchanged', + }); + expect( + foldCondition( + "${{ !cancelled() && github.event_name != 'merge_group' }}", + facts, + ), + ).toEqual({ + kind: 'text', + text: '${{ !cancelled() }}', + }); + }); + + test('decides a condition that is the same for every event the workflow has', () => { + // facts: a workflow with pull requests and pushes only + expect( + foldCondition( + "github.event_name != 'pull_request' && github.event_name != 'push' && needs.x.result == 'success'", + facts, + ), + ).toEqual({ kind: 'never' }); + expect( + foldCondition( + "github.event_name == 'pull_request' || github.event_name == 'push'", + facts, + ), + ).toEqual({ kind: 'always' }); + // one that depends on the event stays + expect( + foldCondition( + "github.event_name != 'pull_request' && needs.x.result == 'success'", + facts, + ), + ).toEqual({ kind: 'unchanged' }); + }); + + test('keeps the status function a fold would drop, as an `if:` without one waits for success', () => { + const always = { kind: 'text', text: 'always()' } as const; + for (const source of [ + "always() || github.event_name != 'merge_group'", + "!cancelled() || github.event_name != 'merge_group'", + "failure() || github.event_name != 'merge_group'", + "github.event_name != 'merge_group' || always()", + "!(always() && github.event_name == 'merge_group')", + ]) + expect(foldCondition(source, facts), source).toEqual(always); + expect( + foldCondition( + "${{ always() || github.event_name != 'merge_group' }}", + facts, + ), + ).toEqual({ kind: 'text', text: '${{ always() }}' }); + expect( + foldCondition( + "(always() || github.event_name != 'merge_group') && github.event.pull_request.draft != true", + facts, + ), + ).toEqual({ + kind: 'text', + text: 'always() && github.event.pull_request.draft != true', + }); + // a condition that holds for each of the workflow's events, not for one comparison alone, keeps it too + for (const source of [ + "always() || github.event_name == 'push' || github.event_name == 'pull_request'", + "failure() || (github.event_name == 'push' || github.event_name == 'pull_request')", + ]) + expect(foldCondition(source, facts), source).toEqual(always); + expect( + foldCondition( + "${{ always() || github.event_name == 'push' || github.event_name == 'pull_request' }}", + facts, + ), + ).toEqual({ kind: 'text', text: '${{ always() }}' }); + // a condition that is false is false whatever the status, and one with no status function has none to keep + expect( + foldCondition("always() && github.event_name == 'merge_group'", facts), + ).toEqual({ kind: 'never' }); + expect( + foldCondition("github.event_name != 'merge_group' || x.y", facts), + ).toEqual({ kind: 'always' }); + expect( + foldCondition( + "github.event_name == 'push' || github.event_name == 'pull_request'", + facts, + ), + ).toEqual({ kind: 'always' }); + }); + + test('refuse a wrapped condition with text around it', () => { + expect(() => foldCondition('${{ a }} and ${{ b }}', facts)).toThrow( + 'one expression', + ); + }); +}); + +describe('foldWorkflow', () => { + test('reports the jobs that can never run on Forgejo', () => { + const { dead, report } = fold(COMMITLINT); + expect(dead).toEqual(['candidate-source']); + expect(report.changes.map((change) => change.rule)).toContain( + 'condition-never', + ); + }); + + test('decides the long candidate condition once the candidate job is a known skip', () => { + const { doc } = fold(COMMITLINT); + const job = jobOf(doc, 'commitlint'); + expect(job?.get('if')).toBe( + '!cancelled() && github.event.pull_request.draft != true', + ); + }); + + test('keeps the status function of a job condition that folds to true', () => { + const { doc } = fold(`name: x +on: + push: +jobs: + a: + runs-on: ubuntu-latest + steps: + - run: echo a + b: + needs: a + if: always() || github.event_name != 'merge_group' + runs-on: ubuntu-latest + steps: + - run: echo b +`); + expect(jobOf(doc, 'b')?.get('if')).toBe('always()'); + }); + + test('drops an action input that comes to nothing, and types a constant', () => { + const { doc } = fold(COMMITLINT); + const checkout = stepsOf(jobOf(doc, 'commitlint') ?? ({} as never)) + ?.items[0]; + const written = writeWorkflow(doc); + expect(checkout).toBeDefined(); + expect(written).not.toContain('ref:'); + expect(written).toContain('fetch-depth: 0'); + expect(written).toContain('filter: blob:none'); + }); + + test('writes an env value that folds to nothing as an empty string, not as a missing key', () => { + const { doc } = fold(COMMITLINT); + expect(writeWorkflow(doc)).toMatch(/CANDIDATE_SHA: ''/); + }); + + test('drops run-name when it comes to nothing and settles the concurrency group', () => { + const { doc } = fold(COMMITLINT); + const written = writeWorkflow(doc); + expect(written).not.toContain('run-name'); + expect(written).toContain( + 'group: ${{ github.workflow }}-${{ github.ref }}', + ); + expect(written).toContain('cancel-in-progress: true'); + }); + + test('removes a step that can never run and keeps the others in order', () => { + const source = `jobs: + a: + runs-on: ubuntu-latest + steps: + - run: one + - if: github.event_name == 'merge_group' + run: two + - run: three + - if: github.event_name != 'merge_group' + run: four +`; + const { doc, report } = fold(source); + const written = writeWorkflow(doc); + expect(written).toContain('run: one'); + expect(written).not.toContain('run: two'); + expect(written).toContain('run: three'); + expect(written).toContain('run: four'); + expect(written).not.toContain('if:'); + expect( + report.changes.some((change) => change.at === 'jobs.a.steps[1]'), + ).toBe(true); + }); + + test('warns, and keeps the text, when an expression does not parse', () => { + const { doc, report } = fold(`jobs: + a: + runs-on: ubuntu-latest + steps: + - run: echo \${{ a @ b }} +`); + expect(report.warnings).toHaveLength(1); + expect(writeWorkflow(doc)).toContain('echo ${{ a @ b }}'); + }); + + test('changes nothing in a workflow that has nothing to decide', () => { + const source = `name: Plain + +on: + push: + branches: [main] + +jobs: + build: + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + steps: + - run: echo \${{ github.sha }} +`; + const { doc, report, dead } = fold(source); + expect(dead).toEqual([]); + expect(report.changes).toEqual([]); + expect(writeWorkflow(doc)).toBe(source); + }); +}); diff --git a/tools/cli/scripts/forgejo-port/workflow.ts b/tools/cli/scripts/forgejo-port/workflow.ts new file mode 100644 index 0000000000..517ff86e37 --- /dev/null +++ b/tools/cli/scripts/forgejo-port/workflow.ts @@ -0,0 +1,638 @@ +/** + * Reading, folding and writing one workflow document. + * + * Everything works on `yaml`'s Document, which keeps comments, so a ported + * workflow still explains itself. The port never re-implements what a workflow + * means: it removes what cannot run on Forgejo, decides what the generated file's + * own triggers decide, and leaves the rest as it was. + */ + +import { + Document, + Scalar, + YAMLMap, + YAMLSeq, + isMap, + isNode, + isScalar, + isSeq, + parseDocument, + visit, + type Pair, +} from 'yaml'; + +import { + ExpressionError, + type Expr, + foldTemplate, + hasExpression, + hasStatusFunction, + keepStatusFunction, + parseExpression, + parseTemplate, + printExpression, + simplify, + truthy, + type Facts, +} from './expression'; + +export type Workflow = Document.Parsed; + +export class WorkflowError extends Error { + constructor( + message: string, + readonly file: string, + ) { + super(`${file}: ${message}`); + this.name = 'WorkflowError'; + } +} + +/** One thing the port did, said once so a reviewer can read the whole rewrite. */ +export interface Change { + readonly file: string; + /** Where in the workflow: `jobs.build.steps[2]`. */ + readonly at: string; + readonly rule: string; + readonly detail: string; +} + +/** What a run of the port did, and what it could not make sense of. */ +export interface Report { + readonly changes: Change[]; + readonly warnings: Change[]; +} + +export function emptyReport(): Report { + return { changes: [], warnings: [] }; +} + +// --- reading and writing ------------------------------------------------------ + +/** Parse a workflow, refuse a broken one, and expand its anchors and aliases. */ +export function readWorkflow(source: string, file: string): Workflow { + const doc = parseDocument(source); + const [first] = doc.errors; + if (first) throw new WorkflowError(first.message, file); + if (!isMap(doc.contents)) throw new WorkflowError('not a mapping', file); + expandAliases(doc, file); + return doc; +} + +/** + * Replace every alias with a copy of what it points at and drop the anchors. The + * port removes and rewrites jobs, so an anchor defined in one job and used in + * another must not decide what survives. + */ +function expandAliases(doc: Document, file: string): void { + visit(doc, { + Alias(_key, alias) { + const target = alias.resolve(doc); + if (!target) + throw new WorkflowError(`unknown anchor ${alias.source}`, file); + return copyOf(target); + }, + }); + visit(doc, { + Node(_key, node) { + if (isNode(node) && 'anchor' in node && node.anchor) + node.anchor = undefined; + }, + }); +} + +/** `clone()` keeps the node's class, which yaml's declarations only say is "a node". */ +function copyOf(target: T): T { + return target.clone() as T; +} + +export function writeWorkflow(doc: Document): string { + return doc.toString({ + lineWidth: 0, + indent: 2, + flowCollectionPadding: false, + }); +} + +// --- reading the tree --------------------------------------------------------- + +export function rootOf(doc: Document): YAMLMap { + if (!isMap(doc.contents)) + throw new WorkflowError('not a mapping', 'document'); + return doc.contents; +} + +function mapAt(map: YAMLMap, key: string): YAMLMap | undefined { + const node = map.get(key); + return isMap(node) ? node : undefined; +} + +export function jobsOf(doc: Document): YAMLMap { + const jobs = mapAt(rootOf(doc), 'jobs'); + if (!jobs) throw new WorkflowError('has no jobs', 'document'); + return jobs; +} + +export function stringOf(node: unknown): string | undefined { + if (typeof node === 'string') return node; + return isScalar(node) && typeof node.value === 'string' + ? node.value + : undefined; +} + +export function jobIds(doc: Document): string[] { + return jobsOf(doc).items.flatMap((pair) => { + const id = stringOf(pair.key); + return id === undefined ? [] : [id]; + }); +} + +export function jobOf(doc: Document, id: string): YAMLMap | undefined { + return mapAt(jobsOf(doc), id); +} + +export function stepsOf(job: YAMLMap): YAMLSeq | undefined { + const steps = job.get('steps'); + return isSeq(steps) ? steps : undefined; +} + +/** The ids a job needs, whether `needs:` is one name or a list. */ +export function needsOf(job: YAMLMap): string[] { + const node = job.get('needs'); + const single = stringOf(node); + if (single !== undefined) return [single]; + if (!isSeq(node)) return []; + return node.items.flatMap((item) => { + const name = stringOf(item); + return name === undefined ? [] : [name]; + }); +} + +/** Write `needs:` back as a list, or take it away when nothing is left. */ +export function setNeeds(job: YAMLMap, ids: readonly string[]): void { + if (ids.length === 0) { + job.delete('needs'); + return; + } + const seq = new YAMLSeq(); + seq.flow = true; + for (const id of ids) seq.add(new Scalar(id)); + job.set('needs', seq); +} + +/** Remove jobs, and the names of those jobs from every other job's `needs:`. */ +export function removeJobs(doc: Document, ids: readonly string[]): void { + const gone = new Set(ids); + const jobs = jobsOf(doc); + for (const id of gone) jobs.delete(id); + // The blank line that separated the first job from its neighbour would now open the map. + const [first] = jobs.items; + if (isScalar(first?.key)) first.key.spaceBefore = false; + for (const pair of jobs.items) { + const job = isMap(pair.value) ? pair.value : undefined; + if (!job) continue; + const needs = needsOf(job); + const kept = needs.filter((id) => !gone.has(id)); + if (kept.length !== needs.length) setNeeds(job, kept); + } +} + +// --- folding ------------------------------------------------------------------ + +/** What a condition came to once the facts were applied. */ +type Condition = + | { readonly kind: 'unchanged' } + | { readonly kind: 'always' } + | { readonly kind: 'never' } + | { readonly kind: 'text'; readonly text: string }; + +/** Fold one `if:` value: a bare expression, or one wrapped in `${{ }}`. */ +export function foldCondition(source: string, facts: Facts): Condition { + let wrapped = false; + const expression = ((): ReturnType => { + if (!hasExpression(source)) return parseExpression(source); + wrapped = true; + const parts = parseTemplate(source); + const only = parts.length === 1 ? parts[0] : undefined; + if (only?.kind !== 'expr') + throw new ExpressionError( + 'A condition must be one expression', + source, + 0, + ); + return only.expr; + })(); + const folded = keepStatusFunction( + expression, + simplify(expression, facts, 'condition'), + ); + const after = printExpression(folded); + if (folded.kind === 'literal' && after !== printExpression(expression)) + return { kind: truthy(folded.value) ? 'always' : 'never' }; + const everywhere = holdsForEveryEvent(folded, facts); + if (everywhere !== undefined) { + // A condition that holds for every event still waits for success once its status function is gone. + if (everywhere && hasStatusFunction(expression)) + return { kind: 'text', text: wrapped ? '${{ always() }}' : 'always()' }; + return { kind: everywhere ? 'always' : 'never' }; + } + if (after === printExpression(expression)) return { kind: 'unchanged' }; + return { kind: 'text', text: wrapped ? `\${{ ${after} }}` : after }; +} + +/** + * Whether a condition comes to the same answer for each event the workflow has. A + * condition like `event != 'pull_request' && event != 'push'` mentions no event twice + * in the same way, so folding one comparison at a time cannot see that a workflow with + * only those two events never meets it. + */ +function holdsForEveryEvent( + condition: ReturnType, + facts: Facts, +): boolean | undefined { + const events = facts.oneOf?.get('github.event_name'); + if (!events || events.length < 2) return undefined; + const answers = events.map((event) => { + const here = simplify( + condition, + { + ...facts, + values: new Map([ + ...(facts.values ?? []), + ['github.event_name', event], + ]), + }, + 'condition', + ); + return here.kind === 'literal' ? truthy(here.value) : undefined; + }); + if (answers.every((answer) => answer === true)) return true; + if (answers.every((answer) => answer === false)) return false; + return undefined; +} + +export interface FoldContext { + readonly file: string; + readonly facts: Facts; + readonly report: Report; + /** Facts that hold inside one job only, such as the size of its own matrix. */ + readonly jobFacts?: ReadonlyMap; +} + +/** The facts of a context with another set added on top. */ +function withFacts( + context: FoldContext, + extra: Facts | undefined, +): FoldContext { + if (!extra) return context; + const values = new Map([ + ...(context.facts.values ?? []), + ...(extra.values ?? []), + ]); + const oneOf = new Map([ + ...(context.facts.oneOf ?? []), + ...(extra.oneOf ?? []), + ]); + return { + ...context, + facts: { + values, + oneOf, + absent: [...(context.facts.absent ?? []), ...(extra.absent ?? [])], + conditional: new Map([ + ...(context.facts.conditional ?? []), + ...(extra.conditional ?? []), + ]), + aliases: context.facts.aliases, + }, + }; +} + +/** + * Fold what a workflow says by what the port knows. Returns the jobs that can + * never run (their own condition is decided false); the caller removes them and + * folds again, because a removed job is itself a fact for the jobs that needed it. + * A step that can never run is removed here. + */ +export function foldWorkflow(doc: Document, context: FoldContext): string[] { + const dead: string[] = []; + for (const pair of jobsOf(doc).items) { + const id = stringOf(pair.key); + const job = isMap(pair.value) ? pair.value : undefined; + if (id === undefined || !job) continue; + const at = `jobs.${id}`; + const here = withFacts(context, context.jobFacts?.get(id)); + if (foldIf(job, at, here) === 'dead') { + dead.push(id); + continue; + } + const steps = stepsOf(job); + if (steps) foldSteps(steps, at, here); + foldMapValues(job, at, here, new Set(['if', 'steps'])); + } + foldMapValues(rootOf(doc), '', context, new Set(['jobs'])); + return dead; +} + +/** Fold a composite action the way a workflow is: its steps, and the strings around them. */ +export function foldAction(doc: Document, context: FoldContext): void { + const root = rootOf(doc); + const runs = root.get('runs'); + if (isMap(runs)) { + const steps = runs.get('steps'); + if (isSeq(steps)) foldSteps(steps, 'runs', context); + foldMapValues(runs, 'runs', context, new Set(['steps'])); + } + foldMapValues(root, '', context, new Set(['runs'])); +} + +function foldSteps(steps: YAMLSeq, jobAt: string, context: FoldContext): void { + for (let index = steps.items.length - 1; index >= 0; index -= 1) { + const step = steps.items[index]; + if (!isMap(step)) continue; + const at = `${jobAt}.steps[${index}]`; + if (foldIf(step, at, context) === 'dead') { + steps.items.splice(index, 1); + continue; + } + foldMapValues(step, at, context, new Set(['if'])); + } +} + +function foldIf( + owner: YAMLMap, + at: string, + context: FoldContext, +): 'alive' | 'dead' { + const source = stringOf(owner.get('if')); + if (source === undefined) return 'alive'; + let outcome: Condition; + try { + outcome = foldCondition(source, context.facts); + } catch (error) { + if (!(error instanceof ExpressionError)) throw error; + context.report.warnings.push({ + file: context.file, + at, + rule: 'fold-condition', + detail: error.message, + }); + return 'alive'; + } + const written = oneLine(source); + switch (outcome.kind) { + case 'unchanged': + return 'alive'; + case 'always': + owner.delete('if'); + context.report.changes.push({ + file: context.file, + at, + rule: 'condition-always', + detail: `dropped \`if: ${written}\`, which always holds here`, + }); + return 'alive'; + case 'never': + context.report.changes.push({ + file: context.file, + at, + rule: 'condition-never', + detail: `removed: \`if: ${written}\` can never hold here`, + }); + return 'dead'; + case 'text': { + owner.set('if', new Scalar(outcome.text)); + context.report.changes.push({ + file: context.file, + at, + rule: 'condition-folded', + detail: `\`if: ${written}\` is now \`${oneLine(outcome.text)}\``, + }); + return 'alive'; + } + } +} + +/** Fold every string below a mapping except the keys named in `skip`. */ +function foldMapValues( + map: YAMLMap, + at: string, + context: FoldContext, + skip: ReadonlySet, +): void { + // Backwards: folding may delete the pair it is looking at. + for (let index = map.items.length - 1; index >= 0; index -= 1) { + const pair = map.items[index]; + const key = pair && stringOf(pair.key); + if (!pair || key === undefined || skip.has(key)) continue; + foldValue( + map, + pair, + at === '' ? key : `${at}.${key}`, + key === 'with' || key === 'run-name', + context, + ); + } +} + +function foldValue( + parent: YAMLMap, + pair: Pair, + at: string, + dropWhenEmpty: boolean, + context: FoldContext, +): void { + const value = pair.value; + if (isScalar(value)) { + const outcome = foldScalar(value, at, context); + // What stood above `run-name` is the file's own description: the next key keeps it. + if (outcome === 'empty' && dropWhenEmpty) + deletePair(parent, pair, at === 'run-name'); + return; + } + if (isMap(value)) { + // The inputs of an action: an input that comes to nothing is an input not given. + for (let index = value.items.length - 1; index >= 0; index -= 1) { + const inner = value.items[index]; + const key = inner && stringOf(inner.key); + if (!inner || key === undefined) continue; + const here = `${at}.${key}`; + const innerValue = inner.value; + if (isScalar(innerValue)) { + if (foldScalar(innerValue, here, context) === 'empty' && dropWhenEmpty) + value.delete(inner.key); + } else foldValue(value, inner, here, false, context); + } + // An action given nothing is given no inputs: `with: {}` says nothing. + if (value.items.length === 0 && dropWhenEmpty) + deletePair(parent, pair, false); + return; + } + if (isSeq(value)) { + for (const [index, item] of value.items.entries()) { + const here = `${at}[${index}]`; + if (isScalar(item)) foldScalar(item, here, context); + else if (isMap(item)) foldMapValues(item, here, context, new Set()); + } + } +} + +/** Delete a pair; with `carry`, the comment that stood above it moves to the pair that follows. */ +function deletePair(parent: YAMLMap, pair: Pair, carry: boolean): void { + const index = parent.items.indexOf(pair); + if (index < 0) return; + const comment = isNode(pair.key) ? pair.key.commentBefore : undefined; + parent.items.splice(index, 1); + const next = parent.items[index]; + if (carry && comment && next && isNode(next.key)) + next.key.commentBefore = next.key.commentBefore + ? `${comment}\n${next.key.commentBefore}` + : comment; +} + +/** `empty` when a whole value came to nothing (null or the empty string). */ +function foldScalar( + node: Scalar, + at: string, + context: FoldContext, +): 'kept' | 'changed' | 'empty' { + if (typeof node.value !== 'string' || !hasExpression(node.value)) + return 'kept'; + const source = node.value; + let folded: ReturnType; + try { + folded = foldTemplate(source, context.facts, 'value'); + } catch (error) { + if (!(error instanceof ExpressionError)) throw error; + context.report.warnings.push({ + file: context.file, + at, + rule: 'fold-value', + detail: error.message, + }); + return 'kept'; + } + if (folded.kind === 'text') { + if (sameTemplate(source, folded.text)) return 'kept'; + node.value = folded.text; + context.report.changes.push({ + file: context.file, + at, + rule: 'value-folded', + detail: `\`${oneLine(source)}\` is now \`${oneLine(folded.text)}\``, + }); + return 'changed'; + } + context.report.changes.push({ + file: context.file, + at, + rule: 'value-constant', + detail: `\`${oneLine(source)}\` is always ${JSON.stringify(folded.value)}`, + }); + if (folded.value === null || folded.value === '') { + node.value = ''; + node.type = Scalar.QUOTE_SINGLE; + return 'empty'; + } + node.value = folded.value; + node.type = Scalar.PLAIN; + return 'changed'; +} + +/** Whether two strings hold the same text and the same expressions, spacing aside. */ +function sameTemplate(a: string, b: string): boolean { + const left = parseTemplate(a); + const right = parseTemplate(b); + return ( + left.length === right.length && + left.every((part, index) => { + const other = right[index]; + if (!other || part.kind !== other.kind) return false; + if (part.kind === 'text' && other.kind === 'text') + return part.text === other.text; + if (part.kind === 'expr' && other.kind === 'expr') + return printExpression(part.expr) === printExpression(other.expr); + return false; + }) + ); +} + +function oneLine(text: string): string { + return text.replace(/\s+/g, ' ').trim(); +} + +/** + * Change one `if:` with a function of its expression. The function returns the new + * expression, or `undefined` when nothing is left of the condition (it always holds). + * Returns whether the condition changed. + */ +export function editCondition( + owner: YAMLMap, + edit: (expression: Expr) => Expr | undefined, +): boolean { + const source = stringOf(owner.get('if')); + if (source === undefined) return false; + const wrapped = hasExpression(source); + let expression: Expr; + if (wrapped) { + const parts = parseTemplate(source); + const only = parts.length === 1 ? parts[0] : undefined; + if (only?.kind !== 'expr') + throw new ExpressionError( + 'A condition must be one expression', + source, + 0, + ); + expression = only.expr; + } else expression = parseExpression(source); + const edited = edit(expression); + if (edited === undefined) { + owner.delete('if'); + return true; + } + if (printExpression(edited) === printExpression(expression)) return false; + const text = printExpression(edited); + owner.set('if', new Scalar(wrapped ? `\${{ ${text} }}` : text)); + return true; +} + +/** The text of a step's or job's `if:`, as written. */ +export function conditionOf(owner: YAMLMap): string | undefined { + return stringOf(owner.get('if')); +} + +/** Every list of steps a document has: one per job of a workflow, or the steps of a composite action. */ +export function stepLists(doc: Document): { at: string; steps: YAMLSeq }[] { + const root = rootOf(doc); + const lists: { at: string; steps: YAMLSeq }[] = []; + const runs = root.get('runs'); + if (isMap(runs)) { + const steps = runs.get('steps'); + if (isSeq(steps)) lists.push({ at: 'runs', steps }); + } + const jobs = root.get('jobs'); + if (isMap(jobs)) { + for (const pair of jobs.items) { + const id = stringOf(pair.key); + const job = isMap(pair.value) ? pair.value : undefined; + const steps = job && stepsOf(job); + if (id !== undefined && steps) lists.push({ at: `jobs.${id}`, steps }); + } + } + return lists; +} + +/** A step's `uses:`, split into what it names and the ref after the `@`. */ +export function parseUses( + uses: string, +): + | { kind: 'remote'; name: string; ref: string } + | { kind: 'local'; path: string } + | { kind: 'docker' } { + if (uses.startsWith('./')) return { kind: 'local', path: uses }; + if (uses.startsWith('docker://')) return { kind: 'docker' }; + const at = uses.lastIndexOf('@'); + return at === -1 + ? { kind: 'remote', name: uses, ref: '' } + : { kind: 'remote', name: uses.slice(0, at), ref: uses.slice(at + 1) }; +} diff --git a/tools/lint-links/README.md b/tools/lint-links/README.md index 7f3b744ad6..4d7c9abeb8 100644 --- a/tools/lint-links/README.md +++ b/tools/lint-links/README.md @@ -53,7 +53,9 @@ The base commit is chosen in this order: `LINT_LINKS_BASE`, if set. In GitHub Ac `HEAD^1`: a pull request is checked out as GitHub's merge commit, whose first parent is the base branch, and a push or merge group as the commit on top of it. That is why CI's Format job checks out with `fetch-depth: 2`, and a missing parent there is an error, never a skip. Locally it is the -merge base with `origin/main`; without `origin/main` the rules are skipped with a warning. +merge base with `origin/main`; without `origin/main` the rules are skipped with a warning. The +Forgejo port (`tools/cli/scripts/forgejo-port`) sets `LINT_LINKS_BASE` to that merge base, because +a run there checks out a pull request's head, not a merge commit. ## Extending it