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/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4eb1c36d..252395fe 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2177,12 +2177,23 @@ 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, `.` +names the repository root, and empty or `.` path components are normalized as +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`, +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..e0e48ee7 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -229,6 +229,346 @@ 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"), "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(); + fs::create_dir(root.join("subdirectory")).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"]); + + 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": command_root, + "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(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.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"] + ); + + 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] +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"); + } + + // 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=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"]); + 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"]); + + // 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] fn git_status_returns_contract_shape() { let root = temporary_root("git"); 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 4d84e3cb..cb8d2f57 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -262,17 +262,127 @@ pub fn comparison(request: GitComparisonRequest) -> Result = pathspecs + .iter() + .map(|pathspec| format_literal_pathspec(pathspec, ignore_case)) + .collect(); + let diff_entries = 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, platform, ignore_case, precompose_unicode) + }) + .collect() + } else { + std::collections::HashSet::new() + }; + 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 }); + } + let mut by_path = std::collections::BTreeMap::new(); + for file in files { + by_path.insert(file.path.clone(), file); + } + if pathspecs.is_empty() { + let snapshot = status(GitStatusRequest { + root, + include_index_only_changes: false, + repository_roots: Vec::new(), + summarize_untracked_directories: false, + })?; + for change in snapshot + .changes + .into_iter() + .filter(|change| change.untracked) + { + by_path + .entry(change.path.clone()) + .or_insert(GitFileResponse { + status: "A".into(), + path: change.path, + is_untracked: true, + }); + } + } else { + for file in comparison_untracked_for_pathspec(&command_root, &git_pathspecs)? { + if !request.exact_paths + || exact_keys.contains(&canonical_comparison_key( + &file.path, + lithe_platform::Platform::Unix, + ignore_case, + precompose_unicode, + )) + { + by_path.entry(file.path.clone()).or_insert(file); + } + } + } + Ok(GitComparisonResponse { + files: by_path.into_values().collect(), + }) +} + +struct ComparisonDiffEntry { + status: String, + previous_path: Option, + path: String, +} + +fn comparison_diff( + command_root: &str, + reference: &str, + git_pathspecs: &[String], +) -> 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(), + ]; + arguments.extend(git_pathspecs.iter().cloned()); let response = readonly_command(GitCommandRequest { - root: root.clone(), - arguments: vec![ - "-c".to_string(), - "core.quotepath=false".to_string(), - "diff".to_string(), - "--name-status".to_string(), - "--find-renames".to_string(), - reference, - "--".to_string(), - ], + root: command_root.to_string(), + arguments, input: None, })?; if response.exit_code != 0 { @@ -281,36 +391,232 @@ pub fn comparison(request: GitComparisonRequest) -> Result 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(), + }); + } + } } - let snapshot = status(GitStatusRequest { - root, - include_index_only_changes: false, - repository_roots: Vec::new(), - summarize_untracked_directories: false, + 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( + command_root: &str, + git_pathspecs: &[String], +) -> Result, CoreError> { + let mut arguments = vec![ + "-c".to_string(), + "core.quotepath=false".to_string(), + "ls-files".to_string(), + "--others".to_string(), + "--exclude-standard".to_string(), + "-z".to_string(), + "--".to_string(), + ]; + arguments.extend(git_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)) + if response.exit_code != 0 { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "Git comparison failed") + .with_details(response.output), + ); + } + Ok(response + .stdout + .split('\0') + .filter(|path| !path.is_empty()) + .map(|path| GitFileResponse { + status: "A".into(), + path: path.to_string(), + is_untracked: true, + }) + .collect()) +} + +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(); - for change in snapshot - .changes - .into_iter() - .filter(|change| change.untracked) - { - by_path - .entry(change.path.clone()) - .or_insert(GitFileResponse { - status: "A".into(), - path: change.path, - is_untracked: true, - }); + 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 git_bool_config(root: &str, key: &str) -> Result { + 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, + platform: lithe_platform::Platform, + ignore_case: bool, + precompose_unicode: bool, +) -> String { + use unicode_normalization::UnicodeNormalization; + + let normalized = normalize_comparison_pathspec(path, platform); + let composed = if precompose_unicode { + normalized.nfc().collect::() + } else { + normalized + }; + if ignore_case { + composed.to_lowercase() + } else { + composed } - Ok(GitComparisonResponse { - files: by_path.into_values().collect(), - }) } pub(crate) fn commit_selected_paths( @@ -672,3 +978,77 @@ pub(crate) fn required_text(value: Option<&str>, label: &str) -> Result = [ + "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), + ] + ); + } +} diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index b77dd0ee..c7a8f1cf 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -390,6 +390,28 @@ pub(crate) fn repository_root(root: &str) -> 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, diff --git a/rust/crates/git/src/requests.rs b/rust/crates/git/src/requests.rs index d86d21c2..1d8ef436 100644 --- a/rust/crates/git/src/requests.rs +++ b/rust/crates/git/src/requests.rs @@ -471,6 +471,14 @@ 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, + /// 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)] 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" } + ] +}