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 b8472f6..1455091 100644
--- a/docs/src/content/docs/cli.md
+++ b/docs/src/content/docs/cli.md
@@ -1,6 +1,6 @@
---
title: CLI
-description: cigen validate, generate, hash, explain and expand, with every option.
+description: cigen validate, generate, hash, explain, expand and plan, with every option.
---
```text
@@ -233,6 +233,47 @@ The YAML loads to the same config as the directory, but comments aren't kept. Co
stay as references (`- setup`): expanding them into steps is the provider's job. The config is checked first, so a
config with problems prints the same errors as `cigen validate` and nothing on stdout.
+## `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 --hash-dir /tmp/cigen/hashes \
+ --output .circleci/planned.yml
+```
+
+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. 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, 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 |
+| ---------------------------- | ------------------------------------------------------------------------------------------------- |
+| `--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
| Variable | 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/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 98fd6b6..da424da 100644
--- a/internal_docs/STATUS.md
+++ b/internal_docs/STATUS.md
@@ -24,6 +24,14 @@ What the code does today, checked against the code in December 2026. Where cigen
(`src/hashing/matrix.rs` mixes the entry into the job's hash, for `hash --matrix` too).
`cigen expand [--config ] [--format yaml|json]` checks the config and prints it as one `cigen.yml` document,
a `.cigen/` directory's files merged the way the loader merges them (comments aren't kept).
+ `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`, 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, 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
@@ -128,6 +136,12 @@ 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; 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 (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 129dbc5..8710fc3 100644
--- a/src/commands/hash.rs
+++ b/src/commands/hash.rs
@@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail};
use cigen::hashing::{FileHasher, HashCache, JobHash, hash_job};
use clap::Args;
use sha2::{Digest, Sha256};
-use std::collections::BTreeSet;
+use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -168,3 +168,34 @@ fn write_github_output(name: &str, value: &str) -> Result<()> {
}
Ok(())
}
+
+/// Hashes several jobs with one config load and one file cache, for `cigen plan --hash-dir`.
+/// Each job is `(id, modules digest)`, and gets the hash `cigen hash --job` gives it; a job it
+/// can't hash gets its error, so the others still get theirs.
+pub fn job_hashes(
+ base_dir: &Path,
+ config: Option<&Path>,
+ jobs: &[(String, Option)],
+) -> Result>> {
+ let root = canonicalize_path(base_dir)?;
+ let config_path = match config {
+ Some(path) => resolve_path(&root, path),
+ None => cigen::config::find(base_dir)?,
+ };
+ let config = cigen::config::load(&config_path)?;
+ let mut file_hasher = FileHasher::new(None);
+ Ok(jobs
+ .iter()
+ .map(|(job_id, modules_digest)| {
+ let hash = hash_job(
+ &config,
+ job_id,
+ &root,
+ &mut file_hasher,
+ modules_digest.as_deref(),
+ None,
+ );
+ (job_id.clone(), hash)
+ })
+ .collect())
+}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 423f64c..bc5a14d 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -2,6 +2,8 @@ mod expand;
mod explain;
mod generate;
mod hash;
+mod plan;
+mod plan_circleci;
pub mod report;
mod validate;
@@ -9,4 +11,5 @@ pub use expand::{ExpandArgs, expand_command};
pub use explain::{ExplainArgs, explain_command};
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..1ffac32
--- /dev/null
+++ b/src/commands/plan.rs
@@ -0,0 +1,136 @@
+//! `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 `/`. 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,
+
+ /// 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 = "jobs"
+ )]
+ 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, args.hash_dir.as_deref(), 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()
+ }
+ };
+ // 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(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:#}");
+ unplanned()
+ }
+ };
+ 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()
+ .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/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..3d10eb2
--- /dev/null
+++ b/src/commands/plan_circleci/mod.rs
@@ -0,0 +1,256 @@
+//! `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";
+
+/// 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
+/// 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 gates = gates(&root);
+ 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| !gates.contains(&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(),
+ });
+ }
+
+ // 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.
+ 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..1afa8e9
--- /dev/null
+++ b/src/commands/plan_circleci/rewrite.rs
@@ -0,0 +1,111 @@
+//! 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 anyhow::{Result, bail};
+use serde_yaml::Value;
+use std::collections::BTreeSet;
+
+/// `root` without the `leaving` entries.
+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 {
+ 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, gates);
+ 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, 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(|name| gates.contains(name)) {
+ 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/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/main.rs b/src/main.rs
index cbc404f..629caff 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,12 @@ enum Commands {
#[command(flatten)]
args: commands::ExpandArgs,
},
+ /// 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)]
@@ -78,6 +84,7 @@ fn run(cli: Cli) -> Result {
}
Some(Commands::Expand { args }) => commands::expand_command(args)?,
Some(Commands::Explain { args }) => commands::explain_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/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
new file mode 100644
index 0000000..93f9d3e
--- /dev/null
+++ b/tests/cigen_plan.rs
@@ -0,0 +1,270 @@
+//! `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();
+ // 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"),
+ 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");
+}
+
+/// 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 }] }
+ 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}");
+ }
+ }
+}
+
+/// `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
new file mode 100644
index 0000000..ab59bc0
--- /dev/null
+++ b/tests/cigen_plan_circleci.rs
@@ -0,0 +1,189 @@
+//! `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}");
+}
+
+#[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/cmd/help.trycmd b/tests/cmd/help.trycmd
index 57a5ec6..6ede20a 100644
--- a/tests/cmd/help.trycmd
+++ b/tests/cmd/help.trycmd
@@ -11,6 +11,7 @@ Commands:
hash Compute hashes for file patterns or jobs
explain Show what a job's hash covers: its inputs, the files they match, and the hash
expand Print the whole config as one cigen.yml document, the way the loader sees it
+ plan Plan a setup job: hash jobs, then write the config to continue with, without the jobs that already passed
validate Check the config and list every problem in it
help Print this message or the help of the given subcommand(s)
@@ -87,10 +88,10 @@ Options:
Base directory the patterns are evaluated relative to (defaults to current dir) [default: .]
--cache
Optional cache file path to persist per-file hashes
- -v, --verbose...
- Enable verbose output (use -vv for debug output)
--modules-digest
The digest of the job's module expansions when its CI config was generated. It goes into the hash, so the hash covers the steps that config runs
+ -v, --verbose...
+ Enable verbose output (use -vv for debug output)
--matrix
The job's matrix entry as JSON (`${{ toJSON(matrix) }}`), for a job that runs GitHub's own matrix. It goes into the hash, so each entry has its own hash and pass marker
-h, --help
@@ -111,3 +112,22 @@ Options:
-h, --help Print help
```
+
+```console
+$ cigen plan --help
+Plan a setup job: hash jobs, then write the config to continue with, without the jobs that already passed
+
+Usage: cigen plan [OPTIONS]
+
+Options:
+ --hash-dir 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
+ --job A job to hash, as `` or `=` (the digest its own hash step passes)
+ --config The config: a cigen.yml file or a .cigen/ directory (found in --base-dir by default)
+ --base-dir The directory job inputs are relative to [default: .]
+ --circleci-continue The CircleCI config to continue with (the generated `.circleci/main.yml`)
+ --passed A directory holding a file named after each job whose pass was found
+ --output Where to write the planned config
+ -v, --verbose... Enable verbose output (use -vv for debug output)
+ -h, --help Print help
+
+```
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}");
+ }
+}