Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion docs/src/content/docs/cli.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: CLI
description: cigen validate, cigen generate, cigen hash and cigen explain, with every option.
description: cigen validate, cigen generate, cigen hash, cigen explain and cigen plan, with every option.
---

```text
Expand Down Expand Up @@ -183,6 +183,44 @@ With `--format json`, it prints one object with `job`, `workflow`, `inputs` (eac
`hash`), `also_hashed`, `runs_matrix`, `matrix_entry` (the entry given, or `null`) and `hash`. An unknown job is an
error that suggests the closest id.

## `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 `<dir>/<job>`: the bytes `cigen hash --job` prints, newline
included. Give a job as `<id>=<digest>` when its hash step passes `--modules-digest <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_<workflow>`) 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 <dir>` | Write the hashes of the `--job`s here, or, with `--circleci-continue`, check passes against them. |
| `--job <id>[=<digest>]` | A job to hash. Repeat it for more jobs. |
| `--config <path>` | The config. Default: the one in `--base-dir`. |
| `--base-dir <dir>` | The project root that inputs are relative to. Default `.`. |
| `--circleci-continue <file>` | The CircleCI config to continue with. |
| `--passed <dir>` | A directory holding a file named after each job whose pass was found. |
| `--output <file>` | Where to write the planned config. |

## Environment

| Variable | What it does |
Expand Down
2 changes: 2 additions & 0 deletions internal_docs/DIRECTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ What the code does today, checked against the code in December 2026. Where cigen
generated step passes no `--modules-digest` for the needed job): a one-time rerun of those jobs, never a skip. For a
job that runs GitHub's matrix, explain says each entry is hashed in, and with `--matrix` it shows that entry's hash
(`src/hashing/matrix.rs` mixes the entry into the job's hash, for `hash --matrix` too).
`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, 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/<name>.yml`, `workflows/<name>.yml` or `workflows/<name>/config.yml` for a workflow's settings, and
Expand Down Expand Up @@ -126,6 +132,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, 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
Expand Down
34 changes: 33 additions & 1 deletion src/commands/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -168,3 +168,35 @@ 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<String>)],
) -> Result<BTreeMap<String, Result<String>>> {
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,
)
.map(|job_hash| job_hash.hash);
(job_id.clone(), hash)
})
.collect())
}
3 changes: 3 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
mod explain;
mod generate;
mod hash;
mod plan;
mod plan_circleci;
pub mod report;
mod validate;

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};
131 changes: 131 additions & 0 deletions src/commands/plan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//! `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 `<dir>/<job id>`. 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<PathBuf>,

/// A job to hash, as `<id>` or `<id>=<modules digest>` (the digest its own hash step passes)
#[arg(long = "job", value_name = "ID[=DIGEST]")]
pub jobs: Vec<String>,

/// The config: a cigen.yml file or a .cigen/ directory (found in --base-dir by default)
#[arg(long = "config")]
pub config: Option<PathBuf>,

/// 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<PathBuf>,

/// 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<PathBuf>,

/// Where to write the planned config
#[arg(long = "output", value_name = "FILE", requires = "circleci_continue")]
pub output: Option<PathBuf>,
}

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 <dir>` and `--output <file>`");
};
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 <dir> --job <id>...` hashes jobs, `--circleci-continue <file> --passed <dir> --output <file>` writes the config to continue with"
);
};
if args.jobs.is_empty() {
bail!("`--hash-dir` needs at least one `--job <id>`");
}
write_hashes(&args, dir)
}

fn write_hashes(args: &PlanArgs, dir: &Path) -> Result<()> {
let jobs: Vec<(String, Option<String>)> = 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(hash) => {
println!("{id} {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 `<dir>/<id>`: 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())
}
110 changes: 110 additions & 0 deletions src/commands/plan_circleci/entries.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<String>> {
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<Entry<'_>> {
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: <statuses>`.
pub fn required_name(item: &Value) -> Result<String> {
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<Vec<(String, Vec<Entry<'_>>)>> {
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::<Result<Vec<_>>>()?));
}
Ok(all)
}
Loading
Loading