From d57a8a1ffb49362d722c209b3cb7baabc7ffcc60 Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Tue, 1 Dec 2026 04:00:09 +0000 Subject: [PATCH 1/7] fix(git): limit comparisons by literal pathspecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- rust/contracts/rust-core-api.md | 14 +++-- rust/crates/core/src/tests/git.rs | 53 +++++++++++++++++++ rust/crates/git/src/commits.rs | 49 ++++++++++++----- rust/crates/git/src/requests.rs | 3 ++ .../fixtures/git/comparison-pathspecs-v1.json | 10 ++++ 5 files changed, 110 insertions(+), 19 deletions(-) create mode 100644 rust/fixtures/git/comparison-pathspecs-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5c8b5545..3af2fcb2 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2171,12 +2171,16 @@ range comparisons. `git.comparison` accepts `root` plus the same `reference` or `gitReference` / `targetGitReference` forms and returns the deterministically ordered changed -files. `includeUntracked: true` adds untracked worktree files with status `A` -and `isUntracked: true`, deduplicated by path; omitted or false keeps the -previous response. The flag is invalid for a two-reference range. If status +files. Optional `pathspecs` limit both sides of the comparison as literal +repository-relative paths; naming a directory covers the paths below it, and +omitting the list keeps the whole-repository response. `includeUntracked: true` +adds untracked worktree files with status `A` and `isUntracked: true`, +deduplicated by path and limited by the same pathspecs; omitted or false keeps +the previous response. The flag is invalid for a two-reference range. If status cannot be read, the request fails rather than returning an incomplete result. -See `rust/fixtures/git/comparison-untracked-v1.json`. Platforms must not -construct a two-ref range themselves. +See `rust/fixtures/git/comparison-untracked-v1.json` and +`rust/fixtures/git/comparison-pathspecs-v1.json`. Platforms must not construct +a two-ref range themselves. `git.apply` accepts `root`, `patch`, and `mode`; supported modes are `stage`, `unstage`, `discard`, `restoreIndex`, `worktree`, `restoreIndexCheck`, and `worktreeCheck`. The two `*Check` modes only test whether the reverse patch diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index c947f7f6..c2c94e98 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -229,6 +229,59 @@ fn git_comparison_can_include_untracked_worktree_files() { assert_eq!(range_response["error"]["code"], "invalid_request"); } +#[test] +fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let root = temporary_root("comparison-pathspecs"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(&root).unwrap(); + let run = |arguments: &[&str]| { + let result = Command::new("git") + .args(arguments) + .current_dir(&root) + .output() + .unwrap(); + assert!( + result.status.success(), + "{:?}: {}", + arguments, + String::from_utf8_lossy(&result.stderr) + ); + }; + run(&["init", "--template=", "-q"]); + run(&["config", "core.autocrlf", "false"]); + run(&["config", "user.name", "Lithe Test"]); + run(&["config", "user.email", "test@example.com"]); + fs::write(root.join("a-first.txt"), "before\n").unwrap(); + fs::write(root.join("z-target.txt"), "before\n").unwrap(); + run(&["add", "a-first.txt", "z-target.txt"]); + run(&["-c", "commit.gpgsign=false", "commit", "-qm", "initial"]); + fs::write(root.join("a-first.txt"), "after\n").unwrap(); + fs::write(root.join("z-target.txt"), "after\n").unwrap(); + fs::write(root.join("a-untracked.txt"), "new\n").unwrap(); + + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/git/comparison-pathspecs-v1.json" + )) + .unwrap(); + let mut payload = fixture["request"].clone(); + payload["root"] = serde_json::json!(root); + let response: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-pathspecs", "command": "git.comparison", "payload": payload + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["files"], fixture["expected"]); +} + #[test] fn git_status_returns_contract_shape() { let root = temporary_root("git"); diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 4d84e3cb..e4ab3ba8 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -262,17 +262,26 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result Result bool { + let pathspec = pathspec.trim_end_matches('/'); + path == pathspec + || path + .strip_prefix(pathspec) + .is_some_and(|rest| rest.starts_with('/')) +} + pub(crate) fn commit_selected_paths( root: &str, paths: Vec, diff --git a/rust/crates/git/src/requests.rs b/rust/crates/git/src/requests.rs index d86d21c2..09d1c7ab 100644 --- a/rust/crates/git/src/requests.rs +++ b/rust/crates/git/src/requests.rs @@ -471,6 +471,9 @@ pub struct GitComparisonRequest { /// Include untracked worktree files; incompatible with reference-to-reference comparisons. #[serde(default)] pub include_untracked: bool, + /// Optional literal pathspecs limiting the comparison. + #[serde(default)] + pub pathspecs: Vec, } #[derive(Debug, Deserialize)] diff --git a/rust/fixtures/git/comparison-pathspecs-v1.json b/rust/fixtures/git/comparison-pathspecs-v1.json new file mode 100644 index 00000000..37fbb0f4 --- /dev/null +++ b/rust/fixtures/git/comparison-pathspecs-v1.json @@ -0,0 +1,10 @@ +{ + "request": { + "reference": "HEAD", + "includeUntracked": true, + "pathspecs": ["z-target.txt"] + }, + "expected": [ + { "path": "z-target.txt", "status": "M" } + ] +} From 310dd22226b9a1b083442bae3be1457ff32b878a Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Tue, 1 Dec 2026 04:24:24 +0000 Subject: [PATCH 2/7] fix(git): normalize comparison pathspecs for untracked files Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- rust/contracts/rust-core-api.md | 5 +++-- rust/crates/core/src/tests/git.rs | 29 +++++++++++++++++++++++++++++ rust/crates/git/src/commits.rs | 14 +++++++++++--- 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 3af2fcb2..8cb62317 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2172,8 +2172,9 @@ range comparisons. `git.comparison` accepts `root` plus the same `reference` or `gitReference` / `targetGitReference` forms and returns the deterministically ordered changed files. Optional `pathspecs` limit both sides of the comparison as literal -repository-relative paths; naming a directory covers the paths below it, and -omitting the list keeps the whole-repository response. `includeUntracked: true` +repository-relative paths; naming a directory covers the paths below it, `.` +names the repository root, and empty or `.` path components are normalized as +in Git. Omitting the list keeps the whole-repository response. `includeUntracked: true` adds untracked worktree files with status `A` and `isUntracked: true`, deduplicated by path and limited by the same pathspecs; omitted or false keeps the previous response. The flag is invalid for a two-reference range. If status diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index c2c94e98..a3e20055 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -280,6 +280,35 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { .unwrap(); assert_eq!(response["ok"], true, "{response}"); assert_eq!(response["data"]["files"], fixture["expected"]); + + let compare_paths = |pathspecs: &[&str]| { + let response: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-pathspecs-normalized", + "command": "git.comparison", + "payload": { + "root": root.clone(), + "reference": "HEAD", + "includeUntracked": true, + "pathspecs": pathspecs, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{response}"); + response["data"]["files"] + .as_array() + .unwrap() + .iter() + .map(|file| file["path"].as_str().unwrap().to_string()) + .collect::>() + }; + assert_eq!( + compare_paths(&["."]), + vec!["a-first.txt", "a-untracked.txt", "z-target.txt"] + ); + assert_eq!(compare_paths(&["./z-target.txt"]), vec!["z-target.txt"]); } #[test] diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index e4ab3ba8..cc417d05 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -325,12 +325,20 @@ pub fn comparison(request: GitComparisonRequest) -> Result bool { - let pathspec = pathspec.trim_end_matches('/'); + let components = pathspec + .split('/') + .filter(|component| !component.is_empty() && *component != ".") + .collect::>(); + if components.is_empty() { + return true; + } + let pathspec = components.join("/"); path == pathspec || path - .strip_prefix(pathspec) + .strip_prefix(&pathspec) .is_some_and(|rest| rest.starts_with('/')) } From 85939c42e7b3b18776d761a4542331c56b67d501 Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Tue, 1 Dec 2026 04:28:54 +0000 Subject: [PATCH 3/7] fix(git): resolve comparison pathspecs from repository roots Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- rust/contracts/rust-core-api.md | 3 ++- rust/crates/core/src/tests/git.rs | 16 ++++++++++++---- rust/crates/git/src/commits.rs | 7 ++++++- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8cb62317..4a68cd6f 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2174,7 +2174,8 @@ range comparisons. files. Optional `pathspecs` limit both sides of the comparison as literal repository-relative paths; naming a directory covers the paths below it, `.` names the repository root, and empty or `.` path components are normalized as -in Git. Omitting the list keeps the whole-repository response. `includeUntracked: true` +in Git. They remain repository-relative when `root` is a subdirectory of the +repository. Omitting the list keeps the whole-repository response. `includeUntracked: true` adds untracked worktree files with status `A` and `isUntracked: true`, deduplicated by path and limited by the same pathspecs; omitted or false keeps the previous response. The flag is invalid for a two-reference range. If status diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index a3e20055..c1914ec3 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -264,6 +264,7 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { fs::write(root.join("a-first.txt"), "after\n").unwrap(); fs::write(root.join("z-target.txt"), "after\n").unwrap(); fs::write(root.join("a-untracked.txt"), "new\n").unwrap(); + fs::create_dir(root.join("subdirectory")).unwrap(); let fixture: Value = serde_json::from_str(include_str!( "../../../../fixtures/git/comparison-pathspecs-v1.json" @@ -281,13 +282,13 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { assert_eq!(response["ok"], true, "{response}"); assert_eq!(response["data"]["files"], fixture["expected"]); - let compare_paths = |pathspecs: &[&str]| { + let compare_paths = |command_root: std::path::PathBuf, pathspecs: &[&str]| { let response: Value = serde_json::from_str(&execute_json( &serde_json::json!({ "id": "comparison-pathspecs-normalized", "command": "git.comparison", "payload": { - "root": root.clone(), + "root": command_root, "reference": "HEAD", "includeUntracked": true, "pathspecs": pathspecs, @@ -305,10 +306,17 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { .collect::>() }; assert_eq!( - compare_paths(&["."]), + compare_paths(root.clone(), &["."]), + vec!["a-first.txt", "a-untracked.txt", "z-target.txt"] + ); + assert_eq!( + compare_paths(root.clone(), &["./z-target.txt"]), + vec!["z-target.txt"] + ); + assert_eq!( + compare_paths(root.join("subdirectory"), &["."]), vec!["a-first.txt", "a-untracked.txt", "z-target.txt"] ); - assert_eq!(compare_paths(&["./z-target.txt"]), vec!["z-target.txt"]); } #[test] diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index cc417d05..68958e14 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -279,8 +279,13 @@ pub fn comparison(request: GitComparisonRequest) -> Result Date: Wed, 2 Dec 2026 05:21:04 +0000 Subject: [PATCH 4/7] fix(git): keep scoped ref comparisons working in bare repositories Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- rust/contracts/rust-core-api.md | 3 ++- rust/crates/core/src/tests/git.rs | 29 +++++++++++++++++++++++++++++ rust/crates/git/src/commits.rs | 2 +- rust/crates/git/src/repository.rs | 22 ++++++++++++++++++++++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4a68cd6f..04068065 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2175,7 +2175,8 @@ files. Optional `pathspecs` limit both sides of the comparison as literal repository-relative paths; naming a directory covers the paths below it, `.` names the repository root, and empty or `.` path components are normalized as in Git. They remain repository-relative when `root` is a subdirectory of the -repository. Omitting the list keeps the whole-repository response. `includeUntracked: true` +repository, and they also limit two-reference tree comparisons in bare +repositories. Omitting the list keeps the whole-repository response. `includeUntracked: true` adds untracked worktree files with status `A` and `isUntracked: true`, deduplicated by path and limited by the same pathspecs; omitted or false keeps the previous response. The flag is invalid for a two-reference range. If status diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index c1914ec3..f323a4a3 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -261,6 +261,10 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { fs::write(root.join("z-target.txt"), "before\n").unwrap(); run(&["add", "a-first.txt", "z-target.txt"]); run(&["-c", "commit.gpgsign=false", "commit", "-qm", "initial"]); + fs::write(root.join("a-first.txt"), "committed\n").unwrap(); + fs::write(root.join("z-target.txt"), "committed\n").unwrap(); + run(&["add", "a-first.txt", "z-target.txt"]); + run(&["-c", "commit.gpgsign=false", "commit", "-qm", "committed"]); fs::write(root.join("a-first.txt"), "after\n").unwrap(); fs::write(root.join("z-target.txt"), "after\n").unwrap(); fs::write(root.join("a-untracked.txt"), "new\n").unwrap(); @@ -317,6 +321,31 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { compare_paths(root.join("subdirectory"), &["."]), vec!["a-first.txt", "a-untracked.txt", "z-target.txt"] ); + + run(&["clone", "--bare", ".", "bare"]); + let bare_response: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-pathspecs-bare", + "command": "git.comparison", + "payload": { + "root": root.join("bare"), + "reference": "HEAD~1..HEAD", + "pathspecs": ["z-target.txt"], + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(bare_response["ok"], true, "{bare_response}"); + assert_eq!( + bare_response["data"]["files"] + .as_array() + .unwrap() + .iter() + .map(|file| file["path"].as_str().unwrap().to_string()) + .collect::>(), + vec!["z-target.txt"] + ); } #[test] diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 68958e14..1ae08570 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -279,7 +279,7 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result { git_resolved_path(root, &["rev-parse", "--show-toplevel"], "repository root") } +pub(crate) fn repository_is_bare(root: &str) -> Result { + let response = execute_git_readonly( + root, + &["rev-parse".into(), "--is-bare-repository".into()], + None, + )?; + if response.exit_code != 0 { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "Could not inspect repository") + .with_details(response.output), + ); + } + match response.stdout.trim() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(CoreError::new( + ErrorCode::ProcessFailed, + "Could not inspect repository", + )), + } +} + pub(crate) fn git_path(root: &str, path: &str) -> Result { git_resolved_path( root, From 24aa95dd0ef9c194483f04f9f7086b9468dccf4d Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 1 Dec 2026 23:14:19 -0800 Subject: [PATCH 5/7] fix(git): support exactPaths and direct ls-files filtering in git.comparison --- rust/contracts/rust-core-api.md | 6 +- rust/crates/core/src/tests/git.rs | 118 ++++++++++++++++ rust/crates/git/src/commits.rs | 214 ++++++++++++++++++++++-------- rust/crates/git/src/requests.rs | 5 + 4 files changed, 290 insertions(+), 53 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c9a29a4e..252395fe 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2180,7 +2180,11 @@ range comparisons. files. Optional `pathspecs` limit both sides of the comparison as literal repository-relative paths; naming a directory covers the paths below it, `.` names the repository root, and empty or `.` path components are normalized as -in Git. They remain repository-relative when `root` is a subdirectory of the +in Git. Optional `exactPaths: true` restricts each pathspec to exact entries at +that pathspec's depth (excluding descendants when the compared reference has a +directory at the same path) while preserving Git's repository path normalization +(`core.precomposeUnicode`, `core.ignorecase`); it requires at least one non-root +pathspec. They remain repository-relative when `root` is a subdirectory of the repository, and they also limit two-reference tree comparisons in bare repositories. Omitting the list keeps the whole-repository response. `includeUntracked: true` adds untracked worktree files with status `A` and `isUntracked: true`, diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index f323a4a3..50e56bc7 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -348,6 +348,124 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { ); } +#[test] +fn git_comparison_exact_paths_exclude_same_named_directory_contents() { + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let root = temporary_root("comparison-exact-paths"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(&root).unwrap(); + let run = |arguments: &[&str]| { + let result = Command::new("git") + .args(arguments) + .current_dir(&root) + .output() + .unwrap(); + assert!( + result.status.success(), + "{:?}: {}", + arguments, + String::from_utf8_lossy(&result.stderr) + ); + }; + run(&["init", "--template=", "-q"]); + run(&["config", "core.autocrlf", "false"]); + run(&["config", "user.name", "Lithe Test"]); + run(&["config", "user.email", "test@example.com"]); + fs::create_dir_all(root.join("z-target.txt")).unwrap(); + fs::write(root.join("z-target.txt/nested.txt"), "nested\n").unwrap(); + fs::create_dir_all(root.join("u-target.txt")).unwrap(); + fs::write(root.join("u-target.txt/nested.txt"), "nested\n").unwrap(); + fs::create_dir_all(root.join("sub")).unwrap(); + fs::write(root.join("sub/other.txt"), "before\n").unwrap(); + run(&["add", "."]); + run(&["-c", "commit.gpgsign=false", "commit", "-qm", "directories"]); + run(&["branch", "dir-branch"]); + + // Replace both directories with regular files (one tracked, one untracked). + fs::remove_dir_all(root.join("z-target.txt")).unwrap(); + fs::remove_dir_all(root.join("u-target.txt")).unwrap(); + fs::write(root.join("z-target.txt"), "tracked\n").unwrap(); + run(&["add", "z-target.txt"]); + run(&[ + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "tracked file", + ]); + fs::write(root.join("z-target.txt"), "tracked-edit\n").unwrap(); + fs::write(root.join("u-target.txt"), "untracked\n").unwrap(); + fs::write(root.join("sub/other.txt"), "after\n").unwrap(); + + // Without exactPaths, pathspecs include the former directory's nested entry. + let broad: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-broad", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "dir-branch", + "includeUntracked": true, + "pathspecs": ["z-target.txt"], + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(broad["ok"], true, "{broad}"); + assert_eq!(broad["data"]["files"].as_array().unwrap().len(), 2); + + // With exactPaths, tracked and untracked files match while z-target.txt/nested.txt is excluded, + // even when combined with a deeper pathspec (sub/other.txt). + let exact: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-exact", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "dir-branch", + "includeUntracked": true, + "pathspecs": ["z-target.txt", "u-target.txt", "sub/other.txt"], + "exactPaths": true, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(exact["ok"], true, "{exact}"); + let files = exact["data"]["files"].as_array().unwrap(); + let paths: Vec<_> = files + .iter() + .map(|file| file["path"].as_str().unwrap()) + .collect(); + assert_eq!(paths, vec!["sub/other.txt", "u-target.txt", "z-target.txt"]); + assert_eq!(files[1]["isUntracked"], true); + + for invalid_pathspecs in [serde_json::json!([]), serde_json::json!(["."])] { + let invalid: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-exact-invalid", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "dir-branch", + "pathspecs": invalid_pathspecs, + "exactPaths": true, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(invalid["ok"], false, "{invalid}"); + assert_eq!(invalid["error"]["code"], "invalid_request"); + } +} + #[test] fn git_status_returns_contract_shape() { let root = temporary_root("git"); diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 1ae08570..51857d27 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -267,6 +267,88 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result, CoreError> { let mut arguments = vec!["-c".to_string(), "core.quotepath=false".to_string()]; if !pathspecs.is_empty() { arguments.push("--literal-pathspecs".to_string()); @@ -275,17 +357,12 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result Result, CoreError> { + let mut arguments = vec![ + "-c".to_string(), + "core.quotepath=false".to_string(), + "--literal-pathspecs".to_string(), + "ls-files".to_string(), + "--others".to_string(), + "--exclude-standard".to_string(), + "-z".to_string(), + "--".to_string(), + ]; + arguments.extend(pathspecs.iter().cloned()); + let response = readonly_command(GitCommandRequest { + root: command_root.to_string(), + arguments, + input: None, })?; - let mut by_path: std::collections::BTreeMap<_, _> = files - .into_iter() - .map(|file| (file.path.clone(), file)) - .collect(); - for change in snapshot.changes.into_iter().filter(|change| { - change.untracked - && (pathspecs.is_empty() - || pathspecs - .iter() - .any(|pathspec| literal_pathspec_matches(pathspec, &change.path))) - }) { - by_path - .entry(change.path.clone()) - .or_insert(GitFileResponse { - status: "A".into(), - path: change.path, - is_untracked: true, - }); + if response.exit_code != 0 { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "Git comparison failed") + .with_details(response.output), + ); } - Ok(GitComparisonResponse { - files: by_path.into_values().collect(), - }) + Ok(response + .stdout + .split('\0') + .filter(|path| !path.is_empty()) + .map(|path| GitFileResponse { + status: "A".into(), + path: path.to_string(), + is_untracked: true, + }) + .collect()) } -/// Matches a repository-relative status path against a literal pathspec. As in -/// Git, naming a directory also covers everything below it, and `.` or empty -/// path components do not change the pathspec. -fn literal_pathspec_matches(pathspec: &str, path: &str) -> bool { - let components = pathspec - .split('/') +/// Counts normalized non-root path components so exact-path comparisons can drop +/// descendants of a same-named former directory without rejecting Git's Unicode +/// or case normalization. +fn normalized_path_depth(path: &str) -> usize { + path.split('/') .filter(|component| !component.is_empty() && *component != ".") - .collect::>(); - if components.is_empty() { - return true; - } - let pathspec = components.join("/"); - path == pathspec - || path - .strip_prefix(&pathspec) - .is_some_and(|rest| rest.starts_with('/')) + .count() +} + +fn filter_exact_depth(files: Vec, depth: usize) -> Vec { + files + .into_iter() + .filter(|file| normalized_path_depth(&file.path) == depth) + .collect() } pub(crate) fn commit_selected_paths( @@ -706,3 +788,31 @@ pub(crate) fn required_text(value: Option<&str>, label: &str) -> Result, + /// When true, keep only entries at the exact depth of each pathspec instead + /// of descending into directories of the same name, while preserving Git's + /// repository path normalization (`core.precomposeUnicode`, `core.ignorecase`). + #[serde(default)] + pub exact_paths: bool, } #[derive(Debug, Deserialize)] From d038499decca0393720f073fa67cdfdf6ec5dc82 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 1 Dec 2026 23:32:09 -0800 Subject: [PATCH 6/7] fix(git): handle renames, ignorecase, and trailing dots in git.comparison --- rust/Cargo.lock | 1 + rust/crates/core/src/tests/git.rs | 66 +++++++++++ rust/crates/git/Cargo.toml | 1 + rust/crates/git/src/commits.rs | 180 ++++++++++++++++++------------ 4 files changed, 178 insertions(+), 70 deletions(-) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 66cf5b38..64fd3eb5 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1181,6 +1181,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "unicode-normalization", ] [[package]] diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index 50e56bc7..6bdbdf71 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -317,6 +317,10 @@ fn git_comparison_pathspecs_limit_tracked_and_untracked_files() { compare_paths(root.clone(), &["./z-target.txt"]), vec!["z-target.txt"] ); + assert_eq!( + compare_paths(root.clone(), &["a-untracked.txt/."]), + vec!["a-untracked.txt"] + ); assert_eq!( compare_paths(root.join("subdirectory"), &["."]), vec!["a-first.txt", "a-untracked.txt", "z-target.txt"] @@ -464,6 +468,68 @@ fn git_comparison_exact_paths_exclude_same_named_directory_contents() { assert_eq!(invalid["ok"], false, "{invalid}"); assert_eq!(invalid["error"]["code"], "invalid_request"); } + + // Selecting both endpoints of a rename with exactPaths keeps the rename pairing. + fs::write(root.join("old.txt"), "same content\n").unwrap(); + run(&["add", "old.txt"]); + run(&[ + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "before rename", + ]); + run(&["mv", "old.txt", "new.txt"]); + let rename: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-exact-rename", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "HEAD", + "pathspecs": ["old.txt", "new.txt"], + "exactPaths": true, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(rename["ok"], true, "{rename}"); + let rename_files = rename["data"]["files"].as_array().unwrap(); + assert_eq!(rename_files.len(), 1); + assert!(rename_files[0]["status"].as_str().unwrap().starts_with('R')); + assert_eq!(rename_files[0]["path"], "new.txt"); + + // With core.ignorecase=true, differently cased exact pathspecs match tracked and untracked files. + run(&["config", "core.ignorecase", "true"]); + fs::write(root.join("Readme.md"), "before\n").unwrap(); + run(&["add", "Readme.md"]); + run(&["-c", "commit.gpgsign=false", "commit", "-qm", "case file"]); + fs::write(root.join("Readme.md"), "after\n").unwrap(); + fs::write(root.join("OtherCase.txt"), "untracked\n").unwrap(); + let icase: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-exact-icase", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "HEAD", + "includeUntracked": true, + "pathspecs": ["README.md", "OTHERCASE.TXT"], + "exactPaths": true, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(icase["ok"], true, "{icase}"); + let icase_paths: Vec<_> = icase["data"]["files"] + .as_array() + .unwrap() + .iter() + .map(|file| file["path"].as_str().unwrap()) + .collect(); + assert_eq!(icase_paths, vec!["OtherCase.txt", "Readme.md"]); } #[test] diff --git a/rust/crates/git/Cargo.toml b/rust/crates/git/Cargo.toml index 3e3214c7..3264b69c 100644 --- a/rust/crates/git/Cargo.toml +++ b/rust/crates/git/Cargo.toml @@ -28,3 +28,4 @@ regex = "1.11" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } sha2 = "0.10" +unicode-normalization = "0.1" diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 51857d27..327640e1 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -266,12 +266,12 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result = pathspecs + .iter() + .map(|pathspec| format_literal_pathspec(pathspec, ignore_case)) + .collect(); + let files = comparison_diff(&command_root, &reference, &git_pathspecs)?; + let precompose_unicode = if request.exact_paths { + git_bool_config(&command_root, "core.precomposeunicode")? + } else { + false + }; + let exact_keys: std::collections::HashSet = if request.exact_paths { + pathspecs + .iter() + .map(|pathspec| canonical_comparison_key(pathspec, ignore_case, precompose_unicode)) + .collect() + } else { + std::collections::HashSet::new() + }; + let filter_files = |items: Vec| -> Vec { + if !request.exact_paths { + return items; } - return Ok(GitComparisonResponse { - files: by_path.into_values().collect(), - }); - } - let files = comparison_diff(&command_root, &reference, &pathspecs)?; + items + .into_iter() + .filter(|file| { + exact_keys.contains(&canonical_comparison_key( + &file.path, + ignore_case, + precompose_unicode, + )) + }) + .collect() + }; + let files = filter_files(files); if !request.include_untracked { return Ok(GitComparisonResponse { files }); } + let mut by_path = std::collections::BTreeMap::new(); for file in files { by_path.insert(file.path.clone(), file); } @@ -335,7 +346,10 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result Result, CoreError> { - let mut arguments = vec!["-c".to_string(), "core.quotepath=false".to_string()]; - if !pathspecs.is_empty() { - arguments.push("--literal-pathspecs".to_string()); - } - arguments.extend([ + let mut arguments = vec![ + "-c".to_string(), + "core.quotepath=false".to_string(), "diff".to_string(), "--name-status".to_string(), "--find-renames".to_string(), reference.to_string(), "--".to_string(), - ]); - arguments.extend(pathspecs.iter().cloned()); + ]; + arguments.extend(git_pathspecs.iter().cloned()); let response = readonly_command(GitCommandRequest { root: command_root.to_string(), arguments, @@ -377,19 +389,18 @@ fn comparison_diff( fn comparison_untracked_for_pathspec( command_root: &str, - pathspecs: &[String], + git_pathspecs: &[String], ) -> Result, CoreError> { let mut arguments = vec![ "-c".to_string(), "core.quotepath=false".to_string(), - "--literal-pathspecs".to_string(), "ls-files".to_string(), "--others".to_string(), "--exclude-standard".to_string(), "-z".to_string(), "--".to_string(), ]; - arguments.extend(pathspecs.iter().cloned()); + arguments.extend(git_pathspecs.iter().cloned()); let response = readonly_command(GitCommandRequest { root: command_root.to_string(), arguments, @@ -413,20 +424,51 @@ fn comparison_untracked_for_pathspec( .collect()) } -/// Counts normalized non-root path components so exact-path comparisons can drop -/// descendants of a same-named former directory without rejecting Git's Unicode -/// or case normalization. -fn normalized_path_depth(path: &str) -> usize { - path.split('/') +fn normalize_comparison_pathspec(pathspec: &str) -> String { + let components: Vec<_> = pathspec + .split('/') .filter(|component| !component.is_empty() && *component != ".") - .count() + .collect(); + if components.is_empty() { + ".".to_string() + } else { + components.join("/") + } +} + +fn format_literal_pathspec(pathspec: &str, ignore_case: bool) -> String { + if ignore_case { + format!(":(literal,icase){pathspec}") + } else { + format!(":(literal){pathspec}") + } } -fn filter_exact_depth(files: Vec, depth: usize) -> Vec { - files - .into_iter() - .filter(|file| normalized_path_depth(&file.path) == depth) - .collect() +fn git_bool_config(root: &str, key: &str) -> Result { + Ok(read_git_config_value(root, key)?.is_some_and(|value| { + matches!( + value.to_ascii_lowercase().as_str(), + "true" | "yes" | "on" | "1" + ) + })) +} + +/// Builds the exact-comparison lookup key matching the repository's configured +/// case sensitivity and Unicode composition behavior. +fn canonical_comparison_key(path: &str, ignore_case: bool, precompose_unicode: bool) -> String { + use unicode_normalization::UnicodeNormalization; + + let normalized = normalize_comparison_pathspec(path); + let composed = if precompose_unicode { + normalized.nfc().collect::() + } else { + normalized + }; + if ignore_case { + composed.to_lowercase() + } else { + composed + } } pub(crate) fn commit_selected_paths( @@ -794,25 +836,23 @@ mod tests { use super::*; #[test] - fn exact_depth_keeps_normalized_unicode_matches_and_drops_descendants() { - let depth = normalized_path_depth("./dir/cafe\u{0301}.txt"); - assert_eq!(depth, 2); - let kept = filter_exact_depth( - vec![ - GitFileResponse { - status: "M".into(), - path: "dir/caf\u{00e9}.txt".into(), - is_untracked: false, - }, - GitFileResponse { - status: "D".into(), - path: "dir/caf\u{00e9}.txt/nested.txt".into(), - is_untracked: false, - }, - ], - depth, + fn exact_comparison_key_respects_unicode_and_case_flags() { + assert_eq!(normalize_comparison_pathspec("./draft.txt/."), "draft.txt"); + assert_eq!( + canonical_comparison_key("./dir/cafe\u{0301}.txt", false, true), + canonical_comparison_key("dir/caf\u{00e9}.txt", false, true) + ); + assert_ne!( + canonical_comparison_key("dir/cafe\u{0301}.txt", false, false), + canonical_comparison_key("dir/caf\u{00e9}.txt", false, false) + ); + assert_eq!( + canonical_comparison_key("README.md", true, false), + canonical_comparison_key("Readme.md", true, false) + ); + assert_ne!( + canonical_comparison_key("README.md", false, false), + canonical_comparison_key("Readme.md", false, false) ); - assert_eq!(kept.len(), 1); - assert_eq!(kept[0].path, "dir/caf\u{00e9}.txt"); } } From a24823232046a288fca6052fe1b9938527dccaf7 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 1 Dec 2026 23:46:16 -0800 Subject: [PATCH 7/7] fix(git): use -z name-status, platform path normalization, and bool config --- rust/crates/core/src/tests/git.rs | 41 ++++- rust/crates/git/src/commits.rs | 286 +++++++++++++++++++++++++----- 2 files changed, 280 insertions(+), 47 deletions(-) diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index 6bdbdf71..e0e48ee7 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -500,8 +500,8 @@ fn git_comparison_exact_paths_exclude_same_named_directory_contents() { assert!(rename_files[0]["status"].as_str().unwrap().starts_with('R')); assert_eq!(rename_files[0]["path"], "new.txt"); - // With core.ignorecase=true, differently cased exact pathspecs match tracked and untracked files. - run(&["config", "core.ignorecase", "true"]); + // With core.ignorecase=2 (nonstandard Git bool), differently cased exact pathspecs match. + run(&["config", "core.ignorecase", "2"]); fs::write(root.join("Readme.md"), "before\n").unwrap(); run(&["add", "Readme.md"]); run(&["-c", "commit.gpgsign=false", "commit", "-qm", "case file"]); @@ -530,6 +530,43 @@ fn git_comparison_exact_paths_exclude_same_named_directory_contents() { .map(|file| file["path"].as_str().unwrap()) .collect(); assert_eq!(icase_paths, vec!["OtherCase.txt", "Readme.md"]); + + // Moving a selected file under another selected path emits a deletion when destination is unselected. + run(&["config", "core.ignorecase", "false"]); + fs::write(root.join("docs-slot"), "slot\n").unwrap(); + fs::write( + root.join("notes.md"), + "note body to keep rename detection high\n", + ) + .unwrap(); + run(&["add", "docs-slot", "notes.md"]); + run(&["-c", "commit.gpgsign=false", "commit", "-qm", "move source"]); + run(&["branch", "before-move"]); + fs::remove_file(root.join("docs-slot")).unwrap(); + fs::create_dir_all(root.join("docs-slot")).unwrap(); + run(&["mv", "notes.md", "docs-slot/index.md"]); + let moved: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "id": "comparison-exact-moved-source", + "command": "git.comparison", + "payload": { + "root": root, + "reference": "before-move", + "pathspecs": ["docs-slot", "notes.md"], + "exactPaths": true, + } + }) + .to_string(), + )) + .unwrap(); + assert_eq!(moved["ok"], true, "{moved}"); + assert_eq!( + moved["data"]["files"], + serde_json::json!([ + { "path": "docs-slot", "status": "D" }, + { "path": "notes.md", "status": "D" }, + ]) + ); } #[test] diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 327640e1..cb8d2f57 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -262,12 +262,13 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result Result = if request.exact_paths { pathspecs .iter() - .map(|pathspec| canonical_comparison_key(pathspec, ignore_case, precompose_unicode)) + .map(|pathspec| { + canonical_comparison_key(pathspec, platform, ignore_case, precompose_unicode) + }) .collect() } else { std::collections::HashSet::new() }; - let filter_files = |items: Vec| -> Vec { - if !request.exact_paths { - return items; - } - items - .into_iter() - .filter(|file| { - exact_keys.contains(&canonical_comparison_key( - &file.path, - ignore_case, - precompose_unicode, - )) - }) - .collect() - }; - let files = filter_files(files); + let files = filter_comparison_diff_entries( + diff_entries, + request.exact_paths, + &exact_keys, + ignore_case, + precompose_unicode, + ); if !request.include_untracked { return Ok(GitComparisonResponse { files }); } @@ -346,11 +340,17 @@ pub fn comparison(request: GitComparisonRequest) -> Result Result, + path: String, +} + fn comparison_diff( command_root: &str, reference: &str, git_pathspecs: &[String], -) -> Result, CoreError> { +) -> Result, CoreError> { let mut arguments = vec![ "-c".to_string(), "core.quotepath=false".to_string(), "diff".to_string(), "--name-status".to_string(), "--find-renames".to_string(), + "-z".to_string(), reference.to_string(), "--".to_string(), ]; @@ -384,7 +391,129 @@ fn comparison_diff( .with_details(response.output), ); } - Ok(parse_name_status(&response.output)) + Ok(parse_comparison_name_status_nul(&response.stdout)) +} + +fn parse_comparison_name_status_nul(output: &str) -> Vec { + let mut entries = Vec::new(); + let mut parts = output.split('\0'); + while let Some(status) = parts.next() { + if status.is_empty() { + continue; + } + if status.starts_with('R') || status.starts_with('C') { + let Some(previous) = parts.next() else { + break; + }; + let Some(path) = parts.next() else { + break; + }; + if !path.is_empty() { + entries.push(ComparisonDiffEntry { + status: status.to_string(), + previous_path: (!previous.is_empty()).then(|| previous.to_string()), + path: path.to_string(), + }); + } + } else if let Some(path) = parts.next() { + if !path.is_empty() { + entries.push(ComparisonDiffEntry { + status: status.to_string(), + previous_path: None, + path: path.to_string(), + }); + } + } + } + entries +} + +fn filter_comparison_diff_entries( + entries: Vec, + exact_paths: bool, + exact_keys: &std::collections::HashSet, + ignore_case: bool, + precompose_unicode: bool, +) -> Vec { + if !exact_paths { + return entries + .into_iter() + .map(|entry| GitFileResponse { + status: entry.status, + path: entry.path, + is_untracked: false, + }) + .collect(); + } + let is_exact = |path: &str| { + exact_keys.contains(&canonical_comparison_key( + path, + lithe_platform::Platform::Unix, + ignore_case, + precompose_unicode, + )) + }; + let mut by_path = std::collections::BTreeMap::new(); + for entry in entries { + if let Some(previous) = entry.previous_path { + let previous_match = is_exact(&previous); + let path_match = is_exact(&entry.path); + if entry.status.starts_with('R') { + match (previous_match, path_match) { + (true, true) => { + by_path.insert( + entry.path.clone(), + GitFileResponse { + status: entry.status, + path: entry.path, + is_untracked: false, + }, + ); + } + (true, false) => { + by_path.insert( + previous.clone(), + GitFileResponse { + status: "D".into(), + path: previous, + is_untracked: false, + }, + ); + } + (false, true) => { + by_path.insert( + entry.path.clone(), + GitFileResponse { + status: "A".into(), + path: entry.path, + is_untracked: false, + }, + ); + } + (false, false) => {} + } + } else if path_match { + by_path.insert( + entry.path.clone(), + GitFileResponse { + status: "A".into(), + path: entry.path, + is_untracked: false, + }, + ); + } + } else if is_exact(&entry.path) { + by_path.insert( + entry.path.clone(), + GitFileResponse { + status: entry.status, + path: entry.path, + is_untracked: false, + }, + ); + } + } + by_path.into_values().collect() } fn comparison_untracked_for_pathspec( @@ -424,8 +553,9 @@ fn comparison_untracked_for_pathspec( .collect()) } -fn normalize_comparison_pathspec(pathspec: &str) -> String { - let components: Vec<_> = pathspec +fn normalize_comparison_pathspec(pathspec: &str, platform: lithe_platform::Platform) -> String { + let separated = lithe_platform::paths::slash_separated(pathspec, platform); + let components: Vec<_> = separated .split('/') .filter(|component| !component.is_empty() && *component != ".") .collect(); @@ -445,20 +575,38 @@ fn format_literal_pathspec(pathspec: &str, ignore_case: bool) -> String { } fn git_bool_config(root: &str, key: &str) -> Result { - Ok(read_git_config_value(root, key)?.is_some_and(|value| { - matches!( - value.to_ascii_lowercase().as_str(), - "true" | "yes" | "on" | "1" - ) - })) + let root = validate_root(root)?; + let arguments = [ + "config".to_string(), + "--type=bool".to_string(), + "--get".to_string(), + key.to_string(), + ]; + let configured = + capture_git_with_options(&root, &arguments, None, true)?.into_command_response(&arguments); + if configured.exit_code == 1 { + return Ok(false); + } + if configured.exit_code != 0 { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "Could not read Git configuration") + .with_details(configured.output), + ); + } + Ok(configured.output.trim() == "true") } /// Builds the exact-comparison lookup key matching the repository's configured /// case sensitivity and Unicode composition behavior. -fn canonical_comparison_key(path: &str, ignore_case: bool, precompose_unicode: bool) -> String { +fn canonical_comparison_key( + path: &str, + platform: lithe_platform::Platform, + ignore_case: bool, + precompose_unicode: bool, +) -> String { use unicode_normalization::UnicodeNormalization; - let normalized = normalize_comparison_pathspec(path); + let normalized = normalize_comparison_pathspec(path, platform); let composed = if precompose_unicode { normalized.nfc().collect::() } else { @@ -837,22 +985,70 @@ mod tests { #[test] fn exact_comparison_key_respects_unicode_and_case_flags() { - assert_eq!(normalize_comparison_pathspec("./draft.txt/."), "draft.txt"); + use lithe_platform::Platform; + + assert_eq!( + normalize_comparison_pathspec("./draft.txt/.", Platform::Unix), + "draft.txt" + ); + assert_eq!( + normalize_comparison_pathspec(r".\README.md", Platform::Windows), + "README.md" + ); + assert_eq!( + normalize_comparison_pathspec(r".\README.md", Platform::Unix), + r".\README.md" + ); assert_eq!( - canonical_comparison_key("./dir/cafe\u{0301}.txt", false, true), - canonical_comparison_key("dir/caf\u{00e9}.txt", false, true) + canonical_comparison_key("./dir/cafe\u{0301}.txt", Platform::Unix, false, true), + canonical_comparison_key("dir/caf\u{00e9}.txt", Platform::Unix, false, true) ); assert_ne!( - canonical_comparison_key("dir/cafe\u{0301}.txt", false, false), - canonical_comparison_key("dir/caf\u{00e9}.txt", false, false) + canonical_comparison_key("dir/cafe\u{0301}.txt", Platform::Unix, false, false), + canonical_comparison_key("dir/caf\u{00e9}.txt", Platform::Unix, false, false) ); assert_eq!( - canonical_comparison_key("README.md", true, false), - canonical_comparison_key("Readme.md", true, false) + canonical_comparison_key("README.md", Platform::Unix, true, false), + canonical_comparison_key("Readme.md", Platform::Unix, true, false) ); assert_ne!( - canonical_comparison_key("README.md", false, false), - canonical_comparison_key("Readme.md", false, false) + canonical_comparison_key("README.md", Platform::Unix, false, false), + canonical_comparison_key("Readme.md", Platform::Unix, false, false) + ); + } + + #[test] + fn exact_comparison_filter_preserves_renames_and_quoted_paths() { + let exact_keys: std::collections::HashSet = [ + "alpha.md", + "beta.md", + "notes.md", + "target.md", + "draft\"one.txt", + ] + .into_iter() + .map(str::to_string) + .collect(); + let raw = concat!( + "R100\0alpha.md\0beta.md\0", + "R100\0notes.md\0docs/index.md\0", + "R100\0other.md\0target.md\0", + "M\0draft\"one.txt\0" + ); + let entries = parse_comparison_name_status_nul(raw); + let filtered: Vec<_> = + filter_comparison_diff_entries(entries, true, &exact_keys, false, false) + .into_iter() + .map(|file| (file.status, file.path, file.is_untracked)) + .collect(); + assert_eq!( + filtered, + vec![ + ("R100".to_string(), "beta.md".to_string(), false), + ("M".to_string(), "draft\"one.txt".to_string(), false), + ("D".to_string(), "notes.md".to_string(), false), + ("A".to_string(), "target.md".to_string(), false), + ] ); } }