From 1a735d446ffed5af03ea074f8a737bd8b5acfd3f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:09:35 +1300 Subject: [PATCH 1/3] Add cigen plan: hashes for a setup job, and the CircleCI config to continue with CircleCI parity item (b), first part: the command the setup job will call. The provider doesn't call it yet; that's the next PR, with the gate and mockci scenarios. - `cigen plan --hash-dir --job [=]...` writes each job's hash to /, the hash `cigen hash --job` prints, from one pass over the files. A job it can't hash (or a config that doesn't load) gets a one-off value no pass is recorded under, so the job runs. - `cigen plan --circleci-continue --passed --output ` drops each job with a file in --passed, closed under requires: a passed job stays while a job that requires it runs. cigen_gate always stays, requiring the jobs that remain, and its CIGEN_GATE_JOBS list shrinks to match. A config it can't plan is written unchanged, so every job runs; with nothing to skip, the output is the input byte for byte. hash.rs gains only `job_hashes` at the end, so it stays out of the way of tools' #14, which moves hashing to src/hashing/. --- docs/src/content/docs/cli.md | 32 ++++- internal_docs/STATUS.md | 8 +- src/commands/hash.rs | 33 +++++ src/commands/mod.rs | 3 + src/commands/plan.rs | 107 +++++++++++++++++ src/commands/plan_circleci.rs | 219 ++++++++++++++++++++++++++++++++++ src/main.rs | 7 ++ tests/cigen_plan.rs | 208 ++++++++++++++++++++++++++++++++ 8 files changed, 615 insertions(+), 2 deletions(-) create mode 100644 src/commands/plan.rs create mode 100644 src/commands/plan_circleci.rs create mode 100644 tests/cigen_plan.rs diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index c7c064c..370f5a6 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -1,6 +1,6 @@ --- title: CLI -description: cigen validate, cigen generate and cigen hash, with every option. +description: cigen validate, cigen generate, cigen hash and cigen plan, with every option. --- ```text @@ -100,6 +100,36 @@ cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock Patterns that match no files hash to the word `empty`. +## `cigen plan` + +The two halves of a CircleCI setup job that skips jobs which already passed. The CircleCI provider doesn't generate a +setup job that calls it yet (see [providers](/docs/providers/)). + +```sh +cigen plan --hash-dir /tmp/cigen/hashes --job build --job test=4f1c2a9e0b7d3e65 +cigen plan --circleci-continue .circleci/main.yml --passed /tmp/cigen/passed --output .circleci/planned.yml +``` + +With `--hash-dir`, it writes each job's hash to `/`, the same hash `cigen hash --job` prints. Give a job as +`=` when its hash step passes `--modules-digest `. A job it can't hash, or a config that doesn't +load, gets a one-off value that no pass is recorded under, so the job runs. + +With `--circleci-continue`, it writes the config to continue the pipeline with, without each job that has a file in +the `--passed` directory. A passed job stays when a job that requires it runs, since that job may need what it +produces. `cigen_gate` always stays, requiring only the jobs that remain, and the jobs it checks +(`CIGEN_GATE_JOBS` in its `environment`) shrink to match. If it can't plan the config, it writes it unchanged, so +every job runs. + +| Option | What it does | +| ---------------------------- | --------------------------------------------------------------------- | +| `--hash-dir ` | Write the hashes of the `--job`s here. | +| `--job [=]` | A job to hash. Repeat it for more jobs. | +| `--config ` | The config. Default: the one in `--base-dir`. | +| `--base-dir ` | The project root that inputs are relative to. Default `.`. | +| `--circleci-continue ` | The CircleCI config to continue with. | +| `--passed ` | A directory holding a file named after each job whose pass was found. | +| `--output ` | Where to write the planned config. | + ## Environment | Variable | What it does | diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 2b8ee1f..6e226ed 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -10,7 +10,10 @@ What the code does today, checked against the code in December 2026. Where cigen project that holds the config, wherever cigen runs. `cigen validate [--config ] [--format text|json]` loads the config and exits non-zero with every problem it found; `--format json` prints `{valid, config, errors: [{file, line, path, message, suggestion}]}` on stdout. Every command prints config errors - the same way (`src/commands/report.rs`). + the same way (`src/commands/report.rs`). `cigen plan` (`src/commands/plan.rs`, `plan_circleci.rs`) writes job + hashes to files (`--hash-dir`) and the CircleCI config to continue with, without the jobs whose passes were found, + closed under `requires`, keeping `cigen_gate` (`--circleci-continue`); both fail open. No generated config calls it + yet. - **Config loading** (`src/config/`, `src/schema/`): one schema in two layouts. `cigen.yml` is the whole document; `.cigen/` is the same document split into files (`config.yml` and `config/*.yml` for the top level, `commands/.yml`, `workflows/.yml` or `workflows//config.yml` for a workflow's settings, and @@ -112,6 +115,9 @@ What the code does today, checked against the code in December 2026. Where cigen the repository or the clock, and runs it again: an unchanged tree skips, a changed input or job definition runs (so does any key of a step), a failure records no pass, a pass expires after 7 idle days, a pull request reuses `main`'s passes but `main` can't reuse the pull request's. +- `tests/cigen_plan.rs`: `plan --hash-dir` matches `cigen hash --job` (and changes with an input), a job it can't hash + gets a value nothing matches; `plan --circleci-continue` drops passed jobs and trims the gate, keeps a passed job a + running job requires, and continues a config it can't plan unchanged. - `tests/config_layouts.rs`: both layouts load and hash the same, and the errors for both layouts present, a key in two files, unknown and provider-only keys, duplicate job ids and input group cycles. - `tests/json_schema.rs`: the committed schemas match the types, every config in the repository follows them, and they diff --git a/src/commands/hash.rs b/src/commands/hash.rs index a031825..1c8a8e0 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -153,6 +153,39 @@ fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { Ok(()) } +/// The hashes of several jobs, as `cigen hash --job [--modules-digest ]` prints +/// them, sharing one pass over the files. For `cigen plan`. +pub fn job_hashes( + base_dir: &Path, + config: Option<&Path>, + jobs: &[(String, Option)], +) -> Result>> { + let base_dir = canonicalize_path(base_dir)?; + let config_path = match config { + Some(path) => resolve_path(&base_dir, path), + None => cigen::config::find(&base_dir)?, + }; + let config = cigen::config::load(&config_path)?; + let mut file_hasher = FileHasher::new(None); + let mut pattern_cache: BTreeMap> = BTreeMap::new(); + Ok(jobs + .iter() + .map(|(job_id, modules_digest)| { + let digest = job_digest( + &config, + &base_dir, + job_id, + modules_digest.as_deref(), + &mut file_hasher, + &mut pattern_cache, + &mut Vec::new(), + ) + .map(hex::encode); + (job_id.clone(), digest) + }) + .collect()) +} + /// The digest of `job_id`. `generated_modules` is `--modules-digest`, given for the job being /// hashed; `chain` holds the jobs whose hashes are being computed, to catch a cycle in `needs`. fn job_digest( diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 558e145..a3a362d 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,9 +1,12 @@ mod generate; mod hash; mod needs_hash; +mod plan; +mod plan_circleci; pub mod report; mod validate; pub use generate::generate_command; pub use hash::{HashArgs, hash_command}; +pub use plan::{PlanArgs, plan_command}; pub use validate::{ValidateArgs, validate_command}; diff --git a/src/commands/plan.rs b/src/commands/plan.rs new file mode 100644 index 0000000..585f4c4 --- /dev/null +++ b/src/commands/plan.rs @@ -0,0 +1,107 @@ +//! `cigen plan`: what a setup job needs to skip jobs that already passed. On CircleCI it +//! hashes the jobs (`--hash-dir`), and then writes the config to continue with, without the jobs +//! whose passes the setup job restored (`--circleci-continue`). It fails open: a job it can't +//! hash, or a config it can't plan, means jobs run. + +use super::hash::job_hashes; +use super::plan_circleci; +use anyhow::{Context, Result, bail}; +use clap::Args; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Args)] +pub struct PlanArgs { + /// Write each `--job`'s hash to `/` + #[arg(long = "hash-dir", value_name = "DIR")] + pub hash_dir: Option, + + /// A job to hash, as `` or `=` (the digest its own hash step passes) + #[arg(long = "job", value_name = "ID[=DIGEST]")] + pub jobs: Vec, + + /// The config: a cigen.yml file or a .cigen/ directory (found in --base-dir by default) + #[arg(long = "config")] + pub config: Option, + + /// The directory job inputs are relative to + #[arg(long = "base-dir", default_value = ".")] + pub base_dir: PathBuf, + + /// The CircleCI config to continue with (the generated `.circleci/main.yml`) + #[arg( + long = "circleci-continue", + value_name = "FILE", + conflicts_with = "hash_dir" + )] + pub circleci_continue: Option, + + /// A directory holding a file named after each job whose pass was found + #[arg(long = "passed", value_name = "DIR", requires = "circleci_continue")] + pub passed: Option, + + /// Where to write the planned config + #[arg(long = "output", value_name = "FILE", requires = "circleci_continue")] + pub output: Option, +} + +pub fn plan_command(args: PlanArgs) -> Result<()> { + if let Some(main) = &args.circleci_continue { + let (Some(passed), Some(output)) = (&args.passed, &args.output) else { + bail!("`--circleci-continue` needs `--passed ` and `--output `"); + }; + return plan_circleci::continue_config(main, passed, output); + } + let Some(dir) = &args.hash_dir else { + bail!( + "say what to plan: `--hash-dir --job ...` hashes jobs, `--circleci-continue --passed --output ` writes the config to continue with" + ); + }; + if args.jobs.is_empty() { + bail!("`--hash-dir` needs at least one `--job `"); + } + write_hashes(&args, dir) +} + +fn write_hashes(args: &PlanArgs, dir: &Path) -> Result<()> { + let jobs: Vec<(String, Option)> = args + .jobs + .iter() + .map(|job| match job.split_once('=') { + Some((id, digest)) => (id.to_string(), Some(digest.to_string())), + None => (job.clone(), None), + }) + .collect(); + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let hashes = match job_hashes(&args.base_dir, args.config.as_deref(), &jobs) { + Ok(hashes) => hashes, + Err(error) => { + eprintln!("warning: cigen plan can't load the config, so every job runs: {error:#}"); + jobs.iter() + .map(|(id, _)| (id.clone(), Err(anyhow::anyhow!("the config didn't load")))) + .collect() + } + }; + for (id, hash) in hashes { + let value = match hash { + Ok(hash) => { + println!("{id} {hash}"); + hash + } + Err(error) => { + eprintln!("warning: cigen plan can't hash job `{id}`, so it runs: {error:#}"); + unplanned() + } + }; + let path = dir.join(&id); + std::fs::write(&path, value).with_context(|| format!("writing {}", path.display()))?; + } + Ok(()) +} + +/// A value no job records a pass under, so the job's lookup misses and it runs. +fn unplanned() -> String { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + format!("unplanned-{}-{nanos}", std::process::id()) +} diff --git a/src/commands/plan_circleci.rs b/src/commands/plan_circleci.rs new file mode 100644 index 0000000..5cd1168 --- /dev/null +++ b/src/commands/plan_circleci.rs @@ -0,0 +1,219 @@ +//! `cigen plan --circleci-continue`: the config to continue a CircleCI pipeline with, without +//! the jobs whose passes were found. A job is left out only if every job that requires it is +//! left out too (a job that runs may need what an upstream job produces). `cigen_gate` always +//! stays, requiring only the jobs that remain. + +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +/// The job that stands for the whole workflow in required checks. +pub const GATE: &str = "cigen_gate"; +/// The gate's variable listing the jobs it checks, space-separated. +pub const GATE_JOBS: &str = "CIGEN_GATE_JOBS"; + +/// Writes `main` without the passed jobs to `output`. If it can't plan, it writes `main` +/// unchanged, so every job runs. +pub fn continue_config(main: &Path, passed_dir: &Path, output: &Path) -> Result<()> { + let original = + std::fs::read_to_string(main).with_context(|| format!("reading {}", main.display()))?; + let passed = passed_jobs(passed_dir); + let planned = match plan(&original, &passed) { + Ok((text, skipped)) => { + if skipped.is_empty() { + println!("cigen plan: every job runs"); + } else { + let names: Vec<_> = skipped.into_iter().collect(); + println!("cigen plan: skipping {} (passed)", names.join(", ")); + } + text + } + Err(error) => { + eprintln!( + "warning: cigen plan can't plan {}, so every job runs: {error:#}", + main.display() + ); + original + } + }; + std::fs::write(output, planned).with_context(|| format!("writing {}", output.display())) +} + +/// The jobs with a file in `dir`. A missing directory means none passed. +fn passed_jobs(dir: &Path) -> BTreeSet { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|entry| entry.path().is_file()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect() +} + +fn key(name: &str) -> Value { + Value::String(name.to_string()) +} + +/// A workflow job entry's name and its settings, if any. +fn entry_parts(entry: &Value) -> Result<(String, Option<&Mapping>)> { + match entry { + Value::String(name) => Ok((name.clone(), None)), + Value::Mapping(single) if single.len() == 1 => { + let (job, settings) = single.iter().next().expect("one entry"); + let job = job + .as_str() + .context("a workflow job's name must be a string")?; + let settings = settings.as_mapping(); + let name = settings + .and_then(|s| s.get(key("name"))) + .and_then(Value::as_str) + .unwrap_or(job); + Ok((name.to_string(), settings)) + } + other => bail!("unexpected workflow job entry {other:?}"), + } +} + +/// The job a `requires` item names: `build`, or `build: `. +fn required_name(item: &Value) -> Result { + match item { + Value::String(name) => Ok(name.clone()), + Value::Mapping(single) if single.len() == 1 => single + .keys() + .next() + .and_then(Value::as_str) + .map(str::to_string) + .context("a `requires` item must name a job"), + other => bail!("unexpected `requires` item {other:?}"), + } +} + +fn requires_of(settings: Option<&Mapping>) -> Result> { + match settings.and_then(|s| s.get(key("requires"))) { + None => Ok(Vec::new()), + Some(Value::Sequence(items)) => items.iter().map(required_name).collect(), + Some(other) => bail!("`requires` must be a list, found {other:?}"), + } +} + +/// The planned config and the jobs it leaves out. +pub fn plan(text: &str, passed: &BTreeSet) -> Result<(String, BTreeSet)> { + let mut root: Value = serde_yaml::from_str(text).context("parsing the config")?; + let workflows = root + .get("workflows") + .and_then(Value::as_mapping) + .context("the config has no `workflows`")?; + + // Who requires whom, across every workflow; the gate requires everything, so it doesn't count. + let mut names = BTreeSet::new(); + let mut dependents: BTreeMap> = BTreeMap::new(); + for (_, workflow) in workflows { + let jobs = workflow + .get("jobs") + .and_then(Value::as_sequence) + .context("a workflow has no `jobs` list")?; + for entry in jobs { + let (name, settings) = entry_parts(entry)?; + if name == GATE { + continue; + } + for required in requires_of(settings)? { + dependents.entry(required).or_default().insert(name.clone()); + } + names.insert(name); + } + } + let mut skipped: BTreeSet = names.intersection(passed).cloned().collect(); + loop { + let blocked: Vec = skipped + .iter() + .filter(|job| { + dependents + .get(*job) + .is_some_and(|deps| deps.iter().any(|dep| !skipped.contains(dep))) + }) + .cloned() + .collect(); + if blocked.is_empty() { + break; + } + for job in blocked { + skipped.remove(&job); + } + } + + if skipped.is_empty() { + return Ok((text.to_string(), skipped)); + } + rewrite_workflows(&mut root, &skipped)?; + trim_gate_jobs(&mut root, &skipped); + Ok((serde_yaml::to_string(&root)?, skipped)) +} + +fn rewrite_workflows(root: &mut Value, skipped: &BTreeSet) -> Result<()> { + let workflows = root + .get_mut("workflows") + .and_then(Value::as_mapping_mut) + .expect("checked in plan"); + for (name, workflow) in workflows.iter_mut() { + let jobs = workflow + .get_mut("jobs") + .and_then(Value::as_sequence_mut) + .expect("checked in plan"); + let mut kept = Vec::new(); + for entry in jobs.drain(..) { + let (job_name, _) = entry_parts(&entry)?; + if skipped.contains(&job_name) { + continue; + } + kept.push(without_skipped_requires(entry, skipped)?); + } + if kept.is_empty() { + bail!("workflow {name:?} would have no jobs left"); + } + *jobs = kept; + } + Ok(()) +} + +/// `entry` with the skipped jobs taken out of its `requires`. +fn without_skipped_requires(mut entry: Value, skipped: &BTreeSet) -> Result { + let Value::Mapping(single) = &mut entry else { + return Ok(entry); + }; + let Some(Value::Mapping(settings)) = single.values_mut().next() else { + return Ok(entry); + }; + if let Some(Value::Sequence(items)) = settings.get_mut(key("requires")) { + let mut kept = Vec::new(); + for item in items.drain(..) { + if !skipped.contains(&required_name(&item)?) { + kept.push(item); + } + } + if kept.is_empty() { + settings.remove(key("requires")); + } else { + *items = kept; + } + } + Ok(entry) +} + +/// Takes the skipped jobs out of the gate's list of jobs to check. +fn trim_gate_jobs(root: &mut Value, skipped: &BTreeSet) { + let Some(Value::String(list)) = root + .get_mut("jobs") + .and_then(|jobs| jobs.get_mut(GATE)) + .and_then(|gate| gate.get_mut("environment")) + .and_then(|env| env.get_mut(GATE_JOBS)) + else { + return; + }; + *list = list + .split_whitespace() + .filter(|job| !skipped.contains(*job)) + .collect::>() + .join(" "); +} diff --git a/src/main.rs b/src/main.rs index 22e6d4a..5122007 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,12 @@ enum Commands { #[command(flatten)] args: commands::HashArgs, }, + /// Plan a setup job: hash jobs, then write the config to continue with, without the jobs + /// that already passed + Plan { + #[command(flatten)] + args: commands::PlanArgs, + }, /// Check the config and list every problem in it Validate { #[command(flatten)] @@ -66,6 +72,7 @@ fn run(cli: Cli) -> Result { Some(Commands::Hash { args }) => { commands::hash_command(args)?; } + Some(Commands::Plan { args }) => commands::plan_command(args)?, Some(Commands::Validate { args }) => return commands::validate_command(args), None => { // Default to generate command diff --git a/tests/cigen_plan.rs b/tests/cigen_plan.rs new file mode 100644 index 0000000..af21a92 --- /dev/null +++ b/tests/cigen_plan.rs @@ -0,0 +1,208 @@ +//! `cigen plan`: hashes for a setup job, and the CircleCI config to continue with. + +mod support; + +use serde_yaml::Value; +use std::path::Path; +use support::fixture_repo::FixtureRepo; + +const CONFIG: &str = r#"provider: circleci +workflows: + ci: + jobs: + build: + inputs: ["src/**"] + steps: [{ run: make }] + test: + needs: build + inputs: ["tests/**"] + steps: [{ run: make test }] +"#; + +fn cigen(repo: &Path, args: &[&str]) -> std::process::Output { + let output = support::cigen() + .current_dir(repo) + .args(args) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + output +} + +fn stdout(output: &std::process::Output) -> String { + String::from_utf8(output.stdout.clone()).unwrap() +} + +#[test] +fn hashes_match_cigen_hash_and_a_job_it_cant_hash_gets_a_value_nothing_matches() { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("src/lib.rs", "one\n") + .write("tests/a.rs", "a\n"); + repo.commit("initial"); + let path = repo.path(); + cigen( + path, + &[ + "plan", + "--hash-dir", + "hashes", + "--job", + "build", + "--job", + "test=abcd", + "--job", + "nope", + ], + ); + let read = |job: &str| std::fs::read_to_string(path.join("hashes").join(job)).unwrap(); + let hash = |args: &[&str]| stdout(&cigen(path, args)).trim().to_string(); + assert_eq!(read("build"), hash(&["hash", "--job", "build"])); + assert_eq!( + read("test"), + hash(&["hash", "--job", "test", "--modules-digest", "abcd"]) + ); + assert!(read("nope").starts_with("unplanned-"), "{}", read("nope")); + + repo.write("src/lib.rs", "two\n"); + repo.commit("change build's input"); + let before = read("build"); + cigen( + path, + &[ + "plan", + "--hash-dir", + "hashes", + "--job", + "build", + "--job", + "test=abcd", + ], + ); + assert_ne!(read("build"), before, "a changed input changes the hash"); +} + +const MAIN: &str = r#"version: '2.1' +jobs: + build: { docker: [{ image: cimg/base:current }], steps: [{ run: make }] } + test: { docker: [{ image: cimg/base:current }], steps: [{ run: make test }] } + lint: { docker: [{ image: cimg/base:current }], steps: [{ run: make lint }] } + cigen_gate: + docker: [{ image: cimg/base:current }] + environment: { CIGEN_GATE_JOBS: build test lint } + steps: [{ run: echo gate }] +workflows: + ci: + jobs: + - build + - test: { requires: [build] } + - lint + - cigen_gate: + requires: [{ build: terminal }, { test: terminal }, { lint: terminal }] +"#; + +/// Plans `MAIN` with `passed` jobs and returns the planned config. +fn plan(passed: &[&str], main: &str) -> (Value, String) { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("main.yml"), main).unwrap(); + std::fs::create_dir(dir.path().join("passed")).unwrap(); + for job in passed { + std::fs::write(dir.path().join("passed").join(job), "").unwrap(); + } + let output = cigen( + dir.path(), + &[ + "plan", + "--circleci-continue", + "main.yml", + "--passed", + "passed", + "--output", + "planned.yml", + ], + ); + let text = std::fs::read_to_string(dir.path().join("planned.yml")).unwrap(); + let log = format!( + "{}{}", + stdout(&output), + String::from_utf8_lossy(&output.stderr) + ); + ( + serde_yaml::from_str(&text).unwrap_or(Value::Null), + format!("{log}\n{text}"), + ) +} + +fn workflow_jobs(config: &Value) -> Vec { + config["workflows"]["ci"]["jobs"] + .as_sequence() + .unwrap() + .iter() + .map(|entry| match entry { + Value::String(name) => name.clone(), + Value::Mapping(map) => map.keys().next().unwrap().as_str().unwrap().to_string(), + _ => panic!(), + }) + .collect() +} + +#[test] +fn passed_jobs_leave_the_config_and_the_gate_checks_only_the_rest() { + let (config, log) = plan(&["lint"], MAIN); + assert_eq!( + workflow_jobs(&config), + ["build", "test", "cigen_gate"], + "{log}" + ); + let gate = &config["workflows"]["ci"]["jobs"][2]["cigen_gate"]["requires"]; + assert_eq!( + serde_yaml::to_string(gate).unwrap(), + "- build: terminal\n- test: terminal\n", + "{log}" + ); + assert_eq!( + config["jobs"]["cigen_gate"]["environment"]["CIGEN_GATE_JOBS"], "build test", + "{log}" + ); + assert!(log.contains("skipping lint"), "{log}"); +} + +#[test] +fn a_passed_job_stays_while_a_job_that_requires_it_runs() { + let (config, log) = plan(&["build"], MAIN); + assert_eq!( + workflow_jobs(&config), + ["build", "test", "lint", "cigen_gate"], + "{log}" + ); + let (config, log) = plan(&["build", "test"], MAIN); + assert_eq!(workflow_jobs(&config), ["lint", "cigen_gate"], "{log}"); + assert!( + config["workflows"]["ci"]["jobs"][1]["cigen_gate"]["requires"] + .as_sequence() + .unwrap() + .len() + == 1, + "{log}" + ); +} + +#[test] +fn a_config_it_cant_plan_is_continued_unchanged() { + for main in [ + "not: [valid", + "version: 2.1\njobs: {}\n", + "version: 2.1\nworkflows:\n ci:\n jobs: [only]\n", + ] { + let passed: &[&str] = if main.contains("only") { + &["only"] + } else { + &[] + }; + let (_, log) = plan(passed, main); + assert!(log.ends_with(main), "unchanged: {log}"); + if main.contains("only") { + assert!(log.contains("every job runs"), "{log}"); + } + } +} From 274b6684c1c295961a5057a624097dc6fa8aa88a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:59:56 +1300 Subject: [PATCH 2/3] =?UTF-8?q?cigen=20plan:=20fixes=20from=20review=20?= =?UTF-8?q?=E2=80=94=20merge=20keys,=20matrix,=20JSON=20output,=20duplicat?= =?UTF-8?q?e=20names,=20approvals,=20ids?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --circleci-continue applies YAML merge keys first, continues unchanged when a workflow entry has `matrix` or one name runs different jobs in two workflows, and checks that every remaining `requires` names an entry still in its workflow. It writes the planned config as JSON, so CircleCI's YAML 1.1 reads every string as written ("yes", "1:20"). An approval goes when everything waiting on it does. With --hash-dir, a pass counts only if its file holds the job's current hash. --hash-dir writes the bytes `cigen hash --job` prints, newline included (CircleCI keys on the file's checksum, so the setup job's key never matched a job's). Ids with `/` get subdirectories, ids that would leave the directory are refused, and a job that can't be written runs instead of stopping the rest. --- docs/src/content/docs/cli.md | 44 +++--- internal_docs/DIRECTION.md | 2 + internal_docs/STATUS.md | 13 +- src/commands/plan.rs | 34 +++- src/commands/plan_circleci.rs | 219 -------------------------- src/commands/plan_circleci/entries.rs | 110 +++++++++++++ src/commands/plan_circleci/mod.rs | 217 +++++++++++++++++++++++++ src/commands/plan_circleci/rewrite.rs | 107 +++++++++++++ tests/cigen_plan.rs | 36 ++++- tests/cigen_plan_circleci.rs | 159 +++++++++++++++++++ 10 files changed, 694 insertions(+), 247 deletions(-) delete mode 100644 src/commands/plan_circleci.rs create mode 100644 src/commands/plan_circleci/entries.rs create mode 100644 src/commands/plan_circleci/mod.rs create mode 100644 src/commands/plan_circleci/rewrite.rs create mode 100644 tests/cigen_plan_circleci.rs diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 4081911..0a1e09d 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -108,28 +108,36 @@ setup job that calls it yet (see [providers](/docs/providers/)). ```sh cigen plan --hash-dir /tmp/cigen/hashes --job build --job test=4f1c2a9e0b7d3e65 -cigen plan --circleci-continue .circleci/main.yml --passed /tmp/cigen/passed --output .circleci/planned.yml +cigen plan --circleci-continue .circleci/main.yml --passed /tmp/cigen/passed --hash-dir /tmp/cigen/hashes \ + --output .circleci/planned.yml ``` -With `--hash-dir`, it writes each job's hash to `/`, the same hash `cigen hash --job` prints. Give a job as -`=` when its hash step passes `--modules-digest `. A job it can't hash, or a config that doesn't -load, gets a one-off value that no pass is recorded under, so the job runs. +With `--hash-dir` and `--job`, it writes each job's hash to `/`: the bytes `cigen hash --job` prints, newline +included. Give a job as `=` when its hash step passes `--modules-digest `. A job in a subdirectory +(`build/compile`) gets a file in a subdirectory. A job it can't hash, or a config that doesn't load, gets a one-off +value that no pass is recorded under, so the job runs; an id that would leave the directory gets no file, and its job +runs. There's no `--matrix`: a job that runs GitHub's own matrix hashes each entry with `cigen hash --matrix`. With `--circleci-continue`, it writes the config to continue the pipeline with, without each job that has a file in -the `--passed` directory. A passed job stays when a job that requires it runs, since that job may need what it -produces. `cigen_gate` always stays, requiring only the jobs that remain, and the jobs it checks -(`CIGEN_GATE_JOBS` in its `environment`) shrink to match. If it can't plan the config, it writes it unchanged, so -every job runs. - -| Option | What it does | -| ---------------------------- | --------------------------------------------------------------------- | -| `--hash-dir ` | Write the hashes of the `--job`s here. | -| `--job [=]` | A job to hash. Repeat it for more jobs. | -| `--config ` | The config. Default: the one in `--base-dir`. | -| `--base-dir ` | The project root that inputs are relative to. Default `.`. | -| `--circleci-continue ` | The CircleCI config to continue with. | -| `--passed ` | A directory holding a file named after each job whose pass was found. | -| `--output ` | Where to write the planned config. | +the `--passed` directory. With `--hash-dir` too, a pass counts only if its file holds the job's hash from that +directory. A passed job stays when a job that requires it runs, since that job may need what it produces, and an +approval job goes when everything waiting on it does. The gate (`cigen_gate`, or `cigen_gate_`) always stays, +requiring only the jobs that remain, and the jobs it checks (`CIGEN_GATE_JOBS` in its `environment`) shrink to match. +The planned config is JSON, which CircleCI reads as YAML: every string stays quoted, so `"yes"` or `"1:20"` keeps its +meaning. + +It writes the config unchanged, so every job runs, when it can't plan it: a workflow entry with `matrix`, one name for +different jobs in two workflows, or a planned `requires` that would name a job no longer in its workflow. + +| Option | What it does | +| ---------------------------- | ------------------------------------------------------------------------------------------------- | +| `--hash-dir ` | Write the hashes of the `--job`s here, or, with `--circleci-continue`, check passes against them. | +| `--job [=]` | A job to hash. Repeat it for more jobs. | +| `--config ` | The config. Default: the one in `--base-dir`. | +| `--base-dir ` | The project root that inputs are relative to. Default `.`. | +| `--circleci-continue ` | The CircleCI config to continue with. | +| `--passed ` | A directory holding a file named after each job whose pass was found. | +| `--output ` | Where to write the planned config. | ## Environment diff --git a/internal_docs/DIRECTION.md b/internal_docs/DIRECTION.md index 23776e8..92e73cc 100644 --- a/internal_docs/DIRECTION.md +++ b/internal_docs/DIRECTION.md @@ -92,6 +92,8 @@ cigen_gate: - `cigen plan` hashes every planned job, looks the hashes up in the store in one batch, applies the rules below, and writes all its outputs at once at the end. A skipped job gets no runner. + `cigen plan --hash-dir` has no `--matrix` yet: before the GitHub planner uses it, a job that runs GitHub's own + matrix needs one hash per entry, as `cigen hash --matrix` gives it. - **Fail-open by construction.** A job runs unless the planner's output for it is exactly `skip`. A planner that crashes, times out or never starts leaves the output empty, so everything runs. `!cancelled()` stops GitHub's rule that a job is skipped when a job it needs failed: this way a failed planner doesn't skip the whole workflow. The diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 96b5072..2c74f0c 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -10,10 +10,12 @@ What the code does today, checked against the code in December 2026. Where cigen project that holds the config, wherever cigen runs. `cigen validate [--config ] [--format text|json]` loads the config and exits non-zero with every problem it found; `--format json` prints `{valid, config, errors: [{file, line, path, message, suggestion}]}` on stdout. Every command prints config errors - the same way (`src/commands/report.rs`). `cigen plan` (`src/commands/plan.rs`, `plan_circleci.rs`) writes job + the same way (`src/commands/report.rs`). `cigen plan` (`src/commands/plan.rs`, `plan_circleci/`) writes job hashes to files (`--hash-dir`) and the CircleCI config to continue with, without the jobs whose passes were found, - closed under `requires`, keeping `cigen_gate` (`--circleci-continue`); both fail open. No generated config calls it - yet. + closed under `requires`, dropping approvals nothing left waits on, keeping the gate, written as JSON so CircleCI's YAML + 1.1 reads every string as written (`--circleci-continue`; with `--hash-dir`, a pass counts only if it holds the job's + current hash). Both fail open: a matrix entry, one name for different jobs in two workflows, or a `requires` the plan + would leave dangling means the config continues unchanged. No generated config calls it yet. - **Config loading** (`src/config/`, `src/schema/`): one schema in two layouts. `cigen.yml` is the whole document; `.cigen/` is the same document split into files (`config.yml` and `config/*.yml` for the top level, `commands/.yml`, `workflows/.yml` or `workflows//config.yml` for a workflow's settings, and @@ -120,7 +122,10 @@ What the code does today, checked against the code in December 2026. Where cigen reuse the pull request's. - `tests/cigen_plan.rs`: `plan --hash-dir` matches `cigen hash --job` (and changes with an input), a job it can't hash gets a value nothing matches; `plan --circleci-continue` drops passed jobs and trims the gate, keeps a passed job a - running job requires, and continues a config it can't plan unchanged. + running job requires, and continues a config it can't plan unchanged; ids with `/` get subdirectories and none + leave the hash directory. `tests/cigen_plan_circleci.rs`: merge keys, matrix entries, unresolvable `requires`, + values YAML 1.1 would reread, one name in two workflows, approvals with nothing after them, and passes checked + against current hashes. - `tests/config_layouts.rs`: both layouts load and hash the same, and the errors for both layouts present, a key in two files, unknown and provider-only keys, duplicate job ids and input group cycles. - `tests/json_schema.rs`: the committed schemas match the types, every config in the repository follows them, and they diff --git a/src/commands/plan.rs b/src/commands/plan.rs index 585f4c4..968851b 100644 --- a/src/commands/plan.rs +++ b/src/commands/plan.rs @@ -11,7 +11,8 @@ use std::path::{Path, PathBuf}; #[derive(Debug, Args)] pub struct PlanArgs { - /// Write each `--job`'s hash to `/` + /// Write each `--job`'s hash to `/`. With `--circleci-continue`, read them + /// from there: a pass counts only if its file holds the job's hash #[arg(long = "hash-dir", value_name = "DIR")] pub hash_dir: Option, @@ -31,7 +32,7 @@ pub struct PlanArgs { #[arg( long = "circleci-continue", value_name = "FILE", - conflicts_with = "hash_dir" + conflicts_with = "jobs" )] pub circleci_continue: Option, @@ -49,7 +50,7 @@ pub fn plan_command(args: PlanArgs) -> Result<()> { let (Some(passed), Some(output)) = (&args.passed, &args.output) else { bail!("`--circleci-continue` needs `--passed ` and `--output `"); }; - return plan_circleci::continue_config(main, passed, output); + return plan_circleci::continue_config(main, passed, args.hash_dir.as_deref(), output); } let Some(dir) = &args.hash_dir else { bail!( @@ -81,6 +82,7 @@ fn write_hashes(args: &PlanArgs, dir: &Path) -> Result<()> { .collect() } }; + // Each job on its own: one that can't be hashed or written runs, and the rest still plan. for (id, hash) in hashes { let value = match hash { Ok(hash) => { @@ -92,12 +94,34 @@ fn write_hashes(args: &PlanArgs, dir: &Path) -> Result<()> { unplanned() } }; - let path = dir.join(&id); - std::fs::write(&path, value).with_context(|| format!("writing {}", path.display()))?; + if let Err(error) = write_hash(dir, &id, &value) { + eprintln!("warning: cigen plan can't write job `{id}`'s hash, so it runs: {error:#}"); + } } Ok(()) } +/// Writes `/`: the bytes `cigen hash --job` prints, newline included, since CircleCI +/// keys on the file's checksum and each job writes its own file from that command. An id with +/// `/` (a job in a subdirectory) gets subdirectories; one that could leave `dir` is refused. +fn write_hash(dir: &Path, id: &str, value: &str) -> Result<()> { + if id.is_empty() + || id.starts_with('/') + || id + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + bail!("`{id}` isn't a job id that can name a file"); + } + let path = dir.join(id); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("creating {}", parent.display()))?; + } + std::fs::write(&path, format!("{value}\n")) + .with_context(|| format!("writing {}", path.display())) +} + /// A value no job records a pass under, so the job's lookup misses and it runs. fn unplanned() -> String { let nanos = std::time::SystemTime::now() diff --git a/src/commands/plan_circleci.rs b/src/commands/plan_circleci.rs deleted file mode 100644 index 5cd1168..0000000 --- a/src/commands/plan_circleci.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! `cigen plan --circleci-continue`: the config to continue a CircleCI pipeline with, without -//! the jobs whose passes were found. A job is left out only if every job that requires it is -//! left out too (a job that runs may need what an upstream job produces). `cigen_gate` always -//! stays, requiring only the jobs that remain. - -use anyhow::{Context, Result, bail}; -use serde_yaml::{Mapping, Value}; -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - -/// The job that stands for the whole workflow in required checks. -pub const GATE: &str = "cigen_gate"; -/// The gate's variable listing the jobs it checks, space-separated. -pub const GATE_JOBS: &str = "CIGEN_GATE_JOBS"; - -/// Writes `main` without the passed jobs to `output`. If it can't plan, it writes `main` -/// unchanged, so every job runs. -pub fn continue_config(main: &Path, passed_dir: &Path, output: &Path) -> Result<()> { - let original = - std::fs::read_to_string(main).with_context(|| format!("reading {}", main.display()))?; - let passed = passed_jobs(passed_dir); - let planned = match plan(&original, &passed) { - Ok((text, skipped)) => { - if skipped.is_empty() { - println!("cigen plan: every job runs"); - } else { - let names: Vec<_> = skipped.into_iter().collect(); - println!("cigen plan: skipping {} (passed)", names.join(", ")); - } - text - } - Err(error) => { - eprintln!( - "warning: cigen plan can't plan {}, so every job runs: {error:#}", - main.display() - ); - original - } - }; - std::fs::write(output, planned).with_context(|| format!("writing {}", output.display())) -} - -/// The jobs with a file in `dir`. A missing directory means none passed. -fn passed_jobs(dir: &Path) -> BTreeSet { - std::fs::read_dir(dir) - .into_iter() - .flatten() - .flatten() - .filter(|entry| entry.path().is_file()) - .map(|entry| entry.file_name().to_string_lossy().into_owned()) - .collect() -} - -fn key(name: &str) -> Value { - Value::String(name.to_string()) -} - -/// A workflow job entry's name and its settings, if any. -fn entry_parts(entry: &Value) -> Result<(String, Option<&Mapping>)> { - match entry { - Value::String(name) => Ok((name.clone(), None)), - Value::Mapping(single) if single.len() == 1 => { - let (job, settings) = single.iter().next().expect("one entry"); - let job = job - .as_str() - .context("a workflow job's name must be a string")?; - let settings = settings.as_mapping(); - let name = settings - .and_then(|s| s.get(key("name"))) - .and_then(Value::as_str) - .unwrap_or(job); - Ok((name.to_string(), settings)) - } - other => bail!("unexpected workflow job entry {other:?}"), - } -} - -/// The job a `requires` item names: `build`, or `build: `. -fn required_name(item: &Value) -> Result { - match item { - Value::String(name) => Ok(name.clone()), - Value::Mapping(single) if single.len() == 1 => single - .keys() - .next() - .and_then(Value::as_str) - .map(str::to_string) - .context("a `requires` item must name a job"), - other => bail!("unexpected `requires` item {other:?}"), - } -} - -fn requires_of(settings: Option<&Mapping>) -> Result> { - match settings.and_then(|s| s.get(key("requires"))) { - None => Ok(Vec::new()), - Some(Value::Sequence(items)) => items.iter().map(required_name).collect(), - Some(other) => bail!("`requires` must be a list, found {other:?}"), - } -} - -/// The planned config and the jobs it leaves out. -pub fn plan(text: &str, passed: &BTreeSet) -> Result<(String, BTreeSet)> { - let mut root: Value = serde_yaml::from_str(text).context("parsing the config")?; - let workflows = root - .get("workflows") - .and_then(Value::as_mapping) - .context("the config has no `workflows`")?; - - // Who requires whom, across every workflow; the gate requires everything, so it doesn't count. - let mut names = BTreeSet::new(); - let mut dependents: BTreeMap> = BTreeMap::new(); - for (_, workflow) in workflows { - let jobs = workflow - .get("jobs") - .and_then(Value::as_sequence) - .context("a workflow has no `jobs` list")?; - for entry in jobs { - let (name, settings) = entry_parts(entry)?; - if name == GATE { - continue; - } - for required in requires_of(settings)? { - dependents.entry(required).or_default().insert(name.clone()); - } - names.insert(name); - } - } - let mut skipped: BTreeSet = names.intersection(passed).cloned().collect(); - loop { - let blocked: Vec = skipped - .iter() - .filter(|job| { - dependents - .get(*job) - .is_some_and(|deps| deps.iter().any(|dep| !skipped.contains(dep))) - }) - .cloned() - .collect(); - if blocked.is_empty() { - break; - } - for job in blocked { - skipped.remove(&job); - } - } - - if skipped.is_empty() { - return Ok((text.to_string(), skipped)); - } - rewrite_workflows(&mut root, &skipped)?; - trim_gate_jobs(&mut root, &skipped); - Ok((serde_yaml::to_string(&root)?, skipped)) -} - -fn rewrite_workflows(root: &mut Value, skipped: &BTreeSet) -> Result<()> { - let workflows = root - .get_mut("workflows") - .and_then(Value::as_mapping_mut) - .expect("checked in plan"); - for (name, workflow) in workflows.iter_mut() { - let jobs = workflow - .get_mut("jobs") - .and_then(Value::as_sequence_mut) - .expect("checked in plan"); - let mut kept = Vec::new(); - for entry in jobs.drain(..) { - let (job_name, _) = entry_parts(&entry)?; - if skipped.contains(&job_name) { - continue; - } - kept.push(without_skipped_requires(entry, skipped)?); - } - if kept.is_empty() { - bail!("workflow {name:?} would have no jobs left"); - } - *jobs = kept; - } - Ok(()) -} - -/// `entry` with the skipped jobs taken out of its `requires`. -fn without_skipped_requires(mut entry: Value, skipped: &BTreeSet) -> Result { - let Value::Mapping(single) = &mut entry else { - return Ok(entry); - }; - let Some(Value::Mapping(settings)) = single.values_mut().next() else { - return Ok(entry); - }; - if let Some(Value::Sequence(items)) = settings.get_mut(key("requires")) { - let mut kept = Vec::new(); - for item in items.drain(..) { - if !skipped.contains(&required_name(&item)?) { - kept.push(item); - } - } - if kept.is_empty() { - settings.remove(key("requires")); - } else { - *items = kept; - } - } - Ok(entry) -} - -/// Takes the skipped jobs out of the gate's list of jobs to check. -fn trim_gate_jobs(root: &mut Value, skipped: &BTreeSet) { - let Some(Value::String(list)) = root - .get_mut("jobs") - .and_then(|jobs| jobs.get_mut(GATE)) - .and_then(|gate| gate.get_mut("environment")) - .and_then(|env| env.get_mut(GATE_JOBS)) - else { - return; - }; - *list = list - .split_whitespace() - .filter(|job| !skipped.contains(*job)) - .collect::>() - .join(" "); -} diff --git a/src/commands/plan_circleci/entries.rs b/src/commands/plan_circleci/entries.rs new file mode 100644 index 0000000..8fdc677 --- /dev/null +++ b/src/commands/plan_circleci/entries.rs @@ -0,0 +1,110 @@ +//! A CircleCI workflow's job entries, as `cigen plan` reads them: `build`, or +//! `build: { name, requires, type, ... }`. + +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value}; + +pub fn key(name: &str) -> Value { + Value::String(name.to_string()) +} + +/// One entry of a workflow's `jobs` list. +pub struct Entry<'a> { + /// The job it runs (the key under `jobs:`). + pub job: String, + /// What other entries' `requires` call it: its `name`, or the job. + pub name: String, + pub settings: Option<&'a Mapping>, +} + +impl Entry<'_> { + pub fn requires(&self) -> Result> { + match self.settings.and_then(|s| s.get(key("requires"))) { + None => Ok(Vec::new()), + Some(Value::Sequence(items)) => items.iter().map(required_name).collect(), + Some(other) => bail!("`requires` must be a list, found {other:?}"), + } + } + + pub fn is_approval(&self) -> bool { + self.settings + .and_then(|s| s.get(key("type"))) + .and_then(Value::as_str) + == Some("approval") + } + + pub fn has(&self, setting: &str) -> bool { + self.settings.is_some_and(|s| s.contains_key(key(setting))) + } +} + +pub fn entry(value: &Value) -> Result> { + match value { + Value::String(name) => Ok(Entry { + job: name.clone(), + name: name.clone(), + settings: None, + }), + Value::Mapping(single) if single.len() == 1 => { + let (job, settings) = single.iter().next().expect("one entry"); + let job = job + .as_str() + .context("a workflow job's name must be a string")? + .to_string(); + let settings = match settings { + Value::Mapping(settings) => Some(settings), + Value::Null => None, + other => bail!("job `{job}`'s settings must be a mapping, found {other:?}"), + }; + let name = match settings.and_then(|s| s.get(key("name"))) { + None => job.clone(), + Some(Value::String(name)) => name.clone(), + Some(other) => bail!("job `{job}`'s `name` must be a string, found {other:?}"), + }; + Ok(Entry { + job, + name, + settings, + }) + } + other => bail!("unexpected workflow job entry {other:?}"), + } +} + +/// The job a `requires` item names: `build`, or `build: `. +pub fn required_name(item: &Value) -> Result { + match item { + Value::String(name) => Ok(name.clone()), + Value::Mapping(single) if single.len() == 1 => single + .keys() + .next() + .and_then(Value::as_str) + .map(str::to_string) + .context("a `requires` item must name a job"), + other => bail!("unexpected `requires` item {other:?}"), + } +} + +/// Each workflow's name and its entries, in order. +pub fn workflows(root: &Value) -> Result>)>> { + let workflows = root + .get("workflows") + .and_then(Value::as_mapping) + .context("the config has no `workflows`")?; + let mut all = Vec::new(); + for (name, workflow) in workflows { + let name = name + .as_str() + .context("a workflow's name must be a string")? + .to_string(); + if name == "version" { + continue; // config 2.0's `workflows: { version: 2 }` + } + let jobs = workflow + .get("jobs") + .and_then(Value::as_sequence) + .with_context(|| format!("workflow `{name}` has no `jobs` list"))?; + all.push((name, jobs.iter().map(entry).collect::>>()?)); + } + Ok(all) +} diff --git a/src/commands/plan_circleci/mod.rs b/src/commands/plan_circleci/mod.rs new file mode 100644 index 0000000..604ccfd --- /dev/null +++ b/src/commands/plan_circleci/mod.rs @@ -0,0 +1,217 @@ +//! `cigen plan --circleci-continue`: the config to continue a CircleCI pipeline with, without +//! the jobs whose passes were found. A job is left out only if every job that requires it is +//! left out too (a job that runs may need what an upstream job produces), and an approval is +//! left out when everything waiting on it is. The gate (`cigen_gate`, or +//! `cigen_gate_` with several workflows) always stays, requiring only the jobs that +//! remain. +//! +//! It plans only what it can model, and continues with the config unchanged otherwise: a +//! `matrix` entry, or the same name for different jobs in two workflows. Before writing, it +//! checks that every remaining `requires` names an entry still in its workflow. + +mod entries; +mod rewrite; + +use anyhow::{Context, Result, bail}; +use entries::{Entry, workflows}; +use serde_yaml::Value; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +/// The job that stands for the whole workflow in required checks. +pub const GATE: &str = "cigen_gate"; +/// The gate's variable listing the jobs it checks, space-separated. +pub const GATE_JOBS: &str = "CIGEN_GATE_JOBS"; + +/// Whether `name` is a gate: `cigen_gate`, or `cigen_gate_`. +pub fn is_gate(name: &str) -> bool { + name == GATE || name.starts_with("cigen_gate_") +} + +/// Writes `main` without the passed jobs to `output`. With `hash_dir`, a job's pass counts only +/// if its file holds the job's hash from there. If it can't plan, it writes `main` unchanged, +/// so every job runs. +pub fn continue_config( + main: &Path, + passed_dir: &Path, + hash_dir: Option<&Path>, + output: &Path, +) -> Result<()> { + let original = + std::fs::read_to_string(main).with_context(|| format!("reading {}", main.display()))?; + let passed = passed_jobs(passed_dir, hash_dir); + let planned = match plan(&original, &passed) { + Ok(planned) => { + if planned.skipped.is_empty() { + println!("cigen plan: every job runs"); + } else { + let names: Vec<_> = planned.skipped.into_iter().collect(); + println!("cigen plan: skipping {} (passed)", names.join(", ")); + } + if !planned.dropped_approvals.is_empty() { + let names: Vec<_> = planned.dropped_approvals.into_iter().collect(); + println!( + "cigen plan: leaving out {} (nothing left waits on it)", + names.join(", ") + ); + } + planned.text + } + Err(error) => { + eprintln!( + "warning: cigen plan can't plan {}, so every job runs: {error:#}", + main.display() + ); + original + } + }; + std::fs::write(output, planned).with_context(|| format!("writing {}", output.display())) +} + +/// The jobs with a file in `dir` (holding the job's hash from `hash_dir`, when given). A +/// missing directory means none passed. +fn passed_jobs(dir: &Path, hash_dir: Option<&Path>) -> BTreeSet { + let read = |path: &Path| std::fs::read_to_string(path).map(|text| text.trim().to_string()); + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|entry| entry.path().is_file()) + .filter(|entry| { + let Some(hashes) = hash_dir else { + return true; + }; + match (read(&entry.path()), read(&hashes.join(entry.file_name()))) { + (Ok(passed), Ok(hash)) if !hash.is_empty() && passed == hash => true, + _ => { + eprintln!( + "cigen plan: the pass found for {} isn't for its current hash, so it runs", + entry.file_name().to_string_lossy() + ); + false + } + } + }) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect() +} + +pub struct Planned { + /// The config to continue with. + pub text: String, + /// The passed jobs it leaves out. + pub skipped: BTreeSet, + /// The approval jobs it leaves out, since everything after them was. + pub dropped_approvals: BTreeSet, +} + +/// Plans `text` with the `passed` jobs left out. +pub fn plan(text: &str, passed: &BTreeSet) -> Result { + let mut root: Value = serde_yaml::from_str(text).context("parsing the config")?; + root.apply_merge().context("applying `<<` merge keys")?; + + let (names, approvals, dependents) = { + let workflows = workflows(&root)?; + check_names(&workflows)?; + let mut names = BTreeSet::new(); + let mut approvals = BTreeSet::new(); + // Who requires whom; the gate requires everything, so it doesn't count. + let mut dependents: BTreeMap> = BTreeMap::new(); + for (_, entries) in &workflows { + for entry in entries.iter().filter(|entry| !is_gate(&entry.name)) { + for required in entry.requires()? { + dependents + .entry(required) + .or_default() + .insert(entry.name.clone()); + } + if entry.is_approval() { + approvals.insert(entry.name.clone()); + } + names.insert(entry.name.clone()); + } + } + (names, approvals, dependents) + }; + + // Passed jobs, and approvals something waits on, can go; then keep each one that something + // staying requires, until nothing changes. + let mut leaving: BTreeSet = names.intersection(passed).cloned().collect(); + leaving.extend( + approvals + .iter() + .filter(|name| dependents.contains_key(*name)) + .cloned(), + ); + loop { + let kept: Vec = leaving + .iter() + .filter(|job| { + dependents + .get(*job) + .is_some_and(|deps| deps.iter().any(|dep| !leaving.contains(dep))) + }) + .cloned() + .collect(); + if kept.is_empty() { + break; + } + for job in kept { + leaving.remove(&job); + } + } + let (dropped_approvals, skipped): (BTreeSet, BTreeSet) = leaving + .iter() + .cloned() + .partition(|name| approvals.contains(name)); + if skipped.is_empty() { + return Ok(Planned { + text: text.to_string(), + skipped, + dropped_approvals: BTreeSet::new(), + }); + } + + rewrite::without(&mut root, &leaving)?; + rewrite::check_requires(&root)?; + // JSON is YAML, and quotes every string: re-serialised YAML would write `"yes"`, `"1:20"` + // or `"1_000"` bare, and CircleCI reads YAML 1.1, where those are a boolean and numbers. + let text = serde_json::to_string_pretty(&root).context("writing the planned config")?; + Ok(Planned { + text: format!("{text}\n"), + skipped, + dropped_approvals, + }) +} + +/// Refuses what the name model can't plan: a `matrix` entry (its instances and its `alias` +/// have names cigen doesn't derive), or one name for different entries, since a pass is +/// recorded by name. +fn check_names(workflows: &[(String, Vec>)]) -> Result<()> { + let mut seen: BTreeMap<&str, (&str, &Entry<'_>)> = BTreeMap::new(); + for (workflow, entries) in workflows { + let mut in_workflow = BTreeSet::new(); + for entry in entries { + if entry.has("matrix") { + bail!( + "workflow `{workflow}` runs `{}` with `matrix`, which cigen plan doesn't model", + entry.job + ); + } + if !in_workflow.insert(entry.name.as_str()) { + bail!("workflow `{workflow}` has two jobs named `{}`", entry.name); + } + if let Some((other, earlier)) = seen.get(entry.name.as_str()) { + if earlier.job != entry.job || earlier.settings != entry.settings { + bail!( + "workflows `{other}` and `{workflow}` both have a job named `{}`, running different jobs or settings", + entry.name + ); + } + } else { + seen.insert(&entry.name, (workflow, entry)); + } + } + } + Ok(()) +} diff --git a/src/commands/plan_circleci/rewrite.rs b/src/commands/plan_circleci/rewrite.rs new file mode 100644 index 0000000..524e538 --- /dev/null +++ b/src/commands/plan_circleci/rewrite.rs @@ -0,0 +1,107 @@ +//! Taking jobs out of a CircleCI config: their workflow entries, their names in `requires`, +//! and the gates' lists of jobs to check. + +use super::entries::{entry, key, required_name, workflows}; +use super::{GATE_JOBS, is_gate}; +use anyhow::{Result, bail}; +use serde_yaml::Value; +use std::collections::BTreeSet; + +/// `root` without the `leaving` entries. +pub fn without(root: &mut Value, leaving: &BTreeSet) -> Result<()> { + if let Some(Value::Mapping(workflows)) = root.get_mut("workflows") { + for (name, workflow) in workflows.iter_mut() { + let Some(Value::Sequence(jobs)) = workflow.get_mut("jobs") else { + continue; + }; + let mut kept = Vec::new(); + for item in jobs.drain(..) { + if leaving.contains(&entry(&item)?.name) { + continue; + } + kept.push(without_requires(item, leaving)?); + } + if kept.is_empty() { + bail!("workflow {name:?} would have no jobs left"); + } + *jobs = kept; + } + } + trim_gates(root, leaving); + Ok(()) +} + +/// `item` with the leaving jobs taken out of its `requires`. +fn without_requires(mut item: Value, leaving: &BTreeSet) -> Result { + let Value::Mapping(single) = &mut item else { + return Ok(item); + }; + let Some(Value::Mapping(settings)) = single.values_mut().next() else { + return Ok(item); + }; + if let Some(Value::Sequence(items)) = settings.get_mut(key("requires")) { + let mut kept = Vec::new(); + for required in items.drain(..) { + if !leaving.contains(&required_name(&required)?) { + kept.push(required); + } + } + if kept.is_empty() { + settings.remove(key("requires")); + } else { + *items = kept; + } + } + Ok(item) +} + +/// Takes the leaving jobs out of each gate's list of jobs to check (`job`, or +/// `job:`). A gate left with nothing to check has no workspace to attach. +fn trim_gates(root: &mut Value, leaving: &BTreeSet) { + let Some(Value::Mapping(jobs)) = root.get_mut("jobs") else { + return; + }; + for (name, gate) in jobs.iter_mut() { + if !name.as_str().is_some_and(is_gate) { + continue; + } + let Some(Value::String(list)) = gate + .get_mut("environment") + .and_then(|env| env.get_mut(GATE_JOBS)) + else { + continue; + }; + *list = list + .split_whitespace() + .filter(|item| { + let job = item.split_once(':').map_or(*item, |(job, _)| job); + !leaving.contains(job) + }) + .collect::>() + .join(" "); + if list.is_empty() + && let Some(Value::Sequence(steps)) = gate.get_mut("steps") + { + steps.retain(|step| step.get("attach_workspace").is_none()); + } + } +} + +/// Every remaining `requires` names an entry still in its own workflow: whatever the name +/// model missed, the planned config must still compile. +pub fn check_requires(root: &Value) -> Result<()> { + for (workflow, entries) in workflows(root)? { + let names: BTreeSet<&str> = entries.iter().map(|entry| entry.name.as_str()).collect(); + for entry in &entries { + for required in entry.requires()? { + if !names.contains(required.as_str()) { + bail!( + "in workflow `{workflow}`, `{}` would require `{required}`, which isn't in the planned workflow", + entry.name + ); + } + } + } + } + Ok(()) +} diff --git a/tests/cigen_plan.rs b/tests/cigen_plan.rs index af21a92..7c9793c 100644 --- a/tests/cigen_plan.rs +++ b/tests/cigen_plan.rs @@ -56,7 +56,9 @@ fn hashes_match_cigen_hash_and_a_job_it_cant_hash_gets_a_value_nothing_matches() ], ); let read = |job: &str| std::fs::read_to_string(path.join("hashes").join(job)).unwrap(); - let hash = |args: &[&str]| stdout(&cigen(path, args)).trim().to_string(); + // Byte for byte, newline included: CircleCI's cache key is the checksum of the file, and a + // job writes its own with `cigen hash --job > `. + let hash = |args: &[&str]| stdout(&cigen(path, args)); assert_eq!(read("build"), hash(&["hash", "--job", "build"])); assert_eq!( read("test"), @@ -82,6 +84,38 @@ fn hashes_match_cigen_hash_and_a_job_it_cant_hash_gets_a_value_nothing_matches() assert_ne!(read("build"), before, "a changed input changes the hash"); } +/// A job in a subdirectory gets a file in a subdirectory, an id that would leave the directory +/// gets nothing, and neither stops the other jobs being hashed. +#[test] +fn ids_with_slashes_get_subdirectories_and_none_leave_the_hash_dir() { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG).write("src/lib.rs", "one\n"); + repo.commit("initial"); + let path = repo.path(); + let output = cigen( + path, + &[ + "plan", + "--hash-dir", + "out/hashes", + "--job", + "group/nested", + "--job", + "../escaped", + "--job", + "/abs", + "--job", + "build", + ], + ); + let log = String::from_utf8_lossy(&output.stderr); + assert!(path.join("out/hashes/group/nested").is_file(), "{log}"); + assert!(!path.join("out/escaped").exists(), "{log}"); + assert!(log.contains("`../escaped` isn't a job id"), "{log}"); + assert!(log.contains("`/abs` isn't a job id"), "{log}"); + assert!(path.join("out/hashes/build").is_file(), "{log}"); +} + const MAIN: &str = r#"version: '2.1' jobs: build: { docker: [{ image: cimg/base:current }], steps: [{ run: make }] } diff --git a/tests/cigen_plan_circleci.rs b/tests/cigen_plan_circleci.rs new file mode 100644 index 0000000..a04ad9f --- /dev/null +++ b/tests/cigen_plan_circleci.rs @@ -0,0 +1,159 @@ +//! `cigen plan --circleci-continue` on configs its name model doesn't cover: it plans what it +//! can prove compiles and means the same, and continues with the config unchanged otherwise. + +mod support; + +use serde_yaml::Value; +use std::path::Path; + +/// Plans `main` with `passed` (job, file contents) and, when given, `hashes` (job, hash). +/// Returns the planned text and the log. +fn plan(main: &str, passed: &[(&str, &str)], hashes: Option<&[(&str, &str)]>) -> (String, String) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path(); + std::fs::write(path.join("main.yml"), main).unwrap(); + write_files(&path.join("passed"), passed); + let mut args = vec![ + "plan", + "--circleci-continue", + "main.yml", + "--passed", + "passed", + "--output", + "planned.yml", + ]; + if let Some(hashes) = hashes { + write_files(&path.join("hashes"), hashes); + args.extend(["--hash-dir", "hashes"]); + } + let output = support::cigen() + .current_dir(path) + .args(&args) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let text = std::fs::read_to_string(path.join("planned.yml")).unwrap(); + let log = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + (text, log) +} + +fn write_files(dir: &Path, files: &[(&str, &str)]) { + std::fs::create_dir_all(dir).unwrap(); + for (name, contents) in files { + std::fs::write(dir.join(name), contents).unwrap(); + } +} + +/// The names of the entries in `workflow`, in order. +fn entries(text: &str, workflow: &str) -> Vec { + let config: Value = serde_yaml::from_str(text).unwrap(); + config["workflows"][workflow]["jobs"] + .as_sequence() + .unwrap() + .iter() + .map(|entry| match entry { + Value::String(name) => name.clone(), + Value::Mapping(map) => map.keys().next().unwrap().as_str().unwrap().to_string(), + other => panic!("{other:?}"), + }) + .collect() +} + +const JOBS: &str = "jobs:\n build: { docker: [{ image: cimg/base:current }], steps: [{ run: make }] }\n test: { docker: [{ image: cimg/base:current }], steps: [{ run: make test }] }\n deploy: { docker: [{ image: cimg/base:current }], steps: [{ run: make deploy }] }\n"; + +fn config(workflows: &str) -> String { + format!("version: 2.1\n{JOBS}workflows:\n{workflows}") +} + +#[test] +fn merge_keys_count_as_requires() { + let main = config( + " ci:\n jobs:\n - build\n - test: &needs_build\n requires: [build]\n - deploy:\n <<: *needs_build\n", + ); + let (text, log) = plan(&main, &[("build", ""), ("test", "")], None); + assert_eq!(entries(&text, "ci"), ["build", "deploy"], "{log}\n{text}"); +} + +#[test] +fn a_matrix_entry_leaves_the_config_unchanged() { + let main = config( + " ci:\n jobs:\n - build:\n matrix: { alias: builds, parameters: { os: [a, b] } }\n - test: { requires: [builds] }\n", + ); + let (text, log) = plan(&main, &[("build", "")], None); + assert_eq!(text, main, "{log}"); + assert!(log.contains("matrix"), "{log}"); +} + +#[test] +fn a_requires_it_cant_resolve_leaves_the_config_unchanged() { + // `test` requires the entry by its job, not its name: the planned config must still compile. + let main = config( + " ci:\n jobs:\n - build: { name: compile }\n - test: { requires: [build] }\n", + ); + let (text, log) = plan(&main, &[("compile", "")], None); + assert_eq!(text, main, "{log}"); + assert!(log.contains("isn't in the planned workflow"), "{log}"); +} + +#[test] +fn values_in_jobs_that_run_keep_their_meaning() { + let main = format!( + "version: 2.1\n{JOBS} slow:\n docker: [{{ image: cimg/base:current }}]\n environment: {{ RUN_SLOW: \"yes\", TIMEOUT: \"1:20\", SIZE: \"1_000\", FLAG: \"off\" }}\n steps: [{{ run: make slow }}]\nworkflows:\n ci:\n jobs: [build, slow]\n" + ); + let (text, log) = plan(&main, &[("build", "")], None); + let planned: serde_json::Value = serde_json::from_str(&text).expect("the plan is JSON"); + let env = &planned["jobs"]["slow"]["environment"]; + assert_eq!(env["RUN_SLOW"], "yes", "{log}\n{text}"); + assert_eq!(env["TIMEOUT"], "1:20", "{log}\n{text}"); + assert_eq!(env["SIZE"], "1_000", "{log}\n{text}"); + assert_eq!(env["FLAG"], "off", "{log}\n{text}"); +} + +#[test] +fn one_name_for_different_jobs_in_two_workflows_leaves_the_config_unchanged() { + let main = + config(" linux:\n jobs: [build]\n mac:\n jobs:\n - deploy: { name: build }\n"); + let (text, log) = plan(&main, &[("build", "")], None); + assert_eq!(text, main, "{log}"); + assert!(log.contains("both have a job named `build`"), "{log}"); + + // The same job in both workflows is one job with one hash, so its pass counts for both. + let main = config(" linux:\n jobs: [build, test]\n mac:\n jobs: [build, deploy]\n"); + let (text, log) = plan(&main, &[("build", "")], None); + assert_eq!(entries(&text, "linux"), ["test"], "{log}"); + assert_eq!(entries(&text, "mac"), ["deploy"], "{log}"); +} + +#[test] +fn an_approval_with_nothing_left_after_it_goes_too() { + let main = config( + " ci:\n jobs:\n - build\n - hold: { type: approval, requires: [build] }\n - deploy: { requires: [hold] }\n", + ); + let (text, log) = plan(&main, &[("deploy", "")], None); + assert_eq!(entries(&text, "ci"), ["build"], "{log}\n{text}"); + assert!(log.contains("leaving out hold"), "{log}"); + + let (text, log) = plan(&main, &[("build", "")], None); + assert_eq!( + entries(&text, "ci"), + ["build", "hold", "deploy"], + "deploy runs, so hold and build stay: {log}" + ); +} + +#[test] +fn with_hashes_a_pass_counts_only_for_the_jobs_current_hash() { + let main = config(" ci:\n jobs: [build, test]\n"); + let hashes: &[(&str, &str)] = &[("build", "aaa\n"), ("test", "bbb\n")]; + let (text, log) = plan( + &main, + &[("build", "aaa\n"), ("test", "old\n")], + Some(hashes), + ); + assert_eq!(entries(&text, "ci"), ["test"], "{log}\n{text}"); + assert!(log.contains("isn't for its current hash"), "{log}"); +} From da90f748c3aba06c445c752ff3ade8f128ccbeda Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 17:29:58 +1300 Subject: [PATCH 3/3] cigen plan: exact gates, reserved cigen_ ids, YAML 1.1 values, a warning for GitHub matrices A gate is a job named cigen_gate or cigen_gate_ that carries CIGEN_GATE_JOBS, so a user's cigen_gate_smoke keeps the jobs it requires (it lost them: a false skip). The config loader rejects job ids starting with cigen_. src/yaml11 finds plain scalars that YAML 1.1 reads differently from YAML 1.2 (saphyr-parser reports each scalar's style), and --circleci-continue continues unchanged when a config it would rewrite has one. --hash-dir warns for a job that runs GitHub's own matrix, whose base hash matches no entry's. --- Cargo.lock | 17 ++ Cargo.toml | 1 + docs/src/content/docs/cli.md | 5 +- docs/src/content/docs/configuration.md | 6 +- internal_docs/STATUS.md | 10 +- src/commands/hash.rs | 5 +- src/commands/plan.rs | 11 +- src/commands/plan_circleci/mod.rs | 49 +++++- src/commands/plan_circleci/rewrite.rs | 14 +- src/config/lower.rs | 12 ++ src/lib.rs | 1 + src/yaml11/mod.rs | 59 +++++++ src/yaml11/resolve.rs | 213 +++++++++++++++++++++++++ tests/cigen_plan.rs | 28 ++++ tests/cigen_plan_circleci.rs | 30 ++++ tests/validate.rs | 22 +++ 16 files changed, 460 insertions(+), 23 deletions(-) create mode 100644 src/yaml11/mod.rs create mode 100644 src/yaml11/resolve.rs diff --git a/Cargo.lock b/Cargo.lock index d13fa4c..ef6ad0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -102,6 +102,12 @@ version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + [[package]] name = "assert_cmd" version = "2.0.17" @@ -340,6 +346,7 @@ dependencies = [ "predicates", "prost", "regex", + "saphyr-parser", "schemars", "serde", "serde_json", @@ -1760,6 +1767,16 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "saphyr-parser" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8af5472a0fd13242ab1e30a2ae6290d5b875a095dd17b21c26d01d556cf766bd" +dependencies = [ + "arraydeque", + "thiserror", +] + [[package]] name = "schemars" version = "1.2.3" diff --git a/Cargo.toml b/Cargo.toml index 71d2a0d..2f15408 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ hex = "0.4.3" strsim = "0.11.1" schemars = "1.2.3" globset = "0.4.22" +saphyr-parser = "0.4.1" [dev-dependencies] assert_cmd = "2.0.17" diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index a9e0cc3..c0a661c 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -209,7 +209,10 @@ The planned config is JSON, which CircleCI reads as YAML: every string stays quo meaning. It writes the config unchanged, so every job runs, when it can't plan it: a workflow entry with `matrix`, one name for -different jobs in two workflows, or a planned `requires` that would name a job no longer in its workflow. +different jobs in two workflows, a planned `requires` that would name a job no longer in its workflow, or an unquoted +value that CircleCI's YAML 1.1 reads differently from YAML 1.2 (`no`, `on`, `1_000`, `1:20`, `0755`). A gate is a job +named `cigen_gate` or `cigen_gate_` with `CIGEN_GATE_JOBS` in its `environment`. With `--hash-dir`, a job that +runs GitHub's own matrix gets a warning: its hash is the job's, which no entry's pass matches. | Option | What it does | | ---------------------------- | ------------------------------------------------------------------------------------------------- | diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index ffc0fae..f6e6e6b 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -220,5 +220,7 @@ GitHub's `on`, `permissions`, `concurrency`, `timeout-minutes`, `if` and `output ## Job ids -Job ids are unique across all workflows: two workflows can't both have a `test` job. A job in a subdirectory can name a -sibling without its directory: in `build/test`, `needs: [compile]` means `build/compile` when that job exists. +Job ids are unique across all workflows: two workflows can't both have a `test` job. Ids starting with `cigen_` (or a +last part that does, like `build/cigen_x`) are reserved for the jobs cigen adds, such as `cigen_gate`. A job in a +subdirectory can name a sibling without its directory: in `build/test`, `needs: [compile]` means `build/compile` when +that job exists. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 82610b8..53423ac 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -26,8 +26,10 @@ What the code does today, checked against the code in December 2026. Where cigen config to continue with, without the jobs whose passes were found, closed under `requires`, dropping approvals nothing left waits on, keeping the gate, written as JSON so CircleCI's YAML 1.1 reads every string as written (`--circleci-continue`; with `--hash-dir`, a pass counts only if it holds the job's current hash). Both fail open: a - matrix entry, one name for different jobs in two workflows, or a `requires` the plan would leave dangling means the - config continues unchanged. No generated config calls it yet. + matrix entry, one name for different jobs in two workflows, a `requires` the plan would leave dangling, or a plain + scalar YAML 1.1 reads differently (`src/yaml11/`, with saphyr-parser for scalar styles) means the config continues + unchanged. A gate must be `cigen_gate` or `cigen_gate_` and carry `CIGEN_GATE_JOBS`; job ids starting with + `cigen_` are config errors. No generated config calls it yet. - **Config loading** (`src/config/`, `src/schema/`): one schema in two layouts. `cigen.yml` is the whole document; `.cigen/` is the same document split into files (`config.yml` and `config/*.yml` for the top level, `commands/.yml`, `workflows/.yml` or `workflows//config.yml` for a workflow's settings, and @@ -136,8 +138,8 @@ What the code does today, checked against the code in December 2026. Where cigen gets a value nothing matches; `plan --circleci-continue` drops passed jobs and trims the gate, keeps a passed job a running job requires, and continues a config it can't plan unchanged; ids with `/` get subdirectories and none leave the hash directory. `tests/cigen_plan_circleci.rs`: merge keys, matrix entries, unresolvable `requires`, - values YAML 1.1 would reread, one name in two workflows, approvals with nothing after them, and passes checked - against current hashes. + values YAML 1.1 would reread (quoted, kept as written; unquoted, config unchanged), one name in two workflows, a + user job named like a gate, approvals with nothing after them, and passes checked against current hashes. - `tests/config_layouts.rs`: both layouts load and hash the same, and the errors for both layouts present, a key in two files, unknown and provider-only keys, duplicate job ids and input group cycles. - `tests/json_schema.rs`: the committed schemas match the types, every config in the repository follows them, and they diff --git a/src/commands/hash.rs b/src/commands/hash.rs index 14fc21d..8710fc3 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -176,7 +176,7 @@ pub fn job_hashes( base_dir: &Path, config: Option<&Path>, jobs: &[(String, Option)], -) -> Result>> { +) -> Result>> { let root = canonicalize_path(base_dir)?; let config_path = match config { Some(path) => resolve_path(&root, path), @@ -194,8 +194,7 @@ pub fn job_hashes( &mut file_hasher, modules_digest.as_deref(), None, - ) - .map(|job_hash| job_hash.hash); + ); (job_id.clone(), hash) }) .collect()) diff --git a/src/commands/plan.rs b/src/commands/plan.rs index 968851b..1ffac32 100644 --- a/src/commands/plan.rs +++ b/src/commands/plan.rs @@ -85,9 +85,14 @@ fn write_hashes(args: &PlanArgs, dir: &Path) -> Result<()> { // Each job on its own: one that can't be hashed or written runs, and the rest still plan. for (id, hash) in hashes { let value = match hash { - Ok(hash) => { - println!("{id} {hash}"); - hash + Ok(job_hash) => { + if job_hash.runs_matrix { + eprintln!( + "warning: job `{id}` runs GitHub's own matrix, and `cigen plan` has no `--matrix`: its hash is the job's, which matches no entry's (`cigen hash --matrix`), so no pass will match it" + ); + } + println!("{id} {}", job_hash.hash); + job_hash.hash } Err(error) => { eprintln!("warning: cigen plan can't hash job `{id}`, so it runs: {error:#}"); diff --git a/src/commands/plan_circleci/mod.rs b/src/commands/plan_circleci/mod.rs index 604ccfd..3d10eb2 100644 --- a/src/commands/plan_circleci/mod.rs +++ b/src/commands/plan_circleci/mod.rs @@ -23,9 +23,33 @@ pub const GATE: &str = "cigen_gate"; /// The gate's variable listing the jobs it checks, space-separated. pub const GATE_JOBS: &str = "CIGEN_GATE_JOBS"; -/// Whether `name` is a gate: `cigen_gate`, or `cigen_gate_`. -pub fn is_gate(name: &str) -> bool { - name == GATE || name.starts_with("cigen_gate_") +/// The gates in `root`: a job named `cigen_gate`, or `cigen_gate_` for one of its +/// workflows, that has `CIGEN_GATE_JOBS` in its `environment`. Anything else is the user's job, +/// whose `requires` keep the jobs it needs (cigen reserves `cigen_` ids, but the plan doesn't +/// rely on that). +fn gates(root: &Value) -> BTreeSet { + let workflows: Vec<&str> = root + .get("workflows") + .and_then(Value::as_mapping) + .map(|workflows| workflows.keys().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let Some(jobs) = root.get("jobs").and_then(Value::as_mapping) else { + return BTreeSet::new(); + }; + jobs.iter() + .filter_map(|(name, job)| { + let name = name.as_str()?; + let named = name == GATE + || name + .strip_prefix("cigen_gate_") + .is_some_and(|workflow| workflows.contains(&workflow)); + let checks = job + .get("environment") + .and_then(|env| env.get(GATE_JOBS)) + .is_some_and(Value::is_string); + (named && checks).then(|| name.to_string()) + }) + .collect() } /// Writes `main` without the passed jobs to `output`. With `hash_dir`, a job's pass counts only @@ -110,6 +134,7 @@ pub fn plan(text: &str, passed: &BTreeSet) -> Result { let mut root: Value = serde_yaml::from_str(text).context("parsing the config")?; root.apply_merge().context("applying `<<` merge keys")?; + let gates = gates(&root); let (names, approvals, dependents) = { let workflows = workflows(&root)?; check_names(&workflows)?; @@ -118,7 +143,7 @@ pub fn plan(text: &str, passed: &BTreeSet) -> Result { // Who requires whom; the gate requires everything, so it doesn't count. let mut dependents: BTreeMap> = BTreeMap::new(); for (_, entries) in &workflows { - for entry in entries.iter().filter(|entry| !is_gate(&entry.name)) { + for entry in entries.iter().filter(|entry| !gates.contains(&entry.name)) { for required in entry.requires()? { dependents .entry(required) @@ -172,7 +197,21 @@ pub fn plan(text: &str, passed: &BTreeSet) -> Result { }); } - rewrite::without(&mut root, &leaving)?; + // Rewriting writes every value as YAML 1.2 read it; a plain scalar CircleCI's YAML 1.1 + // reads differently (`default: no`, `RETRIES: 1_000`) would change meaning. + let ambiguous = cigen::yaml11::plain_scalars_read_differently(text)?; + if !ambiguous.is_empty() { + let listed: Vec = ambiguous + .iter() + .take(5) + .map(|found| format!("`{}` (line {})", found.value, found.line)) + .collect(); + bail!( + "it has unquoted values that CircleCI's YAML 1.1 reads differently from YAML 1.2: {}", + listed.join(", ") + ); + } + rewrite::without(&mut root, &leaving, &gates)?; rewrite::check_requires(&root)?; // JSON is YAML, and quotes every string: re-serialised YAML would write `"yes"`, `"1:20"` // or `"1_000"` bare, and CircleCI reads YAML 1.1, where those are a boolean and numbers. diff --git a/src/commands/plan_circleci/rewrite.rs b/src/commands/plan_circleci/rewrite.rs index 524e538..1afa8e9 100644 --- a/src/commands/plan_circleci/rewrite.rs +++ b/src/commands/plan_circleci/rewrite.rs @@ -1,14 +1,18 @@ //! Taking jobs out of a CircleCI config: their workflow entries, their names in `requires`, //! and the gates' lists of jobs to check. +use super::GATE_JOBS; use super::entries::{entry, key, required_name, workflows}; -use super::{GATE_JOBS, is_gate}; use anyhow::{Result, bail}; use serde_yaml::Value; use std::collections::BTreeSet; /// `root` without the `leaving` entries. -pub fn without(root: &mut Value, leaving: &BTreeSet) -> Result<()> { +pub fn without( + root: &mut Value, + leaving: &BTreeSet, + gates: &BTreeSet, +) -> Result<()> { if let Some(Value::Mapping(workflows)) = root.get_mut("workflows") { for (name, workflow) in workflows.iter_mut() { let Some(Value::Sequence(jobs)) = workflow.get_mut("jobs") else { @@ -27,7 +31,7 @@ pub fn without(root: &mut Value, leaving: &BTreeSet) -> Result<()> { *jobs = kept; } } - trim_gates(root, leaving); + trim_gates(root, leaving, gates); Ok(()) } @@ -57,12 +61,12 @@ fn without_requires(mut item: Value, leaving: &BTreeSet) -> Result`). A gate left with nothing to check has no workspace to attach. -fn trim_gates(root: &mut Value, leaving: &BTreeSet) { +fn trim_gates(root: &mut Value, leaving: &BTreeSet, gates: &BTreeSet) { let Some(Value::Mapping(jobs)) = root.get_mut("jobs") else { return; }; for (name, gate) in jobs.iter_mut() { - if !name.as_str().is_some_and(is_gate) { + if !name.as_str().is_some_and(|name| gates.contains(name)) { continue; } let Some(Value::String(list)) = gate diff --git a/src/config/lower.rs b/src/config/lower.rs index 612aaee..ed680d8 100644 --- a/src/config/lower.rs +++ b/src/config/lower.rs @@ -95,6 +95,18 @@ pub fn lower(document: &Document) -> Result { ); continue; } + let leaf = id.rsplit('/').next().unwrap_or(&id); + if id.starts_with("cigen_") || leaf.starts_with("cigen_") { + errors.push( + document + .error_at(&at, format!("job id `{id}` starts with `cigen_`")) + .suggest( + "Names starting with `cigen_` are reserved for the jobs cigen adds (`cigen_gate`): rename the job.", + ), + ); + broken.insert(id); + continue; + } match parse::(value, document, &at) { Ok(mut job) => { job.workflow = Some(name.clone()); diff --git a/src/lib.rs b/src/lib.rs index def9f08..97bbb6f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,3 +7,4 @@ pub mod orchestrator; pub mod pathspec; pub mod plugin; pub mod schema; +pub mod yaml11; diff --git a/src/yaml11/mod.rs b/src/yaml11/mod.rs new file mode 100644 index 0000000..86adf53 --- /dev/null +++ b/src/yaml11/mod.rs @@ -0,0 +1,59 @@ +//! YAML 1.1 versus 1.2. cigen reads and writes YAML 1.2 (serde_yaml), but CircleCI reads YAML +//! 1.1, where some plain (unquoted) scalars mean something else: `yes`, `no`, `on` and `off` are +//! booleans, `1_000` and `1:20` are numbers, `0755` is octal, and `0o17` or `1e3` are strings. +//! [`plain_scalars_read_differently`] finds them in a document, so a tool can quote them or +//! refuse to rewrite the document. + +mod resolve; + +use anyhow::{Context, Result}; +use saphyr_parser::{Event, Parser, ScalarStyle}; + +pub use resolve::reads_differently; + +/// A plain scalar that YAML 1.1 reads differently from YAML 1.2. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Ambiguous { + pub value: String, + /// 1-indexed line. + pub line: usize, + /// Where it starts and ends in the document, in characters. + pub start: usize, + pub end: usize, +} + +/// Every plain scalar in `text` that YAML 1.1 reads differently from YAML 1.2, in order. +pub fn plain_scalars_read_differently(text: &str) -> Result> { + let mut found = Vec::new(); + for event in Parser::new_from_str(text) { + let (event, span) = event.context("parsing YAML")?; + if let Event::Scalar(value, ScalarStyle::Plain, _, None) = event + && reads_differently(&value) + { + found.push(Ambiguous { + value: value.into_owned(), + line: span.start.line(), + start: span.start.index(), + end: span.end.index(), + }); + } + } + Ok(found) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_plain_scalars_only() { + let text = "a: yes\nb: \"yes\"\nc: 'no'\nd: [on, off]\ne: 1_000\nf: plain\ng: !!str no\n"; + let found = plain_scalars_read_differently(text).unwrap(); + let values: Vec<_> = found.iter().map(|a| (a.value.as_str(), a.line)).collect(); + assert_eq!(values, [("yes", 1), ("on", 4), ("off", 4), ("1_000", 5)]); + let first = &found[0]; + let chars: Vec = text.chars().collect(); + let spanned: String = chars[first.start..first.end].iter().collect(); + assert_eq!(spanned, "yes"); + } +} diff --git a/src/yaml11/resolve.rs b/src/yaml11/resolve.rs new file mode 100644 index 0000000..3c5d1a3 --- /dev/null +++ b/src/yaml11/resolve.rs @@ -0,0 +1,213 @@ +//! What a plain scalar means under YAML 1.1's types (yaml.org/type, as CircleCI reads them) and +//! YAML 1.2's core schema (as serde_yaml reads them). + +use once_cell::sync::Lazy; +use regex::Regex; + +/// Whether YAML 1.1 and YAML 1.2 give the plain scalar `value` different meanings. +pub fn reads_differently(value: &str) -> bool { + yaml11(value) != yaml12(value) +} + +#[derive(Debug, PartialEq)] +enum Meaning { + Str, + Null, + Bool(bool), + Int(i128), + Float(String), +} + +fn regex(pattern: &str) -> Regex { + Regex::new(pattern).expect("a valid pattern") +} + +static NULL: Lazy = Lazy::new(|| regex(r"^(~|null|Null|NULL|)$")); +static BOOL11_TRUE: Lazy = + Lazy::new(|| regex(r"^(y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON)$")); +static BOOL11_FALSE: Lazy = + Lazy::new(|| regex(r"^(n|N|no|No|NO|false|False|FALSE|off|Off|OFF)$")); +static INT11: Lazy = Lazy::new(|| { + regex(r"^[-+]?(0b[0-1_]+|0[0-7_]+|0|[1-9][0-9_]*|0x[0-9a-fA-F_]+|[1-9][0-9_]*(:[0-5]?[0-9])+)$") +}); +static FLOAT11: Lazy = Lazy::new(|| { + regex( + r"^([-+]?([0-9][0-9_]*)?\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\.[0-9_]*|[-+]?\.(inf|Inf|INF)|\.(nan|NaN|NAN))$", + ) +}); +static INT12: Lazy = Lazy::new(|| regex(r"^([-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$")); +static FLOAT12: Lazy = Lazy::new(|| { + regex( + r"^([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?\.(inf|Inf|INF)|\.(nan|NaN|NAN))$", + ) +}); + +fn yaml11(value: &str) -> Meaning { + if NULL.is_match(value) { + Meaning::Null + } else if BOOL11_TRUE.is_match(value) { + Meaning::Bool(true) + } else if BOOL11_FALSE.is_match(value) { + Meaning::Bool(false) + } else if INT11.is_match(value) { + int11(value).map_or(Meaning::Str, Meaning::Int) + } else if FLOAT11.is_match(value) && value.chars().any(|c| c.is_ascii_alphanumeric()) { + Meaning::Float(float(&value.replace('_', ""), true)) + } else { + Meaning::Str + } +} + +fn yaml12(value: &str) -> Meaning { + if NULL.is_match(value) { + Meaning::Null + } else if matches!(value, "true" | "True" | "TRUE") { + Meaning::Bool(true) + } else if matches!(value, "false" | "False" | "FALSE") { + Meaning::Bool(false) + } else if INT12.is_match(value) { + int12(value).map_or(Meaning::Str, Meaning::Int) + } else if FLOAT12.is_match(value) { + Meaning::Float(float(value, false)) + } else { + Meaning::Str + } +} + +/// A float's value, written one way for both versions; sexagesimal floats (1.1 only) are +/// summed in base 60. +fn float(value: &str, sexagesimal: bool) -> String { + let lower = value.to_ascii_lowercase(); + if lower.ends_with(".inf") { + return if lower.starts_with('-') { + "-inf" + } else { + "inf" + } + .to_string(); + } + if lower == ".nan" { + return "nan".to_string(); + } + if sexagesimal && value.contains(':') { + let negative = value.starts_with('-'); + let total = value + .trim_start_matches(['-', '+']) + .split(':') + .fold(0.0, |total, part| { + total * 60.0 + part.parse::().unwrap_or(0.0) + }); + return format!("{}", if negative { -total } else { total }); + } + value + .parse::() + .map_or_else(|_| value.to_string(), |f| format!("{f}")) +} + +fn int11(value: &str) -> Option { + let (negative, digits) = sign(&value.replace('_', "")); + let magnitude = if let Some(bin) = digits.strip_prefix("0b") { + i128::from_str_radix(bin, 2).ok()? + } else if let Some(hex) = digits.strip_prefix("0x") { + i128::from_str_radix(hex, 16).ok()? + } else if digits.contains(':') { + digits.split(':').try_fold(0i128, |total, part| { + Some(total * 60 + part.parse::().ok()?) + })? + } else if digits.len() > 1 && digits.starts_with('0') { + i128::from_str_radix(&digits[1..], 8).ok()? + } else { + digits.parse().ok()? + }; + Some(if negative { -magnitude } else { magnitude }) +} + +fn int12(value: &str) -> Option { + if let Some(oct) = value.strip_prefix("0o") { + return i128::from_str_radix(oct, 8).ok(); + } + if let Some(hex) = value.strip_prefix("0x") { + return i128::from_str_radix(hex, 16).ok(); + } + let (negative, digits) = sign(value); + let magnitude: i128 = digits.parse().ok()?; + Some(if negative { -magnitude } else { magnitude }) +} + +fn sign(value: &str) -> (bool, String) { + match value.strip_prefix('-') { + Some(rest) => (true, rest.to_string()), + None => (false, value.trim_start_matches('+').to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::reads_differently; + + #[test] + fn the_scalars_yaml_1_1_reads_differently() { + for value in [ + "y", + "Y", + "yes", + "Yes", + "YES", + "n", + "N", + "no", + "No", + "NO", + "on", + "On", + "ON", + "off", + "Off", + "OFF", + "1_000", + "1:20", + "0755", + "0b101", + "0o17", + "1e3", + "1.0e3", + "1_0.5", + "190:20:30.15", + "0x_ff", + ] { + assert!(reads_differently(value), "{value}"); + } + } + + #[test] + fn the_scalars_both_read_the_same() { + for value in [ + "true", + "false", + "True", + "null", + "~", + "", + "0", + "7", + "-12", + "1000", + "0x1F", + "1.5", + ".5", + "-1.5e+3", + ".inf", + "-.Inf", + ".nan", + "plain", + "yesterday", + "1.2.3", + "v1", + "10:30am", + "0.0.0.0", + "a:b", + ] { + assert!(!reads_differently(value), "{value}"); + } + } +} diff --git a/tests/cigen_plan.rs b/tests/cigen_plan.rs index 7c9793c..93f9d3e 100644 --- a/tests/cigen_plan.rs +++ b/tests/cigen_plan.rs @@ -240,3 +240,31 @@ fn a_config_it_cant_plan_is_continued_unchanged() { } } } + +/// `plan --hash-dir` has no `--matrix`, so a job running GitHub's own matrix gets the job's +/// hash, which matches none of its entries': it says so. +#[test] +fn a_job_running_githubs_matrix_gets_a_warning() { + let repo = FixtureRepo::new(); + repo.write( + "cigen.yml", + "provider: github\nworkflows:\n ci:\n jobs:\n test:\n image: ubuntu-latest\n inputs: ['src/**']\n github:\n strategy:\n matrix:\n rust: [stable, nightly]\n steps:\n - run: cargo test\n lint:\n image: ubuntu-latest\n inputs: ['src/**']\n steps:\n - run: cargo clippy\n", + ) + .write("src/lib.rs", "one\n"); + repo.commit("initial"); + let output = cigen( + repo.path(), + &[ + "plan", + "--hash-dir", + "hashes", + "--job", + "test", + "--job", + "lint", + ], + ); + let log = String::from_utf8_lossy(&output.stderr); + assert!(log.contains("job `test` runs GitHub's own matrix"), "{log}"); + assert!(!log.contains("job `lint` runs"), "{log}"); +} diff --git a/tests/cigen_plan_circleci.rs b/tests/cigen_plan_circleci.rs index a04ad9f..ab59bc0 100644 --- a/tests/cigen_plan_circleci.rs +++ b/tests/cigen_plan_circleci.rs @@ -157,3 +157,33 @@ fn with_hashes_a_pass_counts_only_for_the_jobs_current_hash() { assert_eq!(entries(&text, "ci"), ["test"], "{log}\n{text}"); assert!(log.contains("isn't for its current hash"), "{log}"); } + +#[test] +fn a_job_named_like_a_gate_keeps_the_jobs_it_requires() { + // `cigen_gate_smoke` isn't a gate: no workflow `smoke`, no CIGEN_GATE_JOBS. It needs build. + let main = format!( + "version: 2.1\n{JOBS} cigen_gate_smoke: {{ docker: [{{ image: cimg/base:current }}], steps: [{{ run: make smoke }}] }}\nworkflows:\n ci:\n jobs:\n - build\n - cigen_gate_smoke: {{ requires: [build] }}\n - test\n" + ); + let (text, log) = plan(&main, &[("build", ""), ("test", "")], None); + assert_eq!( + entries(&text, "ci"), + ["build", "cigen_gate_smoke"], + "build stays for the job that needs it: {log}\n{text}" + ); +} + +#[test] +fn unquoted_values_yaml_1_1_reads_differently_leave_the_config_unchanged() { + // CircleCI reads `no` as false and `1_000` as 1000; rewritten from YAML 1.2 they'd be the + // strings "no" and "1_000", and the boolean parameter wouldn't compile. + let main = format!( + "version: 2.1\nparameters:\n slow: {{ type: boolean, default: no }}\n{JOBS}workflows:\n ci:\n jobs: [build, test]\n" + ); + let (text, log) = plan(&main, &[("build", "")], None); + assert_eq!(text, main, "{log}"); + assert!(log.contains("`no` (line 3)"), "{log}"); + + let quoted = main.replace("default: no", "default: false"); + let (text, log) = plan("ed, &[("build", "")], None); + assert_eq!(entries(&text, "ci"), ["test"], "{log}\n{text}"); +} diff --git a/tests/validate.rs b/tests/validate.rs index 883d3f1..011d854 100644 --- a/tests/validate.rs +++ b/tests/validate.rs @@ -165,3 +165,25 @@ fn validate_and_generate_print_the_same_errors() { assert_eq!(stderr(&["generate"]), validate); assert_eq!(stderr(&["hash", "--job", "test"]), validate); } + +#[test] +fn job_ids_starting_with_cigen_are_reserved() { + let dir = tempdir().unwrap(); + write( + &dir.path().join("cigen.yml"), + "provider: circleci\nworkflows:\n ci:\n jobs:\n cigen_gate_smoke:\n steps: [{ run: make smoke }]\n build/cigen_x:\n steps: [{ run: make }]\n", + ); + let (valid, report) = validate_json(dir.path()); + assert!(!valid, "{report}"); + let messages: Vec = report["errors"] + .as_array() + .unwrap() + .iter() + .map(|error| format!("{} / {}", error["message"], error["suggestion"])) + .collect(); + assert_eq!(messages.len(), 2, "{messages:?}"); + for message in &messages { + assert!(message.contains("starts with `cigen_`"), "{message}"); + assert!(message.contains("reserved"), "{message}"); + } +}