From 92b6be4c0c03ba15803950a7a222644a98ca5a13 Mon Sep 17 00:00:00 2001 From: "lithe-support[bot]" <356900028+lithe-support[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:52:58 +0000 Subject: [PATCH 1/2] fix(git): preserve literal Unix workspace file names --- rust/crates/core/src/tests/git_colon_paths.rs | 369 ++++++++++++++++++ .../src/tests/git_untracked_directories.rs | 12 +- rust/crates/core/src/tests/mod.rs | 2 + rust/crates/git/src/branches.rs | 2 +- rust/crates/git/src/diff.rs | 5 + rust/crates/git/src/line_history.rs | 6 +- rust/crates/git/src/mutations.rs | 6 +- rust/crates/git/src/references.rs | 10 + rust/crates/git/src/repository.rs | 10 +- rust/crates/git/src/tests.rs | 35 ++ 10 files changed, 441 insertions(+), 16 deletions(-) create mode 100644 rust/crates/core/src/tests/git_colon_paths.rs diff --git a/rust/crates/core/src/tests/git_colon_paths.rs b/rust/crates/core/src/tests/git_colon_paths.rs new file mode 100644 index 00000000..c4f1d7c7 --- /dev/null +++ b/rust/crates/core/src/tests/git_colon_paths.rs @@ -0,0 +1,369 @@ +use super::support::temporary_root; +use crate::execute_json; +use serde_json::{json, Value}; +use std::{fs, path::PathBuf}; + +// These fixtures need Unix file names, not platform-specific Git behavior. +// Every subprocess, including setup, uses Core's five-second request deadline. +// The owner removes the repository when an assertion unwinds too. +struct Repository(PathBuf); + +impl Repository { + fn new(label: &str) -> Self { + let repository = Self(temporary_root(label)); + fs::create_dir_all(&repository.0).unwrap(); + repository.git(&["init", "--template=", "-q", "-b", "main"]); + repository.git(&["config", "core.autocrlf", "false"]); + repository.git(&["config", "core.hooksPath", ".git/empty-hooks"]); + repository.git(&["config", "core.excludesFile", ".git/empty-excludes"]); + repository + } + + fn write(&self, path: &str, content: &str) { + let path = self.0.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + fn data(&self, command: &str, mut payload: Value) -> Value { + payload["root"] = json!(self.0); + let response: Value = serde_json::from_str(&execute_json( + &json!({ + "command": command, "timeoutMilliseconds": 5000, "payload": payload, + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{response}"); + response["data"].clone() + } + + fn git(&self, arguments: &[&str]) -> String { + let data = self.data("git.command", json!({"arguments": arguments})); + assert_eq!(data["exitCode"], 0, "{data}"); + assert!(data["operationError"].is_null(), "{data}"); + data["stdout"].as_str().unwrap().to_string() + } + + fn commit(&self) { + self.git(&[ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-qm", + "initial", + ]); + } + + fn mutate(&self, operation: &str, paths: &[&str]) { + let data = self.data("git.write", json!({"operation": operation, "paths": paths})); + assert_eq!(data["exitCode"], 0, "{data}"); + assert!(data["operationError"].is_null(), "{data}"); + } +} + +impl Drop for Repository { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("Could not remove colon-path repository fixture: {error}"); + } + } +} + +const PATHS: [&str; 4] = ["a:b.txt", ":(glob)*.txt", r"D:\logs", ":(exclude)*.txt"]; + +#[test] +fn stage_and_unstage_keep_unix_colon_file_names_literal() { + let repository = Repository::new("colon-stage"); + repository.commit(); + for path in PATHS { + repository.write(path, "selected\n"); + } + repository.write("unselected.txt", "keep\n"); + repository.mutate("stage", &PATHS); + let tracked = repository.git(&["ls-files", "-z"]); + assert_eq!( + tracked, + ":(exclude)*.txt\0:(glob)*.txt\0D:\\logs\0a:b.txt\0" + ); + repository.mutate("unstage", &PATHS); + assert_eq!(repository.git(&["ls-files", "-z"]), ""); + for path in PATHS { + assert_eq!( + fs::read_to_string(repository.0.join(path)).unwrap(), + "selected\n" + ); + } +} + +#[test] +fn ignore_and_exclude_keep_unix_colon_file_names_literal() { + let repository = Repository::new("colon-ignore"); + for path in PATHS { + repository.write(path, "selected\n"); + } + repository.write("unselected.txt", "keep\n"); + repository.mutate("ignore", &PATHS[..2]); + repository.mutate("exclude", &PATHS[2..]); + assert_eq!( + repository.git(&[ + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "-z" + ]), + ":(exclude)*.txt\0:(glob)*.txt\0D:\\logs\0a:b.txt\0" + ); + assert_eq!( + repository.git(&["ls-files", "--others", "--exclude-standard", "-z"]), + ".gitignore\0unselected.txt\0" + ); +} + +#[test] +fn diff_and_rollback_keep_colon_path_selection_literal() { + let repository = Repository::new("colon-diff"); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "before\n"); + } + repository.git(&["add", "--all"]); + repository.commit(); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "after\n"); + } + for path in PATHS { + for worktree_snapshot in [false, true] { + let diff = repository.data( + "git.diff", + json!({ + "pathspecs": [path], "includeFileSections": true, + "worktreeSnapshot": worktree_snapshot, + }), + ); + let files = diff["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{path}: {diff}"); + assert_eq!(files[0]["path"], path, "{diff}"); + assert!( + files[0]["patch"].as_str().unwrap().contains("+after"), + "{diff}" + ); + } + repository.mutate("discard", &[path]); + assert_eq!( + fs::read_to_string(repository.0.join(path)).unwrap(), + "before\n" + ); + repository.write(path, "staged\n"); + repository.mutate("stage", &[path]); + repository.write(path, "unstaged\n"); + let rollback = repository.data( + "git.rollbackPrepare", + json!({"changes": [{"path": path, "status": "MM"}]}), + ); + assert_eq!( + rollback["steps"], + json!([{"operation": "discardAll", "paths": [path]}]), + "{rollback}" + ); + repository.mutate("discardAll", &[path]); + assert_eq!( + fs::read_to_string(repository.0.join(path)).unwrap(), + "before\n" + ); + } + assert_eq!(repository.git(&["diff", "--cached", "--name-only"]), ""); + assert_eq!( + fs::read_to_string(repository.0.join("unselected.txt")).unwrap(), + "after\n" + ); +} + +#[test] +fn patch_exchange_round_trips_colon_paths_without_touching_other_files() { + let repository = Repository::new("colon-patch"); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "before\n"); + } + repository.git(&["add", "--all"]); + repository.commit(); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "after\n"); + } + let exported = repository.data( + "git.patchExport", + json!({ + "source": "unstaged", "paths": PATHS, + }), + ); + let patch = exported["patch"].as_str().unwrap(); + let preview = repository.data( + "git.patchPreview", + json!({ + "patch": patch, "target": "worktree", "reverse": true, + }), + ); + assert_eq!(preview["applicable"], true, "{preview}"); + assert_eq!( + preview["files"].as_array().unwrap().len(), + PATHS.len(), + "{preview}" + ); + let applied = repository.data( + "git.patchApply", + json!({ + "patch": patch, "target": "worktree", "reverse": true, + "expectedState": preview["expectedState"], + }), + ); + assert_eq!(applied["exitCode"], 0, "{applied}"); + for path in PATHS { + assert_eq!( + fs::read_to_string(repository.0.join(path)).unwrap(), + "before\n" + ); + } + assert_eq!( + fs::read_to_string(repository.0.join("unselected.txt")).unwrap(), + "after\n" + ); +} + +#[test] +fn blame_and_line_history_read_colon_paths_from_the_pinned_revision() { + let repository = Repository::new("colon-history"); + for path in PATHS { + repository.write(path, "one\ntwo\n"); + } + repository.git(&["add", "--all"]); + repository.commit(); + let head = repository.git(&["rev-parse", "HEAD"]).trim().to_string(); + for path in PATHS { + let blame = repository.data("git.blame", json!({"path": path})); + assert_eq!( + blame["lines"].as_array().unwrap().len(), + 2, + "{path}: {blame}" + ); + assert_eq!(blame["lines"][0]["commitHash"], head, "{blame}"); + let history = repository.data( + "git.lineHistory", + json!({ + "path": path, "content": "one\ntwo\n", "startLine": 1, "endLine": 2, + }), + ); + assert_eq!(history["baseCommit"], head, "{path}: {history}"); + assert_eq!(history["unmappedLines"], json!([]), "{history}"); + assert_eq!(history["commits"].as_array().unwrap().len(), 1, "{history}"); + assert_eq!(history["commits"][0]["pathAtCommit"], path, "{history}"); + } +} + +#[test] +fn merge_line_history_replays_a_pathspec_shaped_filename_literally() { + let repository = Repository::new("colon-merge-history"); + let path = ":(exclude)*.txt"; + repository.write(path, "first\nbefore\nlast\n"); + repository.git(&["add", "--all"]); + repository.commit(); + repository.git(&["checkout", "-qb", "side"]); + repository.write(path, "first\nmerged\nlast\n"); + repository.git(&["add", "--all"]); + repository.commit(); + repository.git(&["checkout", "-q", "main"]); + repository.write("unselected.txt", "keep\n"); + repository.git(&["add", "--all"]); + repository.commit(); + repository.git(&[ + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "merge", + "--no-ff", + "--no-edit", + "side", + ]); + let merge = repository.git(&["rev-parse", "HEAD"]).trim().to_string(); + // A later committed insertion moves the queried line. The merge entry + // must still identify the original second line, not lose its range when + // the filename is mistaken for an excluding Git pathspec during replay. + let content = "inserted\nfirst\nmerged\nlast\n"; + repository.write(path, content); + repository.git(&["add", "--all"]); + repository.commit(); + let history = repository.data( + "git.lineHistory", + json!({"path": path, "content": content, "startLine": 3, "endLine": 3}), + ); + assert_eq!(history["unmappedLines"], json!([]), "{history}"); + let entry = history["commits"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["hash"] == merge) + .unwrap_or_else(|| panic!("Merge entry missing: {history}")); + assert_eq!(entry["kind"], "merge-first-parent", "{history}"); + assert_eq!(entry["pathAtCommit"], path, "{history}"); + assert_eq!( + entry["relevantRanges"], + json!([{"oldStart": 2, "oldEnd": 2, "newStart": 2, "newEnd": 2}]), + "{history}" + ); +} + +#[test] +fn untracked_directory_and_diff_preserve_colon_children() { + let repository = Repository::new("colon-untracked"); + repository.commit(); + repository.write("new:dir/a:b.txt", "new\n"); + repository.write("new:dir/sub:dir/nested.txt", "nested\n"); + let listing = repository.data("git.untrackedDirectory", json!({"directory": "new:dir/"})); + let children = listing["changes"].as_array().unwrap(); + assert_eq!(children.len(), 2, "{listing}"); + assert_eq!(children[0]["path"], "new:dir/a:b.txt", "{listing}"); + assert_eq!(children[1]["path"], "new:dir/sub:dir/", "{listing}"); + assert_eq!(children[1]["untrackedFileCount"], 1, "{listing}"); + let diff = repository.data( + "git.diff", + json!({ + "pathspecs": ["new:dir/"], "untracked": true, "includeFileSections": true, + }), + ); + let paths = diff["files"] + .as_array() + .unwrap() + .iter() + .map(|file| file["path"].as_str().unwrap()) + .collect::>(); + assert_eq!( + paths, + ["new:dir/a:b.txt", "new:dir/sub:dir/nested.txt"], + "{diff}" + ); + + repository.write(":(glob)*.txt", "selected\n"); + repository.write(":(exclude)*.txt", "selected\n"); + repository.write("unselected.txt", "keep\n"); + for mode in [ + json!({"reference": "HEAD", "untracked": true}), + json!({"worktreeSnapshot": true}), + ] { + for path in [":(glob)*.txt", ":(exclude)*.txt"] { + let mut request = mode.clone(); + request["pathspecs"] = json!([path]); + request["includeFileSections"] = json!(true); + let diff = repository.data("git.diff", request); + let files = diff["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{diff}"); + assert_eq!(files[0]["path"], path, "{diff}"); + } + } +} diff --git a/rust/crates/core/src/tests/git_untracked_directories.rs b/rust/crates/core/src/tests/git_untracked_directories.rs index 239e066d..50112c0f 100644 --- a/rust/crates/core/src/tests/git_untracked_directories.rs +++ b/rust/crates/core/src/tests/git_untracked_directories.rs @@ -247,13 +247,13 @@ fn summarized_directory_supports_diff_stage_and_discard_as_a_unit() { // `:` cannot appear in a Windows file name. #[cfg(not(windows))] #[test] -fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export() { +fn summarized_directory_diff_preserves_colon_named_files() { let repository = Repository::new("untracked-unexportable"); repository.write("generated/a.txt", "alpha\n"); repository.write("generated/bad:name.txt", "kept\n"); - // Shelve would save the patch and then clean `generated/`, so a patch - // without `bad:name.txt` would delete that file without a copy. + // Shelve saves the patch before cleaning `generated/`. A colon is a + // supported Unix filename, so both files must be captured in that patch. let response: Value = serde_json::from_str(&execute_json( &json!({ "command": "git.diff", @@ -263,7 +263,11 @@ fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export() .to_string(), )) .unwrap(); - assert_eq!(response["ok"], false, "{response}"); + assert_eq!(response["ok"], true, "{response}"); + let patch = response["data"]["patch"].as_str().unwrap(); + assert!(patch.contains("+alpha"), "{patch}"); + assert!(patch.contains("b/generated/bad:name.txt"), "{patch}"); + assert!(patch.contains("+kept"), "{patch}"); assert!(repository.0.join("generated/bad:name.txt").exists()); } diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index bfabf10b..433f428c 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -18,6 +18,8 @@ mod git; mod git_branch_delete; mod git_change_targets; mod git_changed_file_groups; +#[cfg(unix)] +mod git_colon_paths; mod git_diff_blocks; mod git_fetch; mod git_fetch_plan; diff --git a/rust/crates/git/src/branches.rs b/rust/crates/git/src/branches.rs index c402047d..acecfa37 100644 --- a/rust/crates/git/src/branches.rs +++ b/rust/crates/git/src/branches.rs @@ -434,7 +434,7 @@ pub(crate) fn local_branch_name(reference: &str) -> Result { "Only local branches support this Git operation", ) })?; - if !is_safe_pathspec(branch) { + if !is_safe_refspec_name(branch) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Invalid Git branch name", diff --git a/rust/crates/git/src/diff.rs b/rust/crates/git/src/diff.rs index 0636c393..c65c16ec 100644 --- a/rust/crates/git/src/diff.rs +++ b/rust/crates/git/src/diff.rs @@ -196,6 +196,8 @@ pub(crate) fn diff_impl(request: GitDiffRequest) -> Result Result Result bool { + !name.is_empty() + && !name.starts_with('/') + && !name.split('/').any(|component| component == "..") + && !name.contains([':', '\\', '\0']) +} + #[derive(Clone)] pub(crate) struct ValidatedGitReference { pub(crate) full_name: String, diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index 2a8c9c64..fd7a1a5e 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -3,7 +3,7 @@ use super::*; use lithe_platform::names::is_reserved_device_name; -use lithe_platform::paths::{slash_separated, slash_separated_path}; +use lithe_platform::paths::{invalid_native_relative_path, slash_separated, slash_separated_path}; use lithe_platform::Platform; /// Discovers Git repositories for an opened workspace using shared traversal rules. @@ -456,12 +456,10 @@ pub(crate) fn empty_tree_oid(root: &str) -> Result { Ok(oid.to_string()) } +/// Workspace paths follow the host's filename rules, independently of Git refs. +/// Callers passing these paths as pathspecs must keep Git's matching literal. pub(crate) fn is_safe_pathspec(path: &str) -> bool { - let normalized = slash_separated(path, Platform::HOST); - !normalized.is_empty() - && !normalized.starts_with('/') - && !normalized.split('/').any(|component| component == "..") - && !normalized.contains(':') + !invalid_native_relative_path(path, Platform::HOST) } pub(crate) fn null_device() -> &'static str { diff --git a/rust/crates/git/src/tests.rs b/rust/crates/git/src/tests.rs index 270adc3d..ec7d9903 100644 --- a/rust/crates/git/src/tests.rs +++ b/rust/crates/git/src/tests.rs @@ -12,6 +12,41 @@ use lithe_protocol::{CoreError, ErrorCode}; use serde_json::Value; use std::path::PathBuf; +#[test] +fn local_branch_names_reject_colon_refspecs_on_every_platform() { + assert_eq!( + super::local_branch_name("refs/heads/topic/nested").unwrap(), + "topic/nested" + ); + for name in ["topic:main", ":main", "topic:refs/heads/main"] { + let error = super::local_branch_name(&format!("refs/heads/{name}")).unwrap_err(); + assert!( + matches!(error.code, ErrorCode::InvalidRequest), + "{name}: {error:?}" + ); + } +} + +#[test] +fn remote_and_branch_refspec_components_do_not_follow_unix_filename_rules() { + for name in ["origin", "origin/team", "topic/nested", "@"] { + assert!(super::is_safe_refspec_name(name), "{name}"); + } + for name in [ + "", + "/topic", + "../topic", + "topic/../main", + "origin:topic", + ":main", + "topic:refs/heads/main", + "topic\\main", + "topic\0main", + ] { + assert!(!super::is_safe_refspec_name(name), "{name:?}"); + } +} + /// Only an exact `Name ` names an author; the options keep Git's order. #[test] fn commit_identity_requires_an_exact_author() { From 57a4ad82edb19e736922ffacbd6bb5e5ecb4acf9 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 23 Nov 2026 05:11:30 -0800 Subject: [PATCH 2/2] fix(git): keep selected commit and stashPush pathspecs literal --- rust/crates/core/src/tests/git_colon_paths.rs | 88 +++++++++++++++++++ rust/crates/git/src/commits.rs | 9 +- rust/crates/git/src/repository.rs | 6 +- rust/crates/git/src/tests.rs | 23 +++++ rust/crates/git/src/write.rs | 9 +- 5 files changed, 131 insertions(+), 4 deletions(-) diff --git a/rust/crates/core/src/tests/git_colon_paths.rs b/rust/crates/core/src/tests/git_colon_paths.rs index c4f1d7c7..eeec2d5f 100644 --- a/rust/crates/core/src/tests/git_colon_paths.rs +++ b/rust/crates/core/src/tests/git_colon_paths.rs @@ -367,3 +367,91 @@ fn untracked_directory_and_diff_preserve_colon_children() { } } } + +#[test] +fn selected_commit_keeps_colon_paths_literal() { + let repository = Repository::new("colon-commit"); + repository.git(&["config", "user.name", "Fixture"]); + repository.git(&["config", "user.email", "fixture@example.invalid"]); + repository.git(&["config", "commit.gpgsign", "false"]); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "initial\n"); + } + repository.git(&["add", "--all"]); + repository.commit(); + + // Selected commit with pathspec-shaped names must not commit `unselected.txt` + // and must reconcile pre-staged colon paths in the real index. + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "committed\n"); + } + repository.mutate("stage", &["a:b.txt", ":(exclude)*.txt"]); + let committed = repository.data( + "git.write", + json!({ + "operation": "commit", + "message": "commit colon paths", + "paths": PATHS, + }), + ); + assert_eq!(committed["exitCode"], 0, "{committed}"); + assert!(committed["operationError"].is_null(), "{committed}"); + assert_eq!( + repository.git(&[ + "diff-tree", + "--no-commit-id", + "--name-only", + "-r", + "-z", + "HEAD" + ]), + ":(exclude)*.txt\0:(glob)*.txt\0D:\\logs\0a:b.txt\0" + ); + assert_eq!( + fs::read_to_string(repository.0.join("unselected.txt")).unwrap(), + "committed\n" + ); + assert_eq!( + repository.git(&["status", "--porcelain=v1", "-z"]), + " M unselected.txt\0" + ); +} + +#[test] +fn stash_push_keeps_colon_paths_literal() { + let repository = Repository::new("colon-stash"); + repository.git(&["config", "user.name", "Fixture"]); + repository.git(&["config", "user.email", "fixture@example.invalid"]); + repository.git(&["config", "commit.gpgsign", "false"]); + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "initial\n"); + } + repository.git(&["add", "--all"]); + repository.commit(); + + // Selected stash push with pathspec-shaped names must leave `unselected.txt` modified. + for path in PATHS.into_iter().chain(["unselected.txt"]) { + repository.write(path, "stashed\n"); + } + let stashed = repository.data( + "git.write", + json!({ + "operation": "stashPush", + "message": "stash colon paths", + "paths": PATHS, + }), + ); + assert_eq!(stashed["exitCode"], 0, "{stashed}"); + assert!(stashed["operationError"].is_null(), "{stashed}"); + for path in PATHS { + assert_eq!( + fs::read_to_string(repository.0.join(path)).unwrap(), + "initial\n", + "{path}" + ); + } + assert_eq!( + fs::read_to_string(repository.0.join("unselected.txt")).unwrap(), + "stashed\n" + ); +} diff --git a/rust/crates/git/src/commits.rs b/rust/crates/git/src/commits.rs index 5a625f58..4d84e3cb 100644 --- a/rust/crates/git/src/commits.rs +++ b/rust/crates/git/src/commits.rs @@ -391,12 +391,14 @@ pub(crate) fn commit_selected_paths( "--pathspec-from-file=-".to_string(), "--pathspec-file-nul".to_string(), ]; + let mut stage_environment = environment.clone(); + stage_environment.push(("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string())); let staged = execute_git_with_environment( root, &stage_arguments, Some(pathspec_input.clone()), false, - &environment, + &stage_environment, )?; if staged.exit_code != 0 { return Ok(staged); @@ -498,7 +500,8 @@ pub(crate) fn commit_selected_paths( // Reconcile only committed paths in the real index. Unrelated staging that // another Git process created while hooks ran remains intact. - let mut reconciled = execute_git( + let literal = [("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string())]; + let mut reconciled = execute_git_with_environment( root, &[ "reset".to_string(), @@ -508,6 +511,8 @@ pub(crate) fn commit_selected_paths( "--pathspec-file-nul".to_string(), ], Some(pathspec_input), + false, + &literal, )?; if reconciled.exit_code != 0 { reconciled.warnings.push(GitOperationWarning::new( diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index fd7a1a5e..b77dd0ee 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -459,7 +459,11 @@ pub(crate) fn empty_tree_oid(root: &str) -> Result { /// Workspace paths follow the host's filename rules, independently of Git refs. /// Callers passing these paths as pathspecs must keep Git's matching literal. pub(crate) fn is_safe_pathspec(path: &str) -> bool { - !invalid_native_relative_path(path, Platform::HOST) + is_safe_pathspec_for(path, Platform::HOST) +} + +pub(crate) fn is_safe_pathspec_for(path: &str, platform: Platform) -> bool { + !invalid_native_relative_path(path, platform) } pub(crate) fn null_device() -> &'static str { diff --git a/rust/crates/git/src/tests.rs b/rust/crates/git/src/tests.rs index ec7d9903..1410b6c9 100644 --- a/rust/crates/git/src/tests.rs +++ b/rust/crates/git/src/tests.rs @@ -47,6 +47,29 @@ fn remote_and_branch_refspec_components_do_not_follow_unix_filename_rules() { } } +#[test] +fn workspace_pathspecs_follow_platform_filename_rules() { + for path in ["a:b.txt", ":(glob)*.txt", ":(exclude)*.txt", r"D:\logs"] { + assert!( + super::is_safe_pathspec_for(path, lithe_platform::Platform::Unix), + "{path}" + ); + assert!( + !super::is_safe_pathspec_for(path, lithe_platform::Platform::Windows), + "{path}" + ); + } + for platform in lithe_platform::Platform::ALL { + assert!(super::is_safe_pathspec_for("src/main.rs", platform)); + for invalid in ["", "/etc", "../secret", "a/../b", "a\0b"] { + assert!( + !super::is_safe_pathspec_for(invalid, platform), + "{invalid:?} on {platform:?}" + ); + } + } +} + /// Only an exact `Name ` names an author; the options keep Git's order. #[test] fn commit_identity_requires_an_exact_author() { diff --git a/rust/crates/git/src/write.rs b/rust/crates/git/src/write.rs index 1d8ea2ab..cab6a33b 100644 --- a/rust/crates/git/src/write.rs +++ b/rust/crates/git/src/write.rs @@ -581,7 +581,14 @@ fn write_with_trace(request: GitWriteRequest) -> Result {