diff --git a/Cargo.toml b/Cargo.toml index 71d2a0d..c4b5069 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" +tempfile = "3.20.0" [dev-dependencies] assert_cmd = "2.0.17" diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index dcbecd4..bff5617 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -1,6 +1,6 @@ --- title: CLI -description: cigen validate, cigen generate, cigen hash and cigen explain, with every option. +description: cigen validate, cigen generate, cigen hash, cigen explain and cigen replay, with every option. --- ```text @@ -183,6 +183,16 @@ 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 replay` + +Estimates how many job runs cigen would have skipped over the project's git history, with no CI. It's an estimate from +a model that assumes every run passed. See [estimate skipping](/docs/replay/) for the model and every option. + +```sh +cigen replay --last 100 --workflow ci +cigen replay --last 200 --config ../my-cigen.yml --format json +``` + ## Environment | Variable | What it does | diff --git a/docs/src/content/docs/index.md b/docs/src/content/docs/index.md index b2e41fa..e350ced 100644 --- a/docs/src/content/docs/index.md +++ b/docs/src/content/docs/index.md @@ -27,6 +27,7 @@ what to write instead. - `cigen generate` for GitHub Actions and CircleCI. - `cigen hash`, which computes a job's hash from its inputs and the inputs cigen derives. - `cigen explain`, which shows what a job's hash covers: each input, the files it matches, and the derived inputs. +- [`cigen replay`](/docs/replay/), which estimates from git history how many job runs cigen would have skipped. - Skipping on GitHub Actions, using markers in the GitHub Actions cache. - Deterministic output: generating twice gives the same bytes. diff --git a/docs/src/content/docs/replay.md b/docs/src/content/docs/replay.md new file mode 100644 index 0000000..691b1a2 --- /dev/null +++ b/docs/src/content/docs/replay.md @@ -0,0 +1,180 @@ +--- +title: Estimate skipping +description: cigen replay estimates how many job runs cigen would have skipped over a project's git history, with no CI. +--- + +`cigen replay` walks a project's git history and works out, commit by commit, which jobs cigen would have run and which +it would have skipped. It needs no CI and changes nothing: each commit is checked out in a temporary worktree, which is +removed afterwards. + +The result is an **estimate from a model**, not a measurement of real CI. It says so in its output, and the +[model](#the-model) below says exactly what it assumes. + +```sh +cigen replay --last 100 # the last 100 commits of HEAD +cigen replay v1.2.0..main # a range (first-parent history) +cigen replay --last 100 --format json # the same, as data +``` + +## What it does for each commit + +1. Checks the commit out in the temporary worktree. +2. Loads the config: the commit's own, or the one given with `--config`. +3. Hashes every job exactly as [`cigen hash --job`](/docs/cli/#cigen-hash) does in CI, with the job's declared inputs and + everything cigen [derives](/docs/inputs/#derived-inputs): lockfiles, toolchain pins, files the steps name, the files + its modules contribute, the job's definition, and the hashes of the jobs it `needs`. So a job reruns when a job it + needs would have run, as in CI. +4. Counts the job as **skipped** if a run of the same job with the same hash already passed on an earlier commit of the + replay and its marker hasn't expired; otherwise as **ran**. + +For this config, over five commits: + +```yaml +# cigen.yml +provider: github +workflows: + ci: + jobs: + test: + image: rust:latest + inputs: ['src/**', 'tests/**'] + steps: + - run: cargo test --locked + docs: + image: node:24 + inputs: ['docs/**'] + steps: + - run: npm run docs + audit: + image: rust:latest + steps: + - run: cargo audit +``` + +```text +$ cigen replay --last 5 --commits --durations durations.json +cigen replay: an estimate from git history, not a measurement. +Model: every run passed; a job skips when its hash already ran on an earlier commit of this replay; first-parent history of one branch; a pass expires after 7 days unused (by commit date). +Note: workflow triggers (`on:`) aren't modelled: every replayed workflow runs on every commit. +Note: a matrix job counts once per commit, as one job id. +Note: pull requests aren't modelled: in CI they can also reuse the branch's passes. +Config: each commit's own +Workflows: all (use --workflow to choose) +Commits: 5 + +615812012b 2026-01-01 Add the parser: ran audit, docs, test; skipped nothing +76fca80472 2026-01-02 Fix a typo in the README: ran audit; skipped docs, test +b7c0e0c390 2026-01-03 Handle empty input: ran audit, test; skipped docs +df2ea18bc3 2026-01-04 Update serde: ran audit, docs, test; skipped nothing +408a909d43 2026-01-05 Document the parser: ran audit, docs; skipped test + +job ran skipped skip rate +audit 5 0 0% (no inputs: always runs) +docs 3 2 40% +test 3 2 40% + +Skipped 4 of 15 job runs (26.7%). +Estimated CI minutes saved: 30 of 85. +``` + +"Update serde" changed only `Cargo.lock`, which no job lists in its `inputs`, and both jobs still ran: the lockfile is a +derived input. `audit` has no `inputs`, so CI never skips it, and neither does the replay. + +## The model + +Everything the estimate assumes: + +- **Every run passed.** Replay reads no CI history, so it can't know which runs failed. A failed run records no pass in + real CI, so a project with failures skips less than the estimate says. +- **One branch, first-parent history.** It models pushes to one branch, such as `main`, one commit at a time. Commits + that came in on a merged branch aren't replayed. Pull requests aren't modelled; in CI they can also reuse the branch's + passes. +- **Passes expire after 7 days unused**, measured by commit date, as GitHub's cache evicts entries nobody has read for 7 + days. A hit refreshes the marker. `--no-expiry` turns this off. +- **Triggers aren't modelled.** Every replayed workflow counts on every commit, including workflows that only run on + tags or on some paths. Use `--workflow` to pick the workflows that run on every push. +- **A matrix job counts once** per commit, as one job id, not once per combination. +- **The first commit runs everything**: there are no passes yet, as when a project starts using cigen. +- **The hash comes from the cigen you run.** Its version is part of every hash, so it's the same for the whole replay. + +## Trying cigen on a project that doesn't use it yet + +A project that has never used cigen has no config in its history. Write one, keep it outside the repository's history +(or uncommitted), and pass it with `--config`. Replay then applies that config to every commit and hashes each commit's +own files: + +```sh +cigen replay --last 200 --config ../my-cigen.yml --workflow ci --durations ../durations.json +``` + +Without `--config`, replay uses each commit's own config. A commit with no config is listed with `no_config` and left out +of the counts. A commit whose config this version of cigen can't load (often one written for an older version, before +the schema became strict) is listed with `config_error` and left out too; the text output shows the first error. + +## Options + +| Option | What it does | +| --------------------- | ------------------------------------------------------------------------------------------ | +| `..` | The commits to replay, as git reads a range. Only first-parent commits are replayed. | +| `--last ` | The last N first-parent commits of HEAD, in place of a range. | +| `-c`, `--config` | A `cigen.yml` or `.cigen/` to apply to every commit, in place of each commit's own. | +| `--repo ` | The repository to replay. Default: the current directory. | +| `--workflow ` | Replay only this workflow. Repeat it for several. | +| `--no-expiry` | Never expire a pass. | +| `--durations ` | Average minutes per run, by job (`{"test": 12, "docs": 3}`), to estimate CI minutes saved. | +| `--commits` | List every commit with the jobs it ran and skipped (text output). | +| `--format text\|json` | Text (the default) or JSON. | + +With `--durations`, minutes are counted only for the jobs in the file; the others are named in the output +(`minutes_unknown` in JSON) rather than guessed. + +## JSON + +`--format json` prints one object. Every field of the model is in it, so a number is never shown without its +assumptions: + +```json +{ + "estimate": true, + "model": { + "assume_pass": true, + "branch": "first-parent", + "expiry_days": 7, + "workflows": null, + "config": "per-commit", + "notes": [ + "workflow triggers (`on:`) aren't modelled: every replayed workflow runs on every commit." + ] + }, + "range": { "from": "615812012b…", "to": "408a909d43…", "commits": 5 }, + "commits": [ + { + "sha": "df2ea18bc3…", + "date": "2026-01-04T00:00:00Z", + "subject": "Update serde", + "ran": ["audit", "docs", "test"], + "skipped": [] + } + ], + "jobs": { + "test": { + "ran": 3, + "skipped": 2, + "skip_rate": 0.4, + "always_runs": false, + "minutes_per_run": 12.0 + } + }, + "totals": { + "job_runs": 15, + "ran": 11, + "skipped": 4, + "skip_rate": 0.26666666666666666, + "minutes_total": 85.0, + "minutes_saved": 30.0 + } +} +``` + +`expiry_days` is `null` with `--no-expiry`, `workflows` is `null` when every workflow is replayed, and `config` is +`per-commit` or the path given with `--config`. A commit can also carry `no_config: true` or a `config_error`. diff --git a/docs/src/content/docs/roadmap.md b/docs/src/content/docs/roadmap.md index ee4a158..c733f04 100644 --- a/docs/src/content/docs/roadmap.md +++ b/docs/src/content/docs/roadmap.md @@ -24,6 +24,8 @@ right. This page lists what's planned. Nothing on it exists yet; what exists is no 7-day eviction, batch lookup, and a history of why each job ran. Records hold hashes, job names and who wrote them, never code. 7. **CircleCI parity**, including skipping in the setup workflow. +8. **Replay against real CI history.** [`cigen replay`](/docs/replay/) assumes every run passed today; reading which runs + actually passed from a CI provider's history would make its estimate closer to what CI did. ## Not planned diff --git a/docs/src/lib/docs.ts b/docs/src/lib/docs.ts index 6a403f4..daf12bc 100644 --- a/docs/src/lib/docs.ts +++ b/docs/src/lib/docs.ts @@ -12,7 +12,7 @@ export const sections: { title: string; pages: string[] }[] = [ title: "Configure", pages: ["configuration", "jobs", "steps-and-commands", "inputs", "modules"], }, - { title: "Run", pages: ["skipping", "providers", "cli"] }, + { title: "Run", pages: ["skipping", "replay", "providers", "cli"] }, { title: "Project", pages: ["roadmap"] }, ]; diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 8943639..cb71d72 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -22,6 +22,14 @@ 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 replay (.. | --last N) [--config ] [--workflow ] [--no-expiry] [--durations ] +[--format text|json]` (`src/replay/`) estimates skipping from git history: it checks each first-parent commit out in + a temporary worktree, hashes every job with `hashing::hash_job` (modules and `needs` included, as in CI; git runs + through `cigen::git::command`), and counts a run as skipped when the same job and + hash ran on an earlier commit and its marker hasn't gone 7 days unused (by commit date; a hit refreshes it). It + assumes every run passed (no CI history is read), doesn't model workflow triggers, pull requests or matrix + combinations, and says so in its output. `--config` applies one config to every commit, for projects whose history + has none; otherwise commits with no config, or one this cigen can't load, are listed and left out of the counts. - **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 @@ -146,6 +154,11 @@ What the code does today, checked against the code in December 2026. Where cigen - `tests/explain.rs`: `cigen explain` lists declared and derived inputs (module inputs included) with their files and the jobs a job needs, in JSON and text, and its hash equals `cigen hash --job`'s before and after an input, a module input or a needed job changes, and for a matrix entry. +- `tests/replay.rs`: `cigen replay` over histories built in the test, with exact counts: an unchanged input skips, a + change outside the inputs skips, a lockfile change (a derived input) runs, a revert skips, a job definition change + runs, a marker expires after 7 idle days and a hit refreshes it, a range replays first-parent commits only, + `--config` applies to a history with no config, `--workflow` filters, and durations give minutes saved. +- `tests/replay_needs.rs`: a job reruns when a job it `needs` changed. - `tests/derived_inputs.rs`: changing a script a step runs, a command the job uses, a toolchain pin or the `package.json` script that `npm run test` runs (the root's or a sub-package's) makes the job run in mockci, and changing a used command, a named service, a top-level provider block, a local action, a lockfile or the `packageManager` pin changes the job's hash; an unused command or service doesn't. diff --git a/src/commands/mod.rs b/src/commands/mod.rs index a9a5365..64e98ae 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,10 +1,12 @@ mod explain; mod generate; mod hash; +mod replay; pub mod report; mod validate; pub use explain::{ExplainArgs, explain_command}; pub use generate::generate_command; pub use hash::{HashArgs, hash_command}; +pub use replay::{ReplayArgs, replay_command}; pub use validate::{ValidateArgs, validate_command}; diff --git a/src/commands/replay.rs b/src/commands/replay.rs new file mode 100644 index 0000000..cd4d596 --- /dev/null +++ b/src/commands/replay.rs @@ -0,0 +1,105 @@ +use super::report::{OutputFormat, print_json}; +use anyhow::{Context, Result, bail}; +use cigen::replay::{GITHUB_EXPIRY_DAYS, Options, Range, replay}; +use clap::Args; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// Arguments for `cigen replay`. +#[derive(Debug, Args)] +pub struct ReplayArgs { + /// Commits to replay: `..` (first-parent history). Use `--last` instead for the + /// latest commits of HEAD + #[arg(value_name = "RANGE", conflicts_with = "last")] + pub range: Option, + + /// Replay the last N first-parent commits of HEAD + #[arg(long, value_name = "N")] + pub last: Option, + + /// A cigen.yml or .cigen/ to apply to every commit, in place of each commit's own config. + /// Use it to try cigen on a project whose history has no cigen config + #[arg(short, long)] + pub config: Option, + + /// The git repository to replay + #[arg(long, default_value = ".")] + pub repo: PathBuf, + + /// Replay only this workflow (repeatable). Triggers aren't modelled, so pick the workflows + /// that run on every push + #[arg(long = "workflow", value_name = "NAME")] + pub workflows: Vec, + + /// Never expire a pass. By default a pass expires after 7 days unused, as GitHub's cache + /// evicts it + #[arg(long)] + pub no_expiry: bool, + + /// A JSON file of average minutes per job (`{"test": 12.5}`), to estimate minutes saved + #[arg(long, value_name = "FILE")] + pub durations: Option, + + /// List every commit with the jobs it ran and skipped (text output) + #[arg(long)] + pub commits: bool, + + /// Output format + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + pub format: OutputFormat, +} + +pub fn replay_command(args: ReplayArgs) -> Result<()> { + let range = match (args.last, args.range) { + (Some(0), _) => bail!("`--last` needs at least 1 commit"), + (Some(count), _) => Range::Last(count), + (None, Some(spec)) if spec.contains("..") => Range::Between(spec), + (None, Some(spec)) => bail!( + "`{spec}` isn't a range: write `..`, or use `--last ` for the latest \ + commits" + ), + (None, None) => bail!("say which commits to replay: `--last ` or `..`"), + }; + let durations = args.durations.as_deref().map(load_durations).transpose()?; + let options = Options { + repo: args.repo, + range, + config: args.config.map(absolute).transpose()?, + expiry_days: (!args.no_expiry).then_some(GITHUB_EXPIRY_DAYS), + workflows: args.workflows, + durations, + }; + eprintln!("Replaying history (an estimate; see `cigen replay --help`)..."); + let report = replay(&options)?; + match args.format { + OutputFormat::Json => print_json(&report), + OutputFormat::Text => { + print!("{}", report.to_text(args.commits)); + Ok(()) + } + } +} + +/// The config is read outside the worktree, so a relative path is resolved here, once. +fn absolute(path: PathBuf) -> Result { + std::fs::canonicalize(&path) + .with_context(|| format!("can't find the config at {}", path.display())) +} + +fn load_durations(path: &Path) -> Result> { + let text = std::fs::read_to_string(path) + .with_context(|| format!("can't read the durations file {}", path.display()))?; + let durations: BTreeMap = serde_json::from_str(&text).with_context(|| { + format!( + "{} must be a JSON object of minutes per job, such as {{\"test\": 12.5}}", + path.display() + ) + })?; + if let Some((job, minutes)) = durations.iter().find(|(_, m)| !m.is_finite() || **m < 0.0) { + bail!( + "{}: `{job}` has {minutes} minutes; durations must be 0 or more", + path.display() + ); + } + Ok(durations) +} diff --git a/src/lib.rs b/src/lib.rs index def9f08..4cd4856 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,4 +6,5 @@ pub mod modules; pub mod orchestrator; pub mod pathspec; pub mod plugin; +pub mod replay; pub mod schema; diff --git a/src/main.rs b/src/main.rs index 2c95cad..6f49cce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -42,6 +42,11 @@ enum Commands { #[command(flatten)] args: commands::ExplainArgs, }, + /// Estimate how many job runs cigen would have skipped over the project's git history + Replay { + #[command(flatten)] + args: commands::ReplayArgs, + }, /// Check the config and list every problem in it Validate { #[command(flatten)] @@ -72,6 +77,7 @@ fn run(cli: Cli) -> Result { commands::hash_command(args)?; } Some(Commands::Explain { args }) => commands::explain_command(args)?, + Some(Commands::Replay { args }) => commands::replay_command(args)?, Some(Commands::Validate { args }) => return commands::validate_command(args), None => { // Default to generate command diff --git a/src/replay/history.rs b/src/replay/history.rs new file mode 100644 index 0000000..a085795 --- /dev/null +++ b/src/replay/history.rs @@ -0,0 +1,148 @@ +//! The commits to replay, and a temporary worktree to check each one out in. The user's own +//! working tree is never touched. + +use anyhow::{Context, Result, bail}; +use std::path::{Path, PathBuf}; +use tempfile::TempDir; + +/// Which commits to replay. +#[derive(Debug, Clone)] +pub enum Range { + /// The last N first-parent commits of HEAD. + Last(usize), + /// A `..` range, as git understands it. + Between(String), +} + +#[derive(Debug, Clone)] +pub struct Commit { + pub sha: String, + /// Committer date, in seconds since the epoch + pub time: i64, + /// Committer date, ISO 8601 + pub date: String, + pub subject: String, +} + +/// The first-parent commits of `range`, oldest first. +pub fn commits(repo: &Path, range: &Range) -> Result> { + let mut args = vec![ + "log".to_string(), + "--first-parent".to_string(), + "--reverse".to_string(), + "--format=%H%x00%ct%x00%cI%x00%s".to_string(), + ]; + match range { + Range::Last(count) => { + args.push(format!("--max-count={count}")); + args.push("HEAD".to_string()); + } + Range::Between(spec) => args.push(spec.clone()), + } + args.push("--".to_string()); + let output = git(repo, &args)?; + output + .lines() + .filter(|line| !line.is_empty()) + .map(parse_commit) + .collect() +} + +fn parse_commit(line: &str) -> Result { + let mut parts = line.splitn(4, '\0'); + let (Some(sha), Some(time), Some(date), Some(subject)) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + bail!("unexpected `git log` output: {line}"); + }; + Ok(Commit { + sha: sha.to_string(), + time: time.parse().with_context(|| { + format!("commit {sha} has a committer date git didn't print as a number") + })?, + date: date.to_string(), + subject: subject.to_string(), + }) +} + +/// A detached worktree of `repo` in a temporary directory, removed when dropped. +pub struct Worktree { + repo: PathBuf, + path: PathBuf, + _dir: TempDir, +} + +impl Worktree { + pub fn new(repo: &Path, sha: &str) -> Result { + let dir = tempfile::Builder::new() + .prefix("cigen-replay-") + .tempdir() + .context("creating a temporary directory for the replay worktree")?; + let path = dir.path().join("tree"); + git( + repo, + &[ + "worktree".into(), + "add".into(), + "--quiet".into(), + "--detach".into(), + path.display().to_string(), + sha.into(), + ], + )?; + Ok(Self { + repo: repo.to_path_buf(), + path, + _dir: dir, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn checkout(&self, sha: &str) -> Result<()> { + git( + &self.path, + &[ + "checkout".into(), + "--quiet".into(), + "--force".into(), + "--detach".into(), + sha.into(), + ], + )?; + Ok(()) + } +} + +impl Drop for Worktree { + fn drop(&mut self) { + let path = self.path.display().to_string(); + // Best effort: if this fails, `git worktree prune` cleans up once the directory is gone. + let _ = git( + &self.repo, + &["worktree".into(), "remove".into(), "--force".into(), path], + ); + } +} + +/// Runs git in `cwd` (through `crate::git::command`, so a checkout owned by another user works), +/// ignoring any `GIT_*` variables inherited from a git hook. +fn git(cwd: &Path, args: &[String]) -> Result { + let mut command = crate::git::command(cwd); + for (name, _) in std::env::vars_os() { + if name.to_string_lossy().starts_with("GIT_") { + command.env_remove(name); + } + } + let output = command.args(args).output().context("running git")?; + if !output.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr).trim() + ); + } + Ok(String::from_utf8(output.stdout)?) +} diff --git a/src/replay/mod.rs b/src/replay/mod.rs new file mode 100644 index 0000000..8fcc8cf --- /dev/null +++ b/src/replay/mod.rs @@ -0,0 +1,233 @@ +//! `cigen replay`: estimates how many job runs cigen would have skipped over a project's git +//! history, with no CI involved. Each commit is checked out in a temporary worktree and every +//! job is hashed exactly as `cigen hash --job` hashes it in CI (`crate::hashing`); the skip +//! model is in `model`. + +mod history; +mod model; +mod report; + +pub use history::Range; +pub use model::GITHUB_EXPIRY_DAYS; +pub use report::Report; + +use crate::config::{self, ConfigErrors}; +use crate::hashing::{FileHasher, hash_job}; +use crate::schema::CigenConfig; +use anyhow::{Result, bail}; +use history::{Commit, Worktree}; +use model::{Outcome, PassStore}; +use report::{CommitResult, JobTotals, Model, RangeInfo, Totals, rate}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +pub struct Options { + /// The repository to replay + pub repo: PathBuf, + pub range: Range, + /// A config to apply to every commit, in place of each commit's own + pub config: Option, + /// Days a pass survives unused; `None` never expires + pub expiry_days: Option, + /// The workflows to replay; empty means all of them + pub workflows: Vec, + /// Average minutes per run, by job id + pub durations: Option>, +} + +const NOTES: &[&str] = &[ + "workflow triggers (`on:`) aren't modelled: every replayed workflow runs on every commit.", + "a matrix job counts once per commit, as one job id.", + "pull requests aren't modelled: in CI they can also reuse the branch's passes.", +]; + +pub fn replay(options: &Options) -> Result { + let commits = history::commits(&options.repo, &options.range)?; + let Some(first) = commits.first() else { + bail!("no commits to replay in that range"); + }; + let fixed = match &options.config { + Some(path) => Some(load(path)?), + None => None, + }; + + let worktree = Worktree::new(&options.repo, &first.sha)?; + let mut store = PassStore::new(options.expiry_days); + let mut jobs: BTreeMap = BTreeMap::new(); + let mut results = Vec::with_capacity(commits.len()); + let mut seen_workflows = BTreeSet::new(); + + for commit in &commits { + worktree.checkout(&commit.sha)?; + let own; + let config = match &fixed { + Some(config) => config, + None => match own_config(worktree.path())? { + CommitConfig::Loaded(config) => { + own = *config; + &own + } + CommitConfig::Missing => { + results.push(CommitResult { + no_config: true, + ..result(commit, Vec::new(), Vec::new()) + }); + continue; + } + CommitConfig::Broken(error) => { + results.push(CommitResult { + config_error: Some(error), + ..result(commit, Vec::new(), Vec::new()) + }); + continue; + } + }, + }; + + // File digests are cached by path, so each commit starts a fresh cache. + let mut files = FileHasher::new(None); + let (mut ran, mut skipped) = (Vec::new(), Vec::new()); + for (id, job) in &config.jobs { + let workflow = job.workflow.as_deref().unwrap_or("ci"); + seen_workflows.insert(workflow.to_string()); + if !options.workflows.is_empty() && !options.workflows.iter().any(|w| w == workflow) { + continue; + } + let totals = jobs.entry(id.clone()).or_default(); + totals.always_runs = job.inputs.is_empty(); + let outcome = if totals.always_runs { + Outcome::Ran + } else { + let hash = hash_job(config, id, worktree.path(), &mut files, None, None)?.hash; + store.run(id, &hash, commit.time) + }; + match outcome { + Outcome::Ran => { + totals.ran += 1; + ran.push(id.clone()); + } + Outcome::Skipped => { + totals.skipped += 1; + skipped.push(id.clone()); + } + } + } + results.push(result(commit, ran, skipped)); + } + drop(worktree); + + if let Some(missing) = options + .workflows + .iter() + .find(|w| !seen_workflows.contains(*w)) + { + let known: Vec<&str> = seen_workflows.iter().map(String::as_str).collect(); + bail!( + "no commit in that range has a workflow named `{missing}` (workflows found: {})", + if known.is_empty() { + "none".to_string() + } else { + known.join(", ") + } + ); + } + + let totals = totals(&mut jobs, options.durations.as_ref()); + Ok(Report { + estimate: true, + model: Model { + assume_pass: true, + branch: "first-parent", + expiry_days: options.expiry_days, + workflows: (!options.workflows.is_empty()).then(|| options.workflows.clone()), + config: options.config.as_ref().map_or_else( + || "per-commit".to_string(), + |path| path.display().to_string(), + ), + notes: NOTES.to_vec(), + }, + range: RangeInfo { + from: commits.first().map(|c| c.sha.clone()), + to: commits.last().map(|c| c.sha.clone()), + commits: commits.len(), + }, + commits: results, + jobs, + totals, + }) +} + +fn load(path: &Path) -> Result { + config::load(path).map_err(|errors| config_error(path, errors)) +} + +enum CommitConfig { + Loaded(Box), + Missing, + /// A config this version of cigen can't load, such as one written for an older version + Broken(String), +} + +/// The commit's own config. Errors name files relative to the repository, not the worktree. +fn own_config(root: &Path) -> Result { + let relative = |text: String| text.replace(&format!("{}/", root.display()), ""); + let path = match config::find(root) { + Ok(path) => path, + // Both layouts at once is a broken config, not a missing one. + Err(error) if root.join("cigen.yml").is_file() && root.join(".cigen").is_dir() => { + return Ok(CommitConfig::Broken(relative(error.to_string()))); + } + Err(_) => return Ok(CommitConfig::Missing), + }; + Ok(match config::load(&path) { + Ok(config) => CommitConfig::Loaded(Box::new(config)), + Err(errors) => CommitConfig::Broken(relative(errors.to_string())), + }) +} + +fn config_error(origin: &Path, errors: ConfigErrors) -> anyhow::Error { + anyhow::anyhow!("the config at {} doesn't load:\n{errors}", origin.display()) +} + +fn result(commit: &Commit, ran: Vec, skipped: Vec) -> CommitResult { + CommitResult { + sha: commit.sha.clone(), + date: commit.date.clone(), + subject: commit.subject.clone(), + ran, + skipped, + no_config: false, + config_error: None, + } +} + +fn totals( + jobs: &mut BTreeMap, + durations: Option<&BTreeMap>, +) -> Totals { + let mut totals = Totals::default(); + let (mut minutes_total, mut minutes_saved) = (0.0, 0.0); + for (id, job) in jobs.iter_mut() { + let runs = job.ran + job.skipped; + job.skip_rate = rate(job.skipped, runs); + totals.ran += job.ran; + totals.skipped += job.skipped; + if let Some(durations) = durations { + match durations.get(id) { + Some(&minutes) => { + job.minutes_per_run = Some(minutes); + minutes_total += minutes * runs as f64; + minutes_saved += minutes * job.skipped as f64; + } + None => totals.minutes_unknown.push(id.clone()), + } + } + } + totals.job_runs = totals.ran + totals.skipped; + totals.skip_rate = rate(totals.skipped, totals.job_runs); + if durations.is_some() { + totals.minutes_total = Some(minutes_total); + totals.minutes_saved = Some(minutes_saved); + } + totals +} diff --git a/src/replay/model.rs b/src/replay/model.rs new file mode 100644 index 0000000..f240166 --- /dev/null +++ b/src/replay/model.rs @@ -0,0 +1,102 @@ +//! The skip model: which job runs a pass marker would have skipped. +//! +//! A run is assumed to pass and records its hash. A later run of the same job with the same hash +//! is a hit, and skips, unless the marker has gone unused for longer than the expiry (GitHub's +//! cache evicts entries not accessed for 7 days). A hit refreshes the marker, as a cache read does. + +use std::collections::BTreeMap; + +pub const GITHUB_EXPIRY_DAYS: u64 = 7; +const SECONDS_PER_DAY: i64 = 86_400; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Outcome { + Ran, + Skipped, +} + +#[derive(Debug)] +pub struct PassStore { + expiry_seconds: Option, + /// `(job, hash)` → when the marker was last written or read + last_used: BTreeMap<(String, String), i64>, +} + +impl PassStore { + pub fn new(expiry_days: Option) -> Self { + Self { + expiry_seconds: expiry_days.map(|days| days as i64 * SECONDS_PER_DAY), + last_used: BTreeMap::new(), + } + } + + /// The outcome of running `job` with `hash` at `time`, assuming the run passes. + pub fn run(&mut self, job: &str, hash: &str, time: i64) -> Outcome { + let key = (job.to_string(), hash.to_string()); + let alive = self.last_used.get(&key).is_some_and(|&used| { + // Commit dates can go backwards (rebases); treat that as no time passing. + let idle = (time - used).max(0); + self.expiry_seconds.is_none_or(|expiry| idle <= expiry) + }); + let used = self.last_used.entry(key).or_insert(time); + *used = (*used).max(time); + if alive { + Outcome::Skipped + } else { + Outcome::Ran + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DAY: i64 = SECONDS_PER_DAY; + + #[test] + fn the_same_hash_skips_and_a_new_one_runs() { + let mut store = PassStore::new(None); + assert_eq!(store.run("test", "a", 0), Outcome::Ran); + assert_eq!(store.run("test", "a", DAY), Outcome::Skipped); + assert_eq!(store.run("test", "b", DAY), Outcome::Ran); + assert_eq!( + store.run("lint", "a", DAY), + Outcome::Ran, + "markers are per job" + ); + } + + #[test] + fn a_marker_expires_after_seven_idle_days_and_a_hit_refreshes_it() { + let mut store = PassStore::new(Some(GITHUB_EXPIRY_DAYS)); + assert_eq!(store.run("test", "a", 0), Outcome::Ran); + assert_eq!( + store.run("test", "a", 7 * DAY), + Outcome::Skipped, + "exactly 7 days" + ); + assert_eq!( + store.run("test", "a", 14 * DAY), + Outcome::Skipped, + "refreshed at day 7" + ); + assert_eq!( + store.run("test", "a", 21 * DAY + 1), + Outcome::Ran, + "idle too long" + ); + } + + #[test] + fn a_date_that_goes_backwards_counts_as_no_time() { + let mut store = PassStore::new(Some(GITHUB_EXPIRY_DAYS)); + assert_eq!(store.run("test", "a", 10 * DAY), Outcome::Ran); + assert_eq!(store.run("test", "a", 2 * DAY), Outcome::Skipped); + assert_eq!( + store.run("test", "a", 17 * DAY), + Outcome::Skipped, + "last used day 10" + ); + } +} diff --git a/src/replay/report.rs b/src/replay/report.rs new file mode 100644 index 0000000..4d156e9 --- /dev/null +++ b/src/replay/report.rs @@ -0,0 +1,234 @@ +//! What a replay found: per commit, per job and in total. `--format json` prints `Report` as it +//! is; the text form says plainly that it's an estimate and what the model assumes. + +use serde::Serialize; +use std::collections::BTreeMap; +use std::fmt::Write as _; + +#[derive(Debug, Serialize)] +pub struct Report { + /// Always true: a replay models CI, it doesn't measure it. + pub estimate: bool, + pub model: Model, + pub range: RangeInfo, + pub commits: Vec, + pub jobs: BTreeMap, + pub totals: Totals, +} + +#[derive(Debug, Serialize)] +pub struct Model { + /// No CI history is read: every run is assumed to pass. + pub assume_pass: bool, + /// The history replayed: one branch's first-parent commits. + pub branch: &'static str, + /// Days a pass marker survives unused; `null` with `--no-expiry`. + pub expiry_days: Option, + /// The workflows replayed; `null` means all of them + pub workflows: Option>, + /// `per-commit` (each commit's own config) or the path of the config applied to every commit + pub config: String, + pub notes: Vec<&'static str>, +} + +#[derive(Debug, Serialize)] +pub struct RangeInfo { + pub from: Option, + pub to: Option, + pub commits: usize, +} + +#[derive(Debug, Serialize)] +pub struct CommitResult { + pub sha: String, + pub date: String, + pub subject: String, + pub ran: Vec, + pub skipped: Vec, + /// The commit has no cigen config, so it's left out of the counts. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub no_config: bool, + /// The commit's config doesn't load with this version of cigen (often one written for an + /// older version), so it's left out of the counts. + #[serde(skip_serializing_if = "Option::is_none")] + pub config_error: Option, +} + +#[derive(Debug, Default, Serialize)] +pub struct JobTotals { + pub ran: u64, + pub skipped: u64, + pub skip_rate: f64, + /// The job has no `inputs`, so CI never skips it. + pub always_runs: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub minutes_per_run: Option, +} + +#[derive(Debug, Default, Serialize)] +pub struct Totals { + /// Every job run the commits triggered: `ran` + `skipped` + pub job_runs: u64, + pub ran: u64, + pub skipped: u64, + pub skip_rate: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub minutes_total: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub minutes_saved: Option, + /// Jobs with no entry in the durations file, left out of the minutes + #[serde(skip_serializing_if = "Vec::is_empty")] + pub minutes_unknown: Vec, +} + +pub fn rate(skipped: u64, total: u64) -> f64 { + if total == 0 { + 0.0 + } else { + skipped as f64 / total as f64 + } +} + +impl Report { + pub fn to_text(&self, show_commits: bool) -> String { + let mut out = String::new(); + let model = &self.model; + let _ = writeln!( + out, + "cigen replay: an estimate from git history, not a measurement." + ); + let expiry = match model.expiry_days { + Some(days) => format!("a pass expires after {days} days unused (by commit date)"), + None => "passes never expire".to_string(), + }; + let _ = writeln!( + out, + "Model: every run passed; a job skips when its hash already ran on an earlier commit \ + of this replay; first-parent history of one branch; {expiry}." + ); + for note in &model.notes { + let _ = writeln!(out, "Note: {note}"); + } + let config = if model.config == "per-commit" { + "each commit's own".to_string() + } else { + format!("{} for every commit", model.config) + }; + let _ = writeln!(out, "Config: {config}"); + let workflows = model.workflows.as_ref().map_or_else( + || "all (use --workflow to choose)".to_string(), + |w| w.join(", "), + ); + let _ = writeln!(out, "Workflows: {workflows}"); + let _ = writeln!(out, "Commits: {}", self.range.commits); + let missing = self.commits.iter().filter(|c| c.no_config).count(); + if missing > 0 { + let _ = writeln!(out, " {missing} have no cigen config and aren't counted."); + } + let broken: Vec<&CommitResult> = self + .commits + .iter() + .filter(|c| c.config_error.is_some()) + .collect(); + if let Some(first) = broken.first() { + let _ = writeln!( + out, + " {} have a config this cigen can't load and aren't counted. The first, {}:", + broken.len(), + short(&first.sha) + ); + for line in first.config_error.iter().flat_map(|e| e.lines()) { + let _ = writeln!(out, " {line}"); + } + } + + if show_commits { + let _ = writeln!(out); + for commit in &self.commits { + let day = &commit.date[..commit.date.len().min(10)]; + let summary = if commit.no_config { + "no config".to_string() + } else if commit.config_error.is_some() { + "config doesn't load".to_string() + } else { + format!( + "ran {}; skipped {}", + list(&commit.ran), + list(&commit.skipped) + ) + }; + let _ = writeln!( + out, + "{} {day} {}: {summary}", + short(&commit.sha), + commit.subject + ); + } + } + + let _ = writeln!(out); + let width = self.jobs.keys().map(String::len).max().unwrap_or(3).max(5); + let _ = writeln!( + out, + "{:width$} {:>6} {:>7} {:>9}", + "job", "ran", "skipped", "skip rate" + ); + for (id, job) in &self.jobs { + let note = if job.always_runs { + " (no inputs: always runs)" + } else { + "" + }; + let _ = writeln!( + out, + "{id:width$} {:>6} {:>7} {:>9}{note}", + job.ran, + job.skipped, + percent(job.skip_rate) + ); + } + let totals = &self.totals; + let _ = writeln!(out); + let _ = writeln!( + out, + "Skipped {} of {} job runs ({}).", + totals.skipped, + totals.job_runs, + percent(totals.skip_rate) + ); + if let (Some(saved), Some(total)) = (totals.minutes_saved, totals.minutes_total) { + let _ = write!(out, "Estimated CI minutes saved: {saved:.0} of {total:.0}"); + if totals.minutes_unknown.is_empty() { + let _ = writeln!(out, "."); + } else { + let _ = writeln!( + out, + " (no duration given for {}).", + totals.minutes_unknown.join(", ") + ); + } + } + out + } +} + +fn short(sha: &str) -> &str { + &sha[..sha.len().min(10)] +} + +fn list(jobs: &[String]) -> String { + if jobs.is_empty() { + "nothing".to_string() + } else { + jobs.join(", ") + } +} + +fn percent(rate: f64) -> String { + let value = rate * 100.0; + if (value - value.round()).abs() < 0.05 { + format!("{value:.0}%") + } else { + format!("{value:.1}%") + } +} diff --git a/tests/replay.rs b/tests/replay.rs new file mode 100644 index 0000000..f65d4eb --- /dev/null +++ b/tests/replay.rs @@ -0,0 +1,273 @@ +//! `cigen replay` estimates skipping from git history. Each test builds a history with known +//! changes and dates, and checks the exact counts. + +mod support; + +use serde_json::Value; +use std::path::Path; +use support::fixture_repo::FixtureRepo; + +const CONFIG: &str = r#"provider: github +workflows: + ci: + jobs: + test: + image: rust:latest + inputs: ['src/**'] + steps: + - run: cargo test --locked + docs: + image: node:24 + inputs: ['docs/**'] + steps: + - run: npm run docs + audit: + image: rust:latest + steps: + - run: cargo audit +"#; + +const DAY: i64 = 86_400; +const START: i64 = 1_767_225_600; // 2026-01-01 + +/// Eight commits on main. Comments say what each one should do to `test` and `docs` +/// (`audit` has no inputs, so it always runs). +fn history() -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("src/lib.rs", "v1") + .write("docs/index.md", "v1") + .write("Cargo.lock", "lock v1") + .write("README.md", "hello"); + repo.commit_at("c1: everything runs", START); + repo.write("README.md", "hello again"); + repo.commit_at("c2: outside every input: both skip", START + DAY); + repo.write("src/lib.rs", "v2"); + repo.commit_at("c3: src changed: test runs, docs skips", START + 2 * DAY); + repo.write("Cargo.lock", "lock v2"); + repo.commit_at( + "c4: the lockfile is a derived input: both run", + START + 3 * DAY, + ); + repo.write("docs/index.md", "v2"); + repo.commit_at("c5: docs changed: docs runs, test skips", START + 4 * DAY); + repo.write("docs/index.md", "v1"); + repo.commit_at("c6: docs reverted to c4's: both skip", START + 5 * DAY); + repo.write( + "cigen.yml", + &CONFIG.replace("cargo test --locked", "cargo test --locked --all"), + ); + repo.commit_at( + "c7: test's definition changed: test runs, docs skips", + START + 6 * DAY, + ); + repo.write("README.md", "two weeks later"); + repo.commit_at( + "c8: 14 days idle: both markers expired, both run", + START + 20 * DAY, + ); + repo +} + +fn replay(repo: &Path, args: &[&str]) -> Value { + let output = support::cigen() + .arg("replay") + .args(args) + .args(["--format", "json"]) + .current_dir(repo) + .output() + .expect("run cigen replay"); + assert!( + output.status.success(), + "cigen replay failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("replay prints JSON") +} + +fn counts(report: &Value, job: &str) -> (u64, u64) { + let job = &report["jobs"][job]; + ( + job["ran"].as_u64().expect("ran"), + job["skipped"].as_u64().expect("skipped"), + ) +} + +#[test] +fn counts_what_each_commit_would_have_run_and_skipped() { + let repo = history(); + let report = replay(repo.path(), &["--last", "8"]); + + assert_eq!(report["estimate"], true); + assert_eq!(report["model"]["assume_pass"], true); + assert_eq!(report["model"]["expiry_days"], 7); + assert_eq!(report["range"]["commits"], 8); + + assert_eq!(counts(&report, "test"), (5, 3)); + assert_eq!(counts(&report, "docs"), (4, 4)); + assert_eq!(counts(&report, "audit"), (8, 0)); + assert_eq!(report["jobs"]["audit"]["always_runs"], true); + + assert_eq!(report["totals"]["job_runs"], 24); + assert_eq!(report["totals"]["ran"], 17); + assert_eq!(report["totals"]["skipped"], 7); + + let commits = report["commits"].as_array().expect("commits"); + let skipped = |i: usize| commits[i]["skipped"].clone(); + assert_eq!(skipped(1), serde_json::json!(["docs", "test"]), "c2"); + assert_eq!( + skipped(3), + serde_json::json!([]), + "c4: the lockfile changed" + ); + assert_eq!( + skipped(5), + serde_json::json!(["docs", "test"]), + "c6: reverted" + ); + assert_eq!(skipped(7), serde_json::json!([]), "c8: expired"); + assert!(commits[0]["subject"].as_str().unwrap().starts_with("c1:")); +} + +#[test] +fn without_expiry_old_passes_still_count() { + let repo = history(); + let report = replay(repo.path(), &["--last", "8", "--no-expiry"]); + assert_eq!(report["model"]["expiry_days"], Value::Null); + assert_eq!(counts(&report, "test"), (4, 4)); + assert_eq!(counts(&report, "docs"), (3, 5)); + assert_eq!(report["totals"]["skipped"], 9); +} + +#[test] +fn a_hit_keeps_a_pass_alive() { + // docs ran at day 0 and was skipped (a hit) every 5 days: each hit resets the 7-day clock. + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("src/lib.rs", "v1") + .write("docs/index.md", "v1"); + repo.commit_at("docs runs", START); + for i in 1..=4 { + repo.write("src/lib.rs", &format!("v{}", i + 1)); + repo.commit_at("src only", START + i * 5 * DAY); + } + let report = replay(repo.path(), &["--last", "5"]); + assert_eq!(counts(&report, "docs"), (1, 4)); +} + +#[test] +fn a_range_replays_first_parent_history_only() { + let repo = history(); + let first = repo.rev("HEAD~5"); + repo.switch("side", true); + repo.write("src/lib.rs", "side work"); + repo.commit_at("side branch", START + 21 * DAY); + repo.switch("main", false); + repo.merge("side", START + 22 * DAY); + + let range = format!("{first}..HEAD"); + let report = replay(repo.path(), &[range.as_str()]); + // c4 to c8 and the merge: the side branch's own commit isn't replayed. + assert_eq!(report["range"]["commits"], 6); + let subjects: Vec<&str> = report["commits"] + .as_array() + .unwrap() + .iter() + .map(|c| c["subject"].as_str().unwrap()) + .collect(); + assert!(!subjects.contains(&"side branch"), "{subjects:?}"); +} + +#[test] +fn a_config_from_outside_the_history_applies_to_every_commit() { + // The case-study mode: the project's history has no cigen config. + let repo = FixtureRepo::new(); + repo.write("src/lib.rs", "v1").write("docs/index.md", "v1"); + repo.commit_at("first", START); + repo.write("README.md", "readme"); + repo.commit_at("readme", START + DAY); + repo.write("src/lib.rs", "v2"); + repo.commit_at("src", START + 2 * DAY); + + let configs = tempfile::tempdir().unwrap(); + let config = configs.path().join("cigen.yml"); + std::fs::write(&config, CONFIG).unwrap(); + + let report = replay( + repo.path(), + &["--last", "3", "--config", config.to_str().unwrap()], + ); + assert_eq!(counts(&report, "test"), (2, 1)); + assert_eq!(counts(&report, "docs"), (1, 2)); + + let own = replay(repo.path(), &["--last", "3"]); + assert_eq!(own["totals"]["job_runs"], 0); + assert_eq!(own["commits"][0]["no_config"], true); +} + +#[test] +fn durations_estimate_minutes_saved() { + let repo = history(); + let durations = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(durations.path(), r#"{"test": 10, "docs": 2}"#).unwrap(); + let report = replay( + repo.path(), + &[ + "--last", + "8", + "--durations", + durations.path().to_str().unwrap(), + ], + ); + // test: 3 skips of 10 minutes; docs: 4 skips of 2. audit has no duration. + assert_eq!(report["totals"]["minutes_saved"], 38.0); + assert_eq!(report["totals"]["minutes_total"], 96.0); + assert_eq!( + report["totals"]["minutes_unknown"], + serde_json::json!(["audit"]) + ); +} + +#[test] +fn text_output_says_it_is_an_estimate() { + let repo = history(); + let output = support::cigen() + .args(["replay", "--last", "8"]) + .current_dir(repo.path()) + .output() + .unwrap(); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("an estimate"), "{text}"); + assert!(text.contains("every run passed"), "{text}"); + assert!(text.contains("7 of 24 job runs"), "{text}"); +} + +#[test] +fn replay_leaves_no_worktree_behind() { + let repo = history(); + replay(repo.path(), &["--last", "2"]); + let worktrees = repo.git_output(&["worktree", "list"]); + assert_eq!(worktrees.lines().count(), 1, "{worktrees}"); +} + +#[test] +fn workflow_picks_which_workflows_to_replay() { + // Triggers aren't modelled, so a release workflow would count on every commit. + let config = format!( + "{CONFIG} release:\n jobs:\n publish:\n image: rust:latest\n steps:\n - run: cargo publish\n" + ); + let repo = FixtureRepo::new(); + repo.write("cigen.yml", &config).write("src/lib.rs", "v1"); + repo.commit_at("first", START); + repo.write("README.md", "readme"); + repo.commit_at("second", START + DAY); + + let all = replay(repo.path(), &["--last", "2"]); + assert_eq!(counts(&all, "publish"), (2, 0)); + + let ci = replay(repo.path(), &["--last", "2", "--workflow", "ci"]); + assert!(ci["jobs"].get("publish").is_none(), "{}", ci["jobs"]); + assert_eq!(ci["totals"]["job_runs"], 6); + assert_eq!(ci["model"]["workflows"], serde_json::json!(["ci"])); +} diff --git a/tests/replay_needs.rs b/tests/replay_needs.rs new file mode 100644 index 0000000..7abdd0c --- /dev/null +++ b/tests/replay_needs.rs @@ -0,0 +1,69 @@ +//! `cigen replay` hashes jobs exactly as CI does, so a job reruns when a job it `needs` would +//! have run, even though none of its own inputs changed. Counting it as skipped there would +//! overstate the savings with a skip CI never makes. + +mod support; + +use serde_json::Value; +use support::fixture_repo::FixtureRepo; + +const CONFIG: &str = r#"provider: github +workflows: + ci: + jobs: + build: + image: rust:latest + inputs: ['src/**'] + steps: + - run: cargo build + deploy: + image: rust:latest + needs: [build] + inputs: ['deploy/**'] + steps: + - run: ./deploy/run.sh +"#; + +const DAY: i64 = 86_400; +const START: i64 = 1_767_225_600; // 2026-01-01 + +fn counts(report: &Value, job: &str) -> (u64, u64) { + let job = &report["jobs"][job]; + ( + job["ran"].as_u64().expect("ran"), + job["skipped"].as_u64().expect("skipped"), + ) +} + +#[test] +fn a_job_runs_again_when_a_job_it_needs_changed() { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("src/main.rs", "v1") + .write("deploy/run.sh", "deploy") + .write("README.md", "hello"); + repo.commit_at("c1: both run", START); + repo.write("src/main.rs", "v2"); + repo.commit_at("c2: build's input changed: both run", START + DAY); + repo.write("README.md", "hello again"); + repo.commit_at("c3: nothing either reads: both skip", START + 2 * DAY); + + let output = support::cigen() + .args(["replay", "--last", "3", "--format", "json"]) + .current_dir(repo.path()) + .output() + .expect("run cigen replay"); + assert!( + output.status.success(), + "cigen replay failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).expect("replay prints JSON"); + + assert_eq!(counts(&report, "build"), (2, 1)); + assert_eq!( + counts(&report, "deploy"), + (2, 1), + "deploy needs build, so build's change on c2 must rerun it" + ); +} diff --git a/tests/support/fixture_repo.rs b/tests/support/fixture_repo.rs index fd788c9..728b9b8 100644 --- a/tests/support/fixture_repo.rs +++ b/tests/support/fixture_repo.rs @@ -49,6 +49,57 @@ impl FixtureRepo { self.git(&["rev-parse", "HEAD"]).trim().to_string() } + /// Commits everything with author and committer dates set to `unix_time`. + pub fn commit_at(&self, message: &str, unix_time: i64) -> String { + self.git(&["add", "--all"]); + self.git_at( + &["commit", "--quiet", "--allow-empty", "-m", message], + unix_time, + ); + self.rev("HEAD") + } + + /// Merges `branch` into the current branch with a merge commit dated `unix_time`. + pub fn merge(&self, branch: &str, unix_time: i64) -> String { + self.git_at( + &[ + "merge", + "--quiet", + "--no-ff", + "-m", + &format!("Merge {branch}"), + branch, + ], + unix_time, + ); + self.rev("HEAD") + } + + pub fn rev(&self, rev: &str) -> String { + self.git(&["rev-parse", rev]).trim().to_string() + } + + pub fn git_output(&self, args: &[&str]) -> String { + self.git(args) + } + + fn git_at(&self, args: &[&str], unix_time: i64) { + let date = format!("@{unix_time} +0000"); + let output = cigen_mockci::git::command() + .args(args) + .env("GIT_AUTHOR_DATE", &date) + .env("GIT_COMMITTER_DATE", &date) + .current_dir(self.path()) + .output() + .expect("run git"); + assert!( + output.status.success(), + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr) + ); + } + pub fn switch(&self, branch: &str, create: bool) { if create { self.git(&["switch", "--quiet", "--create", branch]);