Skip to content

Commit 04fc99c

Browse files
fix(git): 支持 Unix 冒号文件名并按字面查询历史(#2016) (#181)
* fix(git): preserve literal Unix workspace file names * fix(git): keep selected commit and stashPush pathspecs literal --------- Co-authored-by: lithe-support[bot] <356900028+lithe-support[bot]@users.noreply.github.com> Co-authored-by: lick <2188718831@qq.com>
1 parent 86856b4 commit 04fc99c

12 files changed

Lines changed: 571 additions & 19 deletions

File tree

‎rust/crates/core/src/tests/git_colon_paths.rs‎

Lines changed: 457 additions & 0 deletions
Large diffs are not rendered by default.

‎rust/crates/core/src/tests/git_untracked_directories.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -247,13 +247,13 @@ fn summarized_directory_supports_diff_stage_and_discard_as_a_unit() {
247247
// `:` cannot appear in a Windows file name.
248248
#[cfg(not(windows))]
249249
#[test]
250-
fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export() {
250+
fn summarized_directory_diff_preserves_colon_named_files() {
251251
let repository = Repository::new("untracked-unexportable");
252252
repository.write("generated/a.txt", "alpha\n");
253253
repository.write("generated/bad:name.txt", "kept\n");
254254

255-
// Shelve would save the patch and then clean `generated/`, so a patch
256-
// without `bad:name.txt` would delete that file without a copy.
255+
// Shelve saves the patch before cleaning `generated/`. A colon is a
256+
// supported Unix filename, so both files must be captured in that patch.
257257
let response: Value = serde_json::from_str(&execute_json(
258258
&json!({
259259
"command": "git.diff",
@@ -263,7 +263,11 @@ fn summarized_directory_diff_fails_instead_of_dropping_a_file_it_cannot_export()
263263
.to_string(),
264264
))
265265
.unwrap();
266-
assert_eq!(response["ok"], false, "{response}");
266+
assert_eq!(response["ok"], true, "{response}");
267+
let patch = response["data"]["patch"].as_str().unwrap();
268+
assert!(patch.contains("+alpha"), "{patch}");
269+
assert!(patch.contains("b/generated/bad:name.txt"), "{patch}");
270+
assert!(patch.contains("+kept"), "{patch}");
267271
assert!(repository.0.join("generated/bad:name.txt").exists());
268272
}
269273

‎rust/crates/core/src/tests/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ mod git;
1919
mod git_branch_delete;
2020
mod git_change_targets;
2121
mod git_changed_file_groups;
22+
#[cfg(unix)]
23+
mod git_colon_paths;
2224
mod git_diff_blocks;
2325
mod git_fetch;
2426
mod git_fetch_plan;

‎rust/crates/git/src/branches.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,7 @@ pub(crate) fn local_branch_name(reference: &str) -> Result<String, CoreError> {
434434
"Only local branches support this Git operation",
435435
)
436436
})?;
437-
if !is_safe_pathspec(branch) {
437+
if !is_safe_refspec_name(branch) {
438438
return Err(CoreError::new(
439439
ErrorCode::InvalidRequest,
440440
"Invalid Git branch name",

‎rust/crates/git/src/commits.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,12 +391,14 @@ pub(crate) fn commit_selected_paths(
391391
"--pathspec-from-file=-".to_string(),
392392
"--pathspec-file-nul".to_string(),
393393
];
394+
let mut stage_environment = environment.clone();
395+
stage_environment.push(("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string()));
394396
let staged = execute_git_with_environment(
395397
root,
396398
&stage_arguments,
397399
Some(pathspec_input.clone()),
398400
false,
399-
&environment,
401+
&stage_environment,
400402
)?;
401403
if staged.exit_code != 0 {
402404
return Ok(staged);
@@ -498,7 +500,8 @@ pub(crate) fn commit_selected_paths(
498500

499501
// Reconcile only committed paths in the real index. Unrelated staging that
500502
// another Git process created while hooks ran remains intact.
501-
let mut reconciled = execute_git(
503+
let literal = [("GIT_LITERAL_PATHSPECS".to_string(), "1".to_string())];
504+
let mut reconciled = execute_git_with_environment(
502505
root,
503506
&[
504507
"reset".to_string(),
@@ -508,6 +511,8 @@ pub(crate) fn commit_selected_paths(
508511
"--pathspec-file-nul".to_string(),
509512
],
510513
Some(pathspec_input),
514+
false,
515+
&literal,
511516
)?;
512517
if reconciled.exit_code != 0 {
513518
reconciled.warnings.push(GitOperationWarning::new(

‎rust/crates/git/src/diff.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,8 @@ pub(crate) fn diff_impl(request: GitDiffRequest) -> Result<GitDiffResponse, Core
196196
if request.include_file_sections {
197197
configure_structured_diff(&mut arguments);
198198
}
199+
// A selected filename such as `:(glob)*.txt` must not expand to other files.
200+
arguments.insert(0, "--literal-pathspecs".into());
199201
let root = validate_root(&request.root)?;
200202
let mut output = if expands_untracked_directories {
201203
GitProcessOutput {
@@ -226,6 +228,7 @@ pub(crate) fn diff_impl(request: GitDiffRequest) -> Result<GitDiffResponse, Core
226228
let untracked_paths = readonly_command(GitCommandRequest {
227229
root: root.clone(),
228230
arguments: vec![
231+
"--literal-pathspecs".into(),
229232
"ls-files".into(),
230233
"--others".into(),
231234
"--exclude-standard".into(),
@@ -353,6 +356,7 @@ fn worktree_snapshot_diff(
353356
if request.include_file_sections {
354357
configure_structured_diff(&mut arguments);
355358
}
359+
arguments.insert(0, "--literal-pathspecs".into());
356360
let mut output = capture_git_with_environment(root, &arguments, None, true, &environment)?;
357361
if output.exit_code != 0 {
358362
return Err(
@@ -378,6 +382,7 @@ fn worktree_snapshot_diff(
378382
};
379383
let mut section_bytes = sections.as_ref().map(structured_file_bytes).unwrap_or(0);
380384
let untracked_arguments = vec![
385+
"--literal-pathspecs".into(),
381386
"ls-files".into(),
382387
"--others".into(),
383388
"--exclude-standard".into(),

‎rust/crates/git/src/line_history.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ fn line_history_merge_ranges(
304304
let listing = readonly_command(GitCommandRequest {
305305
root: root.to_string(),
306306
arguments: vec![
307+
"--literal-pathspecs".to_string(),
307308
"log".to_string(),
308309
"--first-parent".to_string(),
309310
"--format=%H".to_string(),
@@ -633,8 +634,9 @@ pub fn line_history(request: GitLineHistoryRequest) -> Result<GitLineHistoryResp
633634
}
634635

635636
// One process traces every interval; `-L` emits only hunks intersecting
636-
// the traced lines, and `--first-parent` pins the merge semantics.
637-
let mut arguments = vec!["log".to_string()];
637+
// the traced lines, and `--first-parent` pins the merge semantics. Even
638+
// -L's filename can activate pathspec magic unless Git is in literal mode.
639+
let mut arguments = vec!["--literal-pathspecs".to_string(), "log".to_string()];
638640
for (start, end) in &intervals {
639641
arguments.push(format!("-L{start},{end}:{}", request.path));
640642
}

‎rust/crates/git/src/mutations.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Shared Git mutation helpers kept outside the command facade.
22
3-
use super::{capture_git_with_options, is_safe_pathspec};
3+
use super::{capture_git_with_options, is_safe_refspec_name};
44
use lithe_protocol::{CoreError, ErrorCode};
55

66
use super::{
@@ -94,8 +94,8 @@ pub(super) fn remote_branch_components(
9494
if branch.is_empty()
9595
|| remote.starts_with('-')
9696
|| branch.starts_with('-')
97-
|| !is_safe_pathspec(remote)
98-
|| !is_safe_pathspec(branch)
97+
|| !is_safe_refspec_name(remote)
98+
|| !is_safe_refspec_name(branch)
9999
{
100100
return Err(CoreError::new(
101101
ErrorCode::InvalidRequest,

‎rust/crates/git/src/references.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22
33
use super::*;
44

5+
/// Guards names combined into refspecs independently of filesystem path rules.
6+
/// Git forbids colons and backslashes in ref names on every platform; complete
7+
/// reference syntax is still checked by the existing `check-ref-format` calls.
8+
pub(crate) fn is_safe_refspec_name(name: &str) -> bool {
9+
!name.is_empty()
10+
&& !name.starts_with('/')
11+
&& !name.split('/').any(|component| component == "..")
12+
&& !name.contains([':', '\\', '\0'])
13+
}
14+
515
#[derive(Clone)]
616
pub(crate) struct ValidatedGitReference {
717
pub(crate) full_name: String,

‎rust/crates/git/src/repository.rs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
44
use super::*;
55
use lithe_platform::names::is_reserved_device_name;
6-
use lithe_platform::paths::{slash_separated, slash_separated_path};
6+
use lithe_platform::paths::{invalid_native_relative_path, slash_separated, slash_separated_path};
77
use lithe_platform::Platform;
88

99
/// Discovers Git repositories for an opened workspace using shared traversal rules.
@@ -456,12 +456,14 @@ pub(crate) fn empty_tree_oid(root: &str) -> Result<String, CoreError> {
456456
Ok(oid.to_string())
457457
}
458458

459+
/// Workspace paths follow the host's filename rules, independently of Git refs.
460+
/// Callers passing these paths as pathspecs must keep Git's matching literal.
459461
pub(crate) fn is_safe_pathspec(path: &str) -> bool {
460-
let normalized = slash_separated(path, Platform::HOST);
461-
!normalized.is_empty()
462-
&& !normalized.starts_with('/')
463-
&& !normalized.split('/').any(|component| component == "..")
464-
&& !normalized.contains(':')
462+
is_safe_pathspec_for(path, Platform::HOST)
463+
}
464+
465+
pub(crate) fn is_safe_pathspec_for(path: &str, platform: Platform) -> bool {
466+
!invalid_native_relative_path(path, platform)
465467
}
466468

467469
pub(crate) fn null_device() -> &'static str {

0 commit comments

Comments
 (0)