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
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
43 changes: 42 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, generate, hash, explain and expand, with every option.
description: cigen validate, generate, hash, explain, expand and plan, with every option.
---

```text
Expand Down Expand Up @@ -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 `<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, 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_<workflow>` 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 <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
6 changes: 4 additions & 2 deletions docs/src/content/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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
14 changes: 14 additions & 0 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>] [--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_<workflow>` 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/<name>.yml`, `workflows/<name>.yml` or `workflows/<name>/config.yml` for a workflow's settings, and
Expand Down Expand Up @@ -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
Expand Down
33 changes: 32 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,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<String>)],
) -> Result<BTreeMap<String, Result<JobHash>>> {
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())
}
3 changes: 3 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ mod expand;
mod explain;
mod generate;
mod hash;
mod plan;
mod plan_circleci;
pub mod report;
mod validate;

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};
136 changes: 136 additions & 0 deletions src/commands/plan.rs
Original file line number Diff line number Diff line change
@@ -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 `<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(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 `<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())
}
Loading
Loading