diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 14623a2..dcbecd4 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,88 @@ 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`. | +| `--matrix ` | For a job that runs GitHub's own matrix: one entry, to show that entry's hash. | + +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) + **/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: 843bac1cb1ef04feb36b3f4f95fa1d00cf1fbacab3372cbead8d85ad403c4d19 +``` + +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. 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`, `runs_matrix`, `matrix_entry` (the entry given, or `null`) 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
  • diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 3d8cc84..8943639 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -11,6 +11,17 @@ 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] [--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. 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 @@ -44,7 +55,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 @@ -132,6 +143,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 and + the jobs a job needs, in JSON and text, and its hash equals `cigen hash --job`'s before and after an input, a module + input or a needed job changes, and for a matrix entry. - `tests/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. @@ -141,8 +155,8 @@ What the code does today, checked against the code in December 2026. Where cigen `cigen generate`; examples of errors must fail with the error they show. Every file it reads must be an input of cigen's own `test` job. - `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 new file mode 100644 index 0000000..a49aacc --- /dev/null +++ b/src/commands/explain.rs @@ -0,0 +1,123 @@ +//! `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, + + /// 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<()> { + let explained = job_hash( + &args.base_dir, + args.config.as_deref(), + None, + &args.job, + None, + args.matrix.as_deref(), + )?; + 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.patterns.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 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() { + 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")); + } + 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 +} + +/// 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..129dbc5 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)] @@ -51,7 +47,15 @@ pub struct HashArgs { 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(), + args.matrix.as_deref(), + )?; + emit(&args, &job_hash.hash) } else { if args.patterns.is_empty() { bail!( @@ -66,23 +70,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,263 +85,54 @@ 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>, + matrix_entry: 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 digest = job_digest( + let mut file_hasher = file_hasher(&root, cache)?; + let job_hash = hash_job( &config, - &base_dir, job_id, - args.modules_digest.as_deref(), + &root, &mut file_hasher, - &mut pattern_cache, - &mut Vec::new(), + modules_digest, + matrix_entry, )?; - if let Some(entry) = &args.matrix { - digest = with_matrix_entry(&digest, entry)?; - } - let digest = hex::encode(digest); - - 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()?; + Ok(job_hash) } -/// 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 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)) } -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); - } +/// 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)?; } - - let digest = aggregate.finalize().to_vec(); - pattern_cache.insert(pattern.to_string(), digest.clone()); - Ok(digest) + println!("{digest}"); + Ok(()) } fn canonicalize_path(path: &Path) -> Result { @@ -385,162 +168,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..a9a5365 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,10 +1,10 @@ +mod explain; mod generate; mod hash; -mod matrix_entry; -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/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/hasher.rs b/src/hashing/hasher.rs new file mode 100644 index 0000000..b06b0d4 --- /dev/null +++ b/src/hashing/hasher.rs @@ -0,0 +1,272 @@ +//! 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, DerivedPattern, 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<(Vec, JobHash)> { + 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 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); + derived_patterns.push(DerivedPattern::new(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(), + patterns: derived_patterns, + }, + 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)) + } + + /// 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 new file mode 100644 index 0000000..a9f917a --- /dev/null +++ b/src/hashing/job.rs @@ -0,0 +1,160 @@ +//! 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 super::hasher::JobHasher; +use super::matrix; +use crate::config::{ConfigError, suggest}; +use crate::inputs::{LOCKFILES, PACKAGE_FILES, TOOLCHAIN_PINS}; +use crate::schema::CigenConfig; +use anyhow::Result; +use serde::Serialize; +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, + /// 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, + /// 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, +} + +/// 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 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)] +pub struct DerivedFile { + pub path: String, + /// Why it's an input: `toolchain pin`, `lockfile`, or `named in a step` + 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`); without it, the digest this cigen computes is used. Either way +/// 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()); + } + 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) { + if generated == current { + return; + } + 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 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(", "))), + } +} 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 new file mode 100644 index 0000000..4f74b39 --- /dev/null +++ b/src/hashing/mod.rs @@ -0,0 +1,14 @@ +//! Hashing what a job depends on: file digests (`files`) and a job's hash with the inputs +//! that went into it (`job`, computed in `hasher`). + +mod files; +mod hasher; +mod job; +mod matrix; +mod needs; + +pub use files::{FileHasher, HashCache}; +pub use job::{ + DeclaredInput, DerivedFile, DerivedInputs, DerivedPattern, 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/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/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..b66e87e --- /dev/null +++ b/tests/explain.rs @@ -0,0 +1,249 @@ +//! `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) + **/package.json (every package.json, no files) + +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\nThe config has 1 problem. `cigen validate --format json` lists them as data.\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"]["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"]) + ); + 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()); +} + +#[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()); +} + +#[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}"); +} 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 [