diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index ffc0fae..5607ae4 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -146,17 +146,18 @@ steps: ## Top-level keys -| Key | What it is | -| --------------- | --------------------------------------------------------------------------------------------- | -| `provider` | Required. `github`, `circleci`, or a list of both. | -| `input_groups` | Named lists of globs that jobs reference as `@name`. See [inputs](/docs/inputs/). | -| `services` | Service containers jobs can name. See [jobs](/docs/jobs/#services). | -| `commands` | Reusable steps. See [steps and commands](/docs/steps-and-commands/). | -| `cigen_install` | How jobs that skip get cigen. See [skipping](/docs/skipping/#installing-cigen-on-the-runner). | -| `workflows` | Workflows by name. Each holds its settings and its `jobs`. | -| `github` | Passed to the GitHub provider untouched. | -| `circleci` | Passed to the CircleCI provider untouched. | -| `$schema` | Ignored by cigen, so an editor can find the [JSON schema](#json-schemas). | +| Key | What it is | +| --------------- | ----------------------------------------------------------------------------------------------------- | +| `provider` | Required. `github`, `circleci`, or a list of both. | +| `input_groups` | Named lists of globs that jobs reference as `@name`. See [inputs](/docs/inputs/). | +| `services` | Service containers jobs can name. See [jobs](/docs/jobs/#services). | +| `commands` | Reusable steps. See [steps and commands](/docs/steps-and-commands/). | +| `cigen_install` | How jobs that skip get cigen. See [skipping](/docs/skipping/#installing-cigen-on-the-runner). | +| `narrow_inputs` | `true` gives every job only the toolchains' files it uses. See [inputs](/docs/inputs/#narrow_inputs). | +| `workflows` | Workflows by name. Each holds its settings and its `jobs`. | +| `github` | Passed to the GitHub provider untouched. | +| `circleci` | Passed to the CircleCI provider untouched. | +| `$schema` | Ignored by cigen, so an editor can find the [JSON schema](#json-schemas). | A config with no `provider` is an error: diff --git a/docs/src/content/docs/inputs.md b/docs/src/content/docs/inputs.md index 63ae960..c0c16a5 100644 --- a/docs/src/content/docs/inputs.md +++ b/docs/src/content/docs/inputs.md @@ -91,14 +91,20 @@ On top of the job's `inputs`, a job's hash covers: - **Files its steps name.** Any word in a step that is a path to a project file: `sh scripts/check.sh`, `require('./.github/wait-for-checks.js')`, a file in an action's `with:`. A local action (`uses: ./path`) brings every file in its directory. -- **Toolchain pins** in the project root: `rust-toolchain.toml`, `rust-toolchain`, `.ruby-version`, `.node-version`, - `.nvmrc`, `.python-version`, `.go-version`, `.java-version`, `.terraform-version`, `.tool-versions`, `mise.toml`, - `.mise.toml`, and `package.json`'s `packageManager`. +- **Toolchain pins and settings** in the project root: `rust-toolchain.toml`, `rust-toolchain`, `.ruby-version`, + `.node-version`, `.nvmrc`, `.npmrc`, `.yarnrc.yml`, `.python-version`, `.go-version`, `go.mod`, `go.work`, + `.java-version`, `gradle/wrapper/gradle-wrapper.properties`, `.mvn/wrapper/maven-wrapper.properties`, + `.terraform-version`, and `package.json`'s `packageManager`. +- **Shared pins**, which can pin any tool: `.tool-versions`, `mise.toml`, `.mise.toml`, `mise.local.toml`, + `.mise.local.toml`, `mise/config.toml`, `.mise/config.toml`, `.config/mise.toml` and `.config/mise/config.toml`. - **Lockfiles** in the project root: `Cargo.lock`, `Gemfile.lock`, `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, - `bun.lock`, `bun.lockb`, `poetry.lock`, `uv.lock`, `Pipfile.lock`, `composer.lock`, `go.sum`. + `bun.lock`, `bun.lockb`, `poetry.lock`, `uv.lock`, `Pipfile.lock`, `composer.lock`, `go.sum`, `go.work.sum`, + `.terraform.lock.hcl`. - **Every `package.json`** in the project, tracked by git. `npm run test` runs whatever the `test` script says, and cigen can't tell which job runs a package manager, or in which package. +Every job gets every toolchain's pins and lockfiles, unless it sets [`narrow_inputs`](#narrow_inputs). + A command or service the job doesn't use isn't in its hash, so changing it doesn't rerun the job. ### Known gaps @@ -107,8 +113,109 @@ A command or service the job doesn't use isn't in its hash, so changing it doesn - Paths in steps are looked up from the project root, so a step with a different working directory can miss its script. - A moving image tag such as `rust:latest` isn't resolved to a digest, so a new image under the same tag doesn't rerun the job. -- Toolchain pins and lockfiles go into every job, so a `yarn.lock` change reruns Rust jobs too. Modules will narrow this - per toolchain. +- Toolchain pins and lockfiles go into every job, so a `yarn.lock` change reruns Rust jobs too, unless the job sets + `narrow_inputs: true`. + +## `narrow_inputs` + +By default a job's hash covers every toolchain's pins and lockfiles, so a `yarn.lock` change reruns a job that only runs +`cargo`. That's safe, and wasteful. `narrow_inputs: true` gives a job only the toolchains it uses: + +```yaml +# cigen.yml +provider: github +narrow_inputs: true + +workflows: + ci: + jobs: + test: + inputs: ['src/**'] + steps: + - run: cargo test + lint: + inputs: ['src/**'] + narrow_inputs: false + steps: + - run: make lint +``` + +Set it at the top level for every job, or on a job, where the job's value wins. A narrowed job gets: + +- the toolchains of the [modules](/docs/modules/) it uses, and those listed in its `toolchains`; +- the toolchains whose commands it visibly runs: `cargo test` brings Rust's files, `bundle exec rake` brings Ruby's; +- every toolchain, as soon as it runs anything cigen can't see into. + +The shared pins can pin any tool, so they go into every job either way. A narrowed job gets the project's `package.json` +files only with Node. + +cigen reads the job's run steps, the commands it uses and its local composite actions. It follows the shell scripts +they run or source (`sh scripts/check.sh`, `. ./env.sh`) in the directory they run in (`working-directory`, GitHub's +`defaults.run`, a literal `cd`). When the job runs npm, pnpm or Yarn, it reads the scripts of every `package.json` in the +project. Every file it read goes into the job's hash, so changing a script that decided the job's toolchains reruns it. + +A toolchain's pins and lockfiles count where its commands run, and in the directories above, as well as in the root: +`cd web && pnpm install` brings `web/pnpm-lock.yaml` and `web/.nvmrc`, and the shared pins there. cigen follows the +options that move a tool to another directory: `yarn --cwd web`, `pnpm -C web`, `terraform -chdir=infra`, +`cargo --manifest-path sub/Cargo.toml`, `go -C dir`. + +cigen trusts a toolchain's own commands to use only that toolchain: `cargo test`, `rake` and `pnpm build` bring their +own toolchain's files, and nothing else. Commands that run another command are read for the command they run: +`bundle exec`, `gem exec`, `npx`, `pnpm exec`, `yarn dlx`, `npm exec`, `rustup run stable`, `uv run`, `poetry run`, +`find -exec`, a word pnpm, Yarn or Bun runs that isn't their own subcommand or a package script (`pnpm make`), and a +prefix such as `timeout` or `sudo`. A subcommand that runs the project's own code, such as `cargo run`, `cargo xtask`, +`cargo make` (or `cargo-make`) or `go generate`, counts as something cigen can't see into. + +Anything cigen can't see into gives the job every toolchain: + +- an unknown command (`make`, a binary on `PATH`), an alias (`git my-alias`, a cargo alias, `alias x=make`), or an + action cigen doesn't know; +- `sh -c` (`bash -lc` too), a shell reading its input, `trap`, a command from a variable, and commands hidden in + arguments: `git rebase --exec`, `git submodule foreach`, `git bisect run`, awk's `system`, sed's `e`, `${X:-$(cmd)}`, + `<(cmd)`, `sort --compress-program`; +- settings that name a command: `git config core.hooksPath`, `GIT_EXTERNAL_DIFF=… git diff`, `export GIT_SSH_COMMAND=…`; +- a `<<` that isn't a heredoc cigen can read (a CircleCI `<< parameter >>`, quoted or not), or a heredoc that never + ends; +- a `cd` it can't follow, when a script or a toolchain's command runs after it: a variable, a directory outside the + project, a `cd` in a subshell, a pipeline or a function, or one that might not happen (inside `if`, a loop or `case`, + after `||`, or after `&&` once the list ends); +- a runner that picks packages itself (`pnpm --filter web exec`, `npm exec --workspace`), and `find -execdir`; +- a step whose `shell:` isn't a POSIX shell, a Windows runner (its steps run in PowerShell), or a runner chosen by an + expression (`runs-on: ${{ matrix.os }}`), which could be Windows. + +That's the trade-off: narrowing saves reruns for jobs whose commands cigen can read, and changes nothing for the rest. A +wrong guess would make a job skip when its toolchain changed, so every unclear case includes more. + +### What narrowing takes on trust + +cigen can't read inside a toolchain's own programs, so it trusts them not to start another toolchain. Projects where +they do: + +- `pip install .` or `uv sync` building a Rust extension (PyO3, maturin) with `cargo`; +- `rails assets:precompile` running `yarn` or `npm`; +- `node build.js` calling `cargo` to build a native addon (napi-rs); +- Gradle or Maven frontend plugins running `npm`; +- a runner in `.cargo/config.toml` that runs tests through another tool. + +Name the other toolchain in the job's `toolchains`, and a narrowed job gets its pins and lockfiles too: + +```yaml +# cigen.yml +provider: github +narrow_inputs: true + +workflows: + ci: + jobs: + assets: + toolchains: [node] + inputs: ['app/**'] + steps: + - run: bundle exec rails assets:precompile +``` + +The toolchains are `go`, `java`, `node`, `php`, `python`, `ruby`, `rust` and `terraform`. Or set `narrow_inputs: false` +on the job. ## See a job's hash diff --git a/docs/src/content/docs/jobs.md b/docs/src/content/docs/jobs.md index 4a8087d..726163a 100644 --- a/docs/src/content/docs/jobs.md +++ b/docs/src/content/docs/jobs.md @@ -37,20 +37,22 @@ workflows: ## Keys -| Key | What it is | -| ----------- | --------------------------------------------------------------------------------------------------- | -| `image` | Where the job runs. Default `ubuntu-latest`. See below. | -| `steps` | What the job does. See [steps and commands](/docs/steps-and-commands/). | -| `needs` | Jobs that must finish first: one id or a list. | -| `inputs` | What the job's result depends on: globs, or `@group` references. See [inputs](/docs/inputs/). | -| `env` | Environment variables for every step. | -| `services` | Names from the top-level `services`. | -| `matrix` | Run the job once per combination of values. See below. | -| `packages` | GitHub only: `rust` or `node` adds a dependency cache restore step. | -| `checkout` | GitHub only: options for the `actions/checkout` step cigen adds, such as `fetch-depth`. | -| `artifacts` | Accepted, but neither provider generates anything from it yet. | -| `github` | Job keys passed to GitHub untouched: `timeout-minutes`, `if`, `outputs`, `strategy`, `environment`. | -| `circleci` | Job keys passed to CircleCI untouched: `resource_class`, `parallelism`, `parameters`. | +| Key | What it is | +| --------------- | ------------------------------------------------------------------------------------------------------------------ | +| `image` | Where the job runs. Default `ubuntu-latest`. See below. | +| `steps` | What the job does. See [steps and commands](/docs/steps-and-commands/). | +| `needs` | Jobs that must finish first: one id or a list. | +| `inputs` | What the job's result depends on: globs, or `@group` references. See [inputs](/docs/inputs/). | +| `env` | Environment variables for every step. | +| `services` | Names from the top-level `services`. | +| `matrix` | Run the job once per combination of values. See below. | +| `modules` | Setup steps by name, such as `rust`. See [modules](/docs/modules/). | +| `narrow_inputs` | Only the toolchains' files the job uses. See [inputs](/docs/inputs/#narrow_inputs). | +| `toolchains` | Toolchains a narrowed job uses without cigen seeing it. See [inputs](/docs/inputs/#what-narrowing-takes-on-trust). | +| `checkout` | GitHub only: options for the `actions/checkout` step cigen adds, such as `fetch-depth`. | +| `artifacts` | Accepted, but neither provider generates anything from it yet. | +| `github` | Job keys passed to GitHub untouched: `timeout-minutes`, `if`, `outputs`, `strategy`, `environment`. | +| `circleci` | Job keys passed to CircleCI untouched: `resource_class`, `parallelism`, `parameters`. | Any other key is an error that says what to write instead. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index e01659d..7045f2c 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -43,7 +43,7 @@ What the code does today, checked against the code in December 2026. Where cigen top level allows `$schema`. `tests/json_schema.rs` fails when they're stale (refresh with `CIGEN_UPDATE_GOLDEN=1 cargo test --test json_schema`) and checks every config in the repository against them. -- **Derived inputs** (`src/inputs.rs`, `src/commands/needs_hash.rs`): `cigen hash --job` adds, on top of a job's +- **Derived inputs** (`src/inputs/`, `src/commands/needs_hash.rs`): `cigen hash --job` adds, on top of a job's `inputs`, the hashes of the jobs it `needs` (transitively, so a changed build reruns the tests that need it), the commands it uses (through other commands too), the services it names, the top-level provider blocks, every project file its steps name (`sh scripts/check.sh`, `require('./x.js')`, every file of a local `uses: ./action`), and the root @@ -68,6 +68,28 @@ What the code does today, checked against the code in December 2026. Where cigen - `rust`: installs the toolchain `rust-toolchain.toml` names (or a channel) with `rustup`, adds components and targets, and caches with `Swatinem/rust-cache` (GitHub) or `restore_cache`/`save_cache` (CircleCI). It adds `Cargo.toml`, `**/Cargo.toml`, `Cargo.lock`, the toolchain files and `.cargo/config.toml` to the job's inputs. +- **`narrow_inputs`** (`src/inputs/narrow.rs`, `src/inputs/shell/`): by default every job gets every toolchain + family's pins and lockfiles (go, java, node, php, python, ruby, rust, terraform), modules or not. With + `narrow_inputs: true` (top level, or per job, where a job's value wins) a job gets only its modules' families, those + in its `toolchains` list, the families whose commands it visibly runs, and every family as soon as it runs anything + cigen can't see into. The shared pins (`.tool-versions` and mise's config files) go into every job either way; the + `package.json` files only with node. cigen reads run steps (including used commands and local composite actions), + the shell scripts they run or source, in the directory they run in (`working-directory`, GitHub's `defaults.run`, + literal `cd`s, and tool options such as `--cwd`, `-chdir`, `--manifest-path`), and, when a Node package manager runs, + the scripts of every `package.json` in the project; every file it read becomes an input. A family's pins and + lockfiles count in each directory its commands ran in, and the directories above. Runners (`bundle exec`, + `gem exec`, `npx`, `rustup run`, `uv run`, `find -exec`, `timeout`, a non-script word given to pnpm, Yarn or Bun) + are read for the command they run (`src/inputs/shell/family.rs`). Opaque: unknown commands, aliases and actions; + subcommands that run project code (`cargo run`, `cargo xtask`, `cargo-make`, `go generate`); `sh -c` and + `bash -lc`; `trap`; commands from variables; commands hidden in arguments or settings (`git rebase --exec`, awk + `system`, sed `e`, `${X:-$(cmd)}`, `<(cmd)`, `git config core.hooksPath`, `GIT_EXTERNAL_DIFF=`); a `<<` that isn't a + readable heredoc, or a CircleCI parameter as a command; a `cd` it can't follow (in a subshell, pipeline or + function, or conditional: under `if`, loops, `case`, `||`, or `&&` once the list ends) before a script or a family + command; runners that pick packages (`pnpm --filter … exec`); a non-POSIX `shell:`; a Windows runner or one chosen + by an expression. Each family's choice carries its reason (`FamilyChoice`), ready for `cigen explain`. The family + files added in PR #26 (`go.mod`, `go.work`, `go.work.sum`, `.terraform.lock.hcl`, `.npmrc`, `.yarnrc.yml`, the + Gradle and Maven wrapper properties, and mise's other config paths) go into every job by default too, so default + hashes change once for projects that have them. - **Job graph** (`src/orchestrator/dag.rs`): dependency resolution and matrix expansion. - **Providers** run as separate binaries spawned over a length-prefixed protobuf stdio protocol (`proto/plugin.proto`, `src/plugin/`), with the config converted to protobuf in `src/orchestrator/convert.rs`: @@ -134,6 +156,12 @@ What the code does today, checked against the code in December 2026. Where cigen - `tests/module_scenarios.rs`: a job using the `rust` module installs nothing when it skips, and reruns in mockci when a file the module contributes or its parameters change; the generated `--modules-digest` changes the hash; unknown modules and parameters fail generation with a fix. +- `tests/narrow_inputs.rs`: in mockci, a narrowed job skips when another toolchain's lockfile changes and reruns + when its own, a shared pin, a script it runs or a `package.json` whose scripts it runs changes; scripts resolve in + the step's working directory and after `cd`; an opaque command, a non-POSIX `shell:` or a job that opts out gets + every family. `tests/narrow_inputs_readers.rs` checks the hash for default working directories, Windows runners, + CircleCI orb steps, known, unknown and local actions, pins in the directory a toolchain runs in, and the newer pin + files; the shell reader's unit tests (`src/inputs/shell/tests/`) cover each false skip the review of PR #26 found. - `tests/module_catalogue.rs`: every registered module has a skill with frontmatter, a README documenting exactly its parameters, a golden fixture (`integration_tests/module_/`) for each provider it supports that mockci's parser loads, and actions pinned to commit SHAs; the index is generated from the registry @@ -144,10 +172,11 @@ What the code does today, checked against the code in December 2026. Where cigen ## Known problems -1. **Derived inputs err towards running but have gaps.** Files that a named script mentions aren't followed. Paths in - steps are looked up from the project root, so a step with a different `working-directory` can miss its script. A - moving image tag (`rust:latest`) isn't resolved to a digest. Toolchain pins and lockfiles go into every job, so a - `yarn.lock` change reruns Rust jobs. +1. **Derived inputs err towards running but have gaps.** Files that a named script mentions aren't followed, except + by a narrowed job, which follows the shell scripts it runs. Outside narrowing, paths in steps are looked up from the + project root, so a step with a different `working-directory` can miss its script. A moving image tag + (`rust:latest`) isn't resolved to a digest. Toolchain pins and lockfiles go into every job unless it sets + `narrow_inputs: true`, so by default a `yarn.lock` change reruns Rust jobs. 2. GitHub Actions skipping happens per step inside a started job, so a skipped job still gets a runner and a checkout. The planner job in DIRECTION.md replaces it. 3. Markers in the GitHub Actions cache inherit its limits: scoped by branch (a pull request's pass is invisible to @@ -197,7 +226,12 @@ What the code does today, checked against the code in December 2026. Where cigen with git's message on any other git error. 22. Resolved (PR #30): a job's hash didn't include the jobs it `needs`, so a change to `build`'s inputs alone left a `test` that uses its artifact skipping. +23. A narrowed job trusts a toolchain's own commands to use only that toolchain. Common ways that fails: `pip install .` + or `uv sync` building a PyO3 crate with cargo, `rails assets:precompile` running yarn, `node build.js` calling cargo + (napi), Gradle or Maven frontend plugins running npm, and `.cargo/config.toml` runners. The docs list them and + tell users to name the toolchain in the job's `toolchains`, or opt out. ## Next -More modules: the `narrow_inputs` opt-in, then `node` and `ruby`. See "Modules" in DIRECTION.md. +More modules: `node`, then Playwright, the Postgres and S3-compatible services and kache, then `ruby`. See "Modules" +in DIRECTION.md. diff --git a/schemas/v1/cigen.schema.json b/schemas/v1/cigen.schema.json index 8fe0ed3..971ed77 100644 --- a/schemas/v1/cigen.schema.json +++ b/schemas/v1/cigen.schema.json @@ -54,6 +54,11 @@ }, "default": {} }, + "narrow_inputs": { + "description": "Give each job only its own toolchains' pins and lockfiles: those of its modules and of\nthe commands it visibly runs, or every toolchain's when it runs something cigen can't see\ninto. A narrowed job reruns less often, and skips wrongly if one of its tools starts\nanother toolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`).\nOff by default; a job's own `narrow_inputs` overrides it.", + "type": "boolean", + "default": false + }, "provider": { "description": "The CI provider(s) to generate for. Required in `cigen.yml` or `.cigen/config.yml`.", "anyOf": [ @@ -267,6 +272,13 @@ "$ref": "#/$defs/ModuleUse" } }, + "narrow_inputs": { + "description": "Only this job's toolchains' pins and lockfiles, overriding the top-level `narrow_inputs`.\nA narrowed job reruns less often, and skips wrongly if one of its tools starts another\ntoolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`).", + "type": [ + "boolean", + "null" + ] + }, "needs": { "description": "Jobs that must finish first", "$ref": "#/$defs/OneOrMany", @@ -287,6 +299,13 @@ "items": { "$ref": "#/$defs/Step" } + }, + "toolchains": { + "description": "Toolchains the job uses without cigen seeing it run them (a Rake task that runs `yarn`):\na narrowed job gets their pins and lockfiles too. One of go, java, node, php, python,\nruby, rust, terraform.", + "type": "array", + "items": { + "type": "string" + } } }, "additionalProperties": false diff --git a/schemas/v1/job.schema.json b/schemas/v1/job.schema.json index d2f2503..cbae9be 100644 --- a/schemas/v1/job.schema.json +++ b/schemas/v1/job.schema.json @@ -74,6 +74,13 @@ "$ref": "#/$defs/ModuleUse" } }, + "narrow_inputs": { + "description": "Only this job's toolchains' pins and lockfiles, overriding the top-level `narrow_inputs`.\nA narrowed job reruns less often, and skips wrongly if one of its tools starts another\ntoolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`).", + "type": [ + "boolean", + "null" + ] + }, "needs": { "description": "Jobs that must finish first", "$ref": "#/$defs/OneOrMany", @@ -94,6 +101,13 @@ "items": { "$ref": "#/$defs/Step" } + }, + "toolchains": { + "description": "Toolchains the job uses without cigen seeing it run them (a Rake task that runs `yarn`):\na narrowed job gets their pins and lockfiles too. One of go, java, node, php, python,\nruby, rust, terraform.", + "type": "array", + "items": { + "type": "string" + } } }, "additionalProperties": false, diff --git a/schemas/v1/workflow.schema.json b/schemas/v1/workflow.schema.json index fd6cddb..4bb3968 100644 --- a/schemas/v1/workflow.schema.json +++ b/schemas/v1/workflow.schema.json @@ -153,6 +153,13 @@ "$ref": "#/$defs/ModuleUse" } }, + "narrow_inputs": { + "description": "Only this job's toolchains' pins and lockfiles, overriding the top-level `narrow_inputs`.\nA narrowed job reruns less often, and skips wrongly if one of its tools starts another\ntoolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`).", + "type": [ + "boolean", + "null" + ] + }, "needs": { "description": "Jobs that must finish first", "$ref": "#/$defs/OneOrMany", @@ -173,6 +180,13 @@ "items": { "$ref": "#/$defs/Step" } + }, + "toolchains": { + "description": "Toolchains the job uses without cigen seeing it run them (a Rake task that runs `yarn`):\na narrowed job gets their pins and lockfiles too. One of go, java, node, php, python,\nruby, rust, terraform.", + "type": "array", + "items": { + "type": "string" + } } }, "additionalProperties": false diff --git a/src/config/lower.rs b/src/config/lower.rs index 612aaee..dda88ae 100644 --- a/src/config/lower.rs +++ b/src/config/lower.rs @@ -24,6 +24,7 @@ pub fn lower(document: &Document) -> Result { Vec::new() }), input_groups: top.input_groups, + narrow_inputs: top.narrow_inputs, services: top.services, cigen_install: top.cigen_install, github: top.github, @@ -114,6 +115,7 @@ pub fn lower(document: &Document) -> Result { resolve_sibling_needs(&mut config.jobs, &broken); errors.extend(check_input_groups(&config)); + errors.extend(super::toolchains::check(&config)); errors.extend(config.validate(&broken)); errors.extend(check_cigen_install(&config, &broken)); let errors: Vec = errors diff --git a/src/config/mod.rs b/src/config/mod.rs index 78d3bdd..03c3630 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -5,6 +5,7 @@ mod error; mod layout; mod lower; pub(crate) mod suggest; +mod toolchains; pub use error::{ConfigError, ConfigErrors}; diff --git a/src/config/toolchains.rs b/src/config/toolchains.rs new file mode 100644 index 0000000..97b3bd4 --- /dev/null +++ b/src/config/toolchains.rs @@ -0,0 +1,28 @@ +//! A job's `toolchains`: each must name a toolchain family cigen knows. +use super::error::ConfigError; +use super::suggest; +use crate::inputs::FAMILIES; +use crate::schema::CigenConfig; + +pub fn check(config: &CigenConfig) -> Vec { + let names: Vec<&str> = FAMILIES.iter().map(|family| family.name).collect(); + let mut errors = Vec::new(); + for (id, job) in &config.jobs { + let workflow = job.workflow.as_deref().unwrap_or_default(); + for (index, name) in job.toolchains.iter().enumerate() { + if names.contains(&name.as_str()) { + continue; + } + let at = index.to_string(); + let error = ConfigError::new(format!( + "job `{id}` lists the toolchain `{name}`, which cigen doesn't know" + )) + .at(&["workflows", workflow, "jobs", id, "toolchains", &at]); + errors.push(match suggest::closest(name, &names) { + Some(close) => error.suggest(format!("did you mean `{close}`?")), + None => error.suggest(format!("Use one of: {}.", names.join(", "))), + }); + } + } + errors +} diff --git a/src/inputs/families.rs b/src/inputs/families.rs new file mode 100644 index 0000000..4e10df6 --- /dev/null +++ b/src/inputs/families.rs @@ -0,0 +1,143 @@ +//! Toolchain families: the pins and lockfiles of one toolchain, and the commands that read +//! them. Every job gets every family's files unless it sets `narrow_inputs`; a narrowed job +//! gets only the families it uses (`super::narrow`). + +/// One toolchain's files and commands. +pub struct Family { + pub name: &'static str, + /// Pins and lockfiles, relative to the project root (or a module's `path`). + pub files: &'static [&'static str], + /// Commands that use the toolchain. + pub commands: &'static [&'static str], + /// Command prefixes that use it, such as `cargo-` for `cargo-nextest`. + pub prefixes: &'static [&'static str], +} + +/// Files that can pin any tool (and put shims in front of every command): in every job. +pub const SHARED_PINS: &[&str] = &[ + ".config/mise.toml", + ".config/mise/config.toml", + ".mise.local.toml", + ".mise.toml", + ".mise/config.toml", + ".tool-versions", + "mise.local.toml", + "mise.toml", + "mise/config.toml", +]; + +pub const FAMILIES: &[Family] = &[ + Family { + name: "go", + files: &[".go-version", "go.mod", "go.sum", "go.work", "go.work.sum"], + commands: &["go", "gofmt"], + prefixes: &[], + }, + Family { + name: "java", + files: &[ + ".java-version", + ".mvn/wrapper/maven-wrapper.properties", + "gradle/wrapper/gradle-wrapper.properties", + ], + commands: &["gradle", "java", "javac", "mvn"], + prefixes: &[], + }, + Family { + name: "node", + files: &[ + ".node-version", + ".npmrc", + ".nvmrc", + ".yarnrc.yml", + "bun.lock", + "bun.lockb", + "package-lock.json", + "pnpm-lock.yaml", + "yarn.lock", + ], + commands: &[ + "bun", "bunx", "corepack", "node", "npm", "npx", "pnpm", "pnpx", "yarn", + ], + prefixes: &[], + }, + Family { + name: "php", + files: &["composer.lock"], + commands: &["composer", "php"], + prefixes: &[], + }, + Family { + name: "python", + files: &[".python-version", "Pipfile.lock", "poetry.lock", "uv.lock"], + commands: &[ + "pip", "pip3", "pipenv", "poetry", "pytest", "python", "python3", "uv", "uvx", + ], + prefixes: &[], + }, + Family { + name: "ruby", + files: &[".ruby-version", "Gemfile.lock"], + commands: &[ + "bundle", "bundler", "gem", "irb", "rails", "rake", "rspec", "rubocop", "ruby", + ], + prefixes: &[], + }, + Family { + name: "rust", + files: &["Cargo.lock", "rust-toolchain", "rust-toolchain.toml"], + commands: &["cargo", "cross", "rustc", "rustup", "rustfmt"], + prefixes: &["cargo-"], + }, + Family { + name: "terraform", + files: &[".terraform-version", ".terraform.lock.hcl"], + commands: &["terraform"], + prefixes: &[], + }, +]; + +/// The family named `name`. +pub fn family(name: &str) -> Option<&'static Family> { + FAMILIES.iter().find(|family| family.name == name) +} + +/// The family whose command `word` is, if any. +pub fn family_of_command(word: &str) -> Option<&'static Family> { + FAMILIES.iter().find(|family| { + family.commands.contains(&word) + || family + .prefixes + .iter() + .any(|prefix| word.starts_with(prefix) && word.len() > prefix.len()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_belong_to_one_family() { + assert_eq!(family_of_command("pnpm").map(|f| f.name), Some("node")); + assert_eq!( + family_of_command("cargo-nextest").map(|f| f.name), + Some("rust") + ); + assert_eq!(family_of_command("cargo-").map(|f| f.name), None); + assert_eq!(family_of_command("make").map(|f| f.name), None); + let mut seen = std::collections::BTreeSet::new(); + for family in FAMILIES { + for command in family.commands { + assert!(seen.insert(*command), "`{command}` is in two families"); + } + } + } + + #[test] + fn every_module_has_a_family() { + for spec in crate::modules::REGISTRY { + assert!(family(spec.family).is_some(), "{}", spec.name); + } + } +} diff --git a/src/inputs/files.rs b/src/inputs/files.rs new file mode 100644 index 0000000..99250a9 --- /dev/null +++ b/src/inputs/files.rs @@ -0,0 +1,113 @@ +//! Files a job's steps name: a word in a run command or an action's inputs that is a path to a +//! file in the project, and every file of a local action. +use anyhow::Result; +use serde_json::{Map, Value}; +use std::collections::BTreeSet; +use std::path::{Component, Path}; + +/// Adds every file in the project that a string in `value` names. +pub(super) fn files_named(value: &Value, root: &Path, files: &mut BTreeSet) -> Result<()> { + match value { + Value::String(text) => { + for word in words(text) { + let Some(relative) = project_path(word) else { + continue; + }; + let path = root.join(&relative); + if path.is_file() { + files.insert(relative); + } + } + } + Value::Array(items) => { + for item in items { + files_named(item, root, files)?; + } + } + Value::Object(map) => { + local_action(map, root, files)?; + for item in map.values() { + files_named(item, root, files)?; + } + } + _ => {} + } + Ok(()) +} + +/// `uses: ./path/to/action` depends on every file in the action's directory. +fn local_action(map: &Map, root: &Path, files: &mut BTreeSet) -> Result<()> { + let Some(Value::String(uses)) = map.get("uses") else { + return Ok(()); + }; + let Some(relative) = uses.strip_prefix("./").and_then(project_path) else { + return Ok(()); + }; + let dir = root.join(&relative); + if !dir.is_dir() { + return Ok(()); + } + for entry in walkdir::WalkDir::new(&dir).sort_by_file_name() { + let entry = entry?; + if entry.file_type().is_file() { + let path = entry.path().strip_prefix(root)?; + files.insert(path.to_string_lossy().replace('\\', "/")); + } + } + Ok(()) +} + +/// The words of a step's text: split on whitespace, quotes and shell punctuation, so +/// `FOO=1 ./bin/run --config=ci/a.yml` gives `./bin/run` and `ci/a.yml`. +pub(super) fn words(text: &str) -> impl Iterator { + text.split(|c: char| c.is_whitespace() || "'\"`;|&()<>=,{}[]".contains(c)) + .filter(|word| !word.is_empty()) +} + +/// A word as a path inside the project, or None for absolute paths and paths that leave it. +pub(crate) fn project_path(word: &str) -> Option { + let path = Path::new(word.strip_prefix("./").unwrap_or(word)); + let mut parts = Vec::new(); + for component in path.components() { + match component { + Component::Normal(part) => parts.push(part.to_str()?), + Component::CurDir => {} + _ => return None, + } + } + (!parts.is_empty()).then(|| parts.join("/")) +} + +#[cfg(test)] +mod tests { + use super::{project_path, words}; + + #[test] + fn words_split_on_shell_punctuation() { + let found: Vec<&str> = + words("FOO=1 ./bin/run --config=ci/a.yml; require('./x.js')").collect(); + assert_eq!( + found, + vec![ + "FOO", + "1", + "./bin/run", + "--config", + "ci/a.yml", + "require", + "./x.js" + ] + ); + } + + #[test] + fn paths_stay_inside_the_project() { + assert_eq!( + project_path("./scripts/a.sh").as_deref(), + Some("scripts/a.sh") + ); + assert_eq!(project_path("/etc/passwd"), None); + assert_eq!(project_path("../outside"), None); + assert_eq!(project_path("a/../../b"), None); + } +} diff --git a/src/inputs.rs b/src/inputs/mod.rs similarity index 56% rename from src/inputs.rs rename to src/inputs/mod.rs index 9e34fcf..4ff7965 100644 --- a/src/inputs.rs +++ b/src/inputs/mod.rs @@ -10,53 +10,33 @@ //! `require('./.github/wait-for-checks.js')`. A local action (`uses: ./path`) brings every file //! in its directory. Files those files mention are not followed. //! - **Toolchain pins and lockfiles** in the project root (`rust-toolchain.toml`, `.ruby-version`, -//! `Cargo.lock`, `pnpm-lock.yaml`, and so on), `package.json`'s `packageManager`, and every -//! tracked `package.json` (its scripts are what `npm run` runs), for every job: cigen can't -//! tell which tools a step runs. +//! `Cargo.lock`, `pnpm-lock.yaml`, and so on), `package.json`'s `packageManager` and every +//! tracked `package.json` (its scripts are what `npm run` runs), by toolchain family +//! (`families`). Every job gets every family unless it sets `narrow_inputs`; +//! a narrowed job gets the families it visibly uses (`narrow`), with their files in each +//! directory their commands ran in and the directories above. `.tool-versions` and mise's +//! config files pin any tool, so every job gets them. //! - **Modules**: each module's resolved parameters and its steps for every provider, and the //! files it contributes (see `crate::modules`). +mod families; +mod files; +mod narrow; mod packages; +mod shell; + +pub use families::{FAMILIES, Family, SHARED_PINS, family}; +use files::files_named; +pub(crate) use files::project_path; +pub use narrow::FamilyChoice; use crate::schema::{CigenConfig, Job}; use anyhow::{Context, Result}; use packages::{PACKAGE_FILES, package_manager}; use serde::Serialize; -use serde_json::{Map, Value}; +use serde_json::Value; use std::collections::BTreeSet; -use std::path::{Component, Path}; - -/// Toolchain version files, hashed into every job that has them in its project root. -pub const TOOLCHAIN_PINS: &[&str] = &[ - ".go-version", - ".java-version", - ".mise.toml", - ".node-version", - ".nvmrc", - ".python-version", - ".ruby-version", - ".terraform-version", - ".tool-versions", - "mise.toml", - "rust-toolchain", - "rust-toolchain.toml", -]; - -/// Lockfiles, hashed into every job that has them in its project root. -pub const LOCKFILES: &[&str] = &[ - "Cargo.lock", - "Gemfile.lock", - "Pipfile.lock", - "bun.lock", - "bun.lockb", - "composer.lock", - "go.sum", - "package-lock.json", - "pnpm-lock.yaml", - "poetry.lock", - "uv.lock", - "yarn.lock", -]; +use std::path::Path; /// What a job depends on beyond its declared `inputs`. #[derive(Debug, Default, PartialEq)] @@ -70,6 +50,8 @@ pub struct Derived { pub patterns: Vec, /// The digest of the job's module expansions (see `crate::modules::for_job`). pub modules_digest: String, + /// Each toolchain family, whether the job gets its files, and why. + pub families: Vec, } /// The inputs `job_id` depends on beyond its declared `inputs`. `project_root` is the directory @@ -106,10 +88,28 @@ pub fn derive(config: &CigenConfig, job_id: &str, project_root: &Path) -> Result derived.config.extend(modules.entries); derived.patterns = modules.inputs; derived.modules_digest = modules.digest; - derived - .patterns - .extend(PACKAGE_FILES.iter().map(|p| p.to_string())); - if let Some(manager) = package_manager(project_root)? { + let narrow_inputs = job.narrow_inputs.unwrap_or(config.narrow_inputs); + let choices = narrow::choose(config, job, &commands, project_root, narrow_inputs)?; + derived.families = choices.families; + let included = |name: &str| { + derived + .families + .iter() + .any(|choice| choice.family == name && choice.included) + }; + if narrow_inputs { + derived + .config + .push(("narrow_inputs".to_string(), "true".to_string())); + } + if included("node") { + derived + .patterns + .extend(PACKAGE_FILES.iter().map(|p| p.to_string())); + } + if included("node") + && let Some(manager) = package_manager(project_root)? + { derived .config .push(("package.json:packageManager".to_string(), manager)); @@ -124,15 +124,45 @@ pub fn derive(config: &CigenConfig, job_id: &str, project_root: &Path) -> Result for value in &steps { files_named(value, project_root, &mut files)?; } - for pin in TOOLCHAIN_PINS.iter().chain(LOCKFILES) { - if project_root.join(pin).is_file() { - files.insert((*pin).to_string()); + files.extend(choices.files_read.iter().cloned()); + // Pins and lockfiles in the root, and in each directory a family's commands ran in and the + // directories above it, where the toolchain looks for them too. + let mut pins: BTreeSet<(String, &str)> = BTreeSet::new(); + for family in FAMILIES.iter().filter(|family| included(family.name)) { + let dirs = choices + .family_dirs + .iter() + .filter(|(name, _)| *name == family.name) + .flat_map(|(_, dir)| ancestors(dir)); + for dir in std::iter::once(String::new()).chain(dirs) { + for pin in family.files.iter().chain(SHARED_PINS) { + pins.insert((dir.clone(), pin)); + } + } + } + for pin in SHARED_PINS { + pins.insert((String::new(), pin)); + } + for (dir, pin) in pins { + let path = if dir.is_empty() { + (*pin).to_string() + } else { + format!("{dir}/{pin}") + }; + if project_root.join(&path).is_file() { + files.insert(path); } } derived.files = files.into_iter().collect(); Ok(derived) } +/// `dir` and the directories above it, short of the root: `web/app` gives `web/app` and `web`. +fn ancestors(dir: &str) -> Vec { + let parts: Vec<&str> = dir.split('/').filter(|part| !part.is_empty()).collect(); + (1..=parts.len()).map(|n| parts[..n].join("/")).collect() +} + /// Commands the job's steps use, directly or through other commands. A step uses a command by /// naming it, as a string (`- setup_db`) or a key (`- setup_db: {…}`); any string or key that /// matches a command's name counts, wherever it is in the steps. @@ -167,79 +197,6 @@ fn strings_and_keys(value: &Value, out: &mut BTreeSet) { } } -/// Adds every file in the project that a string in `value` names. -fn files_named(value: &Value, root: &Path, files: &mut BTreeSet) -> Result<()> { - match value { - Value::String(text) => { - for word in words(text) { - let Some(relative) = project_path(word) else { - continue; - }; - let path = root.join(&relative); - if path.is_file() { - files.insert(relative); - } - } - } - Value::Array(items) => { - for item in items { - files_named(item, root, files)?; - } - } - Value::Object(map) => { - local_action(map, root, files)?; - for item in map.values() { - files_named(item, root, files)?; - } - } - _ => {} - } - Ok(()) -} - -/// `uses: ./path/to/action` depends on every file in the action's directory. -fn local_action(map: &Map, root: &Path, files: &mut BTreeSet) -> Result<()> { - let Some(Value::String(uses)) = map.get("uses") else { - return Ok(()); - }; - let Some(relative) = uses.strip_prefix("./").and_then(project_path) else { - return Ok(()); - }; - let dir = root.join(&relative); - if !dir.is_dir() { - return Ok(()); - } - for entry in walkdir::WalkDir::new(&dir).sort_by_file_name() { - let entry = entry?; - if entry.file_type().is_file() { - let path = entry.path().strip_prefix(root)?; - files.insert(path.to_string_lossy().replace('\\', "/")); - } - } - Ok(()) -} - -/// The words of a step's text: split on whitespace, quotes and shell punctuation, so -/// `FOO=1 ./bin/run --config=ci/a.yml` gives `./bin/run` and `ci/a.yml`. -fn words(text: &str) -> impl Iterator { - text.split(|c: char| c.is_whitespace() || "'\"`;|&()<>=,{}[]".contains(c)) - .filter(|word| !word.is_empty()) -} - -/// A word as a path inside the project, or None for absolute paths and paths that leave it. -pub(crate) fn project_path(word: &str) -> Option { - let path = Path::new(word.strip_prefix("./").unwrap_or(word)); - let mut parts = Vec::new(); - for component in path.components() { - match component { - Component::Normal(part) => parts.push(part.to_str()?), - Component::CurDir => {} - _ => return None, - } - } - (!parts.is_empty()).then(|| parts.join("/")) -} - /// JSON with object keys sorted, so equal values always hash the same. pub fn canonical_json(value: &impl Serialize) -> Result { let value = sort_keys(serde_json::to_value(value)?); @@ -258,37 +215,3 @@ fn sort_keys(value: Value) -> Value { other => other, } } - -#[cfg(test)] -mod tests { - use super::{project_path, words}; - - #[test] - fn words_split_on_shell_punctuation() { - let found: Vec<&str> = - words("FOO=1 ./bin/run --config=ci/a.yml; require('./x.js')").collect(); - assert_eq!( - found, - vec![ - "FOO", - "1", - "./bin/run", - "--config", - "ci/a.yml", - "require", - "./x.js" - ] - ); - } - - #[test] - fn paths_stay_inside_the_project() { - assert_eq!( - project_path("./scripts/a.sh").as_deref(), - Some("scripts/a.sh") - ); - assert_eq!(project_path("/etc/passwd"), None); - assert_eq!(project_path("../outside"), None); - assert_eq!(project_path("a/../../b"), None); - } -} diff --git a/src/inputs/narrow.rs b/src/inputs/narrow.rs new file mode 100644 index 0000000..5980e8b --- /dev/null +++ b/src/inputs/narrow.rs @@ -0,0 +1,245 @@ +//! Which toolchain families' files a job gets, and why. Every job gets every family unless it +//! sets `narrow_inputs: true`; a module always adds its own. A narrowed job gets the families +//! of its modules and of the commands it visibly runs, and every family when it runs anything +//! cigen can't see into. +use super::families::FAMILIES; +use super::shell::{Reader, Seen, StepDir, is_shell, packages}; +use crate::schema::{CigenConfig, Job, RunCommand, Step}; +use anyhow::Result; +use serde_yaml::Value; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +mod actions; +mod defaults; + +use actions::read_action; + +/// Which families a job gets, and the files cigen read to decide. +#[derive(Debug, Default, PartialEq)] +pub struct Choices { + pub families: Vec, + /// Scripts and `package.json` files read for a narrowed job, relative to the project root. + pub files_read: BTreeSet, + /// Each family a narrowed job runs and the directories it runs in, relative to the root. + pub family_dirs: BTreeSet<(&'static str, String)>, +} + +/// Whether a job gets a family's files, and why. +#[derive(Debug, Clone, PartialEq)] +pub struct FamilyChoice { + pub family: &'static str, + pub included: bool, + pub reason: String, +} + +/// CircleCI steps that read no toolchain's files. +const NEUTRAL_CIRCLECI_STEPS: &[&str] = &[ + "add_ssh_keys", + "attach_workspace", + "checkout", + "persist_to_workspace", + "restore_cache", + "save_cache", + "setup_remote_docker", + "store_artifacts", + "store_test_results", +]; + +pub fn choose( + config: &CigenConfig, + job: &Job, + commands: &BTreeSet, + root: &Path, + narrow: bool, +) -> Result { + let mut declared: BTreeMap<&str, String> = BTreeMap::new(); + for module in &job.modules { + let spec = crate::modules::spec(&module.name)?; + declared + .entry(spec.family) + .or_insert_with(|| format!("module `{}`", module.name)); + } + for name in &job.toolchains { + if let Some(family) = super::families::family(name) { + declared + .entry(family.name) + .or_insert_with(|| "it's listed in the job's `toolchains`".to_string()); + } + } + let mut files_read = BTreeSet::new(); + let mut family_dirs = BTreeSet::new(); + let seen = if narrow { + let mut reader = Reader::new(root); + let defaults = defaults::for_job(config, job); + if let Some(shell) = defaults.shell.iter().find(|shell| !is_shell(shell)) { + reader.opaque(format!("steps in `shell: {shell}`")); + } + if let Some(why) = &defaults.unreadable_runner { + reader.opaque(why.clone()); + } + let context = Context { + commands, + root, + dir: defaults + .dir + .as_deref() + .map_or(StepDir::Root, StepDir::Named), + }; + read_steps(&mut reader, &job.steps, "a step", &context); + for name in commands { + let origin = format!("command `{name}`"); + read_steps(&mut reader, &config.commands[name].steps, &origin, &context); + } + if reader + .seen + .iter() + .any(|seen| matches!(seen, Seen::Family("node", _))) + { + read_package_scripts(&mut reader, root)?; + } + files_read = reader.files_read().clone(); + family_dirs = std::mem::take(&mut reader.dirs); + reader.seen + } else { + Vec::new() + }; + let opaque = seen.iter().find_map(|seen| match seen { + Seen::Opaque(why) => Some(why.clone()), + Seen::Family(..) => None, + }); + let families = FAMILIES + .iter() + .map(|family| { + let name = family.name; + let used = seen.iter().find_map(|seen| match seen { + Seen::Family(found, where_) if *found == name => Some(where_.clone()), + _ => None, + }); + let (included, reason) = if let Some(module) = declared.get(name) { + (true, module.clone()) + } else if !narrow { + ( + true, + "every job gets every toolchain's files unless it sets `narrow_inputs: true`" + .to_string(), + ) + } else if let Some(where_) = used { + (true, format!("it runs {where_}")) + } else if let Some(why) = &opaque { + (true, format!("it runs {why}")) + } else { + (false, "narrowed: nothing the job runs uses it".to_string()) + }; + FamilyChoice { + family: name, + included, + reason, + } + }) + .collect(); + Ok(Choices { + families, + files_read, + family_dirs, + }) +} + +/// What every step of a job shares. +struct Context<'a> { + commands: &'a BTreeSet, + root: &'a Path, + /// The job's default working directory (GitHub's `defaults.run.working-directory`). + dir: StepDir<'a>, +} + +fn read_steps(reader: &mut Reader, steps: &[Step], origin: &str, context: &Context) { + for step in steps { + match step { + Step::Run(run) => { + let mut keys = run.extra.clone(); + if let RunCommand::Options(options) = &run.run { + keys.extend(options.extra.clone()); + } + read_run(reader, run.run.command(), origin, &keys, context.dir); + } + Step::Uses(uses) => read_action(reader, &uses.uses, context.root, &mut BTreeSet::new()), + Step::RestoreCache { .. } | Step::SaveCache { .. } => {} + Step::Custom(value) => read_custom(reader, value, origin, context.commands), + } + } +} + +/// A run step: its `shell:` must be a POSIX shell for cigen to read it, and it runs in its own +/// working directory, or the job's. +pub(super) fn read_run( + reader: &mut Reader, + command: &str, + origin: &str, + keys: &BTreeMap, + default_dir: StepDir, +) { + if let Some(shell) = keys.get("shell") { + match shell.as_str() { + Some(shell) if is_shell(shell) => {} + _ => return reader.opaque(format!("a step in {origin} with `shell: {}`", yaml(shell))), + } + } + let dir = ["working-directory", "working_directory"] + .iter() + .find_map(|key| keys.get(*key)); + match dir { + None => reader.step(command, origin, default_dir), + Some(Value::String(dir)) => reader.step(command, origin, StepDir::Named(dir)), + Some(other) => reader.opaque(format!( + "a step in {origin} with `working-directory: {}`", + yaml(other) + )), + } +} + +fn yaml(value: &Value) -> String { + serde_yaml::to_string(value) + .unwrap_or_default() + .trim() + .to_string() +} + +/// A step only one provider understands, or a command used by name. +fn read_custom(reader: &mut Reader, value: &Value, origin: &str, commands: &BTreeSet) { + let name = match value { + Value::String(name) => Some(name.as_str()), + Value::Mapping(map) if map.len() == 1 => map.keys().next().and_then(Value::as_str), + _ => None, + }; + if let Some(name) = name + && (commands.contains(name) || NEUTRAL_CIRCLECI_STEPS.contains(&name)) + { + return; // a used command's steps are read on their own + } + if let (Some(Value::String(run)), Value::Mapping(map)) = (value.get("run"), value) { + let keys = map + .iter() + .filter_map(|(key, value)| Some((key.as_str()?.to_string(), value.clone()))) + .collect(); + return read_run(reader, run, origin, &keys, StepDir::Root); + } + reader.opaque(format!("a step cigen doesn't know in {origin}")); +} + +/// `pnpm build` runs whatever the `build` script says, in whichever package it runs in, so a +/// job that runs a Node package manager also runs every script of every `package.json` in the +/// project, each in its own directory. +fn read_package_scripts(reader: &mut Reader, root: &Path) -> Result<()> { + for package in packages(root)? { + reader.mark_read(&package.relative); + for (name, script) in package.scripts { + let origin = format!("the `{name}` script in `{}`", package.relative); + match script { + Some(text) => reader.step(&text, &origin, StepDir::Named(&package.dir)), + None => reader.opaque(origin), + } + } + } + Ok(()) +} diff --git a/src/inputs/narrow/actions.rs b/src/inputs/narrow/actions.rs new file mode 100644 index 0000000..d6dee1e --- /dev/null +++ b/src/inputs/narrow/actions.rs @@ -0,0 +1,84 @@ +//! GitHub actions in a narrowed job: known actions by name, local composite actions by their +//! steps, and anything else is opaque. +use super::read_run; +use crate::inputs::shell::{Reader, Seen, StepDir}; +use serde_yaml::Value; +use std::collections::BTreeSet; +use std::path::Path; + +/// GitHub actions cigen knows: `None` reads no toolchain's files, `Some` sets one up. +const KNOWN_ACTIONS: &[(&str, Option<&str>)] = &[ + ("actions/cache", None), + ("actions/cache/restore", None), + ("actions/cache/save", None), + ("actions/checkout", None), + ("actions/download-artifact", None), + ("actions/upload-artifact", None), + ("actions-rust-lang/setup-rust-toolchain", Some("rust")), + ("actions/setup-go", Some("go")), + ("actions/setup-java", Some("java")), + ("actions/setup-node", Some("node")), + ("actions/setup-python", Some("python")), + ("dtolnay/rust-toolchain", Some("rust")), + ("oven-sh/setup-bun", Some("node")), + ("pnpm/action-setup", Some("node")), + ("ruby/setup-ruby", Some("ruby")), + ("Swatinem/rust-cache", Some("rust")), +]; + +/// A GitHub action: known ones by name, a local composite action by its steps. +pub(super) fn read_action( + reader: &mut Reader, + uses: &str, + root: &Path, + visited: &mut BTreeSet, +) { + if let Some(local) = uses.strip_prefix("./") { + return read_local_action(reader, local, root, visited); + } + let name = uses.split('@').next().unwrap_or(uses); + match KNOWN_ACTIONS.iter().find(|(known, _)| *known == name) { + Some((_, None)) => {} + Some((_, Some(family))) => reader + .seen + .push(Seen::Family(family, format!("the `{name}` action"))), + None => reader.opaque(format!("the `{name}` action, which cigen can't see into")), + } +} + +fn read_local_action(reader: &mut Reader, path: &str, root: &Path, visited: &mut BTreeSet) { + if !visited.insert(path.to_string()) { + return; + } + let definition = ["action.yml", "action.yaml"] + .iter() + .map(|file| root.join(path).join(file)) + .find(|file| file.is_file()) + .and_then(|file| std::fs::read_to_string(file).ok()) + .and_then(|text| serde_yaml::from_str::(&text).ok()); + let runs = definition.as_ref().and_then(|action| action.get("runs")); + let composite = runs + .and_then(|runs| runs.get("using")) + .and_then(Value::as_str) + == Some("composite"); + let Some(Value::Sequence(steps)) = runs + .and_then(|runs| runs.get("steps")) + .filter(|_| composite) + else { + return reader.opaque(format!( + "the local action `./{path}`, which isn't a composite action" + )); + }; + let origin = format!("the local action `./{path}`"); + for step in steps { + if let (Some(Value::String(run)), Value::Mapping(map)) = (step.get("run"), step) { + let keys = map + .iter() + .filter_map(|(key, value)| Some((key.as_str()?.to_string(), value.clone()))) + .collect(); + read_run(reader, run, &origin, &keys, StepDir::Root); + } else if let Some(Value::String(uses)) = step.get("uses") { + read_action(reader, uses, root, visited); + } + } +} diff --git a/src/inputs/narrow/defaults.rs b/src/inputs/narrow/defaults.rs new file mode 100644 index 0000000..220211f --- /dev/null +++ b/src/inputs/narrow/defaults.rs @@ -0,0 +1,97 @@ +//! A job's default shell and working directory for its run steps, from the provider blocks: +//! GitHub's `defaults.run` (job, then workflow, then top level) and a CircleCI job's `shell`, +//! and whether it runs somewhere whose steps cigen can't read (a Windows runner). +//! +//! A CircleCI job's `working_directory` needs nothing: the checkout goes there, so the job's +//! commands start in the project root either way. +use crate::schema::{CigenConfig, Job}; +use serde_yaml::{Mapping, Value}; + +pub struct Defaults { + /// Every default shell a provider gives the job's steps. + pub shell: Vec, + /// The default working directory, as written. + pub dir: Option, + /// Why cigen can't read the job's steps at all, if it can't. + pub unreadable_runner: Option, +} + +pub fn for_job(config: &CigenConfig, job: &Job) -> Defaults { + let workflow = job + .workflow + .as_ref() + .and_then(|name| config.workflows.get(name)) + .and_then(|workflow| workflow.github.as_ref()); + let github = [job.github.as_ref(), workflow, config.github.as_ref()]; + let run_default = |key: &str| { + github + .iter() + .flatten() + .find_map(|block| block_value(block, &["defaults", "run", key])) + .map(text) + }; + let mut shell: Vec = run_default("shell").into_iter().collect(); + if let Some(circleci) = job + .circleci + .as_ref() + .and_then(|b| block_value(b, &["shell"])) + { + shell.push(text(circleci)); + } + Defaults { + shell, + dir: run_default("working-directory"), + unreadable_runner: unreadable_runner(job), + } +} + +/// Windows runners run steps in PowerShell by default, and a runner chosen by an expression +/// (a matrix of operating systems) could be one. +fn unreadable_runner(job: &Job) -> Option { + let runs_on = job + .github + .as_ref() + .and_then(|block| block_value(block, &["runs-on"])) + .map_or_else(|| job.image.clone(), text); + let circleci = job + .circleci + .as_ref() + .map(|block| text(&Value::Mapping(block.clone()))) + .unwrap_or_default(); + let circleci = circleci.to_lowercase(); + if runs_on.to_lowercase().contains("windows") + || circleci.contains("windows") + || circleci.contains("win/") + { + Some(format!( + "a Windows runner (`{}`), whose steps run in PowerShell", + runs_on.trim() + )) + } else if runs_on.contains("${{") { + Some(format!( + "a runner chosen by an expression (`{}`), which could be Windows", + runs_on.trim() + )) + } else { + None + } +} + +fn block_value<'a>(block: &'a Mapping, path: &[&str]) -> Option<&'a Value> { + let (first, rest) = path.split_first()?; + let value = block.get(*first)?; + if rest.is_empty() { + return Some(value); + } + block_value(value.as_mapping()?, rest) +} + +fn text(value: &Value) -> String { + match value { + Value::String(text) => text.clone(), + other => serde_yaml::to_string(other) + .unwrap_or_default() + .trim() + .to_string(), + } +} diff --git a/src/inputs/shell/arguments.rs b/src/inputs/shell/arguments.rs new file mode 100644 index 0000000..e370280 --- /dev/null +++ b/src/inputs/shell/arguments.rs @@ -0,0 +1,196 @@ +//! Commands hidden in a neutral command's arguments: the options that run a command +//! (`find -exec`, `git rebase --exec`, awk's `system`, sed's `e`) and settings that name one +//! (`alias`, `git config core.hooksPath`, `export GIT_SSH_COMMAND=`). A toolchain's own +//! commands are in `super::family`. +use super::sed; +use super::subcommands::{GH, GIT}; +use super::words::{GIT_CONFIG_PLAIN, names_a_command}; + +pub(super) enum Arguments<'a> { + /// Nothing hidden. + Plain, + /// Commands to read, each a word list. + Run(Vec<&'a [String]>), + /// Something cigen can't see into: why, after the command's name. + Opaque(&'static str), +} + +pub(super) fn neutral_arguments<'a>(word: &str, args: &'a [String]) -> Arguments<'a> { + match word { + "find" if has_option(args, &["-execdir", "-okdir"]) => { + Arguments::Opaque("runs a command in each file's directory") + } + "find" => { + let runs: Vec<&[String]> = args + .iter() + .enumerate() + .filter(|(_, arg)| matches!(arg.as_str(), "-exec" | "-ok")) + .map(|(index, _)| &args[index + 1..(index + 2).min(args.len())]) + .collect(); + if runs.is_empty() { + Arguments::Plain + } else { + Arguments::Run(runs) + } + } + "git" => git(args), + "gh" => match args.iter().find(|arg| !arg.starts_with('-')) { + Some(sub) if !GH.contains(&sub.as_str()) => { + Arguments::Opaque("runs an alias or extension cigen can't see") + } + _ => Arguments::Plain, + }, + "awk" => { + let script_runs = args.iter().any(|arg| { + !arg.starts_with('-') + && (arg.contains("system") || arg.contains("getline") || arg.contains('|')) + }); + if script_runs || has_option(args, &["-f", "--file", "-E", "--exec", "-i", "--include"]) + { + Arguments::Opaque("runs an awk program that can run commands") + } else { + Arguments::Plain + } + } + "alias" if args.iter().any(|arg| arg.contains('=')) => { + Arguments::Opaque("defines an alias, which can run anything") + } + "export" | "declare" | "typeset" | "readonly" + if args.iter().any(|arg| { + arg.split_once('=') + .is_some_and(|(name, _)| names_a_command(name)) + }) => + { + Arguments::Opaque("sets a variable that names a command to run") + } + "sort" if has_option(args, &["--compress-program"]) => { + Arguments::Opaque("runs a command named in its options") + } + "sed" if !sed::is_plain(args) => { + Arguments::Opaque("runs a sed program that can run commands") + } + "tar" if tar_runs(args) => Arguments::Opaque("runs a command named in its options"), + "rsync" + if has_option(args, &["--rsh", "--rsync-path"]) + || args.iter().any(|arg| { + arg.starts_with('-') && !arg.starts_with("--") && arg.contains('e') + }) => + { + Arguments::Opaque("runs a command named in its options") + } + "ssh" | "scp" + if has_option(args, &["-F", "-S"]) + || args + .iter() + .any(|arg| arg.contains("Command") || arg.contains("Match")) => + { + Arguments::Opaque("runs a local command named in its options") + } + _ => Arguments::Plain, + } +} + +fn git(args: &[String]) -> Arguments<'_> { + let mut index = 0; + while let Some(arg) = args.get(index) { + match arg.as_str() { + "-C" | "--git-dir" | "--work-tree" | "--namespace" => index += 2, + "-c" | "--config-env" => { + return Arguments::Opaque("sets config, which can name commands to run"); + } + arg if arg.starts_with("--exec-path") || arg.starts_with("--config-env") => { + return Arguments::Opaque("sets config, which can name commands to run"); + } + arg if arg.starts_with('-') => index += 1, + _ => break, + } + } + let Some(sub) = args.get(index).map(String::as_str) else { + return Arguments::Plain; + }; + let rest = &args[index + 1..]; + let first = rest.first().map(String::as_str); + let runs = match sub { + _ if !GIT.contains(&sub) => true, + "submodule" => first == Some("foreach"), + "config" => config_names_a_command(rest), + "bisect" => first == Some("run"), + "rebase" => rest + .iter() + .any(|arg| arg == "-x" || arg.starts_with("--exec") || arg == "-i"), + "grep" => rest + .iter() + .any(|arg| arg.starts_with("-O") || arg.starts_with("--open-files-in-pager")), + _ => false, + }; + if runs { + Arguments::Opaque("runs an alias or a command named in its arguments") + } else { + Arguments::Plain + } +} + +/// `git config ` setting a key that can name a command (`core.hooksPath`, +/// `alias.*`, `core.pager`): any key that isn't known to be plain. +fn config_names_a_command(args: &[String]) -> bool { + let reads = [ + "--get", + "--get-all", + "--get-regexp", + "--list", + "-l", + "--unset", + "--unset-all", + "--name-only", + "--show-origin", + ]; + if args.iter().any(|arg| reads.contains(&arg.as_str())) { + return false; + } + let positionals: Vec<&String> = args.iter().filter(|arg| !arg.starts_with('-')).collect(); + let [key, _value, ..] = positionals.as_slice() else { + return false; // reading a key + }; + let key = key.to_lowercase(); + !GIT_CONFIG_PLAIN + .iter() + .any(|plain| key == *plain || (plain.ends_with('.') && key.starts_with(plain))) +} + +/// tar's options that run a program: `--to-command`, `-I`/`--use-compress-program`, scripts. +fn tar_runs(args: &[String]) -> bool { + let long = [ + "--to-command", + "--use-compress-program", + "--checkpoint-action", + "--info-script", + "--new-volume-script", + "--rsh-command", + "--rmt-command", + ]; + args.iter().enumerate().any(|(index, arg)| { + long.iter().any(|option| arg.starts_with(option)) + || (arg.starts_with('-') && !arg.starts_with("--") && arg.contains(['I', 'F'])) + || (index == 0 && !arg.starts_with('-') && arg.contains(['I', 'F'])) + }) +} + +/// Whether any argument is one of `options`, or one of them with its value attached. +pub(super) fn has_option(args: &[String], options: &[&str]) -> bool { + args.iter().any(|arg| { + options.iter().any(|option| { + arg == option + || (option.starts_with("--") && arg.starts_with(&format!("{option}="))) + || (!option.starts_with("--") && arg.starts_with(option) && arg.len() > 2) + }) + }) +} + +/// The words from the first that isn't an option (or `--`). +pub(super) fn after_flags(args: &[String]) -> &[String] { + let start = args + .iter() + .position(|arg| !arg.starts_with('-')) + .unwrap_or(args.len()); + &args[start..] +} diff --git a/src/inputs/shell/commands.rs b/src/inputs/shell/commands.rs new file mode 100644 index 0000000..66318a8 --- /dev/null +++ b/src/inputs/shell/commands.rs @@ -0,0 +1,126 @@ +//! What one command runs: a family's command (and the commands its runners run), a shell, a +//! `cd`, a sourced script, a neutral command (and the commands hidden in its arguments), or +//! something cigen can't see into. +use super::arguments::{Arguments, neutral_arguments}; +use super::family::{Dir, plan}; +use super::words::{NEUTRAL, SHELLS}; +use super::{Reader, Seen, family_of_command}; + +impl Reader<'_> { + pub(super) fn command(&mut self, word: &str, args: &[String], origin: &str) { + if word.starts_with('$') { + return self.opaque(format!("a command from a variable (`{word}`) in {origin}")); + } + if let Some(family) = family_of_command(word) { + return self.family_command(family.name, word, args, origin); + } + if SHELLS.contains(&word) { + return self.shell(word, args, origin); + } + match word { + "cd" if self.unsure_of_cd => { + // In a subshell or a function, a `cd` may or may not carry on. + self.cwd = None; + return; + } + "cd" => return self.change_directory(args), + "pushd" | "popd" => { + self.cwd = None; + return; + } + "source" | "." => { + return match args.first() { + Some(file) => self.file(file, origin, false), + None => self.opaque(format!("`{word}` without a file in {origin}")), + }; + } + _ => {} + } + if NEUTRAL.contains(&word) { + return self.arguments(neutral_arguments(word, args), word, origin); + } + // A bare word runs from `PATH`, even when a file of that name is in the directory. + if word.contains('/') { + return self.file(word, origin, true); + } + self.opaque(format!("`{word}` in {origin}, which cigen can't see into")); + } + + /// A toolchain's command: its family counts however it was written (`\cargo`), its pins + /// count in the directory it works in, and the commands it runs are read there. + fn family_command(&mut self, family: &'static str, word: &str, args: &[String], origin: &str) { + self.seen + .push(Seen::Family(family, format!("`{word}` in {origin}"))); + // Only these run a package script by its bare name; reading the names makes the + // `package.json` files inputs. + let scripts = if matches!(word, "pnpm" | "yarn" | "bun") { + self.package_scripts() + } else { + Default::default() + }; + let plan = plan(word, args, &scripts); + let outside = self.cwd.clone(); + match plan.dir { + Dir::Here => {} + Dir::Named(dir) => self.change_directory(&[dir.to_string()]), + Dir::Of(manifest) => { + let dir = manifest.rsplit_once('/').map_or(".", |(dir, _)| dir); + self.change_directory(&[dir.to_string()]); + } + } + match self.cwd.clone() { + Some(dir) => { + self.dirs.insert((family, dir)); + self.arguments(plan.arguments, word, origin); + } + None => self.opaque(format!( + "`{word}` in {origin}, working in a directory cigen can't follow, so it can't tell \ + which pins and lockfiles it reads" + )), + } + self.cwd = outside; + } + + fn arguments(&mut self, arguments: Arguments, word: &str, origin: &str) { + match arguments { + Arguments::Plain => {} + Arguments::Run(commands) => { + for command in commands { + match command.split_first() { + Some((first, rest)) => self.command(first, rest, origin), + None => self.opaque(format!( + "`{word}` in {origin}, running a command cigen can't find" + )), + } + } + } + Arguments::Opaque(why) => self.opaque(format!("`{word}` {why} in {origin}")), + } + } + + /// `sh script.sh` reads the script; `sh -c`, `bash -lc` and a shell reading its input run + /// text cigen doesn't have. + fn shell(&mut self, shell: &str, args: &[String], origin: &str) { + let mut index = 0; + while index < args.len() { + let arg = args[index].as_str(); + if arg == "-c" || (is_short_flags(arg) && arg.contains(['c', 's'])) { + return self.opaque(format!("`{shell} {arg}` in {origin}")); + } + match arg { + "-o" | "+o" | "-O" | "+O" => index += 2, + "--rcfile" | "--init-file" => { + return self.opaque(format!("`{shell} {arg}` in {origin}")); + } + _ if arg.starts_with(['-', '+']) => index += 1, + file => return self.file(file, origin, true), + } + } + self.opaque(format!("`{shell}` reading its input in {origin}")) + } +} + +/// `-eu`, `-lc`: single-letter flags run together. +fn is_short_flags(arg: &str) -> bool { + arg.len() > 1 && arg.starts_with('-') && !arg.starts_with("--") +} diff --git a/src/inputs/shell/family.rs b/src/inputs/shell/family.rs new file mode 100644 index 0000000..0bfd8fb --- /dev/null +++ b/src/inputs/shell/family.rs @@ -0,0 +1,218 @@ +//! A toolchain's own command: the directory it works in, and the commands it runs for the job. +//! Runners (`bundle exec`, `npx`, `rustup run`) run the command after them; pnpm, Yarn and Bun +//! run a word that isn't their own subcommand or a package script as a command; subcommands +//! that run project code (`cargo xtask`, `go generate`) are opaque. +use super::arguments::{Arguments, after_flags, has_option}; +use super::subcommands::{BUN, CARGO, COREPACK, GO, PNPM, YARN}; +use std::collections::BTreeSet; + +/// What a family's command does. +pub(super) struct Plan<'a> { + pub dir: Dir<'a>, + pub arguments: Arguments<'a>, +} + +/// Where a family's command works, relative to where it's run. +pub(super) enum Dir<'a> { + Here, + /// A directory an option names (`yarn --cwd web`, `terraform -chdir=infra`). + Named(&'a str), + /// The directory of a manifest an option names (`cargo --manifest-path sub/Cargo.toml`). + Of(&'a str), +} + +/// Subcommands that run the command after them, and how many words (a toolchain) come first. +const RUNNERS: &[(&str, &[&str], usize)] = &[ + ("bun", &["exec", "x"], 0), + ("bundle", &["exec"], 0), + ("bundler", &["exec"], 0), + ("gem", &["exec"], 0), + ("npm", &["exec", "x"], 0), + ("pipenv", &["run"], 0), + ("pnpm", &["dlx", "exec"], 0), + ("poetry", &["run"], 0), + ("rustup", &["run"], 1), + ("uv", &["run"], 0), + ("yarn", &["dlx", "exec"], 0), +]; + +/// Family commands whose first word is the command they run. +const WHOLE_RUNNERS: &[&str] = &["bunx", "npx", "pnpx", "uvx"]; + +/// Options naming the directory a tool works in. +const DIR_OPTIONS: &[(&str, &[&str])] = &[ + ("bun", &["--cwd"]), + ("go", &["-C"]), + ("gradle", &["-p", "--project-dir"]), + ("npm", &["--prefix"]), + ("pnpm", &["-C", "--dir"]), + ("poetry", &["-C", "--directory", "-P", "--project"]), + ("terraform", &["-chdir"]), + ("uv", &["--directory", "--project"]), + ("yarn", &["--cwd"]), +]; + +/// Options naming a manifest file, whose directory the tool works in. +const MANIFEST_OPTIONS: &[(&str, &[&str])] = + &[("cargo", &["--manifest-path"]), ("mvn", &["-f", "--file"])]; + +/// Options that pick packages for the tool to run in: cigen can't tell which directories. +const FILTERS: &[&str] = &[ + "--filter", + "--filter-prod", + "-F", + "-r", + "--recursive", + "--workspace", + "-w", + "--workspaces", + "-ws", + "workspace", + "workspaces", +]; + +/// Options whose value is the next word. +const VALUED: &[&str] = &[ + "--cwd", + "--dir", + "--directory", + "--filter", + "--filter-prod", + "--prefix", + "--project", + "-C", + "-F", + "-P", + "--workspace", +]; + +pub(super) fn plan<'a>(word: &str, args: &'a [String], scripts: &BTreeSet) -> Plan<'a> { + let dir = DIR_OPTIONS + .iter() + .find(|(tool, _)| *tool == word) + .and_then(|(_, options)| option_value(args, options)) + .map(Dir::Named) + .or_else(|| { + MANIFEST_OPTIONS + .iter() + .find(|(tool, _)| *tool == word) + .and_then(|(_, options)| option_value(args, options)) + .map(Dir::Of) + }) + .unwrap_or(Dir::Here); + Plan { + dir, + arguments: arguments(word, args, scripts), + } +} + +fn arguments<'a>(word: &str, args: &'a [String], scripts: &BTreeSet) -> Arguments<'a> { + if WHOLE_RUNNERS.contains(&word) { + return Arguments::Run(vec![after_flags(args)]); + } + if let Some((_, subcommands, skip)) = RUNNERS.iter().find(|(runner, ..)| *runner == word) + && let Some(index) = args + .iter() + .position(|arg| subcommands.contains(&arg.as_str())) + { + if args.iter().any(|arg| is_filter(arg)) { + return Arguments::Opaque( + "runs a command in packages it picks, which cigen can't tell", + ); + } + return Arguments::Run(vec![after_positionals(&args[index + 1..], *skip)]); + } + let positionals = positionals(args); + let subcommand = positionals.first().map(|index| args[*index].as_str()); + if let Some(plugin) = word.strip_prefix("cargo-") { + return cargo(plugin); + } + match (word, subcommand) { + ("corepack", Some(sub)) if !COREPACK.contains(&sub) => { + Arguments::Run(vec![after_flags(args)]) + } + ("cargo", Some(sub)) => cargo(sub), + ("go", Some(sub)) if !GO.contains(&sub) => { + Arguments::Opaque("runs a subcommand that runs code cigen can't see") + } + ("go", _) if has_option(args, &["-exec", "-toolexec", "-vettool"]) => { + Arguments::Opaque("runs a tool named in its options") + } + ("pnpm" | "yarn" | "bun", Some(_)) => { + // `yarn workspace ` runs in that package. + let mut index = positionals[0]; + if word == "yarn" && args[index] == "workspace" { + match positionals.get(2) { + Some(third) => index = *third, + None => return Arguments::Plain, + } + } + let own = match word { + "pnpm" => PNPM, + "yarn" => YARN, + _ => BUN, + }; + let sub = args[index].as_str(); + let a_file_bun_runs = word == "bun" && sub.contains(['.', '/']); + if own.contains(&sub) || scripts.contains(sub) || a_file_bun_runs { + Arguments::Plain + } else { + Arguments::Run(vec![&args[index..]]) + } + } + _ => Arguments::Plain, + } +} + +fn cargo<'a>(sub: &str) -> Arguments<'a> { + if CARGO.contains(&sub) { + Arguments::Plain + } else { + Arguments::Opaque("runs a subcommand or alias that runs code cigen can't see") + } +} + +fn is_filter(arg: &str) -> bool { + FILTERS + .iter() + .any(|filter| arg == *filter || arg.starts_with(&format!("{filter}="))) +} + +/// The indexes of the words that aren't options or their values. +fn positionals(args: &[String]) -> Vec { + let mut found = Vec::new(); + let mut index = 0; + while let Some(arg) = args.get(index) { + if VALUED.contains(&arg.as_str()) { + index += 2; + continue; + } + if !arg.starts_with(['-', '+']) { + found.push(index); + } + index += 1; + } + found +} + +/// The command after `skip` leading words (a toolchain), past any options. +fn after_positionals(args: &[String], skip: usize) -> &[String] { + let mut rest = after_flags(args); + for _ in 0..skip { + rest = after_flags(rest.get(1..).unwrap_or(&[])); + } + rest +} + +/// The value of the first of `options`: `--opt value` or `--opt=value`. +fn option_value<'a>(args: &'a [String], options: &[&str]) -> Option<&'a str> { + args.iter().enumerate().find_map(|(index, arg)| { + options.iter().find_map(|option| { + if arg == option { + args.get(index + 1).map(String::as_str) + } else { + arg.strip_prefix(option)?.strip_prefix('=') + } + }) + }) +} diff --git a/src/inputs/shell/lines.rs b/src/inputs/shell/lines.rs new file mode 100644 index 0000000..193e4a4 --- /dev/null +++ b/src/inputs/shell/lines.rs @@ -0,0 +1,163 @@ +//! Checks on a whole line of shell: heredocs, hidden commands and subshells. + +/// What a line's `<<` is. +#[derive(Debug, PartialEq)] +pub(super) enum Heredoc { + None, + /// A heredoc whose body ends at a line holding `tag`; `quoted` bodies are literal, and + /// `strip_tabs` (`<<-`) allows tabs before the tag. + Start { + tag: String, + quoted: bool, + strip_tabs: bool, + }, + /// Something cigen can't read: an unquoted `<< x >>` (a CircleCI parameter) or a `<<` + /// without a word after it. + Unclear, +} + +/// The heredoc a line starts: an unquoted `< Heredoc { + let chars: Vec = line.chars().collect(); + let mut quote: Option = None; + let mut index = 0; + while index < chars.len() { + let c = chars[index]; + match quote { + Some(open) if c == open => quote = None, + Some('"') if c == '\\' => index += 1, + Some(_) => {} + None if c == '\\' => index += 1, + None if c == '\'' || c == '"' => quote = Some(c), + None if c == '<' && chars.get(index + 1) == Some(&'<') => { + if chars.get(index + 2) == Some(&'<') { + index += 3; + continue; + } + return heredoc_after(&chars[index + 2..]); + } + None => {} + } + index += 1; + } + Heredoc::None +} + +fn heredoc_after(rest: &[char]) -> Heredoc { + let rest: String = rest.iter().collect(); + let (strip_tabs, rest) = match rest.strip_prefix('-') { + Some(after) => (true, after), + None => (false, rest.as_str()), + }; + let rest = rest.trim_start(); + let quoted = rest.starts_with(['\'', '"', '\\']); + let tag: String = rest + .trim_start_matches(['\'', '"', '\\']) + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-' || *c == '.') + .collect(); + let after_tag = rest + .trim_start_matches(['\'', '"', '\\']) + .get(tag.len()..) + .unwrap_or(""); + if tag.is_empty() || after_tag.trim_start().starts_with(">>") { + return Heredoc::Unclear; + } + Heredoc::Start { + tag, + quoted, + strip_tabs, + } +} + +/// Whether a line hides a command where the reader doesn't look: a command substitution +/// inside `${…}` (`${X:-$(make)}`) or a process substitution (`<(make)`, `>(make)`). +pub(super) fn hides_a_command(line: &str) -> bool { + let chars: Vec = line.chars().collect(); + let mut quote: Option = None; + let mut index = 0; + while index < chars.len() { + let c = chars[index]; + let next = chars.get(index + 1).copied(); + match quote { + Some('\'') if c == '\'' => quote = None, + Some('\'') => {} + Some('"') if c == '"' => quote = None, + None if c == '\'' || c == '"' => quote = Some(c), + None if (c == '<' || c == '>') && next == Some('(') => return true, + _ if c == '$' && next == Some('{') => { + let mut depth = 0; + for (offset, inner) in chars[index + 1..].iter().enumerate() { + match inner { + '{' => depth += 1, + '}' => depth -= 1, + '`' => return true, + '(' if chars[index + offset] == '$' => return true, + _ => {} + } + if depth == 0 { + break; + } + } + } + _ => {} + } + index += 1; + } + false +} + +/// Whether a `cd` on this line might run in a subshell, so that it doesn't carry on: the line +/// has parentheses, a command substitution, a backtick, a pipe or a background `&`. +pub(super) fn may_run_in_a_subshell(line: &str) -> bool { + let chars: Vec = line.chars().collect(); + let mut quote: Option = None; + for (index, &c) in chars.iter().enumerate() { + let previous = index.checked_sub(1).map(|i| chars[i]); + let next = chars.get(index + 1).copied(); + match quote { + Some('\'') if c == '\'' => quote = None, + Some('\'') => {} + Some('"') if c == '"' => quote = None, + Some(_) if c == '`' || (c == '$' && next == Some('(')) => return true, + Some(_) => {} + None if c == '\'' || c == '"' => quote = Some(c), + None if c == '(' || c == ')' || c == '`' => return true, + None if c == '|' && previous != Some('|') && next != Some('|') => return true, + None if c == '&' + && previous != Some('&') + && next != Some('&') + && previous != Some('>') + && next != Some('>') => + { + return true; + } + None => {} + } + } + false +} + +/// How many subshells a line opens (positive) or closes (negative), counting unquoted +/// parentheses that aren't part of `$(…)`. +pub(super) fn subshell_change(line: &str) -> i32 { + let chars: Vec = line.chars().collect(); + let mut quote: Option = None; + let mut substitutions = 0; + let mut change = 0; + for (index, &c) in chars.iter().enumerate() { + let previous = index.checked_sub(1).map(|i| chars[i]); + match quote { + Some(open) if c == open => quote = None, + Some(_) => {} + None if c == '\'' || c == '"' => quote = Some(c), + None if c == '(' && previous == Some('$') => substitutions += 1, + None if c == '(' => change += 1, + None if c == ')' && substitutions > 0 => substitutions -= 1, + None if c == ')' => change -= 1, + None => {} + } + } + change +} diff --git a/src/inputs/shell/mod.rs b/src/inputs/shell/mod.rs new file mode 100644 index 0000000..c7ed648 --- /dev/null +++ b/src/inputs/shell/mod.rs @@ -0,0 +1,275 @@ +//! Reading shell text for the commands it runs, to find the toolchains a narrowed job uses. +//! Every misreading errs towards including: a word wrongly taken for a command is unknown, so +//! the job gets every family; a family's command anywhere in the text counts, even outside a +//! command position. +use super::families::family_of_command; +use lines::{Heredoc, heredoc, hides_a_command, may_run_in_a_subshell, subshell_change}; +use segment::Flow; +use std::collections::BTreeSet; +use std::path::Path; +use syntax::{all_words, segments, strip_comment}; + +mod arguments; +mod commands; +mod family; +mod lines; +mod packages; +mod sed; +mod segment; +mod subcommands; +mod syntax; +mod words; + +use words::SHELLS; + +/// What a piece of shell text showed. +#[derive(Debug, Clone, PartialEq)] +pub enum Seen { + /// It runs a family's command: the family and where. + Family(&'static str, String), + /// It runs something cigen can't see into: why. + Opaque(String), +} + +/// Whether `program` (a path or a name, with or without arguments) is a POSIX shell. +pub fn is_shell(program: &str) -> bool { + let first = program.split_whitespace().next().unwrap_or(""); + SHELLS.contains(&first.rsplit('/').next().unwrap_or(first)) +} + +pub struct Reader<'a> { + root: &'a Path, + visited: BTreeSet, + /// Scripts read, with the directory they were read in: a script's relative paths depend on it. + read: BTreeSet<(String, Option)>, + /// The directory commands run in, relative to the root; `None` after a `cd` cigen can't follow. + cwd: Option, + /// Whether the current line may run in a subshell (so a `cd` on it doesn't carry on), or + /// the text defines functions (so a `cd` runs whenever they're called). + unsure_of_cd: bool, + pub seen: Vec, + /// Each family's command and the directory it ran in, relative to the root: its pins and + /// lockfiles there (and above) are inputs too. + pub dirs: BTreeSet<(&'static str, String)>, + /// Every package script's name, once something asks. + scripts: Option>, +} + +pub use packages::packages; + +/// Where a step's commands start. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum StepDir<'a> { + Root, + /// A directory as the step names it, relative to the root. + Named(&'a str), +} + +impl<'a> Reader<'a> { + pub fn new(root: &'a Path) -> Self { + Self { + root, + visited: BTreeSet::new(), + read: BTreeSet::new(), + cwd: Some(String::new()), + unsure_of_cd: false, + seen: Vec::new(), + dirs: BTreeSet::new(), + scripts: None, + } + } + + /// Reads a step's shell text, run in `dir`. A directory cigen can't work out (a variable, one + /// that isn't in the project) makes every script and toolchain the step runs opaque. + pub fn step(&mut self, text: &str, origin: &str, dir: StepDir) { + self.cwd = Some(String::new()); + match dir { + StepDir::Root => {} + StepDir::Named(dir) => self.change_directory(&[dir.to_string()]), + } + self.text(text, origin); + } + + /// `word` as a path relative to the root (`""` for the root itself), if cigen knows where + /// the commands run and the path stays inside the project. + fn resolve(&self, word: &str) -> Option { + if word.starts_with('/') { + return None; + } + let mut parts: Vec<&str> = self + .cwd + .as_ref()? + .split('/') + .filter(|p| !p.is_empty()) + .collect(); + for part in word.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop()?; + } + part => parts.push(part), + } + } + Some(parts.join("/")) + } + + /// `cd `: later relative paths resolve there. A directory cigen can't work out (a + /// variable, `-`, `~`, none) means it no longer knows where they resolve. + pub(super) fn change_directory(&mut self, args: &[String]) { + self.cwd = match args + .iter() + .find(|arg| !arg.starts_with('-') || arg.as_str() == "-") + { + Some(dir) if !dir.contains(['$', '`', '~', '*', '?']) && dir != "-" => self + .resolve(dir) + .filter(|path| self.root.join(path).is_dir()), + _ => None, + }; + } + + /// The project files read so far (scripts the text runs, `package.json`): their contents + /// decided what the job uses, so they're inputs. + pub fn files_read(&self) -> &BTreeSet { + &self.visited + } + + pub fn mark_read(&mut self, relative: &str) { + self.visited.insert(relative.to_string()); + } + + pub fn opaque(&mut self, why: String) { + self.seen.push(Seen::Opaque(why)); + } + + /// Reads shell text; `origin` says where it came from, for the reasons. Whatever the reader + /// can't positively understand makes the job opaque. + fn text(&mut self, text: &str, origin: &str) { + for word in all_words(text) { + if let Some(family) = family_of_command(word) { + self.seen + .push(Seen::Family(family.name, format!("`{word}` in {origin}"))); + } + } + let joined = text.replace("\\\n", " "); + let defines_functions = joined.lines().any(|line| { + let code = strip_comment(line); + code.trim_start().starts_with("function ") || code.replace("$()", "").contains("()") + }); + let outer = self.unsure_of_cd; + let mut subshells = 0; + let mut flow = Flow::default(); + let mut body: Option<(String, bool, bool)> = None; + for line in joined.lines() { + if let Some((tag, quoted, strip_tabs)) = &body { + let end = if *strip_tabs { + line.trim_start_matches('\t') + } else { + line + }; + if end == tag { + body = None; + } else if !quoted && (line.contains("$(") || line.contains('`')) { + self.opaque(format!("a command inside a heredoc in {origin}")); + } + continue; + } + let code = strip_comment(line); + match heredoc(code) { + Heredoc::None => {} + Heredoc::Start { + tag, + quoted, + strip_tabs, + } => body = Some((tag, quoted, strip_tabs)), + Heredoc::Unclear => self.opaque(format!( + "a `<<` in {origin} that isn't a heredoc cigen can read (a `<< parameter >>`?)" + )), + } + if hides_a_command(code) { + self.opaque(format!( + "a command inside `${{…}}` or `<(…)` in {origin}, which cigen doesn't read" + )); + } + let unsure = outer || defines_functions || subshells > 0 || may_run_in_a_subshell(code); + subshells = (subshells + subshell_change(code)).max(0); + if flow.new_line() { + self.cwd = None; + } + for segment in segments(code) { + let (may_not_run, forget) = flow.before(&segment); + if forget { + self.cwd = None; + } + self.unsure_of_cd = unsure || may_not_run; + self.segment(&segment.text, origin); + flow.after(&segment.text); + } + flow.continues = ["&&", "||", "|"] + .iter() + .any(|op| code.trim_end().ends_with(op)); + } + if flow.end_list() { + self.cwd = None; + } + if let Some((tag, ..)) = body { + self.opaque(format!( + "a heredoc in {origin} that never ends (no `{tag}` line)" + )); + } + self.unsure_of_cd = outer; + } + + /// A script the text runs: shell scripts are read in turn; anything else can run anything. + /// A script run in a `subshell` can't change the directory of the commands after it; a + /// sourced one can. + pub(super) fn file(&mut self, word: &str, origin: &str, subshell: bool) { + if self.cwd.is_none() { + return self.opaque(format!( + "`{word}` in {origin}, after a `cd` cigen can't follow" + )); + } + let Some(relative) = self + .resolve(word) + .filter(|path| !path.is_empty() && self.root.join(path).is_file()) + else { + return self.opaque(format!( + "`{word}` in {origin}, which isn't a file in the project" + )); + }; + self.visited.insert(relative.clone()); + if !self.read.insert((relative.clone(), self.cwd.clone())) { + return; + } + let Ok(text) = std::fs::read_to_string(self.root.join(&relative)) else { + return self.opaque(format!("`{relative}`, which isn't a text file")); + }; + if !is_shell_script(&relative, &text) { + return self.opaque(format!("`{relative}`, which isn't a shell script")); + } + let cwd = self.cwd.clone(); + self.text(&text, &format!("`{relative}`")); + if subshell { + self.cwd = cwd; + } + } +} + +fn is_shell_script(path: &str, text: &str) -> bool { + match text.lines().next().and_then(|line| line.strip_prefix("#!")) { + Some(shebang) => { + let mut words = shebang.split_whitespace(); + let first = words.next().unwrap_or(""); + let program = match first.rsplit('/').next() { + Some("env") => words.find(|word| !word.starts_with('-')).unwrap_or(""), + Some(name) => name, + None => "", + }; + is_shell(program) + } + None => path.ends_with(".sh") || path.ends_with(".bash"), + } +} + +#[cfg(test)] +mod tests; diff --git a/src/inputs/shell/packages.rs b/src/inputs/shell/packages.rs new file mode 100644 index 0000000..ce026c9 --- /dev/null +++ b/src/inputs/shell/packages.rs @@ -0,0 +1,79 @@ +//! The project's `package.json` files and their scripts: a package manager runs a script by +//! name, so its scripts are commands, and its names decide what `pnpm ` runs. +use super::Reader; +use std::collections::BTreeSet; +use std::path::Path; + +pub struct Package { + /// The file, relative to the root. + pub relative: String, + /// Its directory, relative to the root (`""` for the root). + pub dir: String, + /// Its scripts, by name; a script that isn't a string is `None`. + pub scripts: Vec<(String, Option)>, +} + +/// Every `package.json` in the project, outside `node_modules` and dot directories, sorted. +pub fn packages(root: &Path) -> anyhow::Result> { + let walk = walkdir::WalkDir::new(root) + .sort_by_file_name() + .into_iter() + .filter_entry(|entry| { + let name = entry.file_name().to_string_lossy(); + entry.depth() == 0 || !(name == "node_modules" || name.starts_with('.')) + }); + let mut found = Vec::new(); + for entry in walk { + let entry = entry?; + if !entry.file_type().is_file() || entry.file_name() != "package.json" { + continue; + } + let relative = entry + .path() + .strip_prefix(root)? + .to_string_lossy() + .replace('\\', "/"); + let dir = relative + .strip_suffix("package.json") + .unwrap_or("") + .trim_end_matches('/') + .to_string(); + let scripts = std::fs::read_to_string(entry.path()) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|json| json.get("scripts").cloned()); + let scripts = match scripts { + Some(serde_json::Value::Object(scripts)) => scripts + .into_iter() + .map(|(name, script)| (name, script.as_str().map(str::to_string))) + .collect(), + _ => Vec::new(), + }; + found.push(Package { + relative, + dir, + scripts, + }); + } + Ok(found) +} + +impl Reader<'_> { + /// The names of every package's scripts. A project cigen can't walk has none, so every + /// word a package manager runs counts as a command. + pub(super) fn package_scripts(&mut self) -> BTreeSet { + if self.scripts.is_none() { + let packages = packages(self.root).unwrap_or_default(); + for package in &packages { + self.visited.insert(package.relative.clone()); + } + self.scripts = Some( + packages + .into_iter() + .flat_map(|package| package.scripts.into_iter().map(|(name, _)| name)) + .collect(), + ); + } + self.scripts.clone().unwrap_or_default() + } +} diff --git a/src/inputs/shell/sed.rs b/src/inputs/shell/sed.rs new file mode 100644 index 0000000..762c6a6 --- /dev/null +++ b/src/inputs/shell/sed.rs @@ -0,0 +1,176 @@ +//! Whether a sed command can run a command: GNU sed's `e` command and the `e` flag of `s` +//! run their text as shell, and a script file (`-f`) is text cigen doesn't read. + +/// Whether `sed` with these arguments runs nothing but sed. +pub(super) fn is_plain(args: &[String]) -> bool { + let mut scripts: Vec<&str> = Vec::new(); + let mut index = 0; + while let Some(arg) = args.get(index) { + let arg = arg.as_str(); + if arg == "-f" || arg.starts_with("--file") { + return false; + } + if arg == "-e" || arg == "--expression" { + scripts.extend(args.get(index + 1).map(String::as_str)); + index += 2; + continue; + } + if let Some(script) = arg.strip_prefix("--expression=") { + scripts.push(script); + } else if arg.starts_with("-i") || arg.starts_with("--") { + // `-i.bak` has a suffix, not flags. + } else if arg.len() > 1 && arg.starts_with('-') { + let flags = &arg[1..]; + if let Some(at) = flags.find(['e', 'f']) { + if flags[at..].starts_with('f') { + return false; + } + // `-ne script`, or `-nes/a/b/` with the script attached. + let attached = &flags[at + 1..]; + if attached.is_empty() { + scripts.extend(args.get(index + 1).map(String::as_str)); + index += 1; + } else { + scripts.push(attached); + } + } + } + index += 1; + } + if scripts.is_empty() { + // Without `-e`, the first word that isn't an option is the script. + scripts.extend( + args.iter() + .find(|arg| !arg.starts_with('-')) + .map(String::as_str), + ); + } + scripts.into_iter().all(script_is_plain) +} + +/// Reads a sed script command by command; anything it can't follow counts as running. +fn script_is_plain(script: &str) -> bool { + let chars: Vec = script.chars().collect(); + let mut index = 0; + while index < chars.len() { + let c = chars[index]; + index += 1; + match c { + ' ' | '\t' | '\n' | ';' | '{' | '}' | '!' | ',' | '$' | '~' | '+' => {} + '0'..='9' => {} + '#' => index = skip_to(&chars, index, '\n'), + '/' | '\\' => { + // An address: `/re/` or `\cREc`. + let delimiter = if c == '\\' { + let Some(&d) = chars.get(index) else { + return false; + }; + index += 1; + d + } else { + '/' + }; + match past(&chars, index, delimiter, 1) { + Some(next) => index = next, + None => return false, + } + // `I` and `M` modify an address. + while matches!(chars.get(index), Some('I' | 'M')) { + index += 1; + } + } + 's' | 'y' => { + let Some(&delimiter) = chars.get(index) else { + return false; + }; + let Some(next) = past(&chars, index + 1, delimiter, 2) else { + return false; + }; + index = next; + if c == 's' { + while let Some(flag) = chars.get(index).filter(|f| f.is_ascii_alphanumeric()) { + if *flag == 'e' { + return false; + } + if *flag == 'w' { + break; // the rest is a file name + } + index += 1; + } + } + if matches!(chars.get(index), Some('w')) { + index = skip_to(&chars, index, '\n'); + } + } + 'e' => return false, + // Text or a file name to the end of the line. + 'a' | 'i' | 'c' | 'r' | 'R' | 'w' | 'W' => index = skip_to(&chars, index, '\n'), + // A label to the end of the command. + 'b' | 't' | 'T' | ':' => { + while index < chars.len() && !matches!(chars[index], ';' | '\n' | '}') { + index += 1; + } + } + c if c.is_ascii_alphabetic() || c == '=' => {} + _ => return false, + } + } + true +} + +fn skip_to(chars: &[char], from: usize, end: char) -> usize { + chars[from..] + .iter() + .position(|c| *c == end) + .map_or(chars.len(), |at| from + at + 1) +} + +/// The index after the `count`th unescaped `delimiter` from `from`. +fn past(chars: &[char], from: usize, delimiter: char, count: usize) -> Option { + let mut seen = 0; + let mut index = from; + while index < chars.len() { + match chars[index] { + '\\' => index += 1, + c if c == delimiter => { + seen += 1; + if seen == count { + return Some(index + 1); + } + } + _ => {} + } + index += 1; + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plain(args: &[&str]) -> bool { + is_plain(&args.iter().map(|a| a.to_string()).collect::>()) + } + + #[test] + fn substitutions_and_prints_are_plain() { + assert!(plain(&["-i", "s/a/b/g", "f"])); + assert!(plain(&["-i.bak", "-e", "s|a b|c;d|", "-e", "/x/d", "f"])); + assert!(plain(&["-n", "1,/end/p"])); + assert!(plain(&["-E", "s/version = .*/version = 1/w out.txt", "f"])); + assert!(plain(&["-ne", "s/a/b/p"])); + assert!(plain(&["/^#/!s/x/y/;$a\\", "f"])); + } + + #[test] + fn e_and_script_files_run_commands() { + assert!(!plain(&["s/x/make/e", "f"])); + assert!(!plain(&["-e", "1e make", "f"])); + assert!(!plain(&["-n", "-e", "/x/ { e make\n}"])); + assert!(!plain(&["-f", "script.sed", "f"])); + assert!(!plain(&["--file=script.sed", "f"])); + assert!(!plain(&["-nf", "script.sed"])); + assert!(!plain(&["s/unterminated", "f"])); + } +} diff --git a/src/inputs/shell/segment.rs b/src/inputs/shell/segment.rs new file mode 100644 index 0000000..db15ac8 --- /dev/null +++ b/src/inputs/shell/segment.rs @@ -0,0 +1,138 @@ +//! One segment of a line (a simple command), and whether it always runs: a `cd` after `&&` +//! following another command, after `||`, or inside `if`, a loop or `case` may not happen. +use super::Reader; +use super::syntax::{Segment, is_assignment, is_redirect_operator, words}; +use super::words::names_a_command; +use super::words::{KEYWORDS_BEFORE_A_COMMAND, KEYWORDS_WITHOUT_A_COMMAND, PREFIXES}; + +/// Words that open a construct whose body may not run, and those that close one. +const OPENERS: &[&str] = &["case", "for", "if", "select", "until", "while"]; +const CLOSERS: &[&str] = &["done", "esac", "fi"]; + +/// Where the reader is in the text's control flow. +#[derive(Default)] +pub(super) struct Flow { + /// How many `if`s, loops and `case`s it's inside. + depth: i32, + /// Whether the rest of this and-or list may not run at all (after `||`). + after_or: bool, + /// Whether the rest of this list runs only if earlier commands passed (`&&` after a + /// command other than `cd`): a `cd` here holds for the list, but not after it. + after_and: bool, + /// Whether this and-or list has run a command other than `cd`. + ran_other: bool, + /// Whether this list ran a `cd` that only holds for the list. + cd_in_list: bool, + /// Whether the last line ended in `&&`, `||` or `|`, so this one carries on its list. + pub continues: bool, +} + +impl Flow { + /// Starts a line. Returns whether the directory is no longer known: the list that ended + /// ran a `cd` that might not have happened. + pub fn new_line(&mut self) -> bool { + if self.continues { + false + } else { + self.end_list() + } + } + + /// Ends an and-or list; whether the directory is no longer known. + pub fn end_list(&mut self) -> bool { + let forget = self.cd_in_list; + self.after_or = false; + self.after_and = false; + self.ran_other = false; + self.cd_in_list = false; + forget + } + + /// Reads where `segment` starts. Returns whether a `cd` in it may not happen at all, and + /// whether the directory is no longer known (a list ended). + pub fn before(&mut self, segment: &Segment) -> (bool, bool) { + let before = segment.before.as_str(); + let mut forget = false; + if before.contains("||") { + self.after_or = true; + } else if before.contains("&&") { + self.after_and |= self.ran_other; + } else if !before.is_empty() { + forget = self.end_list(); + } + for word in words(&segment.text) { + if OPENERS.contains(&word.as_str()) { + self.depth += 1; + } else if !KEYWORDS_BEFORE_A_COMMAND.contains(&word.as_str()) { + break; + } + } + (self.depth > 0 || self.after_or, forget) + } + + pub fn after(&mut self, segment: &str) { + let command = words(segment).into_iter().find(|word| { + !OPENERS.contains(&word.as_str()) && !KEYWORDS_BEFORE_A_COMMAND.contains(&word.as_str()) + }); + match command.as_deref() { + Some(word) if CLOSERS.contains(&word) => self.depth = (self.depth - 1).max(0), + Some("cd") => self.cd_in_list |= self.after_and, + _ => self.ran_other = true, + } + } +} + +/// A CircleCI parameter (`<< parameters.cmd >>`), quoted so it reads as one word. +fn is_template(word: &str) -> bool { + word.starts_with("<<") && word[2..].contains(">>") +} + +impl Reader<'_> { + pub(super) fn segment(&mut self, segment: &str, origin: &str) { + let words = words(segment); + let mut index = 0; + while index < words.len() { + let word = words[index].as_str(); + if is_assignment(word) { + let name = word.split_once('=').map_or(word, |(name, _)| name); + if names_a_command(name) { + return self.opaque(format!( + "`{name}` in {origin}, which names a command another program runs" + )); + } + index += 1; + } else if KEYWORDS_BEFORE_A_COMMAND.contains(&word) { + index += 1; + } else if is_redirect_operator(word) { + index += 2; + } else if (word.starts_with('<') || word.starts_with('>')) && !is_template(word) { + index += 1; + } else { + break; + } + } + let Some(command) = words.get(index) else { + return; + }; + let rest = &words[index + 1..]; + if KEYWORDS_WITHOUT_A_COMMAND.contains(&command.as_str()) { + return; + } + if PREFIXES.contains(&command.as_str()) { + // Which word is the command depends on each prefix's options, so every word after it + // counts as one: a neutral word costs nothing, and an unknown one includes every family. + for word in rest { + let plain = word.starts_with('-') + || is_assignment(word) + || word + .chars() + .all(|c| c.is_ascii_digit() || ".smhd".contains(c)); + if !plain { + self.command(word, &[], origin); + } + } + return; + } + self.command(command, rest, origin); + } +} diff --git a/src/inputs/shell/subcommands.rs b/src/inputs/shell/subcommands.rs new file mode 100644 index 0000000..07321ce --- /dev/null +++ b/src/inputs/shell/subcommands.rs @@ -0,0 +1,252 @@ +//! Subcommands the shell reader knows run no code of the project's. + +/// cargo's subcommands that build and check with the toolchain, and plugins that do no more. +/// Any other (`run`, `xtask`, `make`, an alias) runs code cigen can't see. +pub(super) const CARGO: &[&str] = &[ + "add", + "audit", + "b", + "bench", + "build", + "c", + "check", + "clean", + "clippy", + "d", + "deny", + "doc", + "fetch", + "fix", + "fmt", + "generate-lockfile", + "help", + "info", + "init", + "install", + "llvm-cov", + "locate-project", + "machete", + "metadata", + "new", + "nextest", + "package", + "pkgid", + "publish", + "remove", + "rustc", + "rustdoc", + "search", + "semver-checks", + "t", + "test", + "tree", + "udeps", + "uninstall", + "update", + "vendor", + "version", +]; + +/// go's subcommands that don't run project code (`run`, `generate` and `tool` do). +pub(super) const GO: &[&str] = &[ + "build", "clean", "doc", "env", "fix", "fmt", "get", "install", "list", "mod", "test", + "version", "vet", "work", +]; + +/// corepack's own subcommands; any other word is the package manager it runs. +pub(super) const COREPACK: &[&str] = &[ + "cache", "disable", "enable", "install", "pack", "prepare", "up", "use", +]; + +/// git's subcommands that run no command of the project's (with the exceptions checked below). +pub(super) const GIT: &[&str] = &[ + "add", + "apply", + "archive", + "bisect", + "blame", + "branch", + "cat-file", + "checkout", + "cherry-pick", + "clean", + "clone", + "commit", + "config", + "describe", + "diff", + "fetch", + "for-each-ref", + "gc", + "grep", + "init", + "lfs", + "log", + "ls-files", + "ls-remote", + "ls-tree", + "merge", + "merge-base", + "mv", + "pull", + "push", + "rebase", + "reset", + "restore", + "rev-list", + "rev-parse", + "rm", + "shortlog", + "show", + "sparse-checkout", + "stash", + "status", + "submodule", + "switch", + "symbolic-ref", + "tag", + "update-index", + "version", + "worktree", +]; + +/// gh's subcommands; any other word is an alias or an extension, which can run anything. +pub(super) const GH: &[&str] = &[ + "api", + "attestation", + "auth", + "browse", + "cache", + "codespace", + "gist", + "issue", + "label", + "org", + "pr", + "project", + "release", + "repo", + "ruleset", + "run", + "search", + "secret", + "status", + "variable", + "workflow", +]; + +/// pnpm's own subcommands; any other word is a package script or a command it runs. +pub(super) const PNPM: &[&str] = &[ + "add", + "approve-builds", + "audit", + "bin", + "cat-file", + "cat-index", + "ci", + "config", + "create", + "dedupe", + "deploy", + "doctor", + "env", + "fetch", + "find-hash", + "i", + "import", + "init", + "install", + "install-test", + "it", + "licenses", + "link", + "list", + "ln", + "ls", + "outdated", + "pack", + "patch", + "patch-commit", + "prune", + "publish", + "rb", + "rebuild", + "remove", + "rm", + "root", + "run", + "sbom", + "self-update", + "server", + "setup", + "start", + "store", + "t", + "test", + "uninstall", + "unlink", + "up", + "update", + "why", +]; + +/// Yarn's own subcommands (Classic and Berry); any other word is a script or a binary. +pub(super) const YARN: &[&str] = &[ + "add", + "audit", + "autoclean", + "bin", + "cache", + "check", + "config", + "constraints", + "create", + "dedupe", + "explain", + "generate-lock-entry", + "global", + "import", + "info", + "init", + "install", + "licenses", + "link", + "list", + "login", + "logout", + "node", + "npm", + "outdated", + "owner", + "pack", + "patch", + "patch-commit", + "plugin", + "policies", + "publish", + "rebuild", + "remove", + "run", + "set", + "stage", + "start", + "tag", + "team", + "test", + "unlink", + "unplug", + "up", + "upgrade", + "upgrade-interactive", + "version", + "versions", + "why", + "workspaces", +]; + +/// Bun's own subcommands; a file is run by Bun, and any other word is a script or a binary. +pub(super) const BUN: &[&str] = &[ + "a", "add", "audit", "build", "create", "help", "i", "info", "init", "install", "link", + "outdated", "patch", "pm", "publish", "remove", "repl", "rm", "run", "test", "unlink", + "update", "upgrade", "why", +]; diff --git a/src/inputs/shell/syntax.rs b/src/inputs/shell/syntax.rs new file mode 100644 index 0000000..c3888d0 --- /dev/null +++ b/src/inputs/shell/syntax.rs @@ -0,0 +1,152 @@ +//! Shell syntax, as far as finding commands needs it. + +/// Every word of the text, split on whitespace, quotes and shell punctuation. +pub(super) fn all_words(text: &str) -> impl Iterator { + text.split(|c: char| c.is_whitespace() || "'\"`;|&(){}<>=,$".contains(c)) + .filter(|word| !word.is_empty()) +} + +/// The line split where a new command can start: at `;`, `&&`, `||`, `|`, `&`, parentheses, +/// braces and backticks outside quotes, and at command substitutions inside double quotes. +/// Text in quotes is otherwise literal. Each segment comes with the punctuation before it +/// (`&&`, `||`, `;`, `|`, `(`), which says whether it always runs. +pub(super) fn segments(line: &str) -> Vec { + let line = line.replace(">&", "> ").replace("&>", "> "); + let mut segments = vec![String::new()]; + let mut befores = vec![String::new()]; + let mut quote: Option = None; + let mut substitutions = 0usize; + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + if c == '$' && quote != Some('\'') && chars.peek() == Some(&'{') { + // `${NAME}` is a variable, not a brace group. + let segment = segments.last_mut().expect("never empty"); + segment.push(c); + for inner in chars.by_ref() { + segment.push(inner); + if inner == '}' { + break; + } + } + continue; + } + let split = match (quote, c) { + (Some('\''), '\'') => { + quote = None; + false + } + (Some('\''), _) => false, + (Some('"'), '"') => { + quote = None; + false + } + (Some('"'), '$') if chars.peek() == Some(&'(') => { + chars.next(); + substitutions += 1; + true + } + (Some('"'), ')') if substitutions > 0 => { + substitutions -= 1; + true + } + (Some('"'), '`') => true, + (Some(_), _) => false, + (None, '\'' | '"') => { + quote = Some(c); + false + } + (None, '$') if chars.peek() == Some(&'(') => { + chars.next(); + substitutions += 1; + true + } + (None, ')') => { + substitutions = substitutions.saturating_sub(1); + true + } + (None, ';' | '|' | '&' | '(' | '{' | '}' | '`') => true, + (None, _) => false, + }; + if split { + if segments.last().expect("never empty").trim().is_empty() { + segments.last_mut().expect("never empty").clear(); + } else { + segments.push(String::new()); + befores.push(String::new()); + } + befores.last_mut().expect("never empty").push(c); + } else { + segments.last_mut().expect("never empty").push(c); + } + } + segments + .into_iter() + .zip(befores) + .filter(|(text, _)| !text.trim().is_empty()) + .map(|(text, before)| Segment { text, before }) + .collect() +} + +/// A piece of a line where a command can start. +pub(super) struct Segment { + pub text: String, + /// The punctuation between the previous segment and this one. + pub before: String, +} + +/// The line up to a `#` that starts a word outside quotes. +pub(super) fn strip_comment(line: &str) -> &str { + let mut quote: Option = None; + let mut previous = ' '; + for (index, c) in line.char_indices() { + match quote { + Some(open) if c == open => quote = None, + Some(_) => {} + None if c == '\'' || c == '"' => quote = Some(c), + None if c == '#' && previous.is_whitespace() => return &line[..index], + None => {} + } + previous = c; + } + line +} + +pub(super) fn is_assignment(word: &str) -> bool { + word.split_once('=').is_some_and(|(name, _)| { + !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + }) +} + +pub(super) fn is_redirect_operator(word: &str) -> bool { + let operator = word.trim_start_matches(|c: char| c.is_ascii_digit()); + matches!(operator, ">" | ">>" | "<" | "<<<") +} + +/// A segment's words, split on whitespace outside quotes, with the quotes removed. An +/// unclosed quote runs to the end. +pub(super) fn words(segment: &str) -> Vec { + let mut words = Vec::new(); + let mut word: Option = None; + let mut quote: Option = None; + let mut chars = segment.chars(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some(open), c) if c == open => quote = None, + (Some('"') | None, '\\') => { + if let Some(next) = chars.next() { + word.get_or_insert_with(String::new).push(next); + } + } + (Some(_), c) => word.get_or_insert_with(String::new).push(c), + (None, '\'' | '"') => { + quote = Some(c); + word.get_or_insert_with(String::new); + } + (None, c) if c.is_whitespace() => words.extend(word.take()), + (None, c) => word.get_or_insert_with(String::new).push(c), + } + } + words.extend(word); + words.retain(|word| !word.is_empty()); + words +} diff --git a/src/inputs/shell/tests/hidden.rs b/src/inputs/shell/tests/hidden.rs new file mode 100644 index 0000000..aeb8d06 --- /dev/null +++ b/src/inputs/shell/tests/hidden.rs @@ -0,0 +1,152 @@ +//! Findings of the independent review of PR #26: each one hid a toolchain from a narrowed job. + +use super::*; + +#[test] +fn runner_subcommands_read_what_they_run() { + let files = [("ci.sh", "#!/bin/sh\ngo test ./...\n")]; + for text in [ + "bundle exec make test", + "npx make", + "pnpm exec make", + "pnpm --filter web exec make", + "yarn dlx make", + "npm exec -- make", + "uv run make", + "poetry run make", + "pipx run make", + "corepack make", + ] { + assert!(opaque(&read(text, &files)), "{text}"); + } + for text in [ + "pnpm exec ./ci.sh", + "uv run ./ci.sh", + "bundle exec sh ci.sh", + ] { + assert!(families(&read(text, &files)).contains(&"go"), "{text}"); + } + // These run code cigen can't see: an alias, a project binary, generated commands. + for text in [ + "cargo xtask ci", + "cargo run --bin tool", + "go run ./cmd/x", + "go generate ./...", + ] { + assert!(opaque(&read(text, &files)), "{text}"); + } + let seen = read( + "cargo test && cargo clippy -- -D warnings && cargo +nightly fmt", + &files, + ); + assert!(!opaque(&seen), "{seen:?}"); +} + +#[test] +fn only_a_real_heredoc_hides_lines() { + let files = [("deploy.sh", "#!/bin/sh\ngo build\n")]; + for text in [ + "echo \"Deploying << pipeline.git.branch >>\"\n./deploy.sh", + "# cat < notes.txt <<'EOF'\nmake\nEOF\n./deploy.sh", &files); + assert_eq!(families(&seen), ["go"], "{seen:?}"); + assert!(!opaque(&seen), "{seen:?}"); + // An unquoted CircleCI parameter is a template cigen can't see into, and a heredoc that + // never ends hides the rest. + assert!(opaque(&read( + "echo << parameters.target >>\n./deploy.sh", + &files + ))); + assert!(opaque(&read("cat < Vec { + read_in(text, files, None) +} + +/// Reads `text` as a step run in `step_dir`. +pub(super) fn read_in(text: &str, files: &[(&str, &str)], step_dir: Option<&str>) -> Vec { + let dir = tempfile::tempdir().unwrap(); + for (path, contents) in files { + let path = dir.path().join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + let mut reader = Reader::new(dir.path()); + reader.step( + text, + "a step", + step_dir.map_or(StepDir::Root, StepDir::Named), + ); + reader.seen +} + +pub(super) fn families(seen: &[Seen]) -> Vec<&'static str> { + let mut names: Vec<&str> = seen + .iter() + .filter_map(|seen| match seen { + Seen::Family(name, _) => Some(*name), + Seen::Opaque(_) => None, + }) + .collect(); + names.sort(); + names.dedup(); + names +} + +pub(super) fn opaque(seen: &[Seen]) -> bool { + seen.iter().any(|seen| matches!(seen, Seen::Opaque(_))) +} + +#[test] +fn family_commands_are_found_in_any_position() { + for text in [ + "cargo test --workspace", + "set -e\ncd crates && cargo build", + "if [ -f Cargo.toml ]; then cargo fmt --check; fi", + "FOO=1 RUST_LOG=debug cargo nextest run", + "echo \"$(cargo --version)\"", + "cargo-nextest run", + "timeout 10m cargo test", + ] { + let seen = read(text, &[("crates/.keep", "")]); + assert_eq!(families(&seen), ["rust"], "{text}: {seen:?}"); + assert!(!opaque(&seen), "{text}: {seen:?}"); + } +} + +#[test] +fn neutral_commands_add_nothing() { + let text = "set -euo pipefail\nmkdir -p out\necho \"done (ok); really\" > out/log 2>&1\n\ + git diff --exit-code || exit 1\nfor f in a b; do echo $f; done\nprintf '%s' ${HOME}"; + let seen = read(text, &[]); + assert!(seen.is_empty(), "{seen:?}"); +} + +#[test] +fn unknown_commands_are_opaque() { + for text in [ + "make test", + "vitest run", + "bash -c 'cargo test'", + "eval \"$CMD\"", + "$RUNNER test", + "sudo -u builder make", + "find . -name '*.rs' -exec rustfmt-wrapper {} +", + "x=$(build-tool)", + "cat < config.toml <<'EOF'\n[section]\nkey = 1\nEOF\necho ok", + &[], + ); + assert!(seen.is_empty(), "{seen:?}"); +} + +#[test] +fn comments_are_ignored() { + let seen = read("echo hi # then run make\n# make", &[]); + assert!(seen.is_empty(), "{seen:?}"); +} + +/// The same script name in two directories: the root's runs nothing, `web`'s runs Bundler. +pub(super) const TWO_CHECKS: &[(&str, &str)] = &[ + ("check.sh", "echo fine\n"), + ("web/check.sh", "bundle exec rake\n"), + ("web/sub/.keep", ""), +]; + +#[test] +fn scripts_resolve_in_the_directory_the_commands_run_in() { + for (text, dir) in [ + ("cd web && sh check.sh", None), + ("cd web\n./check.sh", None), + ("cd web/sub; cd ..; . ./check.sh", None), + ("sh check.sh", Some("web")), + ("./check.sh", Some("./web")), + ("cd sub && sh ../check.sh", Some("web")), + ] { + let seen = read_in(text, TWO_CHECKS, dir); + assert_eq!(families(&seen), ["ruby"], "{text} in {dir:?}: {seen:?}"); + assert!(!opaque(&seen), "{text} in {dir:?}: {seen:?}"); + } + assert!(read_in("cd web && cd .. && sh check.sh", TWO_CHECKS, None).is_empty()); +} + +#[test] +fn a_directory_cigen_cannot_follow_makes_scripts_opaque() { + for (text, dir) in [ + ("cd \"$APP_DIR\" && sh check.sh", None), + ("cd - && sh check.sh", None), + ("cd && sh check.sh", None), + ("pushd web && sh check.sh", None), + ("cd missing && sh check.sh", None), + ("cd .. && sh check.sh", None), + ("sh check.sh", Some("${{ inputs.dir }}")), + ("sh check.sh", Some("not-yet-made")), + ] { + assert!(opaque(&read_in(text, TWO_CHECKS, dir)), "{text} in {dir:?}"); + } +} + +#[test] +fn a_script_run_in_a_subshell_keeps_its_cd_to_itself() { + let files = [ + ("enter.sh", "cd web\n"), + ("check.sh", "echo fine\n"), + ("web/check.sh", "bundle exec rake\n"), + ]; + let seen = read("sh enter.sh && sh check.sh", &files); + assert!(seen.is_empty(), "{seen:?}"); + let seen = read(". ./enter.sh && sh check.sh", &files); + assert_eq!(families(&seen), ["ruby"], "{seen:?}"); +} + +#[test] +fn a_bare_command_runs_from_path_not_the_directory() { + let files = [("check", "#!/bin/sh\necho fine\n")]; + assert!(opaque(&read("check", &files))); +} + +mod hidden; +mod second_review; diff --git a/src/inputs/shell/tests/second_review.rs b/src/inputs/shell/tests/second_review.rs new file mode 100644 index 0000000..2e9d9fd --- /dev/null +++ b/src/inputs/shell/tests/second_review.rs @@ -0,0 +1,143 @@ +//! Findings of the second review of PR #26: each one hid a toolchain from a narrowed job. + +use super::*; + +/// `ci.sh` runs go, `make` is a harmless script in the project, and `web/` has its own. +const FILES: &[(&str, &str)] = &[ + ("ci.sh", "#!/bin/sh\ngo test ./...\n"), + ("web/ci.sh", "#!/bin/sh\ngo test ./...\n"), + ("infra/.keep", ""), + ("sub/Cargo.toml", "[package]\n"), +]; + +#[test] +fn toolchain_commands_that_run_commands_are_read() { + for text in [ + "rustup run stable make test", + "rustup toolchain run stable make", + "gem exec make", + "cargo-make make ci", + "pnpm make", + "yarn make", + "yarn workspace web make", + "bun make", + ] { + assert!(opaque(&read(text, FILES)), "{text}"); + } + let seen = read("rustup run stable ./ci.sh", FILES); + assert!(families(&seen).contains(&"go"), "{seen:?}"); + // Their own subcommands and the package's scripts are what they look like. + let files = [("package.json", "{\"scripts\": {\"lint\": \"echo lint\"}}")]; + for text in [ + "pnpm install", + "pnpm lint", + "yarn lint", + "bun install", + "cargo-nextest run", + ] { + let seen = read(text, &files); + assert!(!opaque(&seen), "{text}: {seen:?}"); + } +} + +#[test] +fn an_escaped_or_quoted_toolchain_command_counts() { + for text in ["\\cargo test", "ca''rgo test", "\"cargo\" test"] { + let seen = read(text, &[]); + assert!(families(&seen).contains(&"rust"), "{text}: {seen:?}"); + } +} + +#[test] +fn a_conditional_cd_leaves_the_directory_unknown() { + for text in [ + "if [ -n \"$WEB\" ]; then cd web; fi\n./ci.sh", + "if [ -n \"$WEB\" ]; then\n cd web\nfi\n./ci.sh", + "test -n \"$WEB\" && cd web\n./ci.sh", + "[ -d web ] || cd web\n./ci.sh", + "for d in web; do cd $d; done\n./ci.sh", + "while false; do\n cd web\ndone\n./ci.sh", + "case $X in a) cd web;; esac\n./ci.sh", + ] { + let seen = read(text, FILES); + assert!(opaque(&seen), "{text}: {seen:?}"); + } + // An unconditional cd is still followed. + let seen = read("set -e\ncd web && cd .. && ./ci.sh || exit 1", FILES); + assert!(!opaque(&seen), "{seen:?}"); +} + +#[test] +fn options_that_change_a_tools_directory_are_followed_or_opaque() { + for text in [ + "pnpm --filter web exec ./ci.sh", + "pnpm -r exec ./ci.sh", + "npm exec --workspace web -- ./ci.sh", + "find . -execdir ./ci.sh {} +", + "cargo test --manifest-path \"$DIR/Cargo.toml\"", + "terraform -chdir=missing plan", + ] { + assert!(opaque(&read(text, FILES)), "{text}"); + } + let dirs = |text: &str| { + let dir = tempfile::tempdir().unwrap(); + for (path, contents) in FILES { + let path = dir.path().join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + let mut reader = Reader::new(dir.path()); + reader.step(text, "a step", StepDir::Root); + assert!(!opaque(&reader.seen), "{text}: {:?}", reader.seen); + reader.dirs + }; + let has = |text: &str, family: &'static str, dir: &str| { + let found = dirs(text); + assert!( + found.contains(&(family, dir.to_string())), + "{text}: {found:?}" + ); + }; + has("yarn --cwd web install", "node", "web"); + has("pnpm -C web install", "node", "web"); + has("pnpm --dir=web install", "node", "web"); + has("terraform -chdir=infra plan", "terraform", "infra"); + has("cargo test --manifest-path sub/Cargo.toml", "rust", "sub"); + has("go -C infra test ./...", "go", "infra"); + // A runner in another directory runs its command there. + let seen = read("yarn --cwd web exec ./ci.sh", FILES); + assert!( + families(&seen).contains(&"go") && !opaque(&seen), + "{seen:?}" + ); +} + +#[test] +fn a_quoted_circleci_parameter_as_the_command_is_opaque() { + for text in [ + "\"<< parameters.cmd >>\"", + "'<< parameters.cmd >>' --verbose", + ] { + assert!(opaque(&read(text, &[])), "{text}"); + } +} + +#[test] +fn settings_that_name_commands_are_opaque() { + for text in [ + "alias cargo=make", + "sort --compress-program=make f", + "GIT_EXTERNAL_DIFF=make git diff", + "export GIT_SSH_COMMAND=make", + "git config core.hooksPath hooks", + "git config --global alias.ci '!make'", + ] { + assert!(opaque(&read(text, &[])), "{text}"); + } + let seen = read( + "git config --global user.name bot && git config --global --add safe.directory \"$PWD\" && \ + git config --get remote.origin.url && sort -u f", + &[], + ); + assert!(seen.is_empty(), "{seen:?}"); +} diff --git a/src/inputs/shell/words.rs b/src/inputs/shell/words.rs new file mode 100644 index 0000000..855d9b1 --- /dev/null +++ b/src/inputs/shell/words.rs @@ -0,0 +1,162 @@ +//! The words the shell reader knows. + +/// Commands that read no toolchain's pins or lockfiles. +pub(super) const NEUTRAL: &[&str] = &[ + "[", + "[[", + ":", + "alias", + "apt", + "apt-get", + "awk", + "base64", + "basename", + "break", + "cat", + "chmod", + "chown", + "cigen", + "cmp", + "continue", + "cp", + "curl", + "cut", + "date", + "df", + "diff", + "dirname", + "du", + "echo", + "egrep", + "exit", + "export", + "false", + "fgrep", + "file", + "find", + "gh", + "git", + "grep", + "gunzip", + "gzip", + "head", + "hostname", + "id", + "jq", + "kill", + "ln", + "local", + "ls", + "md5sum", + "mkdir", + "mktemp", + "mv", + "openssl", + "patch", + "printf", + "ps", + "pwd", + "read", + "readlink", + "realpath", + "return", + "rm", + "rmdir", + "rsync", + "scp", + "sed", + "set", + "sha1sum", + "sha256sum", + "shasum", + "shift", + "sleep", + "sort", + "ssh", + "stat", + "tail", + "tar", + "tee", + "test", + "touch", + "tr", + "true", + "type", + "umask", + "uname", + "uniq", + "unset", + "unzip", + "wait", + "wc", + "wget", + "which", + "whoami", + "yq", + "zip", +]; + +/// Words that start a command but run the word after them (or any word after them). +pub(super) const PREFIXES: &[&str] = &[ + "builtin", "chronic", "command", "env", "exec", "ionice", "nice", "nohup", "stdbuf", "sudo", + "time", "timeout", "xargs", +]; + +/// Shell keywords: some end or open a construct, and the command comes after them. +pub(super) const KEYWORDS_BEFORE_A_COMMAND: &[&str] = + &["!", "do", "elif", "else", "if", "then", "until", "while"]; +pub(super) const KEYWORDS_WITHOUT_A_COMMAND: &[&str] = + &["case", "done", "esac", "fi", "for", "in", "select"]; + +pub(super) const SHELLS: &[&str] = &["bash", "dash", "ksh", "sh"]; + +/// git config keys that name no command, so setting them runs nothing. +pub(super) const GIT_CONFIG_PLAIN: &[&str] = &[ + "advice.", + "color.", + "commit.gpgsign", + "core.autocrlf", + "core.longpaths", + "core.quotepath", + "fetch.", + "gc.", + "http.", + "init.defaultbranch", + "merge.ff", + "protocol.", + "pull.", + "push.", + "safe.directory", + "submodule.recurse", + "tag.gpgsign", + "url.", + "user.", +]; + +/// Variables that name a command another program runs (git's, and the file a shell sources). +pub(super) const COMMAND_VARIABLES: &[&str] = &[ + "BASH_ENV", + "ENV", + "GIT_ASKPASS", + "GIT_CONFIG", + "GIT_CONFIG_COUNT", + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_PARAMETERS", + "GIT_CONFIG_SYSTEM", + "GIT_EDITOR", + "GIT_EXEC_PATH", + "GIT_EXTERNAL_DIFF", + "GIT_PAGER", + "GIT_PROXY_COMMAND", + "GIT_SEQUENCE_EDITOR", + "GIT_SSH", + "GIT_SSH_COMMAND", + "GIT_TEMPLATE_DIR", +]; + +/// Whether assigning `name` can make another program run a command. +pub(super) fn names_a_command(name: &str) -> bool { + COMMAND_VARIABLES.contains(&name) + || name.starts_with("GIT_CONFIG_KEY_") + || name.starts_with("GIT_CONFIG_VALUE_") +} diff --git a/src/schema/config.rs b/src/schema/config.rs index 68cd56a..9a2cd07 100644 --- a/src/schema/config.rs +++ b/src/schema/config.rs @@ -20,6 +20,9 @@ pub struct CigenConfig { /// Named groups of inputs, referenced from jobs as `@name` pub input_groups: BTreeMap>, + /// Give each job only its own toolchains' pins and lockfiles (a job can override it) + pub narrow_inputs: bool, + /// Service containers jobs can name pub services: Mapping, diff --git a/src/schema/document.rs b/src/schema/document.rs index 8e58fe6..31951b8 100644 --- a/src/schema/document.rs +++ b/src/schema/document.rs @@ -31,6 +31,14 @@ pub struct ConfigDocument { #[serde(default)] pub input_groups: BTreeMap>, + /// Give each job only its own toolchains' pins and lockfiles: those of its modules and of + /// the commands it visibly runs, or every toolchain's when it runs something cigen can't see + /// into. A narrowed job reruns less often, and skips wrongly if one of its tools starts + /// another toolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`). + /// Off by default; a job's own `narrow_inputs` overrides it. + #[serde(default)] + pub narrow_inputs: bool, + /// Service containers jobs can name, passed to the provider as written #[serde(default)] #[schemars(with = "BTreeMap")] diff --git a/src/schema/job.rs b/src/schema/job.rs index 10d5e97..4b76e83 100644 --- a/src/schema/job.rs +++ b/src/schema/job.rs @@ -25,6 +25,18 @@ pub struct Job { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub modules: Vec, + /// Only this job's toolchains' pins and lockfiles, overriding the top-level `narrow_inputs`. + /// A narrowed job reruns less often, and skips wrongly if one of its tools starts another + /// toolchain's tools without cigen seeing it (a Rust test that shells out to `pnpm`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub narrow_inputs: Option, + + /// Toolchains the job uses without cigen seeing it run them (a Rake task that runs `yarn`): + /// a narrowed job gets their pins and lockfiles too. One of go, java, node, php, python, + /// ruby, rust, terraform. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub toolchains: Vec, + /// Service containers, by name from the top-level `services` #[serde(default)] pub services: Vec, diff --git a/tests/narrow_inputs.rs b/tests/narrow_inputs.rs new file mode 100644 index 0000000..0df1de7 --- /dev/null +++ b/tests/narrow_inputs.rs @@ -0,0 +1,196 @@ +//! `narrow_inputs`: by default every job gets every toolchain's pins and lockfiles, modules or +//! not. A narrowed job gets only the families of its modules and of the commands it visibly +//! runs, and every family when it runs something cigen can't see into. Each scenario runs the +//! generated workflow in mockci, changes one toolchain file, and checks whether the job reruns. + +mod support; + +use cigen_mockci::Simulator; +use support::fixture_repo::FixtureRepo; +use support::skip::{WORKFLOW, push, simulator, tests_ran}; + +/// A repository whose `test` job uses the rust module and runs `command`. +fn fixture(top: &str, job: &str, command: &str) -> FixtureRepo { + fixture_with_steps( + top, + &format!("{job}steps:\n - run:\n name: Run tests\n command: {command}\n"), + ) +} + +/// A repository whose `test` job uses the rust module, with `rest` after its `inputs:`. +fn fixture_with_steps(top: &str, rest: &str) -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write(".cigen/config.yml", &format!("provider: github\n{top}")) + .write( + ".cigen/workflows/ci/jobs/test.yml", + &format!("modules: [rust]\ninputs: \"src/**\"\n{rest}"), + ) + .write("Cargo.toml", "[package]\nname = \"fixture\"\n") + .write("Cargo.lock", "version = 4\n") + .write("yarn.lock", "# yarn\n") + .write("Gemfile.lock", "GEM\n") + .write(".nvmrc", "22\n") + .write(".tool-versions", "nodejs 22\n") + .write("src/lib.rs", "pub fn one() {}\n") + .generate(); + repo +} + +/// Runs the workflow, adds a comment to `path`, and says whether the job ran again. +fn reruns_after_changing(repo: &FixtureRepo, path: &str) -> bool { + let before = std::fs::read_to_string(repo.path().join(path)).unwrap_or_default(); + reruns_after_writing(repo, path, &format!("{before}# changed\n")) +} + +/// Runs the workflow, writes `contents` to `path`, and says whether the job ran again. +fn reruns_after_writing(repo: &FixtureRepo, path: &str, contents: &str) -> bool { + let mut sim = fake_tools(repo); + let first = repo.commit("initial"); + assert!(tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + assert!(!tests_ran(&sim.run(WORKFLOW, &push(&first)).unwrap())); + repo.write(path, contents); + let changed = repo.commit(&format!("change {path}")); + tests_ran(&sim.run(WORKFLOW, &push(&changed)).unwrap()) +} + +/// mockci runs steps on the host, so the tools are fakes. +fn fake_tools(repo: &FixtureRepo) -> Simulator { + let mut sim = simulator(repo); + sim.stub_action("Swatinem/rust-cache", []); + for tool in ["rustup", "cargo", "node", "make", "pnpm", "bundle"] { + sim.provide_command(tool, &format!("echo \"{tool} $*\"\n")) + .unwrap(); + } + sim +} + +#[test] +fn by_default_a_module_does_not_narrow_a_job() { + let repo = fixture("", "", "cargo test"); + assert!(reruns_after_changing(&repo, "yarn.lock")); +} + +#[test] +fn a_narrowed_job_gets_its_modules_toolchains_and_the_shared_pins() { + let narrowed = || fixture("narrow_inputs: true\n", "", "cargo test"); + assert!(!reruns_after_changing(&narrowed(), "yarn.lock")); + assert!(!reruns_after_changing(&narrowed(), "Gemfile.lock")); + assert!(reruns_after_changing(&narrowed(), "Cargo.lock")); + assert!(reruns_after_changing(&narrowed(), ".tool-versions")); +} + +#[test] +fn a_narrowed_job_gets_the_toolchains_it_visibly_runs() { + let repo = fixture("narrow_inputs: true\n", "", "cargo test && node -e 1"); + assert!(reruns_after_changing(&repo, ".nvmrc")); + + let repo = fixture("narrow_inputs: true\n", "", "sh scripts/check.sh"); + repo.write("scripts/check.sh", "#!/bin/sh\n. scripts/more.sh\n") + .write("scripts/more.sh", "bundle exec rake\n"); + assert!(reruns_after_changing(&repo, "Gemfile.lock")); + assert!(reruns_after_changing(&repo, "scripts/more.sh")); +} + +#[test] +fn package_scripts_count_as_commands() { + let repo = fixture("narrow_inputs: true\n", "", "pnpm build"); + repo.write( + "package.json", + "{\"scripts\": {\"build\": \"bundle exec jekyll build\"}}\n", + ); + assert!(reruns_after_changing(&repo, "Gemfile.lock")); + // The scripts decided which toolchains the job uses, so changing them reruns it. + assert!(reruns_after_writing( + &repo, + "package.json", + "{\"scripts\": {\"build\": \"bundle exec jekyll build --verbose\"}}\n", + )); +} + +#[test] +fn anything_cigen_cannot_see_into_gets_every_toolchain() { + let repo = fixture("narrow_inputs: true\n", "", "make test"); + assert!(reruns_after_changing(&repo, "yarn.lock")); +} + +#[test] +fn a_job_can_opt_out_of_a_narrowed_config() { + let repo = fixture( + "narrow_inputs: true\n", + "narrow_inputs: false\n", + "cargo test", + ); + assert!(reruns_after_changing(&repo, "yarn.lock")); +} + +#[test] +fn a_job_can_narrow_itself() { + let repo = fixture("", "narrow_inputs: true\n", "cargo test"); + assert!(!reruns_after_changing(&repo, "yarn.lock")); +} + +/// The same script in two places: the root's runs nothing, `web`'s runs Bundler. +fn two_checks(repo: &FixtureRepo) { + repo.write("check.sh", "echo fine\n") + .write("web/check.sh", "bundle exec rake\n"); +} + +#[test] +fn scripts_resolve_in_the_steps_working_directory() { + let repo = fixture_with_steps( + "narrow_inputs: true\n", + "steps:\n - name: Run tests\n working-directory: web\n run: sh check.sh\n", + ); + two_checks(&repo); + assert!(reruns_after_changing(&repo, "Gemfile.lock")); + + let repo = fixture("narrow_inputs: true\n", "", "cd web && sh check.sh"); + two_checks(&repo); + assert!(reruns_after_changing(&repo, "Gemfile.lock")); + assert!(reruns_after_changing(&repo, "web/check.sh")); +} + +#[test] +fn every_packages_scripts_count_as_commands() { + let repo = fixture("narrow_inputs: true\n", "", "cd web && pnpm build"); + repo.write( + "package.json", + "{\"scripts\": {\"build\": \"echo root\"}}\n", + ) + .write( + "web/package.json", + "{\"scripts\": {\"build\": \"bundle exec jekyll build\"}}\n", + ); + assert!(reruns_after_changing(&repo, "Gemfile.lock")); + assert!(reruns_after_writing( + &repo, + "web/package.json", + "{\"scripts\": {\"build\": \"bundle exec jekyll build --verbose\"}}\n", + )); +} + +fn hash_changes_after_changing(repo: &FixtureRepo, path: &str) -> bool { + repo.hash_changes_after_changing("test", path) +} + +#[test] +fn a_step_in_another_shell_is_opaque() { + let repo = fixture_with_steps( + "narrow_inputs: true\n", + "steps:\n - name: Run tests\n shell: python {0}\n run: print('hi')\n", + ); + assert!(hash_changes_after_changing(&repo, "yarn.lock")); + + let repo = fixture_with_steps( + "narrow_inputs: true\n", + "github:\n defaults:\n run:\n shell: pwsh\nsteps:\n - run: echo hi\n", + ); + assert!(hash_changes_after_changing(&repo, "yarn.lock")); + + // A POSIX shell is read as usual. + let repo = fixture_with_steps( + "narrow_inputs: true\n", + "steps:\n - name: Run tests\n shell: bash\n run: cargo test\n", + ); + assert!(!hash_changes_after_changing(&repo, "yarn.lock")); +} diff --git a/tests/narrow_inputs_readers.rs b/tests/narrow_inputs_readers.rs new file mode 100644 index 0000000..3eeca92 --- /dev/null +++ b/tests/narrow_inputs_readers.rs @@ -0,0 +1,185 @@ +//! What a narrowed job's steps are read for, beyond shell text: default working directories, +//! runners, CircleCI steps and GitHub actions, and the pins a toolchain finds where it runs. +//! Each test checks whether changing one file changes the job's hash. + +mod support; + +use support::fixture_repo::FixtureRepo; + +/// A narrowed `test` job with `job` as its definition, beside files that every toolchain +/// family reads. +fn repo(provider: &str, job: &str) -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write( + ".cigen/config.yml", + &format!("provider: {provider}\nnarrow_inputs: true\n"), + ) + .write(".cigen/workflows/ci/jobs/test.yml", job) + .write("Cargo.lock", "version = 4\n") + .write("yarn.lock", "# yarn\n") + .write("Gemfile.lock", "GEM\n") + .write(".nvmrc", "22\n") + .write("check.sh", "echo fine\n") + .write("web/check.sh", "bundle exec rake\n"); + repo +} + +fn changes(repo: &FixtureRepo, path: &str) -> bool { + repo.hash_changes_after_changing("test", path) +} + +#[test] +fn the_default_working_directory_is_where_scripts_resolve() { + let job = "github:\n defaults:\n run:\n working-directory: web\nsteps:\n - run: sh check.sh\n"; + assert!(changes(&repo("github", job), "Gemfile.lock")); + // Without it, the root's script runs, which uses no toolchain. + assert!(!changes( + &repo("github", "steps:\n - run: sh check.sh\n"), + "Gemfile.lock" + )); +} + +#[test] +fn windows_runners_and_runners_from_expressions_are_opaque() { + for job in [ + "image: windows-latest\nsteps:\n - run: cargo test\n", + "github:\n runs-on: ${{ matrix.os }}\nsteps:\n - run: cargo test\n", + ] { + assert!(changes(&repo("github", job), "yarn.lock"), "{job}"); + } + assert!(!changes( + &repo( + "github", + "image: macos-latest\nsteps:\n - run: cargo test\n" + ), + "yarn.lock" + )); +} + +#[test] +fn circleci_orb_and_unknown_named_steps_are_opaque() { + for step in [ + "node/install", + "some_command", + "node/install: { node-version: '22' }", + ] { + let job = format!("steps:\n - checkout\n - {step}\n - run: cargo test\n"); + assert!(changes(&repo("circleci", &job), "yarn.lock"), "{step}"); + } + let job = "steps:\n - checkout\n - store_test_results: { path: out }\n - run: cargo test\n"; + assert!(!changes(&repo("circleci", job), "yarn.lock")); +} + +#[test] +fn a_circleci_working_directory_is_the_checkout() { + // CircleCI checks out into the job's `working_directory`, so commands start in the root. + let job = "circleci:\n working_directory: ~/app\nsteps:\n - checkout\n - run: sh check.sh\n"; + assert!(!changes(&repo("circleci", job), "Gemfile.lock")); + let job = "circleci:\n working_directory: ~/app\nsteps:\n - checkout\n - run: { command: sh check.sh, working_directory: web }\n"; + assert!(changes(&repo("circleci", job), "Gemfile.lock")); +} + +#[test] +fn known_actions_by_name_and_local_composite_actions_by_their_steps() { + let with = |uses: &str| format!("steps:\n - uses: {uses}\n - run: cargo test\n"); + assert!(!changes( + &repo("github", &with("actions/checkout@v4")), + "yarn.lock" + )); + assert!(changes( + &repo("github", &with("actions/setup-node@v4")), + ".nvmrc" + )); + assert!(!changes( + &repo("github", &with("actions/setup-node@v4")), + "Gemfile.lock" + )); + assert!(changes( + &repo("github", &with("someone/anything@v1")), + "yarn.lock" + )); + + let local = |action: &str| { + let repo = repo("github", &with("./.github/actions/setup")); + repo.write(".github/actions/setup/action.yml", action); + repo + }; + let composite = |step: &str| format!("runs:\n using: composite\n steps:\n - {step}\n"); + let repo = local(&composite("run: bundle exec rake\n shell: bash")); + assert!(changes(&repo, "Gemfile.lock")); + assert!(!changes(&repo, "yarn.lock")); + assert!(changes( + &local(&composite("uses: someone/anything@v1")), + "yarn.lock" + )); + assert!(changes( + &local("runs:\n using: node20\n main: index.js\n"), + "yarn.lock" + )); +} + +#[test] +fn a_toolchain_reads_its_pins_where_it_runs_and_above() { + let repo = repo("github", "steps:\n - run: cd web/app && pnpm install\n"); + repo.write("web/app/pnpm-lock.yaml", "lockfileVersion: '9.0'\n") + .write("web/.nvmrc", "22\n") + .write("web/app/mise.toml", "[tools]\n") + .write("api/pnpm-lock.yaml", "lockfileVersion: '9.0'\n"); + assert!(changes(&repo, "web/app/pnpm-lock.yaml")); + assert!(changes(&repo, "web/.nvmrc")); + assert!(changes(&repo, "web/app/mise.toml")); + assert!(!changes(&repo, "api/pnpm-lock.yaml")); +} + +#[test] +fn more_pins_and_lockfiles_count() { + for (command, file) in [ + ("go test ./...", "go.mod"), + ("terraform validate", ".terraform.lock.hcl"), + ("yarn install", ".yarnrc.yml"), + ("gradle test", "gradle/wrapper/gradle-wrapper.properties"), + ("cargo test", ".config/mise.toml"), + ("cargo test", "mise.local.toml"), + ] { + let repo = repo("github", &format!("steps:\n - run: {command}\n")); + repo.write(file, "# pin\n"); + assert!(changes(&repo, file), "{command}: {file}"); + } +} + +#[test] +fn toolchains_adds_a_family_cigen_cannot_see_the_job_run() { + let job = "steps:\n - run: bundle exec rake assets\n"; + assert!(!changes(&repo("github", job), "yarn.lock")); + let job = "toolchains: [node]\nsteps:\n - run: bundle exec rake assets\n"; + assert!(changes(&repo("github", job), "yarn.lock")); + + let repo = repo("github", "toolchains: [nod]\nsteps:\n - run: cargo test\n"); + let output = support::cigen() + .current_dir(repo.path()) + .args(["validate", "--config", ".cigen"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "{stderr}"); + assert!( + stderr.contains("toolchain `nod`") && stderr.contains("did you mean `node`?"), + "{stderr}" + ); +} + +#[test] +fn a_narrowed_job_gets_package_json_only_with_node() { + let rust = repo("github", "steps:\n - run: cargo test\n"); + rust.write( + "web/package.json", + "{\"scripts\": {\"test\": \"vitest\"}}\n", + ); + assert!(!changes(&rust, "web/package.json")); + let node = repo("github", "steps:\n - run: node --test\n"); + node.write( + "web/package.json", + "{\"scripts\": {\"test\": \"vitest\"}}\n", + ); + assert!(changes(&node, "web/package.json")); +} diff --git a/tests/support/fixture_repo.rs b/tests/support/fixture_repo.rs index fd788c9..d68c3a8 100644 --- a/tests/support/fixture_repo.rs +++ b/tests/support/fixture_repo.rs @@ -42,6 +42,25 @@ impl FixtureRepo { self } + /// `cigen hash` for `job`, as the generated workflow runs it. + pub fn hash(&self, job: &str) -> String { + let output = super::cigen() + .current_dir(self.path()) + .args(["hash", "--job", job, "--config", ".cigen"]) + .output() + .expect("run cigen hash"); + assert!(output.status.success(), "{output:?}"); + String::from_utf8(output.stdout).expect("utf-8 hash") + } + + /// Whether `job`'s hash changes when a line is added to `path`. + pub fn hash_changes_after_changing(&self, job: &str, path: &str) -> bool { + let before = self.hash(job); + let contents = std::fs::read_to_string(self.path().join(path)).unwrap_or_default(); + self.write(path, &format!("{contents}# changed\n")); + before != self.hash(job) + } + /// Commits everything and returns the new commit's sha. pub fn commit(&self, message: &str) -> String { self.git(&["add", "--all"]);