diff --git a/Cargo.lock b/Cargo.lock index e84814f..d13fa4c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -331,7 +331,7 @@ dependencies = [ "base64", "cigen-mockci", "clap", - "globwalk", + "globset", "hex", "insta", "jsonschema", diff --git a/Cargo.toml b/Cargo.toml index 2a05881..71d2a0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,6 @@ sha2 = "0.10.9" tokio = { workspace = true } tracing = { workspace = true } tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } -globwalk = "0.9.1" walkdir = "2.5.0" tonic = { workspace = true } prost = { workspace = true } @@ -52,6 +51,7 @@ tonic-prost = { workspace = true } hex = "0.4.3" strsim = "0.11.1" schemars = "1.2.3" +globset = "0.4.22" [dev-dependencies] assert_cmd = "2.0.17" diff --git a/docs/src/content/docs/cli.md b/docs/src/content/docs/cli.md index 95ec994..c7c064c 100644 --- a/docs/src/content/docs/cli.md +++ b/docs/src/content/docs/cli.md @@ -89,14 +89,14 @@ cigen hash --job test cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock ``` -| Option | What it does | -| ------------------------ | ------------------------------------------------------------------------------------------------- | -| `--job ` | Hash a job: its inputs, its definition and its [derived inputs](/docs/inputs/#derived-inputs). | -| `-p`, `--pattern ` | Hash the files these globs match. Repeat it for more globs. Used when there's no `--job`. | -| `--config ` | The config for `--job`. Default: the one in `--base-dir`. | -| `--base-dir ` | The project root that globs are relative to. Default `.`. | -| `--output ` | Also write `name=` to `$GITHUB_OUTPUT`, when that's set. | -| `--cache ` | Keep per-file hashes in this file, keyed by size and modification time, to hash faster next time. | +| Option | What it does | +| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `--job ` | Hash a job: its inputs, its definition and its [derived inputs](/docs/inputs/#derived-inputs). | +| `-p`, `--pattern ` | Hash the files these globs match, with the same [rules as inputs](/docs/inputs/). Repeat it for more globs. Used when there's no `--job`. | +| `--config ` | The config for `--job`. Default: the one in `--base-dir`. | +| `--base-dir ` | The project root that globs are relative to. Default `.`. | +| `--output ` | Also write `name=` to `$GITHUB_OUTPUT`, when that's set. | +| `--cache ` | Keep per-file hashes in this file, keyed by size and modification time, to hash faster next time. | Patterns that match no files hash to the word `empty`. diff --git a/docs/src/content/docs/inputs.md b/docs/src/content/docs/inputs.md index 34f2407..530576e 100644 --- a/docs/src/content/docs/inputs.md +++ b/docs/src/content/docs/inputs.md @@ -29,7 +29,25 @@ workflows: ``` Globs are relative to the project root, the directory that holds `cigen.yml` or `.cigen/`. In a git repository they match -the files git tracks (`git ls-files`), so build output and untracked files never change a hash. +the files git tracks (`git ls-files`), so build output and untracked files never change a hash. Outside one, the same +rules apply to the files on disk. A checkout owned by another user, as in a container job, works too. If git fails for +any other reason, `cigen hash` stops with git's message rather than guess at the files. + +The rules are gitignore's, which err towards matching more files: a glob that matches too little would skip a job whose +inputs changed. + +| Glob | Matches | +| -------------- | --------------------------------------------------------------------------------------------------------- | +| `*.md` | Markdown files everywhere: a glob with no `/` matches at any depth, like `**/*.md`. | +| `/*.md` | Markdown files at the root only: a leading `/` (or `./`) anchors a glob to the root. | +| `docs/*.md` | Markdown files directly in `docs/`: a glob with a `/` starts at the root, and `*` stays in one directory. | +| `docs/**/*.md` | Markdown files in `docs/` and every directory under it: `**/` is zero or more directories. | +| `docs/**` | Every file under `docs/`. | +| `/docs` | Every file under `docs/`: a glob that matches a directory matches every file under it. | +| `docs` | Every file under each directory named `docs`, at the root or deeper (`site/docs/`). | + +A file name with no `/` matches that name in every directory: `Cargo.lock` includes `tools/Cargo.lock`. Write +`/Cargo.lock` for the root one only. ## `input_groups` diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 4af54a2..15850d0 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -48,6 +48,14 @@ What the code does today, checked against the code in December 2026. Where cigen name (`sh scripts/check.sh`, `require('./x.js')`, every file of a local `uses: ./action`), and the root toolchain pins, lockfiles and `package.json` `packageManager`, plus each module's resolved parameters, its steps for every provider the config names, and the files it contributes. Each rule includes too much rather than too little. +- **Globs** (`src/pathspec.rs`): every glob cigen hashes (job and group `inputs`, module inputs, `hash --pattern`) is + matched by `pathspec::list_files`, with gitignore's rules: a glob with no `/` matches at any depth (`*.md` is + `**/*.md`), a leading `/` or `./` anchors it to the root, a glob with a `/` elsewhere starts at the root with `*` + staying in one directory, `**/` is zero or more directories, and a glob that matches a directory matches everything + under it. In git that's `git ls-files -z -- ':(glob)' ':(glob)/**'` (tracked files only); outside git + the same globs are applied to the files on disk with `globset`. Any other git error fails the command. +- **Running git** (`src/git.rs`): every git command cigen runs carries `-c safe.directory=`, so it + works in a checkout owned by another user, as in CI container jobs. - **Modules** (`src/modules/`): a job lists them under `modules:` (`- rust` or `- rust: { components: [clippy] }`). Before a provider sees the config, each module expands into ordinary steps around the job's own (after the checkout and the skip check, and after the job's steps for CircleCI's `save_cache`). Unknown modules and parameters are errors @@ -109,6 +117,13 @@ What the code does today, checked against the code in December 2026. Where cigen block, and its errors for steps it can't render. - `tests/validate.rs`: `cigen validate` reports several problems at once with their fields in JSON, names the line of a YAML syntax error, and prints the same text as `generate` and `hash --job`. +- `tests/glob_inputs.rs`: what a glob matches, inside git and outside it (the two must agree): `**/*.md` includes root + files, `docs/**/*.md` includes `docs/a.md`, `*.md` matches at any depth, `/*.md` only at the root, `docs/*.md` only + directly in `docs/`, a directory matches everything under it, and `hash --pattern` matches the same way. Each case + changes a file and checks whether the hash changes. +- `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/derived_inputs.rs`: changing a script a step runs, a command the job uses or a toolchain pin 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. @@ -168,6 +183,16 @@ What the code does today, checked against the code in December 2026. Where cigen 19. The install step's checksum comes from the same release as the archive, so it catches a corrupt or truncated download but not a replaced release: it proves nothing about where the binary came from. Possible fixes are in DIRECTION.md ("Installing cigen on the runner"). +20. Resolved (PR #28): globs were passed to `git ls-files` as plain pathspecs, so `**/*.md` missed root files + and `docs/**/*.md` missed `docs/a.md` (a false skip). Found converting a real project. Globs now follow + gitignore's rules (`*.md` still matches every directory; `/*.md` is the root only). The fix changes which + files many globs match, so most job hashes changed once: every job with `inputs` runs again on its first push + after upgrading. +21. Resolved (PR #28): when `git ls-files` failed, `cigen hash` silently fell back to globbing the files on disk, + untracked files and build output included, with different matching rules. In a CI container job the checkout is + owned by another user, so git always failed ("detected dubious ownership") and the job hashed a different file + list from the one computed anywhere else. cigen now passes git `-c safe.directory=` and fails + with git's message on any other git error. ## Next diff --git a/src/commands/hash.rs b/src/commands/hash.rs index 1f8999e..0159135 100644 --- a/src/commands/hash.rs +++ b/src/commands/hash.rs @@ -1,13 +1,11 @@ use anyhow::{Context, Result, bail}; use clap::Args; -use globwalk::{FileType, GlobWalkerBuilder}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::{self, File}; use std::io::{BufReader, Read, Write}; use std::path::{Path, PathBuf}; -use std::process::Command; use std::time::UNIX_EPOCH; /// Arguments for the `cigen hash` subcommand. @@ -59,8 +57,7 @@ pub fn hash_command(args: HashArgs) -> Result<()> { fn hash_patterns(args: &HashArgs) -> Result<()> { let base_dir = canonicalize_path(&args.base_dir)?; - let mut files = collect_files(&base_dir, &args.patterns)?; - files.sort(); + let files = collect_files(&base_dir, &args.patterns)?; let cache_path = args .cache_path @@ -287,9 +284,7 @@ fn hash_pattern( return Ok(existing.clone()); } - let mut files = list_files_with_git(base_dir, pattern)?; - files.sort(); - files.dedup(); + let files = cigen::pathspec::list_files(base_dir, pattern)?; let mut aggregate = Sha256::new(); @@ -310,83 +305,6 @@ fn hash_pattern( Ok(digest) } -fn list_files_with_git(base_dir: &Path, pattern: &str) -> Result> { - match run_git_ls(base_dir, pattern) { - Ok(mut files) => { - if files.is_empty() && pattern_contains_glob(pattern) { - let glob_pattern = format!(":(glob){}", pattern); - files = run_git_ls(base_dir, &glob_pattern)?; - } - Ok(files) - } - Err(_) => { - if pattern_contains_glob(pattern) { - return glob_fallback(base_dir, pattern); - } - - let candidate = base_dir.join(pattern); - if candidate.exists() { - let rel = candidate - .strip_prefix(base_dir) - .unwrap_or(&candidate) - .to_path_buf(); - return Ok(vec![rel]); - } - - Ok(Vec::new()) - } - } -} - -fn run_git_ls(base_dir: &Path, pattern: &str) -> Result> { - let output = Command::new("git") - .arg("ls-files") - .arg("--") - .arg(pattern) - .current_dir(base_dir) - .output() - .with_context(|| format!("Failed to execute git ls-files for pattern '{pattern}'"))?; - - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - bail!( - "git ls-files exited with status {} while evaluating pattern '{pattern}': {stderr}", - output.status - ); - } - - let stdout = String::from_utf8(output.stdout)?; - let mut files = Vec::new(); - for line in stdout.lines() { - let trimmed = line.trim(); - if !trimmed.is_empty() { - files.push(PathBuf::from(trimmed)); - } - } - Ok(files) -} - -fn pattern_contains_glob(pattern: &str) -> bool { - pattern.contains('*') || pattern.contains('?') || pattern.contains('[') || pattern.contains(']') -} - -fn glob_fallback(base_dir: &Path, pattern: &str) -> Result> { - let mut results = Vec::new(); - let walker = GlobWalkerBuilder::from_patterns(base_dir, &[pattern]) - .follow_links(true) - .case_insensitive(cfg!(windows)) - .file_type(FileType::FILE) - .build()?; - - for entry in walker.into_iter().filter_map(Result::ok) { - if let Ok(rel) = entry.path().strip_prefix(base_dir) { - results.push(rel.to_path_buf()); - } - } - - Ok(results) -} - fn canonicalize_path(path: &Path) -> Result { fs::canonicalize(path).with_context(|| format!("Failed to resolve path {}", path.display())) } @@ -401,28 +319,9 @@ fn resolve_path(base_dir: &Path, path: &Path) -> PathBuf { fn collect_files(base_dir: &Path, patterns: &[String]) -> Result> { let mut unique = BTreeSet::new(); - - let walker = GlobWalkerBuilder::from_patterns(base_dir, patterns) - .file_type(FileType::FILE) - .follow_links(false) - .build() - .with_context(|| { - format!( - "Failed to evaluate glob patterns {:?} relative to {}", - patterns, - base_dir.display() - ) - })?; - - for entry in walker { - let entry = entry?; - let relative = entry - .path() - .strip_prefix(base_dir) - .unwrap_or_else(|_| entry.path()); - unique.insert(relative.to_path_buf()); + for pattern in patterns { + unique.extend(cigen::pathspec::list_files(base_dir, pattern)?); } - Ok(unique.into_iter().collect()) } diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..366010c --- /dev/null +++ b/src/git.rs @@ -0,0 +1,63 @@ +//! Running git. Every git command cigen runs starts here, so it works in a checkout owned by +//! another user, as in CI container jobs (`rust:latest` on GitHub Actions), where git otherwise +//! refuses with "detected dubious ownership in repository". + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// A `git` command that runs in `dir`, trusting the repository `dir` is in. git accepts +/// `safe.directory` on the command line, and matches it against the repository's top level, +/// not the directory git runs in, so the value is the nearest directory holding `.git`. +pub fn command(dir: &Path) -> Command { + let mut command = Command::new("git"); + if let Some(root) = repository_root(dir) { + command + .arg("-c") + .arg(format!("safe.directory={}", root.display())); + } + command.current_dir(dir); + command +} + +/// The nearest directory at or above `dir` that holds `.git` (a directory, or a file in a +/// linked worktree), with symlinks resolved as git resolves them. +fn repository_root(dir: &Path) -> Option { + let dir = std::fs::canonicalize(dir).ok()?; + dir.ancestors() + .find(|candidate| candidate.join(".git").exists()) + .map(Path::to_path_buf) +} + +#[cfg(test)] +mod tests { + use super::command; + use std::ffi::OsStr; + + fn args(command: &std::process::Command) -> Vec { + command + .get_args() + .map(OsStr::to_string_lossy) + .map(String::from) + .collect() + } + + #[test] + fn git_trusts_the_repository_top_level_from_any_directory_in_it() { + let dir = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(dir.path()).unwrap(); + std::fs::create_dir(root.join(".git")).unwrap(); + std::fs::create_dir_all(root.join("project/sub")).unwrap(); + let expected = vec![ + "-c".to_string(), + format!("safe.directory={}", root.display()), + ]; + assert_eq!(args(&command(&root)), expected); + assert_eq!(args(&command(&root.join("project/sub"))), expected); + } + + #[test] + fn outside_a_repository_git_runs_as_it_is() { + let dir = tempfile::tempdir().unwrap(); + assert!(args(&command(dir.path())).is_empty()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 1a8b9d2..94fdc18 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,8 @@ pub mod config; +pub mod git; pub mod inputs; pub mod modules; pub mod orchestrator; +pub mod pathspec; pub mod plugin; pub mod schema; diff --git a/src/pathspec.rs b/src/pathspec.rs new file mode 100644 index 0000000..7b297a7 --- /dev/null +++ b/src/pathspec.rs @@ -0,0 +1,147 @@ +//! Which project files a glob matches. Every glob cigen hashes (a job's `inputs`, a group's, +//! a module's, `cigen hash --pattern`) is matched here, so they all mean the same thing. The +//! rules are gitignore's, which err towards matching more: +//! +//! - A glob with no `/` matches at any depth: `*.md` is every Markdown file, and `Cargo.lock` +//! is every `Cargo.lock`. +//! - A leading `/` (or `./`) anchors it to the project root: `/*.md` is the Markdown files at +//! the root. +//! - A glob with a `/` elsewhere is matched from the root: `docs/*.md` is the Markdown files +//! directly in `docs/`, since `*` and `?` stay within one directory. +//! - `**/` matches zero or more directories: `docs/**/*.md` includes `docs/a.md`. +//! - A glob that matches a directory matches every file under it. +//! +//! In a git repository only tracked files count (`git ls-files` with `:(glob)` pathspec magic). +//! Outside one, the same rules are applied to the files on disk. Matching too little is a false +//! skip, so both paths are tested against each other (`tests/glob_inputs.rs`). + +use anyhow::{Context, Result, bail}; +use globset::{GlobBuilder, GlobSetBuilder}; +use std::path::{Path, PathBuf}; + +/// The files under `base_dir` that `pattern` matches, relative to `base_dir` and sorted. +pub fn list_files(base_dir: &Path, pattern: &str) -> Result> { + let globs = globs(pattern)?; + let mut files = match tracked_files(base_dir, pattern, &globs)? { + Some(files) => files, + None => files_on_disk(base_dir, pattern, &globs)?, + }; + files.sort(); + files.dedup(); + Ok(files) +} + +/// The root-relative globs `pattern` stands for: the files it matches, and everything under +/// the directories it matches. +fn globs(pattern: &str) -> Result<[String; 2]> { + // A separator at the start anchors the glob, as in gitignore; `./x` counts as one. + let (anchored, rest) = match pattern.strip_prefix("./").or(pattern.strip_prefix('/')) { + Some(rest) => (true, rest), + None => (false, pattern), + }; + let rest = rest.trim_end_matches('/'); + if rest.is_empty() { + bail!("`{pattern}` names no files: write a path or a glob such as `src/**`"); + } + let glob = if anchored || rest.contains('/') { + rest.to_string() + } else { + format!("**/{rest}") + }; + let under = format!("{glob}/**"); + Ok([glob, under]) +} + +/// `git ls-files` with glob magic, or `None` when `base_dir` isn't in a git repository. +fn tracked_files( + base_dir: &Path, + pattern: &str, + globs: &[String; 2], +) -> Result>> { + let output = crate::git::command(base_dir) + .args(["ls-files", "-z", "--"]) + .args(globs.iter().map(|glob| format!(":(glob){glob}"))) + // Untranslated, so "not a git repository" can be recognised. + .env("LC_ALL", "C") + .output() + .with_context(|| format!("running git ls-files for the glob `{pattern}`"))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + if stderr.contains("not a git repository") { + return Ok(None); + } + bail!( + "git ls-files failed for the glob `{pattern}`: {}", + stderr.trim() + ); + } + let stdout = + String::from_utf8(output.stdout).context("git ls-files printed a non-UTF-8 path")?; + Ok(Some( + stdout + .split('\0') + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .collect(), + )) +} + +/// The same globs, applied to the files on disk. +fn files_on_disk(base_dir: &Path, pattern: &str, globs: &[String; 2]) -> Result> { + let mut set = GlobSetBuilder::new(); + for glob in globs { + set.add( + GlobBuilder::new(glob) + .literal_separator(true) + .backslash_escape(true) + .build() + .with_context(|| format!("`{pattern}` isn't a valid glob"))?, + ); + } + let set = set + .build() + .with_context(|| format!("`{pattern}` isn't a valid glob"))?; + let mut files = Vec::new(); + for entry in walkdir::WalkDir::new(base_dir) + .into_iter() + .filter_entry(|entry| entry.file_name() != ".git") + { + let entry = entry.with_context(|| format!("listing files under {}", base_dir.display()))?; + if !entry.file_type().is_file() { + continue; + } + let relative = entry + .path() + .strip_prefix(base_dir) + .expect("walkdir yields paths under its root"); + if set.is_match(relative) { + files.push(relative.to_path_buf()); + } + } + Ok(files) +} + +#[cfg(test)] +mod tests { + use super::globs; + + #[test] + fn globs_follow_gitignore() { + let cases = [ + ("*.md", "**/*.md"), + ("/*.md", "*.md"), + ("./*.md", "*.md"), + ("docs/*.md", "docs/*.md"), + ("/docs/", "docs"), + ("docs/", "**/docs"), + ("Cargo.lock", "**/Cargo.lock"), + ("src/**", "src/**"), + ]; + for (pattern, expected) in cases { + let [glob, under] = globs(pattern).unwrap(); + assert_eq!(glob, expected, "{pattern}"); + assert_eq!(under, format!("{expected}/**"), "{pattern}"); + } + assert!(globs("/").is_err()); + } +} diff --git a/tests/git_ownership.rs b/tests/git_ownership.rs new file mode 100644 index 0000000..8233ce7 --- /dev/null +++ b/tests/git_ownership.rs @@ -0,0 +1,55 @@ +//! A checkout owned by another user, as in a CI container job (`rust:latest` on GitHub +//! Actions), where git refuses with "detected dubious ownership in repository". cigen's git +//! commands trust the repository they run in, so `cigen hash` works there and matches the hash +//! computed anywhere else. `GIT_TEST_ASSUME_DIFFERENT_OWNER` is git's own switch for testing +//! this (git 2.47 in `rust:latest` honours it). + +mod support; + +use std::path::Path; +use support::fixture_repo::FixtureRepo; + +const CONFIG: &str = "provider: github\nworkflows:\n ci:\n jobs:\n check:\n image: rust:latest\n inputs: ['**/*.md', 'Cargo.lock']\n steps:\n - run: make check\n"; + +fn hash(dir: &Path, other_owner: bool) -> std::process::Output { + let mut command = support::cigen(); + command.args(["hash", "--job", "check"]).current_dir(dir); + if other_owner { + command.env("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1"); + } + command.output().expect("run cigen hash") +} + +fn assert_same_hash(project: &Path) { + let own = hash(project, false); + let other = hash(project, true); + assert!( + other.status.success(), + "{}", + String::from_utf8_lossy(&other.stderr) + ); + assert!(own.status.success()); + assert_eq!(own.stdout, other.stdout); +} + +#[test] +fn hashing_works_in_a_checkout_owned_by_another_user() { + let repo = FixtureRepo::new(); + repo.write("cigen.yml", CONFIG) + .write("README.md", "readme") + .write("Cargo.lock", "lock"); + repo.commit("project"); + assert_same_hash(repo.path()); +} + +#[test] +fn hashing_works_when_the_project_is_a_subdirectory_of_that_checkout() { + // git matches `safe.directory` against the repository's top level, not the directory it + // runs in. + let repo = FixtureRepo::new(); + repo.write("app/cigen.yml", CONFIG) + .write("app/README.md", "readme") + .write("app/Cargo.lock", "lock"); + repo.commit("project"); + assert_same_hash(&repo.path().join("app")); +} diff --git a/tests/glob_inputs.rs b/tests/glob_inputs.rs new file mode 100644 index 0000000..58a9edb --- /dev/null +++ b/tests/glob_inputs.rs @@ -0,0 +1,142 @@ +//! What an input glob matches, by gitignore's rules: a glob with no `/` matches at any depth, a +//! leading `/` anchors it to the root, `*` stays within one directory, `**/` matches zero or more +//! directories, and a directory matches every file under it. The same inside a git repository +//! (where only tracked files count) and outside one. A glob that matches too little is a false +//! skip, so each case changes a file the glob must match and asserts the job's hash changes. + +mod support; + +use std::path::Path; +use support::fixture_repo::FixtureRepo; + +fn config(inputs: &str) -> String { + format!( + "provider: github\nworkflows:\n ci:\n jobs:\n check:\n image: ubuntu-latest\n inputs: {inputs}\n steps:\n - run: make check\n" + ) +} + +fn hash(dir: &Path) -> String { + let output = support::cigen() + .args(["hash", "--job", "check"]) + .current_dir(dir) + .output() + .expect("run cigen hash"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap().trim().to_string() +} + +fn write(dir: &Path, path: &str, contents: &str) { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, contents).unwrap(); +} + +/// A tree with Markdown at the root, in `docs/` and in `docs/guide/`. +fn tree(dir: &Path, inputs: &str) { + write(dir, "cigen.yml", &config(inputs)); + write(dir, "README.md", "readme"); + write(dir, "docs/a.md", "a"); + write(dir, "docs/guide/b.md", "b"); + write(dir, "src/lib.rs", "lib"); +} + +/// Whether changing `path` changes the hash, in a git repository with every file tracked. +fn changes_hash_in_git(inputs: &str, path: &str) -> bool { + let repo = FixtureRepo::new(); + tree(repo.path(), inputs); + repo.commit("tree"); + let before = hash(repo.path()); + write(repo.path(), path, "changed"); + repo.commit("change"); + before != hash(repo.path()) +} + +/// The same, in a directory that isn't a git repository. +fn changes_hash_outside_git(inputs: &str, path: &str) -> bool { + let dir = tempfile::tempdir().unwrap(); + tree(dir.path(), inputs); + let before = hash(dir.path()); + write(dir.path(), path, "changed"); + before != hash(dir.path()) +} + +fn changes_hash(inputs: &str, path: &str) -> bool { + let in_git = changes_hash_in_git(inputs, path); + let outside = changes_hash_outside_git(inputs, path); + assert_eq!( + in_git, outside, + "`{inputs}` and {path}: git and the fallback disagree" + ); + in_git +} + +#[test] +fn a_double_star_matches_files_at_the_root() { + assert!(changes_hash("['**/*.md']", "README.md")); + assert!(changes_hash("['**/*.md']", "docs/guide/b.md")); +} + +#[test] +fn a_double_star_matches_files_directly_in_its_directory() { + assert!(changes_hash("['docs/**/*.md']", "docs/a.md")); + assert!(changes_hash("['docs/**/*.md']", "docs/guide/b.md")); + assert!(!changes_hash("['docs/**/*.md']", "README.md")); +} + +#[test] +fn a_glob_without_a_slash_matches_at_any_depth() { + assert!(changes_hash("['*.md']", "README.md")); + assert!(changes_hash("['*.md']", "docs/a.md")); + assert!(changes_hash("['*.md']", "docs/guide/b.md")); + assert!(changes_hash("['lib.rs']", "src/lib.rs")); + assert!(!changes_hash("['*.md']", "src/lib.rs")); +} + +#[test] +fn a_leading_slash_anchors_a_glob_to_the_root() { + assert!(changes_hash("['/*.md']", "README.md")); + assert!(!changes_hash("['/*.md']", "docs/a.md")); + assert!(changes_hash("['./*.md']", "README.md")); + assert!(!changes_hash("['./*.md']", "docs/a.md")); +} + +#[test] +fn a_single_star_after_a_slash_stays_in_one_directory() { + assert!(changes_hash("['docs/*.md']", "docs/a.md")); + assert!(!changes_hash("['docs/*.md']", "docs/guide/b.md")); + assert!(!changes_hash("['docs/*.md']", "README.md")); +} + +#[test] +fn a_directory_matches_every_file_under_it() { + assert!(changes_hash("['docs']", "docs/guide/b.md")); + assert!(changes_hash("['docs/**']", "docs/guide/b.md")); + assert!(changes_hash("['guide']", "docs/guide/b.md")); + assert!(!changes_hash("['/guide']", "docs/guide/b.md")); + assert!(!changes_hash("['docs']", "src/lib.rs")); +} + +#[test] +fn hash_patterns_match_like_inputs() { + // `cigen hash --pattern` uses the same matching as a job's inputs. + let repo = FixtureRepo::new(); + tree(repo.path(), "['src/**']"); + repo.commit("tree"); + let pattern = |dir: &Path| { + let output = support::cigen() + .args(["hash", "--pattern", "**/*.md"]) + .current_dir(dir) + .output() + .unwrap(); + assert!(output.status.success()); + String::from_utf8(output.stdout).unwrap() + }; + let before = pattern(repo.path()); + write(repo.path(), "README.md", "changed"); + repo.commit("change"); + assert_ne!(before, pattern(repo.path())); +}