Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ 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 }
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"
Expand Down
16 changes: 8 additions & 8 deletions docs/src/content/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@ cigen hash --job test
cigen hash --pattern 'src/**/*.rs' --pattern Cargo.lock
```

| Option | What it does |
| ------------------------ | ------------------------------------------------------------------------------------------------- |
| `--job <id>` | Hash a job: its inputs, its definition and its [derived inputs](/docs/inputs/#derived-inputs). |
| `-p`, `--pattern <glob>` | Hash the files these globs match. Repeat it for more globs. Used when there's no `--job`. |
| `--config <path>` | The config for `--job`. Default: the one in `--base-dir`. |
| `--base-dir <dir>` | The project root that globs are relative to. Default `.`. |
| `--output <name>` | Also write `name=<hash>` to `$GITHUB_OUTPUT`, when that's set. |
| `--cache <file>` | Keep per-file hashes in this file, keyed by size and modification time, to hash faster next time. |
| Option | What it does |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `--job <id>` | Hash a job: its inputs, its definition and its [derived inputs](/docs/inputs/#derived-inputs). |
| `-p`, `--pattern <glob>` | 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 <path>` | The config for `--job`. Default: the one in `--base-dir`. |
| `--base-dir <dir>` | The project root that globs are relative to. Default `.`. |
| `--output <name>` | Also write `name=<hash>` to `$GITHUB_OUTPUT`, when that's set. |
| `--cache <file>` | 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`.

Expand Down
20 changes: 19 additions & 1 deletion docs/src/content/docs/inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
25 changes: 25 additions & 0 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>' ':(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=<repository root>`, 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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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=<repository root>` and fails
with git's message on any other git error.

## Next

Expand Down
109 changes: 4 additions & 105 deletions src/commands/hash.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();

Expand All @@ -310,83 +305,6 @@ fn hash_pattern(
Ok(digest)
}

fn list_files_with_git(base_dir: &Path, pattern: &str) -> Result<Vec<PathBuf>> {
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<Vec<PathBuf>> {
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<Vec<PathBuf>> {
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<PathBuf> {
fs::canonicalize(path).with_context(|| format!("Failed to resolve path {}", path.display()))
}
Expand All @@ -401,28 +319,9 @@ fn resolve_path(base_dir: &Path, path: &Path) -> PathBuf {

fn collect_files(base_dir: &Path, patterns: &[String]) -> Result<Vec<PathBuf>> {
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())
}

Expand Down
63 changes: 63 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf> {
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<String> {
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());
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading