diff --git a/docs/design/affected-checks.md b/docs/design/affected-checks.md index 89ac46a7..1b1285ee 100644 --- a/docs/design/affected-checks.md +++ b/docs/design/affected-checks.md @@ -133,12 +133,31 @@ command when every selected name resolves and every command in its body is under its session runs on any change. Even isolated checks run on ignore-file changes and when Git cannot rule out symlinked inputs. -An `actions/checkout` step with a major tag or full commit SHA and no inputs, or another supported -session, may precede the command. Setup actions and install steps can change the runner environment -or generate a different configuration. Even checkout with `fetch-depth` or a tag such as `v4.2.2` -currently leaves the session to CI. - -The synthetic fixtures model the named invocations in two public workflows. Both real jobs stay in CI. +A job on a literal GitHub-hosted Ubuntu, macOS or Windows runner can check out the current revision, +set up Python tools and then run a supported session. DiffCI reads the steps in order. It runs only +the named session, using tools already installed locally. Hosted CI still performs its own setup +and checks the versions it installed. + +| Preceding step | Supported forms | +| --- | --- | +| `actions/checkout` | No inputs, or literal `fetch-depth` and `persist-credentials`. An empty `ref` selects the default revision. A different ref, repository, path or sparse checkout leaves the session to CI. | +| `actions/setup-python` | A single string `python-version` such as `'3.12'` or `'3.12.1'`, optionally with `cache: pip`. Quote a two-part version so YAML preserves its digits. | +| `astral-sh/setup-uv` | An explicit three-part version such as `'0.12.22'`, optionally with a Boolean `enable-cache`. | +| Install tools | `pip install`, `python -m pip install` and `uv pip install --system` with bare names from `tox`, `tox-uv`, `nox`, `black`, `ruff`, `mypy`, `pyright`, `basedpyright` and `pyrefly`. `uv tool install` takes one name. Both pip forms also accept `--upgrade pip`. Every line in a multiline installer step must qualify or be a whole-line `#` comment. | + +Setup actions accept major or three-part release tags and the recorded commit pins for checkout v4.4.0, +setup-python v5.6.0 and setup-uv v5.4.2. The earlier checkout-only form still accepts an input-free +major tag or full SHA. An unknown step keeps subsequent sessions in that job with CI. + +Installers must run unconditionally at the repository root in the default shell. Requirements files, +extras, local packages or pip modules, custom actions, expressions and other options leave the +session to CI. For `uv pip`, DiffCI also needs to rule out project-specific uv settings: `uv.toml` +may contain only comments, and `pyproject.toml` may mention uv in values such as a description or +dependency but not as a key or table name. +An installer package name does not add a supported tool to a session body. + +With a static session body, the synthetic fixtures for both workflows now contribute their named check. +The two real projects still have configuration outside that subset. - mykrok's `misc` job sets up Python and installs `tox tox-uv` before `tox -e lint,type`. Its selected environments also install the project's `.[devel]` dependencies. diff --git a/packages/diffci-cli/src/client/gate-checks.ts b/packages/diffci-cli/src/client/gate-checks.ts index 046cb310..dc791b28 100644 --- a/packages/diffci-cli/src/client/gate-checks.ts +++ b/packages/diffci-cli/src/client/gate-checks.ts @@ -5,7 +5,7 @@ import { narrowGateChecks, type ChangedPath } from "@diffci.com/core/planner/che import { discoverGateChecks, workflowGateScripts, type GateCheckKind } from "@diffci.com/core/planner/pipeline-steps"; import { discoverPythonChecks, narrowPythonChecks, type WorkflowFile } from "@diffci.com/core/planner/python-checks"; import type { CheckBaseline } from "./failure-baseline.js"; -import { isPythonSession, readPythonSessionFile, withSessionEnvironment } from "./python-session-files.js"; +import { isPythonSession, pythonSetupInputReader, readPythonSessionFile, withSessionEnvironment } from "./python-session-files.js"; import { measureCommand } from "./verify-savings.js"; /** One leaf of the repository's gate (`npm run check`), as an agent or verify runs it. */ @@ -153,11 +153,12 @@ function packageChecks(repoPath: string, change: CheckChange | undefined, option */ function pythonChecks(repoPath: string, change: CheckChange | undefined): PlannedCheck[] { const read = (file: string) => readRepositoryFile(repoPath, file); - // The package's previous Core pin uses only the Makefile reader and discovers no sessions. - const discover: (files: WorkflowFile[], readFile: typeof read, readSession: typeof read) => ReturnType = discoverPythonChecks; + // The released Core pin ignores the extra setup reader and retains its own session rules. + const discover: (files: WorkflowFile[], readFile: typeof read, readSession: typeof read, + readSetup: (file: string) => string | null | undefined) => ReturnType = discoverPythonChecks; // Exclude linked session declarations before Core keeps the first occurrence of each command. const files = workflowFiles(repoPath).map((file) => ({ ...file, canDeclareSessions: regularWorkflow(repoPath, file.path) })); - let checks = discover(files, read, (file) => readPythonSessionFile(repoPath, file)); + let checks = discover(files, read, (file) => readPythonSessionFile(repoPath, file), pythonSetupInputReader(repoPath)); if (checks.length === 0) return []; if (change) { // Older Core releases accept only the first two arguments and discover no sessions. diff --git a/packages/diffci-cli/src/client/python-session-files.ts b/packages/diffci-cli/src/client/python-session-files.ts index c1190e98..b46fe8cc 100644 --- a/packages/diffci-cli/src/client/python-session-files.ts +++ b/packages/diffci-cli/src/client/python-session-files.ts @@ -25,6 +25,26 @@ function absent(path: string): boolean { try { return lstatSync(path, { throwIfNoEntry: false }) === undefined; } catch { return false; } } +/** Look up root entries without following installer targets. Git checkouts can run on + * case-insensitive hosts, so a differently cased name also makes the input ambiguous. */ +export function pythonSetupInputReader(repoPath: string): (name: string) => string | null | undefined { + let ambiguous: Set | undefined; + return (name) => { + if (!/^[a-z][a-z0-9.-]*$/.test(name)) return null; + if (!ambiguous) { + try { + const names = readdirSync(repoPath); + ambiguous = new Set(names.filter((entry) => entry !== entry.toLowerCase()).map((entry) => entry.toLowerCase())); + if (names.some((entry) => /^pip(?:\.[^/]+)?\.(?:so|pyd)$/i.test(entry))) ambiguous.add("pip"); + } catch { return null; } + } + if (ambiguous.has(name)) return null; + const path = join(repoPath, name); + if (name === "uv.toml" || name === "pyproject.toml") return readInput(path); + return absent(path) ? undefined : null; + }; +} + function pathIsUnambiguous(repoPath: string, env: NodeJS.ProcessEnv): boolean { if (process.platform !== "win32") return env.PATH !== undefined && env.PATH.split(":").every(isAbsolute); diff --git a/packages/diffci-cli/tests/client/python-session-files.test.ts b/packages/diffci-cli/tests/client/python-session-files.test.ts index 4dcf2047..74128b06 100644 --- a/packages/diffci-cli/tests/client/python-session-files.test.ts +++ b/packages/diffci-cli/tests/client/python-session-files.test.ts @@ -3,7 +3,38 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, sym import { tmpdir } from "node:os"; import { delimiter, join } from "node:path"; import { test } from "node:test"; -import { canHandOffNox, readPythonSessionFile, withSessionEnvironment } from "../../src/client/python-session-files.js"; +import { canHandOffNox, pythonSetupInputReader, readPythonSessionFile, withSessionEnvironment } from "../../src/client/python-session-files.js"; + +test("setup discovery reads only bounded uv configuration and treats local packages as opaque", (t) => { + const repo = mkdtempSync(join(tmpdir(), "diffci-setup-inputs-")); + t.after(() => rmSync(repo, { recursive: true, force: true })); + const read = pythonSetupInputReader(repo); + for (const name of ["pip", "pip.py", "ruff", "pyproject.toml", "uv.toml"]) { + assert.equal(read(name), undefined, name); + } + mkdirSync(join(repo, "ruff")); + writeFileSync(join(repo, "pip.py"), "# local module\n"); + assert.equal(read("ruff"), null); + assert.equal(read("pip.py"), null); + for (const name of ["../uv.toml", "/pyproject.toml", "pip/../../setup.py", "pip\\setup.py"]) assert.equal(read(name), null, name); + + const project = '[project]\nname = "sample"\n'; + writeFileSync(join(repo, "pyproject.toml"), project); + assert.equal(read("pyproject.toml"), project); + writeFileSync(join(repo, "uv.toml"), " ".repeat(64 * 1024 + 1)); + assert.equal(read("uv.toml"), null); + writeFileSync(join(repo, "MyPy"), ""); + assert.equal(pythonSetupInputReader(repo)("mypy"), null); + writeFileSync(join(repo, "pip.abi3.so"), ""); + assert.equal(pythonSetupInputReader(repo)("pip"), null); + if (process.platform !== "win32") { + rmSync(join(repo, "uv.toml")); + symlinkSync("pyproject.toml", join(repo, "uv.toml")); + symlinkSync("absent", join(repo, "nox")); + assert.equal(read("uv.toml"), null); + assert.equal(read("nox"), null); + } +}); test("session discovery reads bounded regular files and declines runner overrides", (t) => { const repo = mkdtempSync(join(tmpdir(), "diffci-session-inputs-")); diff --git a/release-files.json b/release-files.json index f52ae0dd..bfa0a5af 100644 --- a/release-files.json +++ b/release-files.json @@ -179,6 +179,7 @@ "src/planner/path-baseline.ts", "src/planner/pipeline-steps.ts", "src/planner/python-checks.ts", + "src/planner/python-session-setup.ts", "src/planner/planner.ts", "src/planner/rust-command.ts", "src/planner/script-reads.ts", diff --git a/src/planner/python-checks.ts b/src/planner/python-checks.ts index d84c2093..d0adf1a3 100644 --- a/src/planner/python-checks.ts +++ b/src/planner/python-checks.ts @@ -39,6 +39,7 @@ import { parse } from "yaml"; import type { ChangedPath } from "./check-narrowing.js"; import { noxCheckCommands } from "./nox-sessions.js"; import type { GateCheck } from "./pipeline-steps.js"; +import { sessionInstallBlock, sessionSetupAction } from "./python-session-setup.js"; import { toxCheckCommands } from "./tox-environments.js"; export interface PythonCheck extends GateCheck { @@ -250,9 +251,10 @@ function sessionCheck(line: string, workflowPath: string, read: (path: string) = type ReadText = (path: string) => string | undefined; -/** Discover checks in workflow order. The CLI supplies a separate reader for session configuration - * so its file and environment checks do not change how Makefiles and their scripts are read. */ -export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: ReadText, readSession: ReadText = read): PythonCheck[] { +/** The optional setup reader distinguishes absent paths (undefined) from directories and + * unreadable entries (null). Without that evidence, installer steps stay with CI. */ +export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: ReadText, readSession: ReadText = read, + readSetup?: (file: string) => string | null | undefined): PythonCheck[] { const checks: PythonCheck[] = []; const seen = new Set(); for (const workflow of workflows) { @@ -266,34 +268,47 @@ export function discoverPythonChecks(workflows: readonly WorkflowFile[], read: R const plainSessionJob = workflow.canDeclareSessions !== false && condition === undefined && doc.env === undefined && !("env" in job) && !("container" in job) && !("services" in job) && !("strategy" in job) && !("continue-on-error" in job) && defaults?.run?.shell === undefined && doc.defaults?.run?.shell === undefined; - let unknownSessionContext = false; + const runner = (job as { "runs-on"?: unknown })["runs-on"]; + const standardSetupJob = plainSessionJob && !("environment" in job) && typeof runner === "string" + && /^(?:ubuntu-(?:latest|\d{2}\.04)|windows-(?:latest|\d{4})|macos-(?:latest|\d+))$/.test(runner); + // Existing input-free checkout pins can precede a session. A job that also uses + // setup needs a known action release at every step, including earlier checkouts. + let plainContext = plainSessionJob; + let setupContext = standardSetupJob; + let checkedOut = false; for (const step of steps) { const { run, if: stepCondition, env, shell, uses, with: inputs, "continue-on-error": optional } = (step ?? {}) as { run?: unknown; if?: unknown; env?: unknown; shell?: unknown; uses?: unknown; with?: unknown; "continue-on-error"?: unknown; }; if (disabled(stepCondition)) continue; // An action can change the checkout, runner defaults or environment for later steps. - if (uses !== undefined && !(typeof uses === "string" && /^actions\/checkout@(?:v\d+|[a-f0-9]{40})$/.test(uses) - && inputs === undefined && env === undefined && stepCondition === undefined && optional === undefined)) unknownSessionContext = true; - if (typeof run !== "string") continue; - const canReadSession = !unknownSessionContext && plainSessionJob && stepCondition === undefined - && uses === undefined && env === undefined && shell === undefined && optional === undefined; - // A preceding script could have generated configuration or updated the runner environment. - // Only a session whose complete command list we can read preserves this context. - unknownSessionContext = true; + if (uses !== undefined) { + plainContext &&= typeof uses === "string" && /^actions\/checkout@(?:v\d+|[a-f0-9]{40})$/.test(uses) + && inputs === undefined && env === undefined && stepCondition === undefined && optional === undefined; + setupContext &&= Object.keys(step).every((key) => ["name", "id", "uses", "with"].includes(key)) && sessionSetupAction(uses, inputs); + if (setupContext && typeof uses === "string" && uses.startsWith("actions/checkout@")) checkedOut = true; + } + if (typeof run !== "string") { + if (uses === undefined) { plainContext = false; setupContext = false; } + continue; + } const rawDir = workingDirectory(step, defaults?.run, doc.defaults?.run); const dir = rawDir === undefined ? undefined : normalizeDir(rawDir); - if (dir === undefined) continue; const block = run.replace(/\r\n/g, "\n"); + const rootStep = (rawDir === "." || rawDir === "./") && stepCondition === undefined && uses === undefined + && env === undefined && shell === undefined && optional === undefined; + if (setupContext && rootStep && Object.keys(step).every((key) => ["name", "id", "run", "working-directory"].includes(key)) + && sessionInstallBlock(block, readSetup)) { + plainContext = false; + continue; + } const lines = block.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); - if (lines.some((line) => CONTEXT_CHANGE.test(line) || line.includes("${{"))) continue; + const session = (plainContext || (setupContext && checkedOut)) && rootStep && lines.length === 1 + && !block.includes("${{") && !/[^\t\n\x20-\x7e]/.test(block) ? sessionCheck(lines[0]!, workflow.path, readSession) : undefined; + if (!session) { plainContext = false; setupContext = false; } + if (dir === undefined || lines.some((line) => CONTEXT_CHANGE.test(line) || line.includes("${{"))) continue; for (const line of lines) { - let check = makeCheck(line, dir, workflow.path, read) ?? (dir === "" ? toolCheck(line, workflow.path) : undefined); - if (!check && canReadSession && /^(?:tox|nox)\s/.test(line) && (rawDir === "." || rawDir === "./") - && lines.length === 1 && !block.includes("${{") && !/[^\t\n\x20-\x7e]/.test(block)) { - check = sessionCheck(line, workflow.path, readSession); - if (check) unknownSessionContext = false; - } + const check = session ?? makeCheck(line, dir, workflow.path, read) ?? (dir === "" ? toolCheck(line, workflow.path) : undefined); if (!check || seen.has(check.command)) continue; seen.add(check.command); checks.push(check); diff --git a/src/planner/python-session-setup.ts b/src/planner/python-session-setup.ts new file mode 100644 index 00000000..d0a710d4 --- /dev/null +++ b/src/planner/python-session-setup.ts @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MIT + +// Pinned releases used by the example workflows or the corresponding setup action. +// Other commit IDs need evidence about the action they identify. +const RELEASE_PINS = new Map([ + ["actions/checkout", "11d5960a326750d5838078e36cf38b85af677262"], // v4.4.0 + ["actions/setup-python", "a26af69be951a213d495a4c3e4e4022e16d87065"], // v5.6.0 + ["astral-sh/setup-uv", "d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86"], // v5.4.2 +]); + +function literalBoolean(value: unknown): boolean { + return value === true || value === false || value === "true" || value === "false"; +} + +/** The checkout must still contain this revision at its default path. Version-file, + * alternate download, environment activation and unknown inputs stay with CI. */ +export function sessionSetupAction(uses: unknown, inputs: unknown): boolean { + if (typeof uses !== "string") return false; + const ref = /^(actions\/checkout|actions\/setup-python|astral-sh\/setup-uv)@(v[1-9]\d*(?:\.\d+\.\d+)?|[a-f0-9]{40})$/.exec(uses); + if (!ref || (!ref[2].startsWith("v") && ref[2] !== RELEASE_PINS.get(ref[1]))) return false; + if (inputs === undefined) return ref[1] === "actions/checkout"; + if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) return false; + const options = inputs as Record; + const entries = Object.entries(options); + if (ref[1] === "actions/checkout") { + return entries.every(([key, value]) => { + if (key === "ref") return value === ""; + if (key === "persist-credentials") return literalBoolean(value); + return key === "fetch-depth" && (typeof value === "string" || typeof value === "number") + && /^(?:0|[1-9]\d*)$/.test(String(value)) && Number.isSafeInteger(Number(value)); + }); + } + if (ref[1] === "actions/setup-python") { + const version = options["python-version"]; + return typeof version === "string" && /^3\.\d+(?:\.\d+)?$/.test(version) + && entries.every(([key, value]) => key === "python-version" || (key === "cache" && value === "pip")); + } + return typeof options.version === "string" && /^\d+\.\d+\.\d+$/.test(options.version) + && entries.every(([key, value]) => key === "version" || (key === "enable-cache" && literalBoolean(value))); +} + +const INSTALLERS = [ + ["pip install ", "pip"], ["python -m pip install ", "python-pip"], + ["uv tool install ", "uv-tool"], ["uv pip install --system ", "uv-pip"], +] as const; +const PACKAGES = new Set(["tox", "tox-uv", "nox", "black", "ruff", "mypy", "pyright", "basedpyright", "pyrefly"]); + +type ReadSetupInput = (file: string) => string | null | undefined; +const COMMENT_OR_EMPTY = /^[ \t]*(?:#[\t\x20-\x7e]*)?$/; + +function setupInputsAreKnown(kind: typeof INSTALLERS[number][1], packages: readonly string[], read: ReadSetupInput): boolean { + // Bare package arguments may refer to a local project. Python -m also searches + // the current directory for its pip module. The reader reports directories too. + if (packages.some((name) => read(name) !== undefined)) return false; + if (kind === "python-pip" && ["pip", "pip.py", "pip.pyc", "pip.pyw"].some((name) => read(name) !== undefined)) return false; + // Only uv pip consults the checkout's uv installer settings. + if (kind !== "uv-pip") return true; + const uv = read("uv.toml"); + const project = read("pyproject.toml"); + if (uv === null || project === null) return false; + if (uv !== undefined) { + if (uv.length > 64 * 1024) return false; + if (!uv.replace(/\r\n/g, "\n").split("\n").every((line) => COMMENT_OR_EMPTY.test(line))) return false; + } + return project === undefined || (project.length <= 64 * 1024 && !/\\|[^\t\n\x20-\x7e]/.test(project) + && !project.replace(/\r\n/g, "\n").split("\n").some(mayNameUvKey)); +} + +/** Without escapes or non-ASCII text, a `uv` key appears literally: in a table header, at + * the start of a key or dotted key, or after `{`, `,` or `.` in an inline table. Prose such + * as `description = "Built with uv"` names no key. Lines inside multiline strings are also + * checked, which can only keep more sessions with CI. */ +function mayNameUvKey(line: string): boolean { + const text = line.trim(); + if (text.startsWith("[")) return /\buv\b/.test(text); + return /(?:^|[{,.])[ \t]*(?:"uv"|'uv'|uv)[ \t]*[=.]/.test(text); +} + +/** Every line must be an ordinary installer or a whole-line comment, which both Bash and + * PowerShell ignore. None becomes a local check. */ +export function sessionInstallBlock(block: string, read: ReadSetupInput | undefined): boolean { + if (!read || /[^\t\n\x20-\x7e]/.test(block)) return false; + const lines = block.split("\n").map((line) => line.trim().replace(/[ \t]+/g, " ")).filter((line) => line && !line.startsWith("#")); + return lines.length > 0 && lines.every((line) => { + const installer = INSTALLERS.find(([prefix]) => line.startsWith(prefix)); + if (!installer) return false; + const [prefix, kind] = installer; + const args = line.slice(prefix.length); + if ((kind === "pip" || kind === "python-pip") && args === "--upgrade pip") { + return setupInputsAreKnown(kind, ["pip"], read); + } + const packages = args.split(" "); + return (kind !== "uv-tool" || packages.length === 1) && packages.every((name) => PACKAGES.has(name)) + && setupInputsAreKnown(kind, packages, read); + }); +} diff --git a/tests/planner/python-checks.test.ts b/tests/planner/python-checks.test.ts index 109baa4e..6151905d 100644 --- a/tests/planner/python-checks.test.ts +++ b/tests/planner/python-checks.test.ts @@ -214,21 +214,90 @@ describe("tox and nox workflow checks", () => { const run = (line: string, config: Record = files) => discoverPythonChecks(workflow("jobs:\n checks:\n steps:\n - run: " + line), reader(config)); - it("leaves sessions to CI when their workflow sets up Python and installs tools", () => { - for (const [command, install] of [ - ["tox -e lint,type", "pip install tox tox-uv"], - ["nox -s lint", "python -m pip install --upgrade pip\n pip install black nox"], - ]) { - const checkout = "jobs:\n checks:\n steps:\n - uses: actions/checkout@v4"; - const setup = " - uses: actions/setup-python@v5\n with:\n python-version: '3.12'"; - const installStep = " - run: |\n " + install; - const session = " - run: " + command; - for (const steps of [[setup], [installStep], [setup, installStep]]) { - const text = [checkout, ...steps, session].join("\n"); - assert.deepEqual(discoverPythonChecks(workflow(text), reader(files)), []); - } - assert.deepEqual(discoverPythonChecks(workflow(checkout + "\n" + session), reader(files)).map((c) => c.command), [command]); + const afterSetup = (steps: string[], command = "nox -s lint", configs = files, + inputs: Record = {}, runner = "ubuntu-latest") => { + const text = ["jobs:", " checks:", " runs-on: " + runner, " steps:", + ...[...steps, "- run: " + command].map((step) => " " + step)].join("\n"); + return discoverPythonChecks(workflow(text), reader(configs), reader(configs), (path) => inputs[path]).map((c) => c.command); + }; + const checkout = "- uses: actions/checkout@v4"; + const setupPython = ["- uses: actions/setup-python@v5", " with:", " python-version: '3.12'"]; + const mykrok = [checkout, ...setupPython, "- run: pip install tox tox-uv"]; + const google = ["- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262", + "- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065", " with:", " python-version: '3.13'", + "- run: |", " python -m pip install --upgrade pip", " pip install black nox"]; + + it("plans the named session after the mykrok and Google setup sequences", () => { + assert.deepEqual(afterSetup(mykrok, "tox -e lint,type"), ["tox -e lint,type"]); + assert.deepEqual(afterSetup(google), ["nox -s lint"]); + assert.deepEqual(afterSetup(mykrok, "tox -e lint,type", { ...files, "tox.ini": tox.replace("skip_install = true", "deps = .[devel]") }), []); + assert.deepEqual(afterSetup(google, "nox -s lint", { ...files, "noxfile.py": nox.replace(/ session\.run\(.+/, " run_formatter(session)") }), []); + }); + + it("accepts literal checkout, interpreter, uv and installer forms", () => { + for (const steps of [ + ["- uses: actions/checkout@v4.2.2", " with:", " fetch-depth: 0", " persist-credentials: 'false'", " ref: ''"], + [checkout, ...setupPython, " cache: pip", "- run: python -m pip install ruff mypy"], + [checkout, "- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86", " with:", " version: '0.12.22'", " enable-cache: false", "- run: uv tool install nox"], + [checkout, "- run: uv pip install --system mypy ruff"], + [checkout, "- run: pip install --upgrade pip", "- run: pip install nox"], + [checkout, "- run: |", " # Tools for the lint session", " pip install nox", " #pip install ruff"], + ]) assert.deepEqual(afterSetup(steps), ["nox -s lint"], steps.join("\n")); + assert.deepEqual(afterSetup([checkout, "- run: |", " # only a comment"]), []); + assert.deepEqual(afterSetup([checkout, "- run: |", " pip install nox # tools"]), []); + }); + + it("keeps changed sources, unknown setup and mixed run blocks with CI", () => { + for (const steps of [ + ["- uses: actions/checkout@v4.2.2", " with:", " ref: main"], + [checkout, " with:", " path: other"], [checkout, " with:", " repository: other/project"], + [checkout, " with:", " sparse-checkout: src"], [checkout, " with:", " fetch-depth: -1"], + ["- uses: actions/setup-python@main"], ["- uses: tools/setup-python@v5"], + ["- uses: actions/setup-python@v5", " with:", " python-version-file: .python-version"], + [...setupPython, " architecture: arm64"], [...setupPython, " if: github.ref"], + ["- uses: actions/setup-python@v5", " with:", " python-version: '${{ matrix.python }}'"], + ["- uses: astral-sh/setup-uv@v5", " with:", " version: latest"], + ["- run: pip install -r requirements.txt"], ["- run: pip install -e ."], ["- run: pip install nox[uv]"], + ["- run: pip install nox unknown"], ["- run: uv tool install nox ruff"], ["- run: uv pip install ruff"], + ["- run: pip install --upgrade nox"], ["- run: pip install ruff && pip install mypy"], + ["- run: pip install nox", " working-directory: other"], ["- run: pip install nox", " shell: custom"], + ["- run: pip install nox", " env: {MODE: custom}"], ["- run: pip install nox", " continue-on-error: true"], + ["- run: |", " pip install nox", " prepare"], ["- run: pip install nox", "- uses: elsewhere/setup@v1"], + ["- run: prepare", ...google], + ]) assert.deepEqual(afterSetup([checkout, ...steps]), [], steps.join("\n")); + assert.deepEqual(afterSetup([...setupPython, "- run: pip install nox"]), []); + for (const runner of ["self-hosted", "'${{ inputs.runner }}'", "[self-hosted, linux]"]) { + assert.deepEqual(afterSetup(google, "nox -s lint", files, {}, runner), []); } + assert.deepEqual(afterSetup(["- run: prepare", ...google, "- run: nox -s lint"], "uv run mypy src"), ["uv run mypy src"]); + }); + + it("requires evidence about local installer inputs", () => { + for (const name of ["nox", "pip.py"]) assert.deepEqual(afterSetup(google, "nox -s lint", files, { [name]: null }), []); + const uv = [checkout, "- run: uv pip install --system nox"]; + assert.deepEqual(afterSetup(uv, "nox -s lint", files, { "uv.toml": "# local comment\n" }), ["nox -s lint"]); + assert.deepEqual(afterSetup(uv, "nox -s lint", files, { "uv.toml": "offline = true" }), []); + assert.deepEqual(afterSetup(uv, "nox -s lint", files, { "pyproject.toml": null }), []); + for (const project of [ + '[project]\nname = "sample"\ndescription = "Linted with uv, ruff and nox"\ndependencies = ["uv>=0.5"]\n', + '[project]\nname = "uv-plugin"\nkeywords = ["uv", "tox"]\n\n[tool.ruff]\nline-length = 100\n', + ]) assert.deepEqual(afterSetup(uv, "nox -s lint", files, { "pyproject.toml": project }), ["nox -s lint"], project); + for (const project of [ + "[tool.uv]\nindex-url = 'x'\n", "[ tool . uv . pip ]\nonly-binary = [':all:']\n", "[[tool.uv.index]]\nurl = 'x'\n", + "[tool]\nuv = { index-url = 'x' }\n", "[tool]\nuv.index-url = 'x'\n", "tool.uv.index-url = 'x'\n", + "tool . 'uv' . index-url = 'x'\n", "tool = { uv = { index-url = 'x' } }\n", 'tool = { ruff = {}, "uv" = {} }\n', + "[tool]\nu\\u0076 = {}\n", + ]) assert.deepEqual(afterSetup(uv, "nox -s lint", files, { "pyproject.toml": project }), [], project); + const steps = "jobs:\n checks:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - run: pip install nox\n - run: nox -s lint"; + assert.deepEqual(discoverPythonChecks(workflow(steps), reader(files)), []); + }); + + it("preserves existing checkout-only pins without extending them to new setup sequences", () => { + const unverified = "- uses: actions/checkout@" + "a".repeat(40); + assert.deepEqual(afterSetup([unverified]), ["nox -s lint"]); + assert.deepEqual(afterSetup([unverified, ...setupPython]), []); + assert.deepEqual(afterSetup(["- run: pip install nox", unverified]), []); + assert.deepEqual(afterSetup([checkout, ...setupPython, "- run: nox -s lint"], "tox -e lint,type"), ["nox -s lint", "tox -e lint,type"]); }); it("keeps the regular workflow's session when a linked workflow declares the same command", () => {