use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use fallow_types::results::{AnalysisResults, SecurityFinding};
use rustc_hash::FxHashSet;
use crate::duplicates::{self, DuplicationReport};
use crate::result_scope::{
Anchor, ComponentRule, OwnerRule, ProjectFinding, ResultScope, SiteRule,
};
pub use crate::git_env::{
AMBIENT_GIT_ENV_VARS, clear_ambient_git_env, git_command as git_command_in,
};
pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChangedFilesError {
InvalidRef(String),
GitMissing(String),
NotARepository,
GitFailed(String),
}
impl ChangedFilesError {
#[must_use]
pub fn describe(&self) -> String {
match self {
Self::InvalidRef(err) => format!("invalid git ref: {err}"),
Self::GitMissing(err) => format!("failed to run git: {err}"),
Self::NotARepository => "not a git repository".to_owned(),
Self::GitFailed(stderr) => augment_git_failed(stderr),
}
}
#[must_use]
pub const fn reason(&self) -> &'static str {
match self {
Self::InvalidRef(_) => "invalid-ref",
Self::GitMissing(_) => "git-missing",
Self::NotARepository => "not-a-repository",
Self::GitFailed(_) => "git-failed",
}
}
#[must_use]
pub fn changed_since_message(&self, git_ref: &str) -> String {
let cause = self
.describe()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
format!(
"--changed-since '{git_ref}' was ignored because {cause}, so this report covers \
the whole project instead of the changed files. {}",
self.changed_since_remedy()
)
}
const fn changed_since_remedy(&self) -> &'static str {
match self {
Self::InvalidRef(_) => {
"Pass a ref git can resolve, such as a branch name or a commit sha."
}
Self::GitMissing(_) => {
"Install git and make it available on PATH, or drop --changed-since."
}
Self::NotARepository => {
"Run fallow from inside the repository, or drop --changed-since."
}
Self::GitFailed(_) => {
"Verify the ref exists in this repository, and check out with full history."
}
}
}
}
fn augment_git_failed(stderr: &str) -> String {
let lower = stderr.to_ascii_lowercase();
if lower.contains("not a valid object name")
|| lower.contains("unknown revision")
|| lower.contains("ambiguous argument")
{
format!(
"{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
)
} else {
stderr.to_owned()
}
}
static EXCLUDE_UNTRACKED: AtomicBool = AtomicBool::new(false);
pub fn exclude_untracked_files() {
EXCLUDE_UNTRACKED.store(true, Ordering::Relaxed);
}
fn untracked_files_excluded() -> bool {
EXCLUDE_UNTRACKED.load(Ordering::Relaxed)
}
pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
let _ = SPAWN_HOOK.set(hook);
}
pub(crate) fn validate_git_ref(s: &str) -> Result<&str, String> {
if s.is_empty() {
return Err("git ref cannot be empty".to_string());
}
if s.starts_with('-') {
return Err("git ref cannot start with '-'".to_string());
}
let mut in_braces = false;
for c in s.chars() {
match c {
'{' => in_braces = true,
'}' => in_braces = false,
':' | ' ' if in_braces => {}
c if c.is_ascii_alphanumeric()
|| matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
_ => return Err(format!("git ref contains disallowed character: '{c}'")),
}
}
if in_braces {
return Err("git ref has unclosed '{'".to_string());
}
Ok(s)
}
pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
});
}
let raw = String::from_utf8_lossy(&output.stdout);
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(ChangedFilesError::GitFailed(
"git rev-parse --show-toplevel returned empty output".to_owned(),
));
}
let path = PathBuf::from(trimmed);
Ok(dunce::canonicalize(&path).unwrap_or(path))
}
pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
let output = spawn_output(&mut git_command(
cwd,
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
});
}
let raw = String::from_utf8_lossy(&output.stdout);
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(ChangedFilesError::GitFailed(
"git rev-parse --git-common-dir returned empty output".to_owned(),
));
}
let path = PathBuf::from(trimmed);
Ok(dunce::canonicalize(&path).unwrap_or(path))
}
pub fn resolve_git_hooks_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--git-path", "hooks"]))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
});
}
let raw = String::from_utf8_lossy(&output.stdout);
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.lines().count() != 1 {
return Err(ChangedFilesError::GitFailed(format!(
"git rev-parse --git-path hooks printed {trimmed:?}"
)));
}
let base = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
Ok(normalize_lexically(&base.join(trimmed)))
}
fn normalize_lexically(path: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
pub fn resolve_git_common_dir_and_toplevel(
cwd: &Path,
) -> Result<(PathBuf, PathBuf), ChangedFilesError> {
let output = spawn_output(&mut git_command(
cwd,
&[
"rev-parse",
"--path-format=absolute",
"--git-common-dir",
"--show-toplevel",
],
))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
});
}
let raw = String::from_utf8_lossy(&output.stdout);
let mut lines = raw.lines();
let (Some(common), Some(toplevel), None) = (lines.next(), lines.next(), lines.next()) else {
return Err(ChangedFilesError::GitFailed(
"git rev-parse did not print one common dir and one toplevel".to_owned(),
));
};
let canonical = |line: &str| {
let path = PathBuf::from(line.trim());
dunce::canonicalize(&path).unwrap_or(path)
};
if common.trim().is_empty() || toplevel.trim().is_empty() {
return Err(ChangedFilesError::GitFailed(
"git rev-parse returned an empty path".to_owned(),
));
}
Ok((canonical(common), canonical(toplevel)))
}
fn try_get_changed_files(
root: &Path,
git_ref: &str,
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
let toplevel = resolve_git_toplevel(root)?;
try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
}
pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
try_get_changed_files(root, git_ref)
}
pub(crate) struct ChangedFilesBatch<'a> {
cwd: &'a Path,
toplevel: PathBuf,
working_tree: Option<FxHashSet<PathBuf>>,
}
impl<'a> ChangedFilesBatch<'a> {
pub(crate) fn new(cwd: &'a Path, first_ref: &str) -> Result<Self, ChangedFilesError> {
validate_git_ref(first_ref).map_err(ChangedFilesError::InvalidRef)?;
Ok(Self {
cwd,
toplevel: resolve_git_toplevel(cwd)?,
working_tree: None,
})
}
pub(crate) fn changed_files(
&mut self,
git_ref: &str,
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
let mut files = committed_changed_files(self.cwd, &self.toplevel, git_ref)?;
if self.working_tree.is_none() {
self.working_tree = Some(working_tree_changed_files(self.cwd, &self.toplevel)?);
}
if let Some(working_tree) = &self.working_tree {
files.extend(working_tree.iter().cloned());
}
Ok(files)
}
}
pub fn try_get_changed_files_with_toplevel(
cwd: &Path,
toplevel: &Path,
git_ref: &str,
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
let mut files = committed_changed_files(cwd, toplevel, git_ref)?;
files.extend(working_tree_changed_files(cwd, toplevel)?);
Ok(files)
}
fn committed_changed_files(
cwd: &Path,
toplevel: &Path,
git_ref: &str,
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
collect_git_paths(
cwd,
toplevel,
&[
"diff",
"--name-only",
"-z",
"--end-of-options",
&format!("{git_ref}...HEAD"),
],
)
}
fn working_tree_changed_files(
cwd: &Path,
toplevel: &Path,
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
let mut files = collect_git_paths(cwd, toplevel, &["diff", "--name-only", "-z", "HEAD"])?;
if untracked_files_excluded() {
return Ok(files);
}
files.extend(collect_git_paths(
cwd,
toplevel,
&[
"ls-files",
"--full-name",
"--others",
"--exclude-standard",
"-z",
],
)?);
Ok(files)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenamedFile {
pub from: PathBuf,
pub to: PathBuf,
}
pub fn try_get_renamed_files(
root: &Path,
git_ref: &str,
) -> Result<Vec<RenamedFile>, ChangedFilesError> {
validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
let toplevel = resolve_git_toplevel(root)?;
let mut renames = collect_git_rename_pairs(
root,
&toplevel,
&[
"diff",
"--name-status",
"-z",
"--find-renames",
"--end-of-options",
&format!("{git_ref}...HEAD"),
],
)?;
let staged = collect_git_rename_pairs(
root,
&toplevel,
&["diff", "--name-status", "-z", "--find-renames", "HEAD"],
)?;
for pair in staged {
if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
chained.to = pair.to;
} else {
renames.push(pair);
}
}
Ok(renames)
}
fn collect_git_rename_pairs(
cwd: &Path,
toplevel: &Path,
args: &[&str],
) -> Result<Vec<RenamedFile>, ChangedFilesError> {
let output = spawn_output(&mut git_command(cwd, args))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
return Err(changed_files_error_from_output(&output));
}
let mut fields = output
.stdout
.split(|byte| *byte == 0)
.filter(|field| !field.is_empty());
let mut renames = Vec::new();
while let Some(status) = fields.next() {
let Some(first_path) = fields.next() else {
break;
};
match status.first() {
Some(b'R') => {
let Some(second_path) = fields.next() else {
break;
};
renames.push(RenamedFile {
from: toplevel.join(git_path_from_bytes(first_path)),
to: toplevel.join(git_path_from_bytes(second_path)),
});
}
Some(b'C') => {
let _ = fields.next();
}
_ => {}
}
}
Ok(renames)
}
pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
changed_diff(root, git_ref, false)
}
pub fn try_get_mutation_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
changed_diff(root, git_ref, true)
}
fn changed_diff(
root: &Path,
git_ref: &str,
detect_copies: bool,
) -> Result<String, ChangedFilesError> {
validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
let toplevel = resolve_git_toplevel(root)?;
let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !merge_base_output.status.success() {
return Err(changed_files_error_from_output(&merge_base_output));
}
let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
.trim()
.to_owned();
if merge_base.is_empty() {
return Err(ChangedFilesError::GitFailed(
"git merge-base returned empty output".to_owned(),
));
}
let mut args = vec!["diff", "--relative", "--unified=0"];
if detect_copies {
args.extend(["-M", "-C"]);
}
args.extend(["--end-of-options", &merge_base]);
let output = spawn_output(&mut git_command(root, &args))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
return Err(changed_files_error_from_output(&output));
}
let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
append_untracked_diffs(root, &toplevel, &mut diff)?;
Ok(diff)
}
fn append_untracked_diffs(
root: &Path,
toplevel: &Path,
diff: &mut String,
) -> Result<(), ChangedFilesError> {
if untracked_files_excluded() {
return Ok(());
}
let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let mut untracked: Vec<PathBuf> = collect_git_paths(
root,
toplevel,
&[
"ls-files",
"--full-name",
"--others",
"--exclude-standard",
"-z",
],
)?
.into_iter()
.filter_map(|path| {
path.strip_prefix(&canonical_root)
.ok()
.map(Path::to_path_buf)
})
.collect();
untracked.sort_unstable();
#[cfg(windows)]
let empty_file = "NUL";
#[cfg(not(windows))]
let empty_file = "/dev/null";
for path in untracked {
let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
command.arg(empty_file).arg(untracked_path_arg(&path));
let output =
spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() && output.status.code() != Some(1) {
return Err(changed_files_error_from_output(&output));
}
if !diff.is_empty() && !diff.ends_with('\n') {
diff.push('\n');
}
diff.push_str(&String::from_utf8_lossy(&output.stdout));
}
Ok(())
}
fn untracked_path_arg(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
}
}
#[must_use]
#[expect(
clippy::print_stderr,
reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
)]
pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
match try_get_changed_files(root, git_ref) {
Ok(files) => Some(files),
Err(err) => {
eprintln!("Warning: {}", err.changed_since_message(git_ref));
None
}
}
}
fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
if let Some(hook) = SPAWN_HOOK.get() {
hook(command)
} else {
command.output()
}
}
fn collect_git_paths(
cwd: &Path,
toplevel: &Path,
args: &[&str],
) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
let output = spawn_output(&mut git_command(cwd, args))
.map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(if stderr.contains("not a git repository") {
ChangedFilesError::NotARepository
} else {
ChangedFilesError::GitFailed(stderr.trim().to_owned())
});
}
let files = output
.stdout
.split(|byte| *byte == 0)
.filter(|path| !path.is_empty())
.map(git_path_from_bytes)
.map(|path| toplevel.join(path))
.collect();
Ok(files)
}
#[cfg(unix)]
pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
PathBuf::from(OsString::from_vec(path.to_vec()))
}
#[cfg(windows)]
pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
}
fn git_command(cwd: &Path, args: &[&str]) -> Command {
let mut command = crate::git_env::git_command(cwd);
command.args(args);
command
}
#[expect(
clippy::implicit_hasher,
reason = "fallow standardizes on FxHashSet across the workspace"
)]
pub fn filter_results_by_changed_files(
results: &mut AnalysisResults,
changed_files: &FxHashSet<PathBuf>,
) {
filter_results_by_path_scope(results, &NormalizedChangedFiles::new(changed_files));
}
#[expect(
clippy::implicit_hasher,
reason = "fallow standardizes on FxHashSet across the workspace"
)]
pub fn filter_results_by_changed_files_keeping_unused_code(
results: &mut AnalysisResults,
changed_files: &FxHashSet<PathBuf>,
) {
keeping_unused_code(results, |results| {
filter_results_by_changed_files(results, changed_files);
});
}
pub(crate) fn keeping_unused_code(
results: &mut AnalysisResults,
filter: impl FnOnce(&mut AnalysisResults),
) {
let unused_files = std::mem::take(&mut results.unused_files);
let unused_exports = std::mem::take(&mut results.unused_exports);
filter(results);
results.unused_files = unused_files;
results.unused_exports = unused_exports;
}
pub(crate) trait ChangedPathScope {
fn contains(&self, path: &Path) -> bool;
fn contains_workspace(&self, path: &Path) -> bool {
self.contains(path)
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct NormalizedChangedFiles(FxHashSet<PathBuf>);
impl NormalizedChangedFiles {
pub(crate) fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
Self(normalize_changed_files_set(changed_files))
}
}
impl ChangedPathScope for NormalizedChangedFiles {
fn contains(&self, path: &Path) -> bool {
contains_normalized(&self.0, path)
}
fn contains_workspace(&self, path: &Path) -> bool {
normalized_set_contains_path(&self.0, path)
}
}
struct ChangedPaths<'a, S: ChangedPathScope>(&'a S);
impl<S: ChangedPathScope> ResultScope for ChangedPaths<'_, S> {
fn keeps(&self, anchor: Anchor<'_>) -> bool {
match anchor {
Anchor::Line { path, .. } | Anchor::File { path } => self.0.contains(path),
}
}
fn keeps_project_finding(&self, finding: ProjectFinding<'_>) -> bool {
match finding {
ProjectFinding::ManifestDependency { .. } | ProjectFinding::CatalogEntry => true,
ProjectFinding::EmptyCatalogGroup { path } => self.0.contains_workspace(path),
ProjectFinding::CatalogReference { path }
| ProjectFinding::DependencyOverride { path } => self.0.contains(path),
}
}
fn keeps_security_finding(&self, finding: &SecurityFinding) -> bool {
security_finding_touches_changed_path(finding, self.0)
}
fn site_rule(&self) -> SiteRule {
SiteRule::AnySite
}
fn owner_rule(&self) -> OwnerRule {
OwnerRule::TrimOwners
}
fn component_rule(&self) -> ComponentRule {
ComponentRule::All
}
}
pub(crate) fn filter_results_by_path_scope(
results: &mut AnalysisResults,
scope: &impl ChangedPathScope,
) {
crate::result_scope::retain_in_scope(results, &ChangedPaths(scope));
}
fn security_finding_touches_changed_path(
finding: &SecurityFinding,
scope: &impl ChangedPathScope,
) -> bool {
scope.contains(&finding.path)
|| finding.trace.iter().any(|hop| scope.contains(&hop.path))
|| finding.reachability.as_ref().is_some_and(|reachability| {
reachability
.untrusted_source_trace
.iter()
.any(|hop| scope.contains(&hop.path))
})
}
fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
changed_files
.iter()
.map(|p| dunce::simplified(p).to_path_buf())
.collect()
}
fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
normalized.contains(dunce::simplified(path))
}
fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
contains_normalized(normalized, path)
|| (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
}
#[expect(
clippy::implicit_hasher,
reason = "fallow standardizes on FxHashSet across the workspace"
)]
pub fn filter_duplication_by_changed_files(
report: &mut DuplicationReport,
changed_files: &FxHashSet<PathBuf>,
root: &Path,
) {
filter_duplication_by_path_scope(report, &NormalizedChangedFiles::new(changed_files), root);
}
pub(crate) fn filter_duplication_by_path_scope(
report: &mut DuplicationReport,
scope: &impl ChangedPathScope,
root: &Path,
) {
report.clone_groups.retain(|group| {
group
.instances
.iter()
.any(|instance| scope.contains(&instance.file))
});
report
.range_marker_problems
.retain(|finding| scope.contains(&finding.path));
duplicates::refresh_scoped_report(report, root);
}
#[cfg(test)]
mod tests {
use super::*;
use fallow_types::{
duplicates::{CloneGroup, CloneInstance, DuplicationStats},
output_dead_code::{
EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
UnusedFileFinding,
},
results::{
DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
},
};
#[test]
fn every_changed_files_cause_reports_its_own_reason() {
let reasons = [
ChangedFilesError::InvalidRef("unclosed brace".to_owned()).reason(),
ChangedFilesError::GitMissing("no such file".to_owned()).reason(),
ChangedFilesError::NotARepository.reason(),
ChangedFilesError::GitFailed("unknown revision".to_owned()).reason(),
];
assert_eq!(
reasons,
[
"invalid-ref",
"git-missing",
"not-a-repository",
"git-failed"
]
);
let unique: std::collections::BTreeSet<&str> = reasons.iter().copied().collect();
assert_eq!(
unique.len(),
reasons.len(),
"two causes must not share a token"
);
}
#[test]
fn the_changed_since_message_names_the_ref_the_widening_and_the_next_step() {
let message = ChangedFilesError::NotARepository.changed_since_message("origin/main");
assert!(
message.contains("--changed-since 'origin/main'"),
"{message}"
);
assert!(message.contains("covers the whole project"), "{message}");
assert!(message.ends_with("or drop --changed-since."), "{message}");
}
#[test]
fn the_changed_since_message_folds_git_stderr_onto_one_line() {
let message = ChangedFilesError::GitFailed(
"fatal: ambiguous argument 'x'\nUse '--' to separate paths".to_owned(),
)
.changed_since_message("x");
assert!(!message.contains('\n'), "{message}");
assert!(
message.contains("ambiguous argument 'x' Use '--'"),
"{message}"
);
}
#[test]
fn git_command_clears_parent_git_environment() {
let command = git_command(Path::new("."), &["status"]);
let envs: Vec<_> = command.get_envs().collect();
for var in AMBIENT_GIT_ENV_VARS {
assert!(
envs.iter()
.any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
"{var} should be cleared from the command env",
);
}
}
#[test]
fn try_get_changed_files_not_a_repository() {
let temp = tempfile::tempdir().expect("tempdir");
let result = try_get_changed_files(temp.path(), "main");
assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
}
#[test]
fn batched_refs_match_independent_changed_file_scopes() {
let repo = tempfile::tempdir().expect("tempdir");
for args in [
&["init", "--quiet"][..],
&["config", "user.email", "test@example.com"][..],
&["config", "user.name", "Test User"][..],
&["config", "commit.gpgsign", "false"][..],
] {
run_git(repo.path(), args);
}
for name in ["committed.ts", "staged.ts", "unstaged.ts"] {
std::fs::write(repo.path().join(name), "old\n").expect("initial file");
}
run_git(repo.path(), &["add", "."]);
run_git(repo.path(), &["commit", "--quiet", "-m", "base"]);
run_git(repo.path(), &["branch", "base"]);
std::fs::write(repo.path().join("committed.ts"), "new\n").expect("committed change");
run_git(repo.path(), &["add", "committed.ts"]);
run_git(repo.path(), &["commit", "--quiet", "-m", "change"]);
std::fs::write(repo.path().join("staged.ts"), "new\n").expect("staged change");
run_git(repo.path(), &["add", "staged.ts"]);
std::fs::write(repo.path().join("unstaged.ts"), "new\n").expect("unstaged change");
std::fs::write(repo.path().join("untracked.ts"), "new\n").expect("untracked file");
let mut batch = ChangedFilesBatch::new(repo.path(), "base").expect("batch");
for reference in ["base", "HEAD"] {
let batched = batch.changed_files(reference).expect("batched changes");
let independent = changed_files(repo.path(), reference).expect("independent changes");
assert_eq!(batched, independent, "{reference} scope changed");
}
}
#[cfg(unix)]
#[test]
fn changed_files_preserve_special_filenames() {
let repo = tempfile::tempdir().expect("tempdir");
for args in [
&["init", "--quiet"][..],
&["config", "user.email", "test@example.com"][..],
&["config", "user.name", "Test User"][..],
&["config", "commit.gpgsign", "false"][..],
&["config", "tag.gpgsign", "false"][..],
] {
run_git(repo.path(), args);
}
std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
run_git(repo.path(), &["add", "."]);
run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
run_git(repo.path(), &["tag", "base"]);
let canonical_root = repo.path().canonicalize().expect("canonical repo");
let special_files = [
"src/line\nbreak.ts",
"src/space name.ts",
"src/quote\"name.ts",
"src/back\\slash.ts",
"src/unicode-λ.ts",
]
.map(|path| canonical_root.join(path));
std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
for special in &special_files {
std::fs::write(special, "changed\n").expect("special fixture");
}
let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
for special in special_files {
assert!(
changed.contains(&special),
"missing {special:?}: {changed:?}"
);
}
}
#[cfg(windows)]
#[test]
fn git_path_bytes_use_windows_separators() {
assert_eq!(
git_path_from_bytes(b"src/nested/file.ts"),
PathBuf::from(r"src\nested\file.ts")
);
}
#[test]
fn changed_diff_covers_staged_unstaged_and_untracked_files() {
let repo = tempfile::tempdir().expect("tempdir");
for args in [
&["init", "--quiet"][..],
&["config", "user.email", "test@example.com"][..],
&["config", "user.name", "Test User"][..],
&["config", "commit.gpgsign", "false"][..],
&["config", "tag.gpgsign", "false"][..],
] {
run_git(repo.path(), args);
}
std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
run_git(repo.path(), &["add", "."]);
run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
run_git(repo.path(), &["tag", "base"]);
std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
run_git(repo.path(), &["add", "committed.ts"]);
run_git(
repo.path(),
&["commit", "--quiet", "-m", "committed change"],
);
std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
run_git(repo.path(), &["add", "staged.ts"]);
std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
for diff in [
try_get_changed_diff(repo.path(), "base"),
try_get_mutation_diff(repo.path(), "base"),
] {
let diff = diff.expect("complete changeset diff");
let index = fallow_output::DiffIndex::from_unified_diff(&diff);
assert!(diff.contains("b/committed.ts"), "{diff}");
assert!(diff.contains("b/staged.ts"), "{diff}");
assert!(diff.contains("b/unstaged.ts"), "{diff}");
assert!(diff.contains("b/untracked.ts"), "{diff}");
assert_eq!(index.hunk_count(), 4);
assert_eq!(index.net_lines(), 2);
}
}
fn run_git(root: &Path, args: &[&str]) {
let output = crate::git_fixture::fixture_git_command_with_identity(
root,
crate::git_fixture::FixtureIdentity::RepositoryConfig,
)
.args(args)
.output()
.expect("git command");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn untracked_path_arg_uses_forward_slashes() {
assert_eq!(
super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
"src/nested/b.ts"
);
assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
}
#[test]
fn changed_files_error_describe_matches_core_contract() {
assert_eq!(
ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
"invalid git ref: bad ref"
);
assert_eq!(
ChangedFilesError::GitMissing("not found".to_string()).describe(),
"failed to run git: not found"
);
assert_eq!(
ChangedFilesError::NotARepository.describe(),
"not a git repository"
);
assert!(
ChangedFilesError::GitFailed("unknown revision main".to_string())
.describe()
.contains("fetch-depth: 0")
);
}
#[test]
fn filter_results_keeps_only_changed_file_findings() {
let mut results = AnalysisResults::default();
results
.unused_files
.push(UnusedFileFinding::with_actions(UnusedFile {
path: PathBuf::from("/repo/a.ts"),
}));
results
.unused_files
.push(UnusedFileFinding::with_actions(UnusedFile {
path: PathBuf::from("/repo/b.ts"),
}));
results
.unused_exports
.push(UnusedExportFinding::with_actions(UnusedExport {
path: PathBuf::from("/repo/a.ts"),
export_name: "foo".to_owned(),
is_type_only: false,
line: 1,
col: 0,
span_start: 0,
is_re_export: false,
deprecated: false,
deprecated_reason: None,
}));
let mut changed = FxHashSet::default();
changed.insert(PathBuf::from("/repo/a.ts"));
filter_results_by_changed_files(&mut results, &changed);
assert_eq!(results.unused_files.len(), 1);
assert_eq!(
results.unused_files[0].file.path,
PathBuf::from("/repo/a.ts")
);
assert_eq!(results.unused_exports.len(), 1);
}
#[test]
fn filter_results_preserves_graph_global_dependency_findings() {
let mut results = AnalysisResults::default();
results
.unused_dependencies
.push(UnusedDependencyFinding::with_actions(UnusedDependency {
package_name: "lodash".to_owned(),
location: DependencyLocation::Dependencies,
path: PathBuf::from("/repo/package.json"),
line: 3,
used_in_workspaces: Vec::new(),
declared_and_imported_in: Vec::new(),
}));
let changed = FxHashSet::default();
filter_results_by_changed_files(&mut results, &changed);
assert_eq!(results.unused_dependencies.len(), 1);
}
#[test]
fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
let finding = |path: &str| {
fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
fallow_types::results::DeprecatedExportInUse {
path: PathBuf::from(path),
export_name: "old".to_owned(),
is_type_only: false,
line: 2,
col: 0,
span_start: 0,
deprecated_reason: None,
consumer_count: 1,
consumers: vec![fallow_types::results::DeprecatedExportConsumer {
path: PathBuf::from("/repo/consumer.ts"),
line: 1,
col: 0,
kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
}],
public_api: false,
},
)
};
let mut results = AnalysisResults::default();
results
.deprecated_exports_in_use
.push(finding("/repo/a.ts"));
results
.deprecated_exports_in_use
.push(finding("/repo/b.ts"));
let mut changed = FxHashSet::default();
changed.insert(PathBuf::from("/repo/a.ts"));
changed.insert(PathBuf::from("/repo/consumer.ts"));
filter_results_by_changed_files(&mut results, &changed);
let kept: Vec<_> = results
.deprecated_exports_in_use
.iter()
.map(|f| f.export.path.clone())
.collect();
assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
}
#[test]
fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
let mut results = AnalysisResults::default();
results
.empty_catalog_groups
.push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
catalog_name: "legacy".to_owned(),
path: PathBuf::from("pnpm-workspace.yaml"),
line: 4,
}));
let mut changed = FxHashSet::default();
changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
filter_results_by_changed_files(&mut results, &changed);
assert_eq!(results.empty_catalog_groups.len(), 1);
}
#[test]
fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
let mut report = DuplicationReport {
clone_groups: vec![
CloneGroup {
instances: vec![
CloneInstance {
is_symlink: false,
file: PathBuf::from("/repo/a.ts"),
start_line: 1,
end_line: 5,
start_col: 0,
end_col: 10,
fragment: "code".to_owned(),
},
CloneInstance {
is_symlink: false,
file: PathBuf::from("/repo/b.ts"),
start_line: 1,
end_line: 5,
start_col: 0,
end_col: 10,
fragment: "code".to_owned(),
},
],
token_count: 20,
line_count: 5,
similarity: None,
},
CloneGroup {
instances: vec![
CloneInstance {
is_symlink: false,
file: PathBuf::from("/repo/c.ts"),
start_line: 1,
end_line: 5,
start_col: 0,
end_col: 10,
fragment: "other".to_owned(),
},
CloneInstance {
is_symlink: false,
file: PathBuf::from("/repo/d.ts"),
start_line: 1,
end_line: 5,
start_col: 0,
end_col: 10,
fragment: "other".to_owned(),
},
],
token_count: 20,
line_count: 5,
similarity: None,
},
],
clone_families: Vec::new(),
mirrored_directories: Vec::new(),
range_marker_problems: Vec::new(),
stats: DuplicationStats {
total_files: 4,
files_with_clones: 4,
total_lines: 100,
duplicated_lines: 20,
total_tokens: 200,
duplicated_tokens: 80,
clone_groups: 2,
clone_families: 0,
clone_instances: 4,
duplication_percentage: 20.0,
clone_groups_below_min_occurrences: 0,
clone_groups_ignored: 0,
near_candidates_skipped: 0,
},
};
let mut changed = FxHashSet::default();
changed.insert(PathBuf::from("/repo/a.ts"));
filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
assert_eq!(report.clone_groups.len(), 1);
assert_eq!(report.stats.clone_groups, 1);
assert_eq!(report.stats.clone_instances, 2);
}
#[test]
fn changed_file_scope_orders_families_by_file_set() {
let group = |files: [&str; 2], line_count: usize| CloneGroup {
instances: files
.iter()
.map(|file| CloneInstance {
is_symlink: false,
file: PathBuf::from(file),
start_line: 1,
end_line: line_count,
start_col: 0,
end_col: 10,
fragment: String::new(),
})
.collect(),
token_count: line_count * 10,
line_count,
similarity: None,
};
let mut report = DuplicationReport {
clone_groups: vec![
group(["/repo/y.ts", "/repo/z.ts"], 46),
group(["/repo/a.ts", "/repo/b.ts"], 7),
],
clone_families: Vec::new(),
mirrored_directories: Vec::new(),
range_marker_problems: Vec::new(),
stats: DuplicationStats::default(),
};
let changed: FxHashSet<PathBuf> = ["/repo/a.ts", "/repo/y.ts"]
.into_iter()
.map(PathBuf::from)
.collect();
filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
let order: Vec<&PathBuf> = report
.clone_families
.iter()
.map(|family| &family.files[0])
.collect();
assert_eq!(
order,
[&PathBuf::from("/repo/a.ts"), &PathBuf::from("/repo/y.ts")]
);
}
#[test]
fn one_probe_resolves_the_common_dir_and_the_toplevel() {
let repo = tempfile::tempdir().expect("tempdir");
run_git(repo.path(), &["init", "--quiet"]);
let nested = repo.path().join("packages/app");
std::fs::create_dir_all(&nested).expect("nested dir");
for cwd in [repo.path(), nested.as_path()] {
let (common, toplevel) =
resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
}
}
#[test]
fn the_combined_probe_fails_without_a_work_tree() {
let repo = tempfile::tempdir().expect("tempdir");
run_git(repo.path(), &["init", "--quiet", "--bare"]);
assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
assert!(resolve_git_common_dir(repo.path()).is_err());
}
}