diff --git a/topos/cli/src/commands/evaluate/inputs.rs b/topos/cli/src/commands/evaluate/inputs.rs index 77df5004..1712b8fb 100644 --- a/topos/cli/src/commands/evaluate/inputs.rs +++ b/topos/cli/src/commands/evaluate/inputs.rs @@ -203,7 +203,10 @@ mod tests { .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); - let dir = std::env::temp_dir().join(format!("topos-eval-inputs-{label}-{nanos}")); + let dir = std::env::temp_dir().join(format!( + "topos-eval-inputs-{label}-{}-{nanos}", + std::process::id() + )); fs::create_dir_all(&dir).unwrap(); dir } diff --git a/topos/engine/src/adapters/discovery.rs b/topos/engine/src/adapters/discovery.rs index 992e26cd..77c3ce88 100644 --- a/topos/engine/src/adapters/discovery.rs +++ b/topos/engine/src/adapters/discovery.rs @@ -81,7 +81,9 @@ pub fn is_virtualenv_root(dir_path: &Path) -> bool { dir_path.join("Scripts").join("python.exe").is_file() } -/// Whether to avoid descending into `dir_path` during discovery (defaulting to top-level skip rules). +/// Whether to avoid descending into `dir_path` during discovery (defaults to +/// top-level skip rules: only correct when `dir_path` is a direct child of the +/// scan/repo root; use `should_skip_dir_context` with an explicit flag in walks). pub fn should_skip_dir(dir_path: &Path) -> bool { should_skip_dir_context(dir_path, true) } @@ -100,6 +102,11 @@ pub fn should_skip_dir_context(dir_path: &Path, is_top_level: bool) -> bool { } /// Check whether a path matches built-in non-source defaults (*.min.*, fixtures, vendor, testdata, __snapshots__). +/// +/// Matches on the given path's own components. Callers walking an absolute +/// tree must pass a scan-root-relative path (see `build_path_skip_checker`), +/// otherwise a parent directory outside the scan (e.g. `/tmp/vendor/repo`) +/// would incorrectly ignore everything underneath it. pub fn is_builtin_ignored_path(path: &Path) -> bool { if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if glob_match(name, "*.min.*") { @@ -138,22 +145,29 @@ pub fn has_generated_header(path: &Path) -> bool { .collect::>() .join("\n") .to_ascii_lowercase(); + // Normalised copy so `do-not-edit`, `do_not_edit`, and `don't edit` + // all match the `do not edit` family below (same for `auto-generated`). + let normalized = header.replace(['-', '_'], " ").replace('\'', ""); if header.contains("@generated") || header.contains("@auto-generated") || header.contains("@autogenerated") || header.contains(" bool { glob_match(rel_posix, pattern) || format!("/{rel_posix}/").contains(&format!("/{pattern}/")) } -fn relative_posix(path: &Path, root: &Path) -> Option { - let rel = path.strip_prefix(root).ok()?; - Some(rel.to_string_lossy().replace('\\', "/")) -} - -fn toposignore_checker(root: &Path) -> Option { - let patterns = load_ignore_patterns(&root.join(TOPOSIGNORE_NAME)); - if patterns.is_empty() { - return None; - } - let root = root.to_path_buf(); - Some(Box::new(move |path: &Path| { - let Some(rel_posix) = relative_posix(path, &root) else { - return false; - }; - patterns - .iter() - .any(|pat| matches_ignore_pattern(&rel_posix, pat)) - })) -} - fn git_available() -> bool { let mut cmd = Command::new("git"); cmd.arg("--version"); @@ -248,44 +241,102 @@ fn git_available() -> bool { .unwrap_or(false) } -fn git_check_ignore_checker(git_root: &Path) -> Option { - if !git_available() { - return None; +fn git_is_ignored(git_root: &Path, rel_git_posix: &str) -> bool { + if rel_git_posix.is_empty() { + return false; } - let git_root = git_root.to_path_buf(); - Some(Box::new(move |path: &Path| { - let Some(rel_posix) = relative_posix(path, &git_root) else { - return false; - }; - let mut cmd = Command::new("git"); - cmd.args(["-C"]) - .arg(&git_root) - .args(["check-ignore", "-q", "--"]) - .arg(&rel_posix); - run_with_timeout(cmd, None, true, Some(Duration::from_secs(1))) - .map(|out| out.status_code == Some(0)) - .unwrap_or(false) - })) + let mut cmd = Command::new("git"); + cmd.args(["-C"]) + .arg(git_root) + .args(["check-ignore", "-q", "--"]) + .arg(rel_git_posix); + run_with_timeout(cmd, None, true, Some(Duration::from_secs(1))) + .map(|out| out.status_code == Some(0)) + .unwrap_or(false) } /// Compose built-in, git-ignore, and `.toposignore` checks for `scan_root`. +/// +/// Built-ins are evaluated against the scan-root-relative path so a parent +/// directory outside the scan (e.g. a checkout at `/tmp/vendor/repo`) never +/// triggers a match. `.toposignore` is loaded from both `scan_root` and the +/// enclosing git root (when different), so `topos evaluate benchmarks/ -r` +/// still honours the repo-root file. Git-ignore is evaluated against the +/// git-root-relative path derived from the scan root, so relative invocations +/// like `topos evaluate .` behave the same as absolute ones. pub fn build_path_skip_checker(scan_root: &Path) -> PathFilter { let git_root = find_git_root(scan_root); - let topos = toposignore_checker(scan_root); - let git_check = git_root + let scan_patterns = load_ignore_patterns(&scan_root.join(TOPOSIGNORE_NAME)); + let scan_root_buf = scan_root.to_path_buf(); + let scan_root_canon = scan_root + .canonicalize() + .unwrap_or_else(|_| scan_root_buf.clone()); + let git_patterns = git_root .as_ref() - .and_then(|gr| git_check_ignore_checker(gr)); + .filter(|gr| **gr != scan_root_canon) + .map(|gr| load_ignore_patterns(&gr.join(TOPOSIGNORE_NAME))) + .unwrap_or_default(); + // `scan_root` expressed relative to the git root ("" when they are equal, + // `None` when the scan sits outside any git repo). Lets us derive a + // git-relative path from a scan-relative one without canonicalizing every + // walked file. + let scan_rel_to_git: Option = git_root.as_ref().and_then(|gr| { + scan_root_canon + .strip_prefix(gr) + .ok() + .map(|p| p.to_path_buf()) + }); + let git_usable = git_root.is_some() && git_available(); + let git_root_buf = git_root.clone(); Box::new(move |path: &Path| { - if is_builtin_ignored_path(path) { + let rel_to_scan: PathBuf = match path.strip_prefix(&scan_root_buf) { + Ok(rel) => rel.to_path_buf(), + Err(_) => match path.canonicalize().ok().and_then(|abs| { + abs.strip_prefix(&scan_root_canon) + .ok() + .map(|p| p.to_path_buf()) + }) { + Some(rel) => rel, + None => return false, + }, + }; + if is_builtin_ignored_path(&rel_to_scan) { return true; } - if git_check.as_ref().is_some_and(|check| check(path)) { + let rel_scan_posix = rel_to_scan.to_string_lossy().replace('\\', "/"); + if !rel_scan_posix.is_empty() + && scan_patterns + .iter() + .any(|pat| matches_ignore_pattern(&rel_scan_posix, pat)) + { return true; } - if topos.as_ref().is_some_and(|check| check(path)) { + let Some(prefix) = scan_rel_to_git.as_ref() else { + return false; + }; + let prefix_posix = prefix.to_string_lossy().replace('\\', "/"); + let rel_git_posix = if rel_scan_posix.is_empty() { + prefix_posix + } else if prefix_posix.is_empty() { + rel_scan_posix.clone() + } else { + format!("{prefix_posix}/{rel_scan_posix}") + }; + if !rel_git_posix.is_empty() + && git_patterns + .iter() + .any(|pat| matches_ignore_pattern(&rel_git_posix, pat)) + { return true; } + if git_usable { + if let Some(gr) = git_root_buf.as_ref() { + if git_is_ignored(gr, &rel_git_posix) { + return true; + } + } + } false }) } @@ -343,7 +394,10 @@ pub fn iter_source_files( let mut out = Vec::new(); if root.is_file() { - if has_suffix(root, suffixes) && !ignored(root) && !has_generated_header(root) { + // Explicit file argument: suffix match alone wins, consistent with + // `collect_source_files`. Ignore filters (builtin/git/toposignore) and + // generated headers only apply to directory discovery. + if has_suffix(root, suffixes) { out.push(root.to_path_buf()); } return out; @@ -352,7 +406,14 @@ pub fn iter_source_files( return out; } + // `ROOT_ONLY_SKIP_DIR_NAMES` (build/dist/coverage/...) are repo-top-level + // outputs, not nested source modules like `src/build`. Anchor "top level" + // to the git root when known so `topos evaluate src -r` still scans + // `src/build`; without git info fall back to the scan root. let git_root = find_git_root(root); + let root_canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + let root_is_repo_top = git_root.as_ref().is_some_and(|g| *g == root_canonical); + let apply_root_only_at_scan_top = git_root.is_none() || root_is_repo_top; let mut stack = vec![root.to_path_buf()]; while let Some(current) = stack.pop() { let Ok(read_dir) = std::fs::read_dir(¤t) else { @@ -361,7 +422,7 @@ pub fn iter_source_files( let mut entries: Vec = read_dir.filter_map(|e| e.ok().map(|e| e.path())).collect(); entries.sort_by(|a, b| a.file_name().cmp(&b.file_name())); - let is_top_level = current == root || git_root.as_ref().is_some_and(|g| ¤t == g); + let is_top_level = current == root && apply_root_only_at_scan_top; let (files, subdirs) = scan_dir_children(entries, suffixes, &ignored, is_top_level); out.extend(files); if include_dirs { @@ -385,6 +446,10 @@ pub fn collect_source_files>( for path_arg in paths { let path = path_arg.as_ref(); if path.is_file() { + // Explicit file: suffix match alone wins (overrides builtin, + // git/toposignore, and generated-header filters, which only + // apply to directory discovery). Matches the `iter_source_files` + // single-file branch. if has_suffix(path, suffixes) { files.insert(path.to_path_buf()); } @@ -695,4 +760,85 @@ mod tests { ); std::fs::remove_dir_all(&tmp).ok(); } + + #[test] + fn subdir_scan_keeps_nested_build_when_git_root_known() { + // `src/build` is a nested source module, not repo-top-level output, + // even when the scan starts at `src/`. + let tmp = unique_tmp_dir("subdir_build_git"); + std::fs::create_dir_all(tmp.join(".git")).unwrap(); + let src_build = tmp.join("src").join("build"); + std::fs::create_dir_all(&src_build).unwrap(); + std::fs::write(src_build.join("builder.rs"), "pub fn build() {}").unwrap(); + + let files = collect_source_files(&[tmp.join("src").as_path()], &[".rs"], true); + let names: Vec<_> = files + .iter() + .map(|p| p.file_name().unwrap().to_str().unwrap()) + .collect(); + assert!(names.contains(&"builder.rs"), "{names:?}"); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn builtin_ignores_are_scan_relative_not_absolute() { + // A parent directory outside the scan named `vendor` must not ignore + // everything underneath it. + let tmp = unique_tmp_dir("parent_vendor"); + let repo = tmp.join("vendor").join("repo"); + let src = repo.join("src"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("main.rs"), "fn main() {}\n").unwrap(); + + let checker = build_path_skip_checker(&repo); + assert!(!checker(&src.join("main.rs"))); + let files = collect_source_files(&[repo.as_path()], &[".rs"], true); + assert_eq!(files.len(), 1); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn has_generated_header_detects_bare_auto_generated_variants() { + let tmp = unique_tmp_dir("gen_variants"); + let cases = [ + ("// auto-generated file - do not edit\nfn x() {}\n", true), + ("// GENERATED CODE - DO NOT EDIT\nfn x() {}\n", true), + ("// Code generated by tool, do-not-edit\nfn x() {}\n", true), + ("// Normal hand-written code\nfn main() {}\n", false), + ]; + for (i, (contents, expected)) in cases.iter().enumerate() { + let path = tmp.join(format!("v{i}.rs")); + std::fs::write(&path, contents).unwrap(); + assert_eq!(has_generated_header(&path), *expected, "{contents}"); + } + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn explicit_file_overrides_generated_and_builtin_filters() { + let tmp = unique_tmp_dir("explicit_override"); + let gen = tmp.join("gen.rs"); + std::fs::write(&gen, "// @generated\npub fn gen() {}\n").unwrap(); + + let files = collect_source_files(&[gen.as_path()], &[".rs"], false); + assert_eq!(files, vec![gen.clone()]); + + let single = iter_source_files(&gen, &[".rs"], false, None, false); + assert_eq!(single, vec![gen]); + std::fs::remove_dir_all(&tmp).ok(); + } + + #[test] + fn toposignore_from_git_root_applies_to_subdir_scans() { + let tmp = unique_tmp_dir("git_toposignore"); + std::fs::create_dir_all(tmp.join(".git")).unwrap(); + std::fs::write(tmp.join(".toposignore"), "benchmarks/\n").unwrap(); + let bench = tmp.join("benchmarks"); + std::fs::create_dir_all(&bench).unwrap(); + std::fs::write(bench.join("foo.rs"), "fn foo() {}\n").unwrap(); + + let files = collect_source_files(&[bench.as_path()], &[".rs"], true); + assert!(files.is_empty(), "{files:?}"); + std::fs::remove_dir_all(&tmp).ok(); + } } diff --git a/topos/engine/src/adapters/gitnexus.rs b/topos/engine/src/adapters/gitnexus.rs index d3a522d7..631aaa12 100644 --- a/topos/engine/src/adapters/gitnexus.rs +++ b/topos/engine/src/adapters/gitnexus.rs @@ -35,7 +35,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use blake2::digest::{Update, VariableOutput}; use blake2::Blake2bVar; -use super::discovery::iter_source_files; +use super::discovery::{build_path_skip_checker, iter_source_files}; use super::process::{command_on_path, run_with_timeout, timeout_duration, RunError}; pub(crate) const GITNEXUS_CMD: &str = "gitnexus"; @@ -216,11 +216,15 @@ pub struct SourceFingerprint { } /// Hash source-file paths and bytes under `root` using existing discovery. +/// Uses the same skip checker as evaluation (builtin ignores, git-ignore, +/// `.toposignore`) so editing an ignored file (fixtures, `*.min.*`, …) +/// neither changes the fingerprint nor marks COMPOSABLE stale. pub fn source_fingerprint(root: &Path) -> SourceFingerprint { let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); let suffixes = crate::graphs::ast::languages::all_source_suffixes(); + let checker = build_path_skip_checker(&root); - let mut files = iter_source_files(&root, &suffixes, true, None, false); + let mut files = iter_source_files(&root, &suffixes, true, Some(&checker), false); files.sort_by(|a, b| { a.strip_prefix(&root) .unwrap_or(a) diff --git a/topos/mcp/src/evaluation/freshness.rs b/topos/mcp/src/evaluation/freshness.rs index 06164e60..6f178c35 100644 --- a/topos/mcp/src/evaluation/freshness.rs +++ b/topos/mcp/src/evaluation/freshness.rs @@ -77,11 +77,14 @@ fn newer_source_file( } } } + // Same evaluation set as `topos evaluate`: ignored files (fixtures, + // `*.min.*`, topos/git-ignored) must not mark COMPOSABLE stale. + let checker = topos_engine::adapters::discovery::build_path_skip_checker(project_root); let paths = topos_engine::adapters::discovery::iter_source_files( project_root, &suffixes, true, - None, + Some(&checker), true, // include_dirs: deletions bump the parent dir's mtime ); let mut seen = 0usize;