From 0a05b3a237002f0a247e5078a02a26f8a9f72b3d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 13:33:34 +1300 Subject: [PATCH 1/7] Add cigen explain : what a job's hash covers Job hashing moves from the hash command into the library (src/hashing/): file digests and the on-disk cache in files.rs, and hash_job in job.rs, which returns the hash with what went into it. hash --job and explain both call it, so explain always describes the hash hash --job prints. The digest is unchanged: the old and new binaries give the same hash for every job in this repo and the fixtures, with and without --cache. explain prints the job's inputs with @groups expanded and the files each pattern matched, the derived inputs (config parts, and files with their reason), what else is hashed, and the hash, as text or JSON. An unknown job is a ConfigError that suggests the closest id. The config-error footer ("The config has N problems") now prints only when there's more than one. --- internal_docs/STATUS.md | 8 + src/commands/explain.rs | 97 ++++++++ src/commands/hash.rs | 474 ++++------------------------------------ src/commands/mod.rs | 2 + src/commands/report.rs | 11 +- src/hashing/files.rs | 159 ++++++++++++++ src/hashing/job.rs | 270 +++++++++++++++++++++++ src/hashing/mod.rs | 8 + src/lib.rs | 1 + src/main.rs | 6 + tests/explain.rs | 175 +++++++++++++++ 11 files changed, 774 insertions(+), 437 deletions(-) create mode 100644 src/commands/explain.rs create mode 100644 src/hashing/files.rs create mode 100644 src/hashing/job.rs create mode 100644 src/hashing/mod.rs create mode 100644 tests/explain.rs diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index bd5bcc7..ab6cd5b 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -11,6 +11,12 @@ What the code does today, checked against the code in December 2026. Where cigen the config and exits non-zero with every problem it found; `--format json` prints `{valid, config, errors: [{file, line, path, message, suggestion}]}` on stdout. Every command prints config errors the same way (`src/commands/report.rs`). + `cigen explain [--config ] [--base-dir ] [--format text|json]` shows what the job's hash covers: + its `inputs` with `@groups` expanded and the files each pattern matched, the derived inputs (config parts by label, + files with their reason: toolchain pin, lockfile or named in a step, and the patterns the job's modules contribute + with their files), what else is hashed, and the hash. Job hashing lives in `src/hashing/`, and `hash --job` and + `explain` both call `hashing::hash_job`, so the two always agree. `explain` hashes as `hash --job` does without + `--modules-digest`, so for a job with modules its hash isn't the one the generated workflow computes. - **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 @@ -131,6 +137,8 @@ What the code does today, checked against the code in December 2026. Where cigen - `tests/git_ownership.rs`: `cigen hash` in a checkout git treats as owned by another user (`GIT_TEST_ASSUME_DIFFERENT_OWNER`), at the repository root and in a subdirectory, matches the hash computed as its owner. +- `tests/explain.rs`: `cigen explain` lists declared and derived inputs (module inputs included) with their files, in + JSON and text, and its hash equals `cigen hash --job`'s before and after an input changes. - `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/explain.rs b/src/commands/explain.rs new file mode 100644 index 0000000..0eea5cc --- /dev/null +++ b/src/commands/explain.rs @@ -0,0 +1,97 @@ +//! `cigen explain `: what a job's hash covers, and the hash itself. + +use super::hash::job_hash; +use super::report::{OutputFormat, print_json}; +use anyhow::Result; +use cigen::hashing::{JobHash, PatternFiles}; +use clap::Args; +use std::path::PathBuf; + +#[derive(Debug, Args)] +pub struct ExplainArgs { + /// The job's id + pub job: String, + + /// The config: a cigen.yml file or a .cigen/ directory (found in --base-dir by default) + #[arg(short, long)] + pub config: Option, + + /// The project root, where input patterns and step paths are looked up + #[arg(long = "base-dir", default_value = ".")] + pub base_dir: PathBuf, + + /// Output format + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + pub format: OutputFormat, +} + +pub fn explain_command(args: ExplainArgs) -> Result<()> { + let explained = job_hash( + &args.base_dir, + args.config.as_deref(), + None, + &args.job, + None, + )?; + match args.format { + OutputFormat::Json => print_json(&explained), + OutputFormat::Text => { + print!("{}", render(&explained)); + Ok(()) + } + } +} + +fn render(job: &JobHash) -> String { + let mut out = format!("Job `{}` in workflow `{}`\n", job.job, job.workflow); + + out.push_str("\nDeclared inputs:\n"); + if job.inputs.is_empty() { + out.push_str(" (none: the job has no `inputs`, so it never skips)\n"); + } + for input in &job.inputs { + let grouped = input.entry.starts_with('@'); + if grouped { + out.push_str(&format!(" {}\n", input.entry)); + } + let indent = if grouped { " " } else { " " }; + for pattern in &input.patterns { + push_pattern(&mut out, indent, pattern, ""); + } + } + + out.push_str("\nDerived inputs:\n"); + let derived = &job.derived; + if derived.config.is_empty() && derived.files.is_empty() && derived.modules.is_empty() { + out.push_str(" (none)\n"); + } + for label in &job.derived.config { + out.push_str(&format!(" {label}\n")); + } + for file in &job.derived.files { + out.push_str(&format!(" {} ({})\n", file.path, file.reason)); + } + for pattern in &job.derived.modules { + push_pattern(&mut out, " ", pattern, "from a module, "); + } + + out.push_str("\nAlso hashed:\n"); + for item in &job.also_hashed { + out.push_str(&format!(" {item}\n")); + } + out.push_str(&format!("\nHash: {}\n", job.hash)); + out +} + +/// A pattern with how many files it matches, then the files. +fn push_pattern(out: &mut String, indent: &str, pattern: &PatternFiles, note: &str) { + let count = match pattern.files.len() { + 0 => "no files".to_string(), + 1 => "1 file".to_string(), + n => format!("{n} files"), + }; + out.push_str(&format!("{indent}{} ({note}{count})\n", pattern.pattern)); + for file in &pattern.files { + out.push_str(&format!("{indent} {file}\n")); + } +} diff --git a/src/commands/hash.rs b/src/commands/hash.rs index 0a129ea..d300708 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -1,15 +1,11 @@ -use super::matrix_entry::with_matrix_entry; -use super::needs_hash; use anyhow::{Context, Result, bail}; -use cigen::schema::CigenConfig; +use cigen::hashing::{FileHasher, HashCache, JobHash, hash_job}; use clap::Args; -use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use std::fs::{self, File}; -use std::io::{BufReader, Read, Write}; +use std::io::Write; use std::path::{Path, PathBuf}; -use std::time::UNIX_EPOCH; /// Arguments for the `cigen hash` subcommand. #[derive(Debug, Args)] @@ -42,16 +38,18 @@ pub struct HashArgs { /// into the hash, so the hash covers the steps that config runs. #[arg(long = "modules-digest", requires = "job")] pub modules_digest: Option, - - /// 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. - #[arg(long = "matrix", requires = "job")] - pub matrix: Option, } pub fn hash_command(args: HashArgs) -> Result<()> { if let Some(job_id) = args.job.as_deref() { - hash_job(&args, job_id) + let job_hash = job_hash( + &args.base_dir, + args.config.as_deref(), + args.cache_path.as_deref(), + job_id, + args.modules_digest.as_deref(), + )?; + emit(&args, &job_hash.hash) } else { if args.patterns.is_empty() { bail!( @@ -66,23 +64,11 @@ fn hash_patterns(args: &HashArgs) -> Result<()> { let base_dir = canonicalize_path(&args.base_dir)?; let files = collect_files(&base_dir, &args.patterns)?; - - let cache_path = args - .cache_path - .as_ref() - .map(|path| resolve_path(&base_dir, path)); - let mut persistent_cache = if let Some(path) = cache_path.as_ref() { - Some(HashCache::load(path)?) - } else { - None - }; - - let mut file_hasher = FileHasher::new(persistent_cache.as_mut()); + let mut file_hasher = file_hasher(&base_dir, args.cache_path.as_deref())?; let mut aggregate = Sha256::new(); for rel in &files { - let absolute = base_dir.join(rel); - let file_hash = file_hasher.hash_file(&absolute, rel)?; + let file_hash = file_hasher.hash_file(&base_dir.join(rel), rel)?; aggregate.update(rel.to_string_lossy().as_bytes()); aggregate.update([0u8]); aggregate.update(&file_hash); @@ -93,265 +79,48 @@ fn hash_patterns(args: &HashArgs) -> Result<()> { } else { hex::encode(aggregate.finalize()) }; - - if let Some(name) = &args.output_name { - write_github_output(name, &digest)?; - } - - println!("{digest}"); - - if let Some(cache) = persistent_cache { - cache.save()?; - } - - Ok(()) + file_hasher.save()?; + emit(args, &digest) } -fn hash_job(args: &HashArgs, job_id: &str) -> Result<()> { - let base_dir = canonicalize_path(&args.base_dir)?; - let config_path = match &args.config { - Some(path) => resolve_path(&base_dir, path), +/// Loads the config and hashes `job_id`, as `cigen hash --job` and `cigen explain` do. +/// `base_dir` is the project root; the config is found there unless `config` names it. +pub fn job_hash( + base_dir: &Path, + config: Option<&Path>, + cache: Option<&Path>, + job_id: &str, + modules_digest: Option<&str>, +) -> Result { + let root = canonicalize_path(base_dir)?; + let config_path = match config { + Some(path) => resolve_path(&root, path), // As given, so errors name files the way the user wrote the directory. - None => cigen::config::find(&args.base_dir)?, + None => cigen::config::find(base_dir)?, }; - let config = cigen::config::load(&config_path)?; - config.jobs.get(job_id).with_context(|| { - format!( - "Job '{job_id}' not found in config at {}", - config_path.display() - ) - })?; - - let cache_path = args - .cache_path - .as_ref() - .map(|path| resolve_path(&base_dir, path)); - let mut persistent_cache = if let Some(path) = cache_path.as_ref() { - Some(HashCache::load(path)?) - } else { - None - }; - - let mut file_hasher = FileHasher::new(persistent_cache.as_mut()); - let mut pattern_cache: BTreeMap> = BTreeMap::new(); + let mut file_hasher = file_hasher(&root, cache)?; + let job_hash = hash_job(&config, job_id, &root, &mut file_hasher, modules_digest)?; + file_hasher.save()?; + Ok(job_hash) +} - let mut digest = job_digest( - &config, - &base_dir, - job_id, - args.modules_digest.as_deref(), - &mut file_hasher, - &mut pattern_cache, - &mut Vec::new(), - )?; - if let Some(entry) = &args.matrix { - digest = with_matrix_entry(&digest, entry)?; - } - let digest = hex::encode(digest); +fn file_hasher(base_dir: &Path, cache: Option<&Path>) -> Result { + let cache = cache + .map(|path| HashCache::load(&resolve_path(base_dir, path))) + .transpose()?; + Ok(FileHasher::new(cache)) +} +/// Prints the digest, and writes it to `$GITHUB_OUTPUT` under `--output`'s name. +fn emit(args: &HashArgs, digest: &str) -> Result<()> { if let Some(name) = &args.output_name { - write_github_output(name, &digest)?; + write_github_output(name, digest)?; } - println!("{digest}"); - - if let Some(cache) = persistent_cache { - cache.save()?; - } - Ok(()) } -/// The digest of `job_id`. `generated_modules` is `--modules-digest`, given for the job being -/// hashed; `chain` holds the jobs whose hashes are being computed, to catch a cycle in `needs`. -fn job_digest( - config: &CigenConfig, - base_dir: &Path, - job_id: &str, - generated_modules: Option<&str>, - file_hasher: &mut FileHasher<'_>, - pattern_cache: &mut BTreeMap>, - chain: &mut Vec, -) -> Result> { - let job = config - .jobs - .get(job_id) - .with_context(|| format!("job `{job_id}` isn't defined"))?; - let workflow_name = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); - - let mut entries: Vec = Vec::new(); - - for entry in &job.inputs { - if let Some(group) = entry.strip_prefix('@') { - entries.push(SourceEntry::Group(group.to_string())); - } else { - entries.push(SourceEntry::Pattern(entry.to_string())); - } - } - - let mut final_hasher = Sha256::new(); - final_hasher.update(env!("CARGO_PKG_VERSION").as_bytes()); - final_hasher.update(job_id.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(workflow_name.as_bytes()); - - let canonical_job = cigen::inputs::canonical_json(job)?; - final_hasher.update([0u8]); - final_hasher.update(canonical_job.as_bytes()); - - // The workflow's settings (environment, provider blocks) can change what the job does. - let workflow_settings = config - .workflows - .get(&workflow_name) - .map(cigen::inputs::canonical_json) - .transpose()? - .unwrap_or_default(); - final_hasher.update(b"\0workflow\0"); - final_hasher.update(workflow_settings.as_bytes()); - - // What the job depends on beyond its declared inputs: commands, services, provider blocks, - // files its steps name and toolchain pins (see `cigen::inputs`). - let derived = cigen::inputs::derive(config, job_id, base_dir)?; - for (label, json) in &derived.config { - final_hasher.update(b"\0derived\0"); - final_hasher.update(label.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(json.as_bytes()); - } - for rel in &derived.files { - let digest = file_hasher.hash_file(&base_dir.join(rel), Path::new(rel))?; - final_hasher.update(b"\0file\0"); - final_hasher.update(rel.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(&digest); - } - - for pattern in &derived.patterns { - let digest = hash_pattern(pattern, base_dir, file_hasher, pattern_cache)?; - final_hasher.update(b"\0module-input\0"); - final_hasher.update(pattern.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(&digest); - } - if let Some(generated) = generated_modules { - if generated != derived.modules_digest { - eprintln!( - "warning: job `{job_id}`'s CI config was generated with modules digest {generated}, \ - but this cigen expands its modules to {}. Regenerate the CI config with the cigen \ - version CI runs. The job's hash covers both, so it won't reuse a pass meanwhile.", - if derived.modules_digest.is_empty() { - "nothing" - } else { - &derived.modules_digest - } - ); - } - final_hasher.update(b"\0modules-digest\0"); - final_hasher.update(generated.as_bytes()); - } - - for entry in entries { - match entry { - SourceEntry::Pattern(pattern) => { - let digest = hash_pattern(&pattern, base_dir, file_hasher, pattern_cache)?; - final_hasher.update(b"pattern\0"); - final_hasher.update(pattern.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(&digest); - } - SourceEntry::Group(name) => { - let patterns = config - .input_group_patterns(&name) - .with_context(|| format!("Job '{job_id}' uses `@{name}`"))?; - let digest = hash_group(&name, &patterns, base_dir, file_hasher, pattern_cache)?; - final_hasher.update(b"group\0"); - final_hasher.update(name.as_bytes()); - final_hasher.update([0u8]); - final_hasher.update(&digest); - } - } - } - - // The jobs it needs, each by its whole hash (see `needs_hash`). - needs_hash::check_chain(chain, job_id)?; - chain.push(job_id.to_string()); - needs_hash::hash_needs(job_id, &job.needs, &mut final_hasher, &mut |need| { - job_digest( - config, - base_dir, - need, - None, - file_hasher, - pattern_cache, - chain, - ) - })?; - chain.pop(); - - Ok(final_hasher.finalize().to_vec()) -} - -fn hash_group( - name: &str, - patterns: &[String], - base_dir: &Path, - file_hasher: &mut FileHasher, - pattern_cache: &mut BTreeMap>, -) -> Result> { - let mut hasher = Sha256::new(); - hasher.update(name.as_bytes()); - hasher.update([0u8]); - - if patterns.is_empty() { - hasher.update(b"empty-group"); - return Ok(hasher.finalize().to_vec()); - } - - let mut sorted: Vec<&String> = patterns.iter().collect(); - sorted.sort(); - - for pattern in sorted { - let digest = hash_pattern(pattern, base_dir, file_hasher, pattern_cache)?; - hasher.update(pattern.as_bytes()); - hasher.update([0u8]); - hasher.update(&digest); - } - - Ok(hasher.finalize().to_vec()) -} - -fn hash_pattern( - pattern: &str, - base_dir: &Path, - file_hasher: &mut FileHasher, - pattern_cache: &mut BTreeMap>, -) -> Result> { - if let Some(existing) = pattern_cache.get(pattern) { - return Ok(existing.clone()); - } - - let files = cigen::pathspec::list_files(base_dir, pattern)?; - - let mut aggregate = Sha256::new(); - - if files.is_empty() { - aggregate.update(b"empty"); - } else { - for rel in files { - let absolute = base_dir.join(&rel); - let digest = file_hasher.hash_file(&absolute, &rel)?; - aggregate.update(rel.to_string_lossy().as_bytes()); - aggregate.update([0u8]); - aggregate.update(&digest); - } - } - - let digest = aggregate.finalize().to_vec(); - pattern_cache.insert(pattern.to_string(), digest.clone()); - Ok(digest) -} - fn canonicalize_path(path: &Path) -> Result { fs::canonicalize(path).with_context(|| format!("Failed to resolve path {}", path.display())) } @@ -385,162 +154,3 @@ fn write_github_output(name: &str, value: &str) -> Result<()> { } Ok(()) } - -#[derive(Debug)] -enum SourceEntry { - Pattern(String), - Group(String), -} - -struct FileHasher<'a> { - cache: BTreeMap>, - persistent: Option<&'a mut HashCache>, -} - -impl<'a> FileHasher<'a> { - fn new(persistent: Option<&'a mut HashCache>) -> Self { - Self { - cache: BTreeMap::new(), - persistent, - } - } - - fn hash_file(&mut self, absolute: &Path, relative: &Path) -> Result> { - if let Some(bytes) = self.cache.get(relative) { - return Ok(bytes.clone()); - } - - let metadata = fs::metadata(absolute) - .with_context(|| format!("Failed to read metadata for {}", absolute.display()))?; - - if let Some(cache) = &mut self.persistent - && let Some(bytes) = cache.lookup(relative, &metadata)? - { - self.cache.insert(relative.to_path_buf(), bytes.clone()); - return Ok(bytes); - } - - let file = File::open(absolute) - .with_context(|| format!("Failed to open file for hashing: {}", absolute.display()))?; - let mut reader = BufReader::new(file); - let mut hasher = Sha256::new(); - let mut buffer = [0u8; 1024 * 64]; - - loop { - let read = reader - .read(&mut buffer) - .with_context(|| format!("Failed to read {}", absolute.display()))?; - if read == 0 { - break; - } - hasher.update(&buffer[..read]); - } - - let digest = hasher.finalize().to_vec(); - if let Some(cache) = &mut self.persistent { - cache.store(relative, &metadata, &digest)?; - } - self.cache.insert(relative.to_path_buf(), digest.clone()); - Ok(digest) - } -} - -#[derive(Default, Serialize, Deserialize)] -struct HashCache { - #[serde(skip)] - path: Option, - entries: BTreeMap, -} - -#[derive(Serialize, Deserialize)] -struct CacheEntry { - modified: u64, - size: u64, - hash: String, -} - -impl HashCache { - fn load(path: &Path) -> Result { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).with_context(|| { - format!("Failed to create cache directory {}", parent.display()) - })?; - } - - let entries = if path.exists() { - let file = File::open(path) - .with_context(|| format!("Failed to open cache file {}", path.display()))?; - serde_json::from_reader(BufReader::new(file)) - .with_context(|| format!("Failed to parse cache file {}", path.display()))? - } else { - BTreeMap::new() - }; - - Ok(Self { - path: Some(path.to_path_buf()), - entries, - }) - } - - fn lookup(&self, relative: &Path, metadata: &fs::Metadata) -> Result>> { - let signature = file_signature(metadata)?; - let key = relative.to_string_lossy(); - if let Some(entry) = self.entries.get(key.as_ref()) - && entry.modified == signature.modified - && entry.size == signature.size - { - return Ok(Some(hex::decode(&entry.hash)?)); - } - Ok(None) - } - - fn store(&mut self, relative: &Path, metadata: &fs::Metadata, hash: &[u8]) -> Result<()> { - let signature = file_signature(metadata)?; - let key = relative.to_string_lossy().to_string(); - self.entries.insert( - key, - CacheEntry { - modified: signature.modified, - size: signature.size, - hash: hex::encode(hash), - }, - ); - Ok(()) - } - - fn save(self) -> Result<()> { - let Some(path) = self.path else { - return Ok(()); - }; - - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).with_context(|| { - format!("Failed to create cache directory {}", parent.display()) - })?; - } - - let mut file = File::create(&path) - .with_context(|| format!("Failed to create cache file {}", path.display()))?; - serde_json::to_writer_pretty(&mut file, &self.entries) - .with_context(|| format!("Failed to write cache file {}", path.display()))?; - Ok(()) - } -} - -struct FileSignature { - modified: u64, - size: u64, -} - -fn file_signature(metadata: &fs::Metadata) -> Result { - let modified = metadata - .modified() - .ok() - .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) - .map(|duration| duration.as_secs()) - .unwrap_or(0); - Ok(FileSignature { - modified, - size: metadata.len(), - }) -} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 4f64c32..388fea2 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,3 +1,4 @@ +mod explain; mod generate; mod hash; mod matrix_entry; @@ -5,6 +6,7 @@ mod needs_hash; pub mod report; mod validate; +pub use explain::{ExplainArgs, explain_command}; pub use generate::generate_command; pub use hash::{HashArgs, hash_command}; pub use validate::{ValidateArgs, validate_command}; diff --git a/src/commands/report.rs b/src/commands/report.rs index 5920b03..6a5d813 100644 --- a/src/commands/report.rs +++ b/src/commands/report.rs @@ -29,9 +29,10 @@ pub fn print_error(error: &anyhow::Error) { for config_error in &errors { eprintln!("error: {config_error}"); } - let count = errors.len(); - let noun = if count == 1 { "problem" } else { "problems" }; - eprintln!( - "\nThe config has {count} {noun}. `cigen validate --format json` lists them as data." - ); + if errors.len() > 1 { + eprintln!( + "\nThe config has {} problems. `cigen validate --format json` lists them as data.", + errors.len() + ); + } } diff --git a/src/hashing/files.rs b/src/hashing/files.rs new file mode 100644 index 0000000..9ad1c3d --- /dev/null +++ b/src/hashing/files.rs @@ -0,0 +1,159 @@ +//! Hashing files: the per-file digest (with an in-memory and an optional on-disk cache), and +//! listing the files a pattern matches. + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::io::{BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +/// Digests files by path relative to the project, each file read at most once. +pub struct FileHasher { + cache: BTreeMap>, + persistent: Option, +} + +impl FileHasher { + pub fn new(persistent: Option) -> Self { + Self { + cache: BTreeMap::new(), + persistent, + } + } + + /// Writes the on-disk cache, if there is one. + pub fn save(self) -> Result<()> { + match self.persistent { + Some(cache) => cache.save(), + None => Ok(()), + } + } + + pub fn hash_file(&mut self, absolute: &Path, relative: &Path) -> Result> { + if let Some(bytes) = self.cache.get(relative) { + return Ok(bytes.clone()); + } + + let metadata = fs::metadata(absolute) + .with_context(|| format!("Failed to read metadata for {}", absolute.display()))?; + + if let Some(cache) = &self.persistent + && let Some(bytes) = cache.lookup(relative, &metadata)? + { + self.cache.insert(relative.to_path_buf(), bytes.clone()); + return Ok(bytes); + } + + let file = File::open(absolute) + .with_context(|| format!("Failed to open file for hashing: {}", absolute.display()))?; + let mut reader = BufReader::new(file); + let mut hasher = Sha256::new(); + let mut buffer = [0u8; 1024 * 64]; + + loop { + let read = reader + .read(&mut buffer) + .with_context(|| format!("Failed to read {}", absolute.display()))?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + + let digest = hasher.finalize().to_vec(); + if let Some(cache) = &mut self.persistent { + cache.store(relative, &metadata, &digest); + } + self.cache.insert(relative.to_path_buf(), digest.clone()); + Ok(digest) + } +} + +/// File digests kept between runs, keyed by path and checked against size and mtime. +#[derive(Default)] +pub struct HashCache { + path: PathBuf, + entries: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +struct CacheEntry { + modified: u64, + size: u64, + hash: String, +} + +impl HashCache { + pub fn load(path: &Path) -> Result { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).with_context(|| { + format!("Failed to create cache directory {}", parent.display()) + })?; + } + + let entries = if path.exists() { + let file = File::open(path) + .with_context(|| format!("Failed to open cache file {}", path.display()))?; + serde_json::from_reader(BufReader::new(file)) + .with_context(|| format!("Failed to parse cache file {}", path.display()))? + } else { + BTreeMap::new() + }; + + Ok(Self { + path: path.to_path_buf(), + entries, + }) + } + + fn lookup(&self, relative: &Path, metadata: &fs::Metadata) -> Result>> { + let (modified, size) = signature(metadata); + let key = relative.to_string_lossy(); + if let Some(entry) = self.entries.get(key.as_ref()) + && entry.modified == modified + && entry.size == size + { + return Ok(Some(hex::decode(&entry.hash)?)); + } + Ok(None) + } + + fn store(&mut self, relative: &Path, metadata: &fs::Metadata, hash: &[u8]) { + let (modified, size) = signature(metadata); + self.entries.insert( + relative.to_string_lossy().to_string(), + CacheEntry { + modified, + size, + hash: hex::encode(hash), + }, + ); + } + + fn save(self) -> Result<()> { + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).with_context(|| { + format!("Failed to create cache directory {}", parent.display()) + })?; + } + let mut file = File::create(&self.path) + .with_context(|| format!("Failed to create cache file {}", self.path.display()))?; + serde_json::to_writer_pretty(&mut file, &self.entries) + .with_context(|| format!("Failed to write cache file {}", self.path.display()))?; + Ok(()) + } +} + +/// `(modified seconds, size)`, what decides whether a cached digest still holds. +fn signature(metadata: &fs::Metadata) -> (u64, u64) { + let modified = metadata + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .map(|duration| duration.as_secs()) + .unwrap_or(0); + (modified, metadata.len()) +} diff --git a/src/hashing/job.rs b/src/hashing/job.rs new file mode 100644 index 0000000..513e772 --- /dev/null +++ b/src/hashing/job.rs @@ -0,0 +1,270 @@ +//! A job's hash, and what went into it. `cigen hash --job` prints the hash; `cigen explain` +//! prints the rest. Both come from `hash_job`, so the explanation always describes the hash. + +use super::files::FileHasher; +use crate::config::{ConfigError, suggest}; +use crate::inputs::{self, LOCKFILES, TOOLCHAIN_PINS}; +use crate::pathspec::list_files; +use crate::schema::CigenConfig; +use anyhow::{Context, Result}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::Path; + +/// A job's hash and everything it covers. +#[derive(Debug, Serialize)] +pub struct JobHash { + pub job: String, + pub workflow: String, + /// The job's `inputs`, in order, with `@group`s expanded and the files each pattern matched + pub inputs: Vec, + /// What cigen adds on top of `inputs` (see `crate::inputs`) + pub derived: DerivedInputs, + /// Hashed besides the inputs: they change what the job does + pub also_hashed: Vec, + pub hash: String, +} + +/// One entry of a job's `inputs`. +#[derive(Debug, Serialize)] +pub struct DeclaredInput { + /// As written: a pattern, or `@group` + pub entry: String, + /// The patterns it stands for, in the order they're hashed + pub patterns: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PatternFiles { + pub pattern: String, + /// Files relative to the project root, sorted + pub files: Vec, +} + +#[derive(Debug, Serialize)] +pub struct DerivedInputs { + /// Parts of the config, by label: `command:`, `service:`, `provider:`, + /// `package.json:packageManager` + pub config: Vec, + pub files: Vec, + /// Patterns of the files the job's modules contribute, with the files they match + pub modules: Vec, +} + +#[derive(Debug, Serialize)] +pub struct DerivedFile { + pub path: String, + /// Why it's an input: `toolchain pin`, `lockfile`, or `named in a step` + pub reason: &'static str, +} + +/// Hashes `job_id`. `base_dir` is the project root, where patterns and step paths are looked up. +/// `modules_digest` is the digest of the job's module expansions that its generated CI config +/// passes (`--modules-digest`); it goes into the hash, with a warning when this cigen expands +/// the job's modules differently. +pub fn hash_job( + config: &CigenConfig, + job_id: &str, + base_dir: &Path, + files: &mut FileHasher, + modules_digest: Option<&str>, +) -> Result { + let job = config + .jobs + .get(job_id) + .ok_or_else(|| unknown_job(config, job_id))?; + let workflow = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); + + let mut hasher = Sha256::new(); + hasher.update(env!("CARGO_PKG_VERSION").as_bytes()); + hasher.update(job_id.as_bytes()); + hasher.update([0u8]); + hasher.update(workflow.as_bytes()); + + hasher.update([0u8]); + hasher.update(inputs::canonical_json(job)?.as_bytes()); + + // The workflow's settings (environment, provider blocks) can change what the job does. + let workflow_settings = config + .workflows + .get(&workflow) + .map(inputs::canonical_json) + .transpose()? + .unwrap_or_default(); + hasher.update(b"\0workflow\0"); + hasher.update(workflow_settings.as_bytes()); + + let derived = inputs::derive(config, job_id, base_dir)?; + for (label, json) in &derived.config { + hasher.update(b"\0derived\0"); + hasher.update(label.as_bytes()); + hasher.update([0u8]); + hasher.update(json.as_bytes()); + } + for rel in &derived.files { + let digest = files.hash_file(&base_dir.join(rel), Path::new(rel))?; + hasher.update(b"\0file\0"); + hasher.update(rel.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + } + + let mut patterns = PatternHasher::default(); + let mut module_inputs = Vec::new(); + for pattern in &derived.patterns { + let (digest, found) = patterns.hash(pattern, base_dir, files)?; + hasher.update(b"\0module-input\0"); + hasher.update(pattern.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + module_inputs.push(found); + } + let mut also_hashed = vec![ + format!("cigen {}", env!("CARGO_PKG_VERSION")), + format!("the job's definition (workflows.{workflow}.jobs.{job_id})"), + format!("the settings of workflow `{workflow}`"), + ]; + if let Some(generated) = modules_digest { + if generated != derived.modules_digest { + warn_stale_modules(job_id, generated, &derived.modules_digest); + } + hasher.update(b"\0modules-digest\0"); + hasher.update(generated.as_bytes()); + also_hashed.push(format!("the generated config's modules digest {generated}")); + } + + let mut declared = Vec::new(); + for entry in &job.inputs { + let (tag, name, digest, matched) = match entry.strip_prefix('@') { + Some(group) => { + let mut list = config + .input_group_patterns(group) + .with_context(|| format!("Job '{job_id}' uses `@{group}`"))?; + list.sort(); + let mut group_hasher = Sha256::new(); + group_hasher.update(group.as_bytes()); + group_hasher.update([0u8]); + if list.is_empty() { + group_hasher.update(b"empty-group"); + } + let mut matched = Vec::new(); + for pattern in &list { + let (digest, found) = patterns.hash(pattern, base_dir, files)?; + group_hasher.update(pattern.as_bytes()); + group_hasher.update([0u8]); + group_hasher.update(&digest); + matched.push(found); + } + ("group", group, group_hasher.finalize().to_vec(), matched) + } + None => { + let (digest, found) = patterns.hash(entry, base_dir, files)?; + ("pattern", entry.as_str(), digest, vec![found]) + } + }; + hasher.update(tag.as_bytes()); + hasher.update([0u8]); + hasher.update(name.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + declared.push(DeclaredInput { + entry: entry.clone(), + patterns: matched, + }); + } + + Ok(JobHash { + job: job_id.to_string(), + workflow: workflow.clone(), + inputs: declared, + derived: DerivedInputs { + config: derived.config.into_iter().map(|(label, _)| label).collect(), + files: derived + .files + .into_iter() + .map(|path| DerivedFile { + reason: reason(&path), + path, + }) + .collect(), + modules: module_inputs, + }, + also_hashed, + hash: hex::encode(hasher.finalize()), + }) +} + +fn warn_stale_modules(job_id: &str, generated: &str, current: &str) { + let current = if current.is_empty() { + "nothing" + } else { + current + }; + eprintln!( + "warning: job `{job_id}`'s CI config was generated with modules digest {generated}, \ + but this cigen expands its modules to {current}. Regenerate the CI config with the cigen \ + version CI runs. The job's hash covers both, so it won't reuse a pass meanwhile." + ); +} + +fn reason(path: &str) -> &'static str { + if TOOLCHAIN_PINS.contains(&path) { + "toolchain pin" + } else if LOCKFILES.contains(&path) { + "lockfile" + } else { + "named in a step" + } +} + +fn unknown_job(config: &CigenConfig, job_id: &str) -> ConfigError { + let ids: Vec<&str> = config.jobs.keys().map(String::as_str).collect(); + let error = ConfigError::new(format!("there's no job named `{job_id}`")); + match suggest::closest(job_id, &ids) { + Some(close) => error.suggest(format!("did you mean `{close}`?")), + None => error.suggest(format!("Jobs: {}.", ids.join(", "))), + } +} + +/// Pattern digests, each pattern listed and hashed once per run. +#[derive(Default)] +struct PatternHasher { + done: BTreeMap, PatternFiles)>, +} + +impl PatternHasher { + fn hash( + &mut self, + pattern: &str, + base_dir: &Path, + files: &mut FileHasher, + ) -> Result<(Vec, PatternFiles)> { + if let Some((digest, found)) = self.done.get(pattern) { + return Ok((digest.clone(), found.clone())); + } + let matched = list_files(base_dir, pattern)?; + let mut aggregate = Sha256::new(); + if matched.is_empty() { + aggregate.update(b"empty"); + } + for rel in &matched { + let digest = files.hash_file(&base_dir.join(rel), rel)?; + aggregate.update(rel.to_string_lossy().as_bytes()); + aggregate.update([0u8]); + aggregate.update(&digest); + } + let result = ( + aggregate.finalize().to_vec(), + PatternFiles { + pattern: pattern.to_string(), + files: matched + .iter() + .map(|rel| rel.to_string_lossy().replace('\\', "/")) + .collect(), + }, + ); + self.done.insert(pattern.to_string(), result.clone()); + Ok(result) + } +} diff --git a/src/hashing/mod.rs b/src/hashing/mod.rs new file mode 100644 index 0000000..8bb8ba4 --- /dev/null +++ b/src/hashing/mod.rs @@ -0,0 +1,8 @@ +//! Hashing what a job depends on: file digests (`files`) and a job's hash with the inputs +//! that went into it (`job`). + +mod files; +mod job; + +pub use files::{FileHasher, HashCache}; +pub use job::{DeclaredInput, DerivedFile, DerivedInputs, JobHash, PatternFiles, hash_job}; diff --git a/src/lib.rs b/src/lib.rs index 94fdc18..def9f08 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod config; pub mod git; +pub mod hashing; pub mod inputs; pub mod modules; pub mod orchestrator; diff --git a/src/main.rs b/src/main.rs index 22e6d4a..2c95cad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,11 @@ enum Commands { #[command(flatten)] args: commands::HashArgs, }, + /// Show what a job's hash covers: its inputs, the files they match, and the hash + Explain { + #[command(flatten)] + args: commands::ExplainArgs, + }, /// Check the config and list every problem in it Validate { #[command(flatten)] @@ -66,6 +71,7 @@ fn run(cli: Cli) -> Result { Some(Commands::Hash { args }) => { commands::hash_command(args)?; } + Some(Commands::Explain { args }) => commands::explain_command(args)?, Some(Commands::Validate { args }) => return commands::validate_command(args), None => { // Default to generate command diff --git a/tests/explain.rs b/tests/explain.rs new file mode 100644 index 0000000..11e9fe4 --- /dev/null +++ b/tests/explain.rs @@ -0,0 +1,175 @@ +//! `cigen explain `: the inputs behind a job's hash, and the same hash `cigen hash --job` +//! prints. + +mod support; + +use serde_json::{Value, json}; +use support::fixture_repo::FixtureRepo; + +/// A job with a nested input group, a plain pattern, a script named in a step, a command, a +/// lockfile and a toolchain pin. +fn fixture() -> FixtureRepo { + let repo = FixtureRepo::new(); + repo.write( + ".cigen/config.yml", + "provider: github\ninput_groups:\n rust: ['src/**/*.rs', '@manifests']\n manifests: ['Cargo.toml']\n", + ) + .write( + ".cigen/commands/setup.yml", + "steps:\n - run: echo setting up\n", + ) + .write( + ".cigen/workflows/ci/jobs/test.yml", + "image: rust:latest\ninputs: ['@rust', 'tests/**']\nsteps:\n - setup\n - run: sh scripts/check.sh\n", + ) + .write("src/lib.rs", "pub fn one() {}\n") + .write("src/main.rs", "fn main() {}\n") + .write("Cargo.toml", "[package]\nname = \"demo\"\n") + .write("Cargo.lock", "# lock\n") + .write("rust-toolchain.toml", "[toolchain]\nchannel = \"stable\"\n") + .write("scripts/check.sh", "echo ok\n"); + repo.commit("initial"); + repo +} + +fn run(repo: &FixtureRepo, args: &[&str]) -> String { + let output = support::cigen() + .current_dir(repo.path()) + .args(args) + .output() + .unwrap(); + assert!(output.status.success(), "{args:?}: {output:?}"); + String::from_utf8(output.stdout).unwrap() +} + +fn explain_json(repo: &FixtureRepo) -> Value { + serde_json::from_str(&run(repo, &["explain", "test", "--format", "json"])).unwrap() +} + +#[test] +fn explain_lists_declared_and_derived_inputs_with_their_files() { + let repo = fixture(); + let explained = explain_json(&repo); + assert_eq!(explained["job"], "test"); + assert_eq!(explained["workflow"], "ci"); + assert_eq!( + explained["inputs"], + json!([ + { + "entry": "@rust", + "patterns": [ + { "pattern": "Cargo.toml", "files": ["Cargo.toml"] }, + { "pattern": "src/**/*.rs", "files": ["src/lib.rs", "src/main.rs"] }, + ], + }, + { "entry": "tests/**", "patterns": [{ "pattern": "tests/**", "files": [] }] }, + ]) + ); + assert_eq!(explained["derived"]["config"], json!(["command:setup"])); + assert_eq!( + explained["derived"]["files"], + json!([ + { "path": "Cargo.lock", "reason": "lockfile" }, + { "path": "rust-toolchain.toml", "reason": "toolchain pin" }, + { "path": "scripts/check.sh", "reason": "named in a step" }, + ]) + ); +} + +#[test] +fn explain_prints_exactly_the_hash_that_hash_job_prints() { + let repo = fixture(); + let hash = || run(&repo, &["hash", "--job", "test"]).trim().to_string(); + let before = hash(); + assert_eq!(explain_json(&repo)["hash"], before.as_str()); + let text = run(&repo, &["explain", "test"]); + assert!(text.ends_with(&format!("\nHash: {before}\n")), "{text}"); + + // Change a derived input: both move together. + repo.write("scripts/check.sh", "echo changed\n"); + let after = hash(); + assert_ne!(before, after); + assert_eq!(explain_json(&repo)["hash"], after.as_str()); +} + +#[test] +fn the_text_form_reads_top_to_bottom() { + let repo = fixture(); + let text = run(&repo, &["explain", "test"]); + let expected_start = "\ +Job `test` in workflow `ci` + +Declared inputs: + @rust + Cargo.toml (1 file) + Cargo.toml + src/**/*.rs (2 files) + src/lib.rs + src/main.rs + tests/** (no files) + +Derived inputs: + command:setup + Cargo.lock (lockfile) + rust-toolchain.toml (toolchain pin) + scripts/check.sh (named in a step) + +Also hashed: + cigen "; + assert!(text.starts_with(expected_start), "{text}"); +} + +#[test] +fn an_unknown_job_suggests_the_closest() { + let repo = fixture(); + let output = support::cigen() + .current_dir(repo.path()) + .args(["explain", "tset"]) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!( + stderr, + "error: there's no job named `tset`\n help: did you mean `test`?\n" + ); +} + +#[test] +fn module_inputs_are_listed_and_move_the_hash() { + let repo = FixtureRepo::new(); + repo.write( + "cigen.yml", + "provider: github\nworkflows:\n ci:\n jobs:\n test:\n image: rust:latest\n modules: [rust]\n inputs: ['src/**']\n steps:\n - run: cargo test\n", + ) + .write("src/lib.rs", "pub fn one() {}\n") + .write("Cargo.toml", "[package]\nname = \"demo\"\n") + .write("crates/a/Cargo.toml", "[package]\nname = \"a\"\n"); + repo.commit("initial"); + + let explained = explain_json(&repo); + let modules = explained["derived"]["modules"].as_array().unwrap(); + let nested = modules + .iter() + .find(|input| input["pattern"] == "**/Cargo.toml") + .unwrap_or_else(|| panic!("no **/Cargo.toml in {modules:?}")); + assert_eq!( + nested["files"], + json!(["Cargo.toml", "crates/a/Cargo.toml"]) + ); + let text = run(&repo, &["explain", "test"]); + assert!( + text.contains( + " **/Cargo.toml (from a module, 2 files)\n Cargo.toml\n crates/a/Cargo.toml\n" + ), + "{text}" + ); + + // A file only a module contributes moves explain's hash and hash --job's together. + let before = explained["hash"].as_str().unwrap().to_string(); + repo.write("crates/a/Cargo.toml", "[package]\nname = \"a2\"\n"); + repo.commit("change a module input"); + let after = run(&repo, &["hash", "--job", "test"]).trim().to_string(); + assert_ne!(before, after); + assert_eq!(explain_json(&repo)["hash"], after.as_str()); +} From 0aa7145a62377806a9062bc6236910abbc391b98 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 14:33:48 +1300 Subject: [PATCH 2/7] Docs: cigen explain The CLI page documents cigen explain: its options, what the text output lists for an example config, and the JSON fields. The overview, roadmap and homepage list it as built. --- docs/src/content/docs/cli.md | 79 +++++++++++++++++++++++++++++++- docs/src/content/docs/index.md | 1 + docs/src/content/docs/roadmap.md | 6 +-- docs/src/pages/index.astro | 3 +- 4 files changed, 84 insertions(+), 5 deletions(-) diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 14623a2..59d187c 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -1,6 +1,6 @@ --- title: CLI -description: cigen validate, cigen generate and cigen hash, with every option. +description: cigen validate, cigen generate, cigen hash and cigen explain, with every option. --- ```text @@ -101,6 +101,83 @@ cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock Patterns that match no files hash to the word `empty`. +## `cigen explain` + +Shows what a job's hash covers: each declared input with the files it matches, the inputs cigen derived from the job, +and the hash. Use it to see why a job ran or skipped, or to check that a new job's `inputs` match the files you meant. + +```sh +cigen explain test +cigen explain test --format json # the same, as data +``` + +| Option | What it does | +| ----------------------- | --------------------------------------------------------------------------------- | +| `` | The job's id. | +| `-c`, `--config ` | The config. Default: the one in `--base-dir`. | +| `--base-dir ` | The project root, where input patterns and step paths are looked up. Default `.`. | +| `--format ` | `text` (the default) or `json`. | + +For this config: + +```yaml +# cigen.yml +provider: github +input_groups: + rust: + - 'src/**/*.rs' + - Cargo.toml + - Cargo.lock +workflows: + ci: + jobs: + test: + image: rust:1.85 + inputs: + - '@rust' + - scripts/test.sh + steps: + - run: ./scripts/test.sh +``` + +```text +$ cigen explain test +Job `test` in workflow `ci` + +Declared inputs: + @rust + Cargo.lock (1 file) + Cargo.lock + Cargo.toml (1 file) + Cargo.toml + src/**/*.rs (1 file) + src/main.rs + scripts/test.sh (1 file) + scripts/test.sh + +Derived inputs: + Cargo.lock (lockfile) + rust-toolchain (toolchain pin) + scripts/test.sh (named in a step) + +Also hashed: + cigen 0.1.0 + the job's definition (workflows.ci.jobs.test) + the settings of workflow `ci` + +Hash: dec443e28689907db942cae54a59bf3fc5fa66b844566d78ca428ae749c7af77 +``` + +A pattern that matches no files shows `(no files)`, which usually means a typo. Derived inputs are the files cigen adds +on its own (see [derived inputs](/docs/inputs/#derived-inputs)); commands and services the job uses are listed by their +config path, and the patterns a job's modules contribute are marked `from a module`. The hash is the one +`cigen hash --job test` prints. For a job without modules it's also the one the generated workflow looks up; for a job +with modules, the workflow also passes `--modules-digest`, which explain leaves out. + +With `--format json`, it prints one object with `job`, `workflow`, `inputs` (each `entry` with its `patterns` and their +`files`), `derived` (`config` paths, `files` with a `reason`, and `modules`, each pattern with its `files`), +`also_hashed` and `hash`. An unknown job is an error that suggests the closest id. + ## Environment | Variable | What it does | diff --git a/docs/src/content/docs/index.md b/docs/src/content/docs/index.md index 0389429..b2e41fa 100644 --- a/docs/src/content/docs/index.md +++ b/docs/src/content/docs/index.md @@ -26,6 +26,7 @@ what to write instead. - `cigen validate`, which lists every problem in a config, as text or JSON. - `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. - 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/roadmap.md b/docs/src/content/docs/roadmap.md index eea1ca5..ee4a158 100644 --- a/docs/src/content/docs/roadmap.md +++ b/docs/src/content/docs/roadmap.md @@ -15,9 +15,9 @@ right. This page lists what's planned. Nothing on it exists yet; what exists is already passed never start a runner, and a final job counts "skipped" as passed for required checks. 3. **Pluggable pass-record stores.** The GitHub Actions cache by default, self-hosted stores such as Redis and S3, and an open protocol. If a store can't be reached, everything runs. -4. **Agent tools.** `cigen plan`, `cigen explain ` (why a job will run or skip) and `cigen expand `. (The - [JSON schemas](/docs/configuration/#json-schemas) and [`cigen validate`](/docs/cli/#cigen-validate), with errors as - JSON, are already built.) +4. **Agent tools.** `cigen plan` (which jobs will run or skip, and why) and `cigen expand `. (The + [JSON schemas](/docs/configuration/#json-schemas), [`cigen validate`](/docs/cli/#cigen-validate) with errors as JSON, + and [`cigen explain`](/docs/cli/#cigen-explain), which shows what a job's hash covers, are already built.) 5. **Prebuilt binaries** and Docker images with cigen installed. Generated workflows already install the release that generated them; v0.2.0 will be the first release with the archives they download. 6. **Hosted pass records on VisualCI.** A free account, signed in with GitHub, with records visible across branches, diff --git a/docs/src/pages/index.astro b/docs/src/pages/index.astro index 2af626c..3c2b7ed 100644 --- a/docs/src/pages/index.astro +++ b/docs/src/pages/index.astro @@ -193,6 +193,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;
  • cigen validate, with errors as JSON for agents
  • GitHub Actions and CircleCI generation
  • cigen hash with derived inputs
  • +
  • cigen explain: what a job's hash covers
  • Skipping on GitHub Actions, with markers in its cache
  • Generated workflows install a checksum-checked cigen release
  • Byte-for-byte deterministic output
  • @@ -205,7 +206,7 @@ const skipped = run.jobs.filter((job) => job.status === 'skipped').length;
  • The v0.2.0 release, the first those workflows can install
  • A planner job, so skipped jobs never start a runner
  • More modules: Node, Playwright, services and caches
  • -
  • cigen plan, explain and expand for agents
  • +
  • cigen plan and expand for agents
  • Free hosted pass records on VisualCI, shared across branches
  • Skipping on CircleCI
  • From 4140f90ab726dc366acf68354d76ece247741d5f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:10:32 +1300 Subject: [PATCH 3/7] Hash the jobs a job needs in src/hashing, and list them in explain Ports #30's needs hashing into hashing::hash_job: a job's hash covers the hashes of the jobs it needs, transitively, and without --modules-digest it uses the modules digest this cigen computes. cigen explain lists the needed jobs with their hashes. --- docs/src/content/docs/cli.md | 11 +- internal_docs/STATUS.md | 12 +- src/commands/explain.rs | 7 + src/commands/mod.rs | 2 - src/hashing/hasher.rs | 261 ++++++++++++++++++ src/hashing/job.rs | 216 +++------------ src/hashing/mod.rs | 8 +- .../needs_hash.rs => hashing/needs.rs} | 0 tests/explain.rs | 34 +++ 9 files changed, 354 insertions(+), 197 deletions(-) create mode 100644 src/hashing/hasher.rs rename src/{commands/needs_hash.rs => hashing/needs.rs} (100%) diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 59d187c..99c3267 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -170,13 +170,14 @@ Hash: dec443e28689907db942cae54a59bf3fc5fa66b844566d78ca428ae749c7af77 A pattern that matches no files shows `(no files)`, which usually means a typo. Derived inputs are the files cigen adds on its own (see [derived inputs](/docs/inputs/#derived-inputs)); commands and services the job uses are listed by their -config path, and the patterns a job's modules contribute are marked `from a module`. The hash is the one -`cigen hash --job test` prints. For a job without modules it's also the one the generated workflow looks up; for a job -with modules, the workflow also passes `--modules-digest`, which explain leaves out. +config path, and the patterns a job's modules contribute are marked `from a module`. A job that `needs` others lists +them under `Needs` with their own hashes, which are part of its hash, so a change upstream makes it run too. The hash is +the one `cigen hash --job test` prints, and the one the generated workflow looks up while it's up to date with the +config. With `--format json`, it prints one object with `job`, `workflow`, `inputs` (each `entry` with its `patterns` and their -`files`), `derived` (`config` paths, `files` with a `reason`, and `modules`, each pattern with its `files`), -`also_hashed` and `hash`. An unknown job is an error that suggests the closest id. +`files`), `derived` (`config` paths, `files` with a `reason`, and `modules`, each pattern with its `files`), `needs` +(each `job` with its `hash`), `also_hashed` and `hash`. An unknown job is an error that suggests the closest id. ## Environment diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index ab6cd5b..00eb7a1 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -14,9 +14,8 @@ What the code does today, checked against the code in December 2026. Where cigen `cigen explain [--config ] [--base-dir ] [--format text|json]` shows what the job's hash covers: its `inputs` with `@groups` expanded and the files each pattern matched, the derived inputs (config parts by label, files with their reason: toolchain pin, lockfile or named in a step, and the patterns the job's modules contribute - with their files), what else is hashed, and the hash. Job hashing lives in `src/hashing/`, and `hash --job` and - `explain` both call `hashing::hash_job`, so the two always agree. `explain` hashes as `hash --job` does without - `--modules-digest`, so for a job with modules its hash isn't the one the generated workflow computes. + with their files), the jobs it `needs` with their hashes, what else is hashed, and the hash. Job hashing lives in + `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the two always agree. - **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 @@ -49,7 +48,7 @@ What the code does today, checked against the code in December 2026. Where cigen top level allows `$schema`. `tests/json_schema.rs` fails when they're stale (refresh with `CIGEN_UPDATE_GOLDEN=1 cargo test --test json_schema`) and checks every config in the repository against them. -- **Derived inputs** (`src/inputs.rs`, `src/commands/needs_hash.rs`): `cigen hash --job` adds, on top of a job's +- **Derived inputs** (`src/inputs.rs`, `src/hashing/needs.rs`): `cigen hash --job` adds, on top of a job's `inputs`, the hashes of the jobs it `needs` (transitively, so a changed build reruns the tests that need it), the commands it uses (through other commands too), the services it names, the top-level provider blocks, every project file its steps name (`sh scripts/check.sh`, `require('./x.js')`, every file of a local `uses: ./action`), and the root @@ -137,8 +136,9 @@ What the code does today, checked against the code in December 2026. Where cigen - `tests/git_ownership.rs`: `cigen hash` in a checkout git treats as owned by another user (`GIT_TEST_ASSUME_DIFFERENT_OWNER`), at the repository root and in a subdirectory, matches the hash computed as its owner. -- `tests/explain.rs`: `cigen explain` lists declared and derived inputs (module inputs included) with their files, in - JSON and text, and its hash equals `cigen hash --job`'s before and after an input changes. +- `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. - `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/explain.rs b/src/commands/explain.rs index 0eea5cc..24c342d 100644 --- a/src/commands/explain.rs +++ b/src/commands/explain.rs @@ -75,6 +75,13 @@ fn render(job: &JobHash) -> String { push_pattern(&mut out, " ", pattern, "from a module, "); } + if !job.needs.is_empty() { + out.push_str("\nNeeds (each job's own hash):\n"); + for need in &job.needs { + out.push_str(&format!(" {} {}\n", need.job, need.hash)); + } + } + out.push_str("\nAlso hashed:\n"); for item in &job.also_hashed { out.push_str(&format!(" {item}\n")); diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 388fea2..a9a5365 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,8 +1,6 @@ mod explain; mod generate; mod hash; -mod matrix_entry; -mod needs_hash; pub mod report; mod validate; diff --git a/src/hashing/hasher.rs b/src/hashing/hasher.rs new file mode 100644 index 0000000..8a0edf1 --- /dev/null +++ b/src/hashing/hasher.rs @@ -0,0 +1,261 @@ +//! Computes job hashes. A job's hash covers its definition, its workflow's settings, what cigen +//! derives for it (`crate::inputs`), its declared inputs, and the hashes of the jobs it `needs`, +//! transitively: a job usually uses what the jobs before it made (an artifact, an output), so a +//! change to one of them must make it run too. + +use super::files::FileHasher; +use super::job::{DeclaredInput, DerivedFile, DerivedInputs, JobHash, NeededJob, PatternFiles}; +use super::needs; +use crate::inputs; +use crate::pathspec::list_files; +use crate::schema::CigenConfig; +use anyhow::{Context, Result}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::Path; + +pub(super) struct JobHasher<'a, 'f> { + pub config: &'a CigenConfig, + pub base_dir: &'a Path, + pub files: &'f mut FileHasher, + patterns: PatternHasher, + /// Digests of the jobs hashed so far, so a job two others need is hashed once. + done: BTreeMap>, + /// The jobs whose hashes are being computed, to catch a cycle in `needs`. + chain: Vec, +} + +impl<'a, 'f> JobHasher<'a, 'f> { + pub fn new(config: &'a CigenConfig, base_dir: &'a Path, files: &'f mut FileHasher) -> Self { + Self { + config, + base_dir, + files, + patterns: PatternHasher::default(), + done: BTreeMap::new(), + chain: Vec::new(), + } + } + + /// `job_id`'s hash and what went into it. `generated_modules` is the modules digest its CI + /// config was generated with (`--modules-digest`); the jobs it needs are hashed with the + /// digest this cigen computes. + pub fn explain(&mut self, job_id: &str, generated_modules: Option<&str>) -> Result { + self.enter(job_id)?; + let (_, explained) = self.compute(job_id, generated_modules)?; + self.chain.pop(); + Ok(explained) + } + + /// The raw digest of a job another job needs. + fn digest(&mut self, job_id: &str) -> Result> { + if let Some(digest) = self.done.get(job_id) { + return Ok(digest.clone()); + } + self.enter(job_id)?; + let (digest, _) = self.compute(job_id, None)?; + self.chain.pop(); + self.done.insert(job_id.to_string(), digest.clone()); + Ok(digest) + } + + fn enter(&mut self, job_id: &str) -> Result<()> { + needs::check_chain(&self.chain, job_id)?; + self.chain.push(job_id.to_string()); + Ok(()) + } + + fn compute(&mut self, job_id: &str, generated: Option<&str>) -> Result<(Vec, JobHash)> { + let config = self.config; + let base_dir = self.base_dir; + let job = config + .jobs + .get(job_id) + .with_context(|| format!("job `{job_id}` isn't defined"))?; + let workflow = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); + + let mut hasher = Sha256::new(); + hasher.update(env!("CARGO_PKG_VERSION").as_bytes()); + hasher.update(job_id.as_bytes()); + hasher.update([0u8]); + hasher.update(workflow.as_bytes()); + hasher.update([0u8]); + hasher.update(inputs::canonical_json(job)?.as_bytes()); + + // The workflow's settings (environment, provider blocks) can change what the job does. + let workflow_settings = config + .workflows + .get(&workflow) + .map(inputs::canonical_json) + .transpose()? + .unwrap_or_default(); + hasher.update(b"\0workflow\0"); + hasher.update(workflow_settings.as_bytes()); + + let derived = inputs::derive(config, job_id, base_dir)?; + for (label, json) in &derived.config { + hasher.update(b"\0derived\0"); + hasher.update(label.as_bytes()); + hasher.update([0u8]); + hasher.update(json.as_bytes()); + } + for rel in &derived.files { + let digest = self.files.hash_file(&base_dir.join(rel), Path::new(rel))?; + hasher.update(b"\0file\0"); + hasher.update(rel.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + } + let mut module_inputs = Vec::new(); + for pattern in &derived.patterns { + let (digest, found) = self.patterns.hash(pattern, base_dir, self.files)?; + hasher.update(b"\0module-input\0"); + hasher.update(pattern.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + module_inputs.push(found); + } + + let mut also_hashed = vec![ + format!("cigen {}", env!("CARGO_PKG_VERSION")), + format!("the job's definition (workflows.{workflow}.jobs.{job_id})"), + format!("the settings of workflow `{workflow}`"), + ]; + let modules_digest = match generated { + Some(generated) => { + super::job::warn_on_stale_modules(job_id, generated, &derived.modules_digest); + generated + } + None => derived.modules_digest.as_str(), + }; + if generated.is_some() || !modules_digest.is_empty() { + hasher.update(b"\0modules-digest\0"); + hasher.update(modules_digest.as_bytes()); + also_hashed.push(format!( + "the digest of the job's modules ({modules_digest})" + )); + } + + let declared = self.declared_inputs(job_id, &job.inputs, &mut hasher)?; + + // The jobs it needs, each by its whole hash (see `needs`). + let mut needs = Vec::new(); + needs::hash_needs(job_id, &job.needs, &mut hasher, &mut |need| { + let digest = self.digest(need)?; + needs.push(NeededJob { + job: need.to_string(), + hash: hex::encode(&digest), + }); + Ok(digest) + })?; + + let digest = hasher.finalize().to_vec(); + let explained = JobHash { + job: job_id.to_string(), + workflow, + inputs: declared, + derived: DerivedInputs { + config: derived.config.into_iter().map(|(label, _)| label).collect(), + files: derived.files.into_iter().map(DerivedFile::new).collect(), + modules: module_inputs, + }, + needs, + also_hashed, + hash: hex::encode(&digest), + }; + Ok((digest, explained)) + } + + /// Hashes the job's `inputs` in order, returning each with the files it matched. + fn declared_inputs( + &mut self, + job_id: &str, + entries: &[String], + hasher: &mut Sha256, + ) -> Result> { + let mut declared = Vec::new(); + for entry in entries { + let (tag, name, digest, matched) = match entry.strip_prefix('@') { + Some(group) => { + let mut list = self + .config + .input_group_patterns(group) + .with_context(|| format!("Job '{job_id}' uses `@{group}`"))?; + list.sort(); + let mut group_hasher = Sha256::new(); + group_hasher.update(group.as_bytes()); + group_hasher.update([0u8]); + if list.is_empty() { + group_hasher.update(b"empty-group"); + } + let mut matched = Vec::new(); + for pattern in &list { + let (digest, found) = + self.patterns.hash(pattern, self.base_dir, self.files)?; + group_hasher.update(pattern.as_bytes()); + group_hasher.update([0u8]); + group_hasher.update(&digest); + matched.push(found); + } + ("group", group, group_hasher.finalize().to_vec(), matched) + } + None => { + let (digest, found) = self.patterns.hash(entry, self.base_dir, self.files)?; + ("pattern", entry.as_str(), digest, vec![found]) + } + }; + hasher.update(tag.as_bytes()); + hasher.update([0u8]); + hasher.update(name.as_bytes()); + hasher.update([0u8]); + hasher.update(&digest); + declared.push(DeclaredInput { + entry: entry.clone(), + patterns: matched, + }); + } + Ok(declared) + } +} + +/// Pattern digests, each pattern listed and hashed once per run. +#[derive(Default)] +struct PatternHasher { + done: BTreeMap, PatternFiles)>, +} + +impl PatternHasher { + fn hash( + &mut self, + pattern: &str, + base_dir: &Path, + files: &mut FileHasher, + ) -> Result<(Vec, PatternFiles)> { + if let Some(done) = self.done.get(pattern) { + return Ok(done.clone()); + } + let matched = list_files(base_dir, pattern)?; + let mut aggregate = Sha256::new(); + if matched.is_empty() { + aggregate.update(b"empty"); + } + for rel in &matched { + let digest = files.hash_file(&base_dir.join(rel), rel)?; + aggregate.update(rel.to_string_lossy().as_bytes()); + aggregate.update([0u8]); + aggregate.update(&digest); + } + let result = ( + aggregate.finalize().to_vec(), + PatternFiles { + pattern: pattern.to_string(), + files: matched + .iter() + .map(|rel| rel.to_string_lossy().replace('\\', "/")) + .collect(), + }, + ); + self.done.insert(pattern.to_string(), result.clone()); + Ok(result) + } +} diff --git a/src/hashing/job.rs b/src/hashing/job.rs index 513e772..311f12d 100644 --- a/src/hashing/job.rs +++ b/src/hashing/job.rs @@ -2,14 +2,12 @@ //! prints the rest. Both come from `hash_job`, so the explanation always describes the hash. use super::files::FileHasher; +use super::hasher::JobHasher; use crate::config::{ConfigError, suggest}; -use crate::inputs::{self, LOCKFILES, TOOLCHAIN_PINS}; -use crate::pathspec::list_files; +use crate::inputs::{LOCKFILES, TOOLCHAIN_PINS}; use crate::schema::CigenConfig; -use anyhow::{Context, Result}; +use anyhow::Result; use serde::Serialize; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; use std::path::Path; /// A job's hash and everything it covers. @@ -21,6 +19,8 @@ pub struct JobHash { pub inputs: Vec, /// What cigen adds on top of `inputs` (see `crate::inputs`) pub derived: DerivedInputs, + /// The jobs it `needs`, each with its own hash + pub needs: Vec, /// Hashed besides the inputs: they change what the job does pub also_hashed: Vec, pub hash: String, @@ -59,10 +59,30 @@ pub struct DerivedFile { pub reason: &'static str, } +impl DerivedFile { + pub(super) fn new(path: String) -> Self { + let reason = if TOOLCHAIN_PINS.contains(&path.as_str()) { + "toolchain pin" + } else if LOCKFILES.contains(&path.as_str()) { + "lockfile" + } else { + "named in a step" + }; + Self { path, reason } + } +} + +/// A job that the job `needs`. Its hash is part of the job's hash. +#[derive(Debug, Serialize)] +pub struct NeededJob { + pub job: String, + pub hash: String, +} + /// Hashes `job_id`. `base_dir` is the project root, where patterns and step paths are looked up. /// `modules_digest` is the digest of the job's module expansions that its generated CI config -/// passes (`--modules-digest`); it goes into the hash, with a warning when this cigen expands -/// the job's modules differently. +/// passes (`--modules-digest`); without it, the digest this cigen computes is used. Either way +/// it goes into the hash, with a warning when the generated one differs. pub fn hash_job( config: &CigenConfig, job_id: &str, @@ -70,132 +90,16 @@ pub fn hash_job( files: &mut FileHasher, modules_digest: Option<&str>, ) -> Result { - let job = config - .jobs - .get(job_id) - .ok_or_else(|| unknown_job(config, job_id))?; - let workflow = job.workflow.clone().unwrap_or_else(|| "ci".to_string()); - - let mut hasher = Sha256::new(); - hasher.update(env!("CARGO_PKG_VERSION").as_bytes()); - hasher.update(job_id.as_bytes()); - hasher.update([0u8]); - hasher.update(workflow.as_bytes()); - - hasher.update([0u8]); - hasher.update(inputs::canonical_json(job)?.as_bytes()); - - // The workflow's settings (environment, provider blocks) can change what the job does. - let workflow_settings = config - .workflows - .get(&workflow) - .map(inputs::canonical_json) - .transpose()? - .unwrap_or_default(); - hasher.update(b"\0workflow\0"); - hasher.update(workflow_settings.as_bytes()); - - let derived = inputs::derive(config, job_id, base_dir)?; - for (label, json) in &derived.config { - hasher.update(b"\0derived\0"); - hasher.update(label.as_bytes()); - hasher.update([0u8]); - hasher.update(json.as_bytes()); - } - for rel in &derived.files { - let digest = files.hash_file(&base_dir.join(rel), Path::new(rel))?; - hasher.update(b"\0file\0"); - hasher.update(rel.as_bytes()); - hasher.update([0u8]); - hasher.update(&digest); - } - - let mut patterns = PatternHasher::default(); - let mut module_inputs = Vec::new(); - for pattern in &derived.patterns { - let (digest, found) = patterns.hash(pattern, base_dir, files)?; - hasher.update(b"\0module-input\0"); - hasher.update(pattern.as_bytes()); - hasher.update([0u8]); - hasher.update(&digest); - module_inputs.push(found); + if !config.jobs.contains_key(job_id) { + return Err(unknown_job(config, job_id).into()); } - let mut also_hashed = vec![ - format!("cigen {}", env!("CARGO_PKG_VERSION")), - format!("the job's definition (workflows.{workflow}.jobs.{job_id})"), - format!("the settings of workflow `{workflow}`"), - ]; - if let Some(generated) = modules_digest { - if generated != derived.modules_digest { - warn_stale_modules(job_id, generated, &derived.modules_digest); - } - hasher.update(b"\0modules-digest\0"); - hasher.update(generated.as_bytes()); - also_hashed.push(format!("the generated config's modules digest {generated}")); - } - - let mut declared = Vec::new(); - for entry in &job.inputs { - let (tag, name, digest, matched) = match entry.strip_prefix('@') { - Some(group) => { - let mut list = config - .input_group_patterns(group) - .with_context(|| format!("Job '{job_id}' uses `@{group}`"))?; - list.sort(); - let mut group_hasher = Sha256::new(); - group_hasher.update(group.as_bytes()); - group_hasher.update([0u8]); - if list.is_empty() { - group_hasher.update(b"empty-group"); - } - let mut matched = Vec::new(); - for pattern in &list { - let (digest, found) = patterns.hash(pattern, base_dir, files)?; - group_hasher.update(pattern.as_bytes()); - group_hasher.update([0u8]); - group_hasher.update(&digest); - matched.push(found); - } - ("group", group, group_hasher.finalize().to_vec(), matched) - } - None => { - let (digest, found) = patterns.hash(entry, base_dir, files)?; - ("pattern", entry.as_str(), digest, vec![found]) - } - }; - hasher.update(tag.as_bytes()); - hasher.update([0u8]); - hasher.update(name.as_bytes()); - hasher.update([0u8]); - hasher.update(&digest); - declared.push(DeclaredInput { - entry: entry.clone(), - patterns: matched, - }); - } - - Ok(JobHash { - job: job_id.to_string(), - workflow: workflow.clone(), - inputs: declared, - derived: DerivedInputs { - config: derived.config.into_iter().map(|(label, _)| label).collect(), - files: derived - .files - .into_iter() - .map(|path| DerivedFile { - reason: reason(&path), - path, - }) - .collect(), - modules: module_inputs, - }, - also_hashed, - hash: hex::encode(hasher.finalize()), - }) + JobHasher::new(config, base_dir, files).explain(job_id, modules_digest) } -fn warn_stale_modules(job_id: &str, generated: &str, current: &str) { +pub(super) fn warn_on_stale_modules(job_id: &str, generated: &str, current: &str) { + if generated == current { + return; + } let current = if current.is_empty() { "nothing" } else { @@ -208,16 +112,6 @@ fn warn_stale_modules(job_id: &str, generated: &str, current: &str) { ); } -fn reason(path: &str) -> &'static str { - if TOOLCHAIN_PINS.contains(&path) { - "toolchain pin" - } else if LOCKFILES.contains(&path) { - "lockfile" - } else { - "named in a step" - } -} - fn unknown_job(config: &CigenConfig, job_id: &str) -> ConfigError { let ids: Vec<&str> = config.jobs.keys().map(String::as_str).collect(); let error = ConfigError::new(format!("there's no job named `{job_id}`")); @@ -226,45 +120,3 @@ fn unknown_job(config: &CigenConfig, job_id: &str) -> ConfigError { None => error.suggest(format!("Jobs: {}.", ids.join(", "))), } } - -/// Pattern digests, each pattern listed and hashed once per run. -#[derive(Default)] -struct PatternHasher { - done: BTreeMap, PatternFiles)>, -} - -impl PatternHasher { - fn hash( - &mut self, - pattern: &str, - base_dir: &Path, - files: &mut FileHasher, - ) -> Result<(Vec, PatternFiles)> { - if let Some((digest, found)) = self.done.get(pattern) { - return Ok((digest.clone(), found.clone())); - } - let matched = list_files(base_dir, pattern)?; - let mut aggregate = Sha256::new(); - if matched.is_empty() { - aggregate.update(b"empty"); - } - for rel in &matched { - let digest = files.hash_file(&base_dir.join(rel), rel)?; - aggregate.update(rel.to_string_lossy().as_bytes()); - aggregate.update([0u8]); - aggregate.update(&digest); - } - let result = ( - aggregate.finalize().to_vec(), - PatternFiles { - pattern: pattern.to_string(), - files: matched - .iter() - .map(|rel| rel.to_string_lossy().replace('\\', "/")) - .collect(), - }, - ); - self.done.insert(pattern.to_string(), result.clone()); - Ok(result) - } -} diff --git a/src/hashing/mod.rs b/src/hashing/mod.rs index 8bb8ba4..4cafcfc 100644 --- a/src/hashing/mod.rs +++ b/src/hashing/mod.rs @@ -1,8 +1,12 @@ //! Hashing what a job depends on: file digests (`files`) and a job's hash with the inputs -//! that went into it (`job`). +//! that went into it (`job`, computed in `hasher`). mod files; +mod hasher; mod job; +mod needs; pub use files::{FileHasher, HashCache}; -pub use job::{DeclaredInput, DerivedFile, DerivedInputs, JobHash, PatternFiles, hash_job}; +pub use job::{ + DeclaredInput, DerivedFile, DerivedInputs, JobHash, NeededJob, PatternFiles, hash_job, +}; diff --git a/src/commands/needs_hash.rs b/src/hashing/needs.rs similarity index 100% rename from src/commands/needs_hash.rs rename to src/hashing/needs.rs diff --git a/tests/explain.rs b/tests/explain.rs index 11e9fe4..5861c71 100644 --- a/tests/explain.rs +++ b/tests/explain.rs @@ -173,3 +173,37 @@ fn module_inputs_are_listed_and_move_the_hash() { assert_ne!(before, after); assert_eq!(explain_json(&repo)["hash"], after.as_str()); } + +#[test] +fn the_jobs_a_job_needs_are_listed_with_their_hashes() { + let repo = FixtureRepo::new(); + repo.write( + "cigen.yml", + "provider: github\nworkflows:\n ci:\n jobs:\n build:\n inputs: ['build/**']\n steps: [{ run: make }]\n test:\n needs: [build]\n inputs: ['src/**']\n steps: [{ run: make test }]\n", + ) + .write("build/version", "1\n") + .write("src/lib.rs", "pub fn one() {}\n"); + repo.commit("initial"); + + let build = run(&repo, &["hash", "--job", "build"]).trim().to_string(); + let explained = explain_json(&repo); + assert_eq!( + explained["needs"], + json!([{ "job": "build", "hash": build }]) + ); + let text = run(&repo, &["explain", "test"]); + assert!( + text.contains(&format!( + "\nNeeds (each job's own hash):\n build {build}\n" + )), + "{text}" + ); + + // A change to what `build` hashes moves `test`'s hash, in explain and hash --job alike. + let before = explained["hash"].as_str().unwrap().to_string(); + repo.write("build/version", "2\n"); + repo.commit("change build"); + let after = run(&repo, &["hash", "--job", "test"]).trim().to_string(); + assert_ne!(before, after); + assert_eq!(explain_json(&repo)["hash"], after.as_str()); +} From 3631d473a94dba1d9ba7132944eb22bf0c876cdf Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:11:58 +1300 Subject: [PATCH 4/7] Test that a local hash --job equals the CI step's for an unchanged config --- tests/module_scenarios.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/module_scenarios.rs b/tests/module_scenarios.rs index 6c48bda..579aee8 100644 --- a/tests/module_scenarios.rs +++ b/tests/module_scenarios.rs @@ -146,6 +146,43 @@ fn the_generated_modules_digest_goes_into_the_hash() { assert!(warning.contains("Regenerate"), "{warning}"); } +#[test] +fn a_local_hash_equals_the_ci_steps_hash_for_an_unchanged_config() { + // CI's skip step passes the digest it was generated with; locally nobody does. For a config + // that hasn't changed since it was generated, both must give the same hash, so what + // `cigen hash --job` and `cigen explain` show is what CI looks up. + let repo = rust_fixture(); + repo.commit("initial"); + let workflow = std::fs::read_to_string(repo.path().join(WORKFLOW)).unwrap(); + let digest = workflow + .split("--modules-digest ") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .expect("the skip step passes the modules digest") + .to_string(); + + let ci = hash(&repo, &["--modules-digest", &digest]); + let local = hash(&repo, &[]); + assert!( + ci.status.success() && local.status.success(), + "{ci:?} {local:?}" + ); + assert_eq!( + String::from_utf8_lossy(&local.stdout), + String::from_utf8_lossy(&ci.stdout) + ); + let explained = support::cigen() + .current_dir(repo.path()) + .args(["explain", "test", "--format", "json"]) + .output() + .unwrap(); + let explained: serde_json::Value = serde_json::from_slice(&explained.stdout).unwrap(); + assert_eq!( + explained["hash"].as_str().unwrap(), + String::from_utf8_lossy(&ci.stdout).trim() + ); +} + #[test] fn an_unknown_module_or_parameter_fails_generation_with_a_fix() { for (modules, expected) in [ From 6f4a008b6299a5a22d8e3c80792d01f5e1f991dc Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:58:45 +1300 Subject: [PATCH 5/7] explain: give each derived pattern its reason #38 made every package.json a derived input, through the same list as the patterns modules contribute, so explain labelled `**/package.json` as coming from a module. Derived patterns now carry a reason, `from a module` or `every package.json`, like derived files do. --- docs/src/content/docs/cli.md | 19 ++++++++++--------- internal_docs/STATUS.md | 12 +++++++----- src/commands/explain.rs | 10 +++++++--- src/hashing/hasher.rs | 10 ++++++---- src/hashing/job.rs | 30 +++++++++++++++++++++++++++--- src/hashing/mod.rs | 3 ++- src/inputs.rs | 3 ++- tests/explain.rs | 4 +++- 8 files changed, 64 insertions(+), 27 deletions(-) diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 99c3267..53329e6 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -159,25 +159,26 @@ Derived inputs: Cargo.lock (lockfile) rust-toolchain (toolchain pin) scripts/test.sh (named in a step) + **/package.json (every package.json, no files) Also hashed: cigen 0.1.0 the job's definition (workflows.ci.jobs.test) the settings of workflow `ci` -Hash: dec443e28689907db942cae54a59bf3fc5fa66b844566d78ca428ae749c7af77 +Hash: 843bac1cb1ef04feb36b3f4f95fa1d00cf1fbacab3372cbead8d85ad403c4d19 ``` -A pattern that matches no files shows `(no files)`, which usually means a typo. Derived inputs are the files cigen adds -on its own (see [derived inputs](/docs/inputs/#derived-inputs)); commands and services the job uses are listed by their -config path, and the patterns a job's modules contribute are marked `from a module`. A job that `needs` others lists -them under `Needs` with their own hashes, which are part of its hash, so a change upstream makes it run too. The hash is -the one `cigen hash --job test` prints, and the one the generated workflow looks up while it's up to date with the -config. +A declared pattern that matches no files shows `(no files)`, which usually means a typo. Derived inputs are the files +cigen adds on its own (see [derived inputs](/docs/inputs/#derived-inputs)); commands and services the job uses are +listed by their config path, and patterns cigen adds (every `package.json`, and the files a job's modules contribute) +say which. A job that `needs` others lists them under `Needs` with their own hashes, which are part of its hash, so a +change upstream makes it run too. The hash is the one `cigen hash --job test` prints, and the one the generated workflow +looks up while it's up to date with the config. With `--format json`, it prints one object with `job`, `workflow`, `inputs` (each `entry` with its `patterns` and their -`files`), `derived` (`config` paths, `files` with a `reason`, and `modules`, each pattern with its `files`), `needs` -(each `job` with its `hash`), `also_hashed` and `hash`. An unknown job is an error that suggests the closest id. +`files`), `derived` (`config` paths, and `files` and `patterns`, each with a `reason`), `needs` (each `job` with its +`hash`), `also_hashed` and `hash`. An unknown job is an error that suggests the closest id. ## Environment diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 00eb7a1..178c611 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -13,9 +13,11 @@ What the code does today, checked against the code in December 2026. Where cigen the same way (`src/commands/report.rs`). `cigen explain [--config ] [--base-dir ] [--format text|json]` shows what the job's hash covers: its `inputs` with `@groups` expanded and the files each pattern matched, the derived inputs (config parts by label, - files with their reason: toolchain pin, lockfile or named in a step, and the patterns the job's modules contribute - with their files), the jobs it `needs` with their hashes, what else is hashed, and the hash. Job hashing lives in - `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the two always agree. + files with their reason: toolchain pin, lockfile or named in a step, and patterns with theirs: from a module or every + `package.json`, with the files they match), the jobs it `needs` with their hashes, what else is hashed, and the hash. + Job hashing lives in `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the two always + agree. Without `--modules-digest`, `hash --job` uses the modules digest this cigen computes, so a local hash equals + the CI step's for a config that hasn't changed since it was generated. - **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,8 +148,8 @@ What the code does today, checked against the code in December 2026. Where cigen (`docs/src/content/case-studies/`, drafts included) and the README, and the homepage's config, is run through `cigen generate`; examples of errors must fail with the error they show. - `tests/module_scenarios.rs`: a job using the `rust` module installs nothing when it skips, and reruns in mockci when - a file the module contributes or its parameters change; the generated `--modules-digest` changes the hash; unknown - modules and parameters fail generation with a fix. + a file the module contributes or its parameters change; the generated `--modules-digest` changes the hash, and a + local `hash --job` without it gives the CI step's hash; unknown modules and parameters fail generation with a fix. - `tests/module_catalogue.rs`: every registered module has a skill with frontmatter, a README documenting exactly its parameters, a golden fixture (`integration_tests/module_/`) for each provider it supports that mockci's parser loads, and actions pinned to commit SHAs; the index is generated from the registry diff --git a/src/commands/explain.rs b/src/commands/explain.rs index 24c342d..25e0684 100644 --- a/src/commands/explain.rs +++ b/src/commands/explain.rs @@ -62,7 +62,7 @@ fn render(job: &JobHash) -> String { out.push_str("\nDerived inputs:\n"); let derived = &job.derived; - if derived.config.is_empty() && derived.files.is_empty() && derived.modules.is_empty() { + if derived.config.is_empty() && derived.files.is_empty() && derived.patterns.is_empty() { out.push_str(" (none)\n"); } for label in &job.derived.config { @@ -71,8 +71,12 @@ fn render(job: &JobHash) -> String { for file in &job.derived.files { out.push_str(&format!(" {} ({})\n", file.path, file.reason)); } - for pattern in &job.derived.modules { - push_pattern(&mut out, " ", pattern, "from a module, "); + for derived in &job.derived.patterns { + let pattern = PatternFiles { + pattern: derived.pattern.clone(), + files: derived.files.clone(), + }; + push_pattern(&mut out, " ", &pattern, &format!("{}, ", derived.reason)); } if !job.needs.is_empty() { diff --git a/src/hashing/hasher.rs b/src/hashing/hasher.rs index 8a0edf1..2458a6d 100644 --- a/src/hashing/hasher.rs +++ b/src/hashing/hasher.rs @@ -4,7 +4,9 @@ //! change to one of them must make it run too. use super::files::FileHasher; -use super::job::{DeclaredInput, DerivedFile, DerivedInputs, JobHash, NeededJob, PatternFiles}; +use super::job::{ + DeclaredInput, DerivedFile, DerivedInputs, DerivedPattern, JobHash, NeededJob, PatternFiles, +}; use super::needs; use crate::inputs; use crate::pathspec::list_files; @@ -106,14 +108,14 @@ impl<'a, 'f> JobHasher<'a, 'f> { hasher.update([0u8]); hasher.update(&digest); } - let mut module_inputs = Vec::new(); + let mut derived_patterns = Vec::new(); for pattern in &derived.patterns { let (digest, found) = self.patterns.hash(pattern, base_dir, self.files)?; hasher.update(b"\0module-input\0"); hasher.update(pattern.as_bytes()); hasher.update([0u8]); hasher.update(&digest); - module_inputs.push(found); + derived_patterns.push(DerivedPattern::new(found)); } let mut also_hashed = vec![ @@ -157,7 +159,7 @@ impl<'a, 'f> JobHasher<'a, 'f> { derived: DerivedInputs { config: derived.config.into_iter().map(|(label, _)| label).collect(), files: derived.files.into_iter().map(DerivedFile::new).collect(), - modules: module_inputs, + patterns: derived_patterns, }, needs, also_hashed, diff --git a/src/hashing/job.rs b/src/hashing/job.rs index 311f12d..7159ad4 100644 --- a/src/hashing/job.rs +++ b/src/hashing/job.rs @@ -4,7 +4,7 @@ use super::files::FileHasher; use super::hasher::JobHasher; use crate::config::{ConfigError, suggest}; -use crate::inputs::{LOCKFILES, TOOLCHAIN_PINS}; +use crate::inputs::{LOCKFILES, PACKAGE_FILES, TOOLCHAIN_PINS}; use crate::schema::CigenConfig; use anyhow::Result; use serde::Serialize; @@ -48,8 +48,32 @@ pub struct DerivedInputs { /// `package.json:packageManager` pub config: Vec, pub files: Vec, - /// Patterns of the files the job's modules contribute, with the files they match - pub modules: Vec, + /// Patterns of tracked files: those the job's modules contribute, and every `package.json` + pub patterns: Vec, +} + +#[derive(Debug, Serialize)] +pub struct DerivedPattern { + pub pattern: String, + /// Why it's an input: `from a module` or `every package.json` + pub reason: &'static str, + /// Files relative to the project root, sorted + pub files: Vec, +} + +impl DerivedPattern { + pub(super) fn new(found: PatternFiles) -> Self { + let reason = if PACKAGE_FILES.contains(&found.pattern.as_str()) { + "every package.json" + } else { + "from a module" + }; + Self { + pattern: found.pattern, + reason, + files: found.files, + } + } } #[derive(Debug, Serialize)] diff --git a/src/hashing/mod.rs b/src/hashing/mod.rs index 4cafcfc..c2562b7 100644 --- a/src/hashing/mod.rs +++ b/src/hashing/mod.rs @@ -8,5 +8,6 @@ mod needs; pub use files::{FileHasher, HashCache}; pub use job::{ - DeclaredInput, DerivedFile, DerivedInputs, JobHash, NeededJob, PatternFiles, hash_job, + DeclaredInput, DerivedFile, DerivedInputs, DerivedPattern, JobHash, NeededJob, PatternFiles, + hash_job, }; diff --git a/src/inputs.rs b/src/inputs.rs index 9e34fcf..d640b0d 100644 --- a/src/inputs.rs +++ b/src/inputs.rs @@ -20,7 +20,8 @@ mod packages; use crate::schema::{CigenConfig, Job}; use anyhow::{Context, Result}; -use packages::{PACKAGE_FILES, package_manager}; +pub use packages::PACKAGE_FILES; +use packages::package_manager; use serde::Serialize; use serde_json::{Map, Value}; use std::collections::BTreeSet; diff --git a/tests/explain.rs b/tests/explain.rs index 5861c71..b578c43 100644 --- a/tests/explain.rs +++ b/tests/explain.rs @@ -113,6 +113,7 @@ Derived inputs: Cargo.lock (lockfile) rust-toolchain.toml (toolchain pin) scripts/check.sh (named in a step) + **/package.json (every package.json, no files) Also hashed: cigen "; @@ -148,11 +149,12 @@ fn module_inputs_are_listed_and_move_the_hash() { repo.commit("initial"); let explained = explain_json(&repo); - let modules = explained["derived"]["modules"].as_array().unwrap(); + let modules = explained["derived"]["patterns"].as_array().unwrap(); let nested = modules .iter() .find(|input| input["pattern"] == "**/Cargo.toml") .unwrap_or_else(|| panic!("no **/Cargo.toml in {modules:?}")); + assert_eq!(nested["reason"], "from a module"); assert_eq!( nested["files"], json!(["Cargo.toml", "crates/a/Cargo.toml"]) From 348aa75a102c6b724e8ac712644dd21943bb8bc2 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:17:01 +1300 Subject: [PATCH 6/7] Carry --matrix into src/hashing, and show the entry in explain Ports #51: hashing::hash_job mixes a GitHub matrix entry into the job's hash (matrix_entry.rs moved to src/hashing/matrix.rs with its tests), so hash --matrix still gives each entry its own hash. cigen explain takes --matrix to show an entry's hash, and for a job that runs a matrix without one, says each entry is hashed in. --- docs/src/content/docs/cli.md | 7 +++- internal_docs/STATUS.md | 18 +++++---- src/commands/explain.rs | 15 ++++++++ src/commands/hash.rs | 16 +++++++- src/hashing/hasher.rs | 13 ++++++- src/hashing/job.rs | 18 ++++++++- .../matrix_entry.rs => hashing/matrix.rs} | 2 +- src/hashing/mod.rs | 1 + tests/explain.rs | 38 +++++++++++++++++++ 9 files changed, 112 insertions(+), 16 deletions(-) rename src/{commands/matrix_entry.rs => hashing/matrix.rs} (97%) diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 53329e6..dcbecd4 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -117,6 +117,7 @@ cigen explain test --format json # the same, as data | `-c`, `--config ` | The config. Default: the one in `--base-dir`. | | `--base-dir ` | The project root, where input patterns and step paths are looked up. Default `.`. | | `--format ` | `text` (the default) or `json`. | +| `--matrix ` | For a job that runs GitHub's own matrix: one entry, to show that entry's hash. | For this config: @@ -174,11 +175,13 @@ cigen adds on its own (see [derived inputs](/docs/inputs/#derived-inputs)); comm listed by their config path, and patterns cigen adds (every `package.json`, and the files a job's modules contribute) say which. A job that `needs` others lists them under `Needs` with their own hashes, which are part of its hash, so a change upstream makes it run too. The hash is the one `cigen hash --job test` prints, and the one the generated workflow -looks up while it's up to date with the config. +looks up while it's up to date with the config. A job that runs GitHub's own matrix hashes each entry in, so each entry +has its own hash: explain says so, and `--matrix '{"rust": "nightly"}'` shows one entry's hash. With `--format json`, it prints one object with `job`, `workflow`, `inputs` (each `entry` with its `patterns` and their `files`), `derived` (`config` paths, and `files` and `patterns`, each with a `reason`), `needs` (each `job` with its -`hash`), `also_hashed` and `hash`. An unknown job is an error that suggests the closest id. +`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. ## Environment diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 178c611..33c4afc 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -11,13 +11,15 @@ What the code does today, checked against the code in December 2026. Where cigen the config and exits non-zero with every problem it found; `--format json` prints `{valid, config, errors: [{file, line, path, message, suggestion}]}` on stdout. Every command prints config errors the same way (`src/commands/report.rs`). - `cigen explain [--config ] [--base-dir ] [--format text|json]` shows what the job's hash covers: - its `inputs` with `@groups` expanded and the files each pattern matched, the derived inputs (config parts by label, - files with their reason: toolchain pin, lockfile or named in a step, and patterns with theirs: from a module or every - `package.json`, with the files they match), the jobs it `needs` with their hashes, what else is hashed, and the hash. - Job hashing lives in `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the two always - agree. Without `--modules-digest`, `hash --job` uses the modules digest this cigen computes, so a local hash equals - the CI step's for a config that hasn't changed since it was generated. + `cigen explain [--config ] [--base-dir ] [--format text|json] [--matrix ]` shows what the job's + hash covers: its `inputs` with `@groups` expanded and the files each pattern matched, the derived inputs (config parts + by label, files with their reason: toolchain pin, lockfile or named in a step, and patterns with theirs: from a module + or every `package.json`, with the files they match), the jobs it `needs` with their hashes, what else is hashed, and + the hash. Job hashing lives in `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the + two always agree. Without `--modules-digest`, `hash --job` uses the modules digest this cigen computes, so a local + hash equals the CI step's for a config that hasn't changed since it was generated. 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). - **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 @@ -140,7 +142,7 @@ What the code does today, checked against the code in December 2026. Where cigen owner. - `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. + input or a needed job changes, and for a matrix entry. - `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/explain.rs b/src/commands/explain.rs index 25e0684..a49aacc 100644 --- a/src/commands/explain.rs +++ b/src/commands/explain.rs @@ -23,6 +23,11 @@ pub struct ExplainArgs { /// Output format #[arg(long, value_enum, default_value_t = OutputFormat::Text)] pub format: OutputFormat, + + /// A matrix entry as JSON, for a job that runs GitHub's own matrix: the hash is that entry's, + /// as its CI hash step computes it + #[arg(long)] + pub matrix: Option, } pub fn explain_command(args: ExplainArgs) -> Result<()> { @@ -32,6 +37,7 @@ pub fn explain_command(args: ExplainArgs) -> Result<()> { None, &args.job, None, + args.matrix.as_deref(), )?; match args.format { OutputFormat::Json => print_json(&explained), @@ -90,7 +96,16 @@ fn render(job: &JobHash) -> String { for item in &job.also_hashed { out.push_str(&format!(" {item}\n")); } + if let Some(entry) = &job.matrix_entry { + out.push_str(&format!(" the matrix entry {entry}\n")); + } out.push_str(&format!("\nHash: {}\n", job.hash)); + if job.runs_matrix && job.matrix_entry.is_none() { + out.push_str( + "\nThe job runs GitHub's matrix, and each entry is hashed in, so each entry's hash differs \ + from this one.\nPass --matrix '' to see an entry's hash.\n", + ); + } out } diff --git a/src/commands/hash.rs b/src/commands/hash.rs index d300708..129dbc5 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -38,6 +38,11 @@ pub struct HashArgs { /// into the hash, so the hash covers the steps that config runs. #[arg(long = "modules-digest", requires = "job")] pub modules_digest: Option, + + /// 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. + #[arg(long = "matrix", requires = "job")] + pub matrix: Option, } pub fn hash_command(args: HashArgs) -> Result<()> { @@ -48,6 +53,7 @@ pub fn hash_command(args: HashArgs) -> Result<()> { args.cache_path.as_deref(), job_id, args.modules_digest.as_deref(), + args.matrix.as_deref(), )?; emit(&args, &job_hash.hash) } else { @@ -91,6 +97,7 @@ pub fn job_hash( cache: Option<&Path>, job_id: &str, modules_digest: Option<&str>, + matrix_entry: Option<&str>, ) -> Result { let root = canonicalize_path(base_dir)?; let config_path = match config { @@ -100,7 +107,14 @@ pub fn job_hash( }; let config = cigen::config::load(&config_path)?; let mut file_hasher = file_hasher(&root, cache)?; - let job_hash = hash_job(&config, job_id, &root, &mut file_hasher, modules_digest)?; + let job_hash = hash_job( + &config, + job_id, + &root, + &mut file_hasher, + modules_digest, + matrix_entry, + )?; file_hasher.save()?; Ok(job_hash) } diff --git a/src/hashing/hasher.rs b/src/hashing/hasher.rs index 2458a6d..b06b0d4 100644 --- a/src/hashing/hasher.rs +++ b/src/hashing/hasher.rs @@ -42,9 +42,13 @@ impl<'a, 'f> JobHasher<'a, 'f> { /// `job_id`'s hash and what went into it. `generated_modules` is the modules digest its CI /// config was generated with (`--modules-digest`); the jobs it needs are hashed with the /// digest this cigen computes. - pub fn explain(&mut self, job_id: &str, generated_modules: Option<&str>) -> Result { + pub fn explain( + &mut self, + job_id: &str, + generated_modules: Option<&str>, + ) -> Result<(Vec, JobHash)> { self.enter(job_id)?; - let (_, explained) = self.compute(job_id, generated_modules)?; + let explained = self.compute(job_id, generated_modules)?; self.chain.pop(); Ok(explained) } @@ -163,6 +167,11 @@ impl<'a, 'f> JobHasher<'a, 'f> { }, needs, also_hashed, + runs_matrix: job + .github + .as_ref() + .is_some_and(|block| block.contains_key("strategy")), + matrix_entry: None, hash: hex::encode(&digest), }; Ok((digest, explained)) diff --git a/src/hashing/job.rs b/src/hashing/job.rs index 7159ad4..a9f917a 100644 --- a/src/hashing/job.rs +++ b/src/hashing/job.rs @@ -3,6 +3,7 @@ use super::files::FileHasher; use super::hasher::JobHasher; +use super::matrix; use crate::config::{ConfigError, suggest}; use crate::inputs::{LOCKFILES, PACKAGE_FILES, TOOLCHAIN_PINS}; use crate::schema::CigenConfig; @@ -23,6 +24,11 @@ pub struct JobHash { pub needs: Vec, /// Hashed besides the inputs: they change what the job does pub also_hashed: Vec, + /// Whether the job runs GitHub's own matrix (a `strategy` in its `github:` block). Each entry + /// is hashed in, so each has its own hash. + pub runs_matrix: bool, + /// The matrix entry hashed in (`--matrix`), with its keys sorted + pub matrix_entry: Option, pub hash: String, } @@ -106,18 +112,26 @@ pub struct NeededJob { /// Hashes `job_id`. `base_dir` is the project root, where patterns and step paths are looked up. /// `modules_digest` is the digest of the job's module expansions that its generated CI config /// passes (`--modules-digest`); without it, the digest this cigen computes is used. Either way -/// it goes into the hash, with a warning when the generated one differs. +/// it goes into the hash, with a warning when the generated one differs. `matrix_entry` is the +/// job's GitHub matrix entry as JSON (`--matrix`), mixed into its hash (see `matrix`). pub fn hash_job( config: &CigenConfig, job_id: &str, base_dir: &Path, files: &mut FileHasher, modules_digest: Option<&str>, + matrix_entry: Option<&str>, ) -> Result { if !config.jobs.contains_key(job_id) { return Err(unknown_job(config, job_id).into()); } - JobHasher::new(config, base_dir, files).explain(job_id, modules_digest) + let (digest, mut explained) = + JobHasher::new(config, base_dir, files).explain(job_id, modules_digest)?; + if let Some(entry) = matrix_entry { + explained.hash = hex::encode(matrix::with_matrix_entry(&digest, entry)?); + explained.matrix_entry = Some(serde_json::from_str(entry)?); + } + Ok(explained) } pub(super) fn warn_on_stale_modules(job_id: &str, generated: &str, current: &str) { diff --git a/src/commands/matrix_entry.rs b/src/hashing/matrix.rs similarity index 97% rename from src/commands/matrix_entry.rs rename to src/hashing/matrix.rs index 83f3b4b..ff836ee 100644 --- a/src/commands/matrix_entry.rs +++ b/src/hashing/matrix.rs @@ -15,7 +15,7 @@ pub(super) fn with_matrix_entry(digest: &[u8], entry: &str) -> Result> { "`--matrix` must be the job's matrix entry as JSON (`${{{{ toJSON(matrix) }}}}`), got `{entry}`" ) })?; - let canonical = cigen::inputs::canonical_json(&value)?; + let canonical = crate::inputs::canonical_json(&value)?; let mut hasher = Sha256::new(); hasher.update(digest); hasher.update(b"\0matrix\0"); diff --git a/src/hashing/mod.rs b/src/hashing/mod.rs index c2562b7..4f74b39 100644 --- a/src/hashing/mod.rs +++ b/src/hashing/mod.rs @@ -4,6 +4,7 @@ mod files; mod hasher; mod job; +mod matrix; mod needs; pub use files::{FileHasher, HashCache}; diff --git a/tests/explain.rs b/tests/explain.rs index b578c43..e0aa59b 100644 --- a/tests/explain.rs +++ b/tests/explain.rs @@ -209,3 +209,41 @@ fn the_jobs_a_job_needs_are_listed_with_their_hashes() { assert_ne!(before, after); assert_eq!(explain_json(&repo)["hash"], after.as_str()); } + +#[test] +fn a_matrix_job_says_each_entry_is_hashed_and_shows_an_entrys_hash() { + let repo = FixtureRepo::new(); + repo.write( + "cigen.yml", + "provider: github\nworkflows:\n ci:\n jobs:\n test:\n inputs: ['src/**']\n github:\n strategy:\n matrix:\n rust: [stable, nightly]\n steps: [{ run: make test }]\n", + ) + .write("src/lib.rs", "pub fn one() {}\n"); + repo.commit("initial"); + + let text = run(&repo, &["explain", "test"]); + assert!(text.contains("each entry is hashed in"), "{text}"); + assert_eq!(explain_json(&repo)["runs_matrix"], true); + + // With an entry, the hash is the one the entry's CI hash step computes. + let entry = r#"{"rust": "nightly", "os": "ubuntu-latest"}"#; + let ci = run(&repo, &["hash", "--job", "test", "--matrix", entry]) + .trim() + .to_string(); + let explained: Value = serde_json::from_str(&run( + &repo, + &["explain", "test", "--format", "json", "--matrix", entry], + )) + .unwrap(); + assert_eq!(explained["hash"], ci.as_str()); + assert_ne!(explained["hash"], explain_json(&repo)["hash"]); + assert_eq!( + explained["matrix_entry"], + json!({ "os": "ubuntu-latest", "rust": "nightly" }) + ); + let text = run(&repo, &["explain", "test", "--matrix", entry]); + assert!( + text.contains(" the matrix entry {\"os\":\"ubuntu-latest\",\"rust\":\"nightly\"}\n"), + "{text}" + ); + assert!(!text.contains("each entry is hashed in"), "{text}"); +} From cf7359a7a695429568967c25ee4d42ae5d49ccc0 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:40:48 +1300 Subject: [PATCH 7/7] Keep the one-problem summary, and note the one-time rerun of jobs that need module jobs The explain commit had dropped "The config has 1 problem." for a single error, which the quick start still shows; main's report.rs is back. STATUS says that a job needing a job with modules gets a new hash once, since needed jobs are hashed with this cigen's modules digest. --- internal_docs/STATUS.md | 8 +++++--- src/commands/report.rs | 11 +++++------ tests/explain.rs | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 33c4afc..6df6e90 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -17,9 +17,11 @@ What the code does today, checked against the code in December 2026. Where cigen or every `package.json`, with the files they match), the jobs it `needs` with their hashes, what else is hashed, and the hash. Job hashing lives in `src/hashing/`, and `hash --job` and `explain` both call `hashing::hash_job`, so the two always agree. Without `--modules-digest`, `hash --job` uses the modules digest this cigen computes, so a local - hash equals the CI step's for a config that hasn't changed since it was generated. 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). + hash equals the CI step's for a config that hasn't changed since it was generated. The jobs a job needs are hashed the + same way, with this cigen's modules digest, so a job that needs a job with modules got a new hash in CI with #14 (its + 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). - **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 diff --git a/src/commands/report.rs b/src/commands/report.rs index 6a5d813..5920b03 100644 --- a/src/commands/report.rs +++ b/src/commands/report.rs @@ -29,10 +29,9 @@ pub fn print_error(error: &anyhow::Error) { for config_error in &errors { eprintln!("error: {config_error}"); } - if errors.len() > 1 { - eprintln!( - "\nThe config has {} problems. `cigen validate --format json` lists them as data.", - errors.len() - ); - } + let count = errors.len(); + let noun = if count == 1 { "problem" } else { "problems" }; + eprintln!( + "\nThe config has {count} {noun}. `cigen validate --format json` lists them as data." + ); } diff --git a/tests/explain.rs b/tests/explain.rs index e0aa59b..b66e87e 100644 --- a/tests/explain.rs +++ b/tests/explain.rs @@ -132,7 +132,7 @@ fn an_unknown_job_suggests_the_closest() { let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!( stderr, - "error: there's no job named `tset`\n help: did you mean `test`?\n" + "error: there's no job named `tset`\n help: did you mean `test`?\n\nThe config has 1 problem. `cigen validate --format json` lists them as data.\n" ); }