From 766e1edc0cf4de39d6d5831491bf6bc0c871c3ba Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:31:14 +0530 Subject: [PATCH] fix(vcs): keep patches and shelves independent of the user's diff and apply config (#7745) The git diff calls that write a patch and the git apply calls that read it back took diff.noprefix, diff.mnemonicPrefix, diff.srcPrefix/dstPrefix, diff.context, diff.submodule and apply.whitespace/ignoreWhitespace from the user's config, so a shelf could unshelve into the wrong path, patches failed or landed on the wrong lines, and restored text was rewritten. They now share fixed option lists (patch::DIFF_FORMAT, patch::APPLY); an explicit path prefix, as a multi-repository shelf uses, still wins. Also covers the plugin working-tree patch, the per-file diffs of a pending commit and the partial-staging calls. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-vcs/src/lib.rs | 3 +- crates/ide-vcs/src/patch.rs | 90 +++------ crates/ide-vcs/src/patch/file_diff.rs | 3 +- crates/ide-vcs/src/preserve.rs | 7 +- crates/ide-vcs/src/shelf.rs | 9 +- crates/ide-vcs/src/write.rs | 4 +- crates/ide-vcs/tests/patch_user_config.rs | 230 ++++++++++++++++++++++ 7 files changed, 271 insertions(+), 75 deletions(-) create mode 100644 crates/ide-vcs/tests/patch_user_config.rs diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index bc6171c20e..c3c410e6c3 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1691,7 +1691,8 @@ impl Repo { let rel = path.map(|p| self.rel_path(p)).transpose()?; let overrides = cli::filter_overrides(self.root(), cancel)?; let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect(); - args.extend(["--literal-pathspecs", "--no-pager", "diff", "--no-ext-diff", "--no-textconv"]); + args.extend(["--literal-pathspecs", "--no-pager", "diff"]); + args.extend(patch::DIFF_FORMAT); args.extend_from_slice(cli::submodule_guards()); args.extend([rev, "--"]); if let Some(rel) = &rel { diff --git a/crates/ide-vcs/src/patch.rs b/crates/ide-vcs/src/patch.rs index df19466ac3..6df5143a7b 100644 --- a/crates/ide-vcs/src/patch.rs +++ b/crates/ide-vcs/src/patch.rs @@ -19,6 +19,15 @@ pub use mapping::{ const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; +/// `git diff` options for text that is parsed as a patch. The user's `diff.*` config must not move +/// a path (`git apply` strips one component), drop the context or replace a submodule's section. +/// A prefix passed after these wins. +pub(crate) const DIFF_FORMAT: [&str; 7] = + ["--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "-U3", "--submodule=short"]; + +/// `git apply` writing exactly what the patch says, whatever the user's `apply.*` config is. +pub(crate) const APPLY: [&str; 4] = ["apply", "--binary", "--whitespace=nowarn", "--no-ignore-whitespace"]; + /// Binary-safe patch of the working-tree changes (staged or not, untracked files /// included) of `rel_paths` against HEAD, plus the files it touches (renames split /// into delete + add). The real index is left untouched. @@ -49,16 +58,9 @@ pub(crate) fn working_patch_with_prefix( run_env(r.root(), &["read-tree", "--empty"], None, &env)?; } cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], rel_paths, None, &env)?; - let mut diff = vec![ - "diff", - "--cached", - "--binary", - "--full-index", - if detect_renames { "-M" } else { "--no-renames" }, - "--no-color", - "--no-ext-diff", - "--no-textconv", - ]; + let mut diff = vec!["diff", "--cached", "--binary", "--full-index"]; + diff.push(if detect_renames { "-M" } else { "--no-renames" }); + diff.extend(DIFF_FORMAT); if reverse { diff.push("-R"); } @@ -129,19 +131,9 @@ pub(crate) fn staging_patch(r: &Repo, entries: &[StagingPatchEntry], reverse: bo let (a, b) = if reverse { ("b", "a") } else { ("a", "b") }; let src = format!("--src-prefix={a}/{prefix}"); let dst = format!("--dst-prefix={b}/{prefix}"); - let mut options = vec![ - "--literal-pathspecs", - "diff", - "--binary", - "--full-index", - "-M", - "--no-color", - "--no-ext-diff", - "--no-textconv", - "--ita-invisible-in-index", - &src, - &dst, - ]; + let mut options = vec!["--literal-pathspecs", "diff", "--binary", "--full-index", "-M", "--ita-invisible-in-index"]; + options.extend(DIFF_FORMAT); + options.extend([src.as_str(), dst.as_str()]); if reverse { options.push("-R"); } @@ -186,7 +178,8 @@ pub(crate) fn commits_patch(r: &Repo, commits: &[String], reverse: bool) -> IdeR let parent = commit.parent_ids().next().map(|p| p.detach().to_string()); (parent.unwrap_or_else(|| EMPTY_TREE.to_string()), id.to_string()) }; - let mut args = vec!["diff", "--binary", "--full-index", "-M", "--no-color", "--no-ext-diff", "--no-textconv"]; + let mut args = vec!["diff", "--binary", "--full-index", "-M"]; + args.extend(DIFF_FORMAT); if reverse { args.push("-R"); } @@ -198,24 +191,11 @@ pub(crate) fn commits_patch(r: &Repo, commits: &[String], reverse: bool) -> IdeR /// An automatic Shelf snapshot follows the same per-path layout as a manually created shelf. pub(crate) fn shelf_tree_patch_with_prefix(r: &Repo, base: &str, tree: &str, prefix: &str) -> IdeResult { - lossless_diff( - r, - &[ - "diff", - "--binary", - "--full-index", - "--no-renames", - "--no-color", - "--no-ext-diff", - "--no-textconv", - &format!("--src-prefix=a/{prefix}"), - &format!("--dst-prefix=b/{prefix}"), - base, - tree, - "--", - ], - &[], - ) + let (src, dst) = (format!("--src-prefix=a/{prefix}"), format!("--dst-prefix=b/{prefix}")); + let mut args = vec!["diff", "--binary", "--full-index", "--no-renames"]; + args.extend(DIFF_FORMAT); + args.extend([src.as_str(), dst.as_str(), base, tree, "--"]); + lossless_diff(r, &args, &[]) } pub(crate) fn revisions_patch(r: &Repo, before: &str, after: &str, paths: &[PathBuf]) -> IdeResult { @@ -233,21 +213,9 @@ pub(crate) fn revisions_patch(r: &Repo, before: &str, after: &str, paths: &[Path }; let before = if before == EMPTY_TREE { empty_tree.as_str() } else { before }; let after = if after == EMPTY_TREE { empty_tree.as_str() } else { after }; - let args = vec![ - "--literal-pathspecs", - "diff", - "--binary", - "--full-index", - "-M", - "--no-color", - "--no-ext-diff", - "--no-textconv", - "--src-prefix=a/", - "--dst-prefix=b/", - before, - after, - "--", - ]; + let mut args = vec!["--literal-pathspecs", "diff", "--binary", "--full-index", "-M"]; + args.extend(DIFF_FORMAT); + args.extend([before, after, "--"]); selected_diff(r, args, &paths, "", &[]) } @@ -401,9 +369,9 @@ fn preview_with_prefix(r: &Repo, patch: &str, prefix: &str) -> IdeResult }) .collect::>>()?; let strip = strip_option(prefix); - let mut args = vec!["apply", "--binary"]; + let mut args = APPLY.to_vec(); args.extend(strip.as_deref()); let check = cli::run_raw(r.root(), &[args.as_slice(), &["--check", "-"]].concat(), Some(patch.as_bytes()))?; if check.code == Some(0) { @@ -908,7 +876,7 @@ pub(crate) fn stage_converted_patch( } run_env( r.root(), - &["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"], + &[&APPLY[..], &["--cached", "--unidiff-zero", "--recount", "-"]].concat(), Some(patch.as_bytes()), &env, )?; diff --git a/crates/ide-vcs/src/patch/file_diff.rs b/crates/ide-vcs/src/patch/file_diff.rs index e11c1c2af7..fee1b4bf98 100644 --- a/crates/ide-vcs/src/patch/file_diff.rs +++ b/crates/ide-vcs/src/patch/file_diff.rs @@ -136,7 +136,8 @@ fn apply_in_sandbox( let boundary = std::env::join_paths([dunce::canonicalize(root)?]).map_err(|error| IdeError::invalid(error.to_string()))?; let strip = strip_option(prefix); - let mut args = vec!["-c", autocrlf, "apply", "--binary"]; + let mut args = vec!["-c", autocrlf]; + args.extend(super::APPLY); args.extend(strip.as_deref()); args.push("-"); let output = run_raw_env(&worktree, &args, Some(patch.as_bytes()), &[("GIT_CEILING_DIRECTORIES", &boundary)])?; diff --git a/crates/ide-vcs/src/preserve.rs b/crates/ide-vcs/src/preserve.rs index d13dfb7e3e..5ec50777dc 100644 --- a/crates/ide-vcs/src/preserve.rs +++ b/crates/ide-vcs/src/preserve.rs @@ -273,7 +273,8 @@ fn merge_saved_index(r: &Repo, snapshot: &str) -> IdeResult IdeResult IdeResult IdeResult> { let _scope = r.execution_scope(); let strip = crate::patch::strip_option(prefix); - let mut apply = vec!["apply"]; + let mut apply = crate::patch::APPLY.to_vec(); apply.extend(strip.as_deref()); let mut out = Vec::new(); for (section, file) in crate::patch::sections(patch) { @@ -954,12 +954,7 @@ fn diff_from_patch(r: &Repo, patch: &str, prefix: &str) -> IdeResult Ide return crate::patch::stage_converted_patch(r, &patch, encoding); } let bytes = crate::patch::encode_text_patch(r, &patch, encoding)?; - run(r.root(), &["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"], Some(&bytes)) + run(r.root(), &[&crate::patch::APPLY[..], &["--cached", "--unidiff-zero", "--recount", "-"]].concat(), Some(&bytes)) .map(|_| ()) } @@ -866,7 +866,7 @@ pub(crate) fn pending_changes( let names = cli::run_env(r.root(), &[&base[..], &["--name-status", "-z"]].concat(), None, env)?; let patch = cli::run_env( r.root(), - &[&base[..], &["--patch", "--src-prefix=a/", "--dst-prefix=b/", "--full-index"]].concat(), + &[&base[..], &crate::patch::DIFF_FORMAT, &["--patch", "--full-index"]].concat(), None, env, )?; diff --git a/crates/ide-vcs/tests/patch_user_config.rs b/crates/ide-vcs/tests/patch_user_config.rs new file mode 100644 index 0000000000..589022bbb7 --- /dev/null +++ b/crates/ide-vcs/tests/patch_user_config.rs @@ -0,0 +1,230 @@ +//! Patches and shelves must come out the same whatever the user's `diff.*` and `apply.*` config says. + +use ide_core::CancellationToken; +use ide_vcs::*; +use std::fmt::Debug; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const CONFIGS: &[&[(&str, &str)]] = &[ + &[("diff.noprefix", "true")], + &[("diff.mnemonicPrefix", "true")], + &[("diff.srcPrefix", "old/"), ("diff.dstPrefix", "new/")], + &[("diff.context", "0")], + &[("diff.submodule", "log")], + &[("diff.submodule", "diff")], + &[("apply.whitespace", "fix")], + &[("apply.whitespace", "error")], + &[("apply.ignoreWhitespace", "change")], +]; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git").current_dir(dir).args(args).output().unwrap(); + assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_owned() +} + +struct Fixture { + _tmp: tempfile::TempDir, + base: PathBuf, + dir: PathBuf, + repo: Repo, +} + +impl Fixture { + fn new() -> Self { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let dir = base.join("work"); + std::fs::create_dir(&dir).unwrap(); + git(&dir, &["init", "-q", "-b", "main"]); + let repo = Repo::discover(&dir).unwrap().unwrap(); + repo.set_execution_allowed(true); + Self { _tmp: tmp, base, dir, repo } + } + fn write(&self, rel: &str, text: &str) { + let path = self.path(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + fn path(&self, rel: &str) -> PathBuf { + self.dir.join(rel) + } + fn commit(&self, message: &str) -> String { + git(&self.dir, &["add", "-A"]); + git(&self.dir, &["commit", "-q", "--no-gpg-sign", "-m", message]); + git(&self.dir, &["rev-parse", "HEAD"]) + } + fn reset(&self) { + git(&self.dir, &["reset", "-q", "--hard"]); + git(&self.dir, &["clean", "-fdq"]); + } + fn files(&self, rel: &[&str]) -> String { + rel.iter() + .map(|rel| format!("{rel}: {:?}\n", std::fs::read_to_string(self.path(rel)).unwrap_or_default())) + .collect() + } +} + +fn lines(from: u32, to: u32) -> String { + (from..=to).map(|n| if n == 4 { "\n".into() } else { format!("line {n}\n") }).collect() +} + +/// `src/a.txt` and its namesake in the root folder have the same content, so a patch that loses +/// one path component still applies, to the wrong file. +fn edited(changed: &str) -> String { + format!("{}{changed}{}", lines(1, 5), lines(7, 30)).replace("line 12\n", "line 12 and more\n") +} + +struct Results(Vec<(&'static str, String)>); + +impl Results { + fn add(&mut self, step: &'static str, value: impl Debug) { + self.0.push((step, format!("{value:#?}"))); + } +} + +const FILES: &[&str] = &["a.txt", "src/a.txt", "new.txt"]; + +fn create_and_apply(out: &mut Results) { + let fx = Fixture::new(); + let repo = &fx.repo; + fx.write("a.txt", &lines(1, 30)); + fx.write("src/a.txt", &lines(1, 30)); + std::fs::create_dir(fx.path("sub")).unwrap(); + git(&fx.path("sub"), &["init", "-q", "-b", "main"]); + fx.write("sub/in.txt", "1\n"); + git(&fx.path("sub"), &["add", "-A"]); + git(&fx.path("sub"), &["commit", "-q", "--no-gpg-sign", "-m", "one"]); + let before = fx.commit("base"); + fx.write("sub/in.txt", "2\n"); + git(&fx.path("sub"), &["commit", "-q", "--no-gpg-sign", "-am", "two"]); + // Trailing spaces are what `apply.whitespace` looks at. + fx.write("src/a.txt", &edited("changed \n\t \n")); + fx.write("new.txt", "new \n"); + let changed = [fx.path("src/a.txt"), fx.path("new.txt")]; + let paths = [fx.path("src/a.txt"), fx.path("new.txt"), fx.path("sub")]; + out.add("create", repo.create_patch(&paths, false)); + out.add("create reversed", repo.create_patch(&paths, true)); + use StagingPatchSide::{Both, Unstaged}; + for (step, side) in [("create from unstaged", Unstaged), ("create from staged and unstaged", Both)] { + let entries: Vec<_> = + paths.iter().map(|path| StagingPatchEntry { path: path.into(), renamed_from: None, side }).collect(); + out.add(step, repo.create_staging_patch(&entries, false, "part/")); + out.add(step, repo.create_staging_patch(&entries, true, "part/")); + } + out.add("plugin diff", repo.working_tree_patch(None, None, 1 << 20, &CancellationToken::new())); + let options = + CommitOptions { run_hooks: true, stage: paths.iter().map(Into::into).collect(), ..CommitOptions::default() }; + let pending = repo.pending_changes(&options, 1 << 20, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + let pending: Vec<_> = pending.into_iter().map(|c| (c.path.file_name().unwrap().to_owned(), c.diff)).collect(); + out.add("pending commit", pending); + + let patch = repo.create_patch(&changed, false).unwrap(); + let reverse = repo.create_patch(&changed, true).unwrap(); + out.add("revert selected", repo.apply_patch(&reverse)); + out.add("revert selected", fx.files(FILES)); + out.add("preview", repo.patch_preview(&patch)); + let encoding = |_: &Path, _: &[u8]| TextEncoding::from(encoding_rs::UTF_8); + out.add("preview diff", repo.patch_file_diff(&patch, "src/a.txt", &encoding).map(|diff| diff.content)); + out.add("apply", repo.apply_patch(&patch)); + out.add("apply", fx.files(FILES)); + + let after = fx.commit("change"); + out.add("commit patch", repo.create_commits_patch(std::slice::from_ref(&after), false)); + out.add("commit patch reversed", repo.create_commits_patch(std::slice::from_ref(&after), true)); + let relative = ["src/a.txt", "new.txt", "sub"].map(PathBuf::from); + out.add("revisions patch", repo.create_revisions_patch(&before, &after, &relative)); + let selected = repo.create_revisions_patch(&after, &before, &relative[..2]).unwrap(); + out.add("revert selected of a commit", repo.apply_patch(&selected)); + out.add("revert selected of a commit", fx.files(FILES)); +} + +fn shelve(out: &mut Results) { + let fx = Fixture::new(); + let repo = &fx.repo; + fx.write("a.txt", &lines(1, 30)); + fx.write("src/a.txt", &lines(1, 30)); + fx.commit("base"); + let change = || { + fx.write("src/a.txt", &edited("changed \n\t \n")); + fx.write("new.txt", "new \n"); + [fx.path("src/a.txt"), fx.path("new.txt")] + }; + let directory = fx.base.join("shelf"); + let entry = repo.shelve(&directory, "one", &change()).unwrap(); + out.add("shelve", shelf::patch_of(&directory, &entry.id)); + out.add("shelve", fx.files(FILES)); + let sides: Vec<_> = shelf::diff_files(repo, &directory, &entry.id) + .unwrap() + .into_iter() + .map(|file| (file.path, file.before, file.after)) + .collect(); + out.add("shelf diff", sides); + out.add("unshelve", repo.unshelve(&directory, &entry.id, true)); + out.add("unshelve", fx.files(FILES)); + + fx.reset(); + let part = shelf::ShelfCapture::capture(repo, &fx.base, &change()).unwrap(); + let entry = shelf::save_combined(&directory, &fx.base, "two", std::slice::from_ref(&part)).unwrap(); + part.revert(repo).unwrap(); + out.add("combined shelf", shelf::patch_of(&directory, &entry.id)); + for selection in shelf::selections(&directory, &entry.id, None).unwrap() { + out.add("combined unshelve", selection.apply(repo)); + } + out.add("combined unshelve", fx.files(FILES)); + + // The same lines with other spacing, where the hunk was: the change belongs to the exact match. + fx.reset(); + fx.write("src/a.txt", &lines(1, 30).replace("line 6\n", "changed\n")); + let entry = repo.shelve(&directory, "three", &[fx.path("src/a.txt")]).unwrap(); + fx.write("src/a.txt", &format!("{}{}", lines(1, 9).replace("line ", "line "), lines(1, 30))); + fx.commit("spacing"); + out.add("unshelve moved", repo.unshelve(&directory, &entry.id, true)); + out.add("unshelve moved", fx.files(FILES)); +} + +#[test] +fn patches_and_shelves_do_not_depend_on_the_user_s_git_config() { + let temp = tempfile::tempdir().unwrap(); + let global = temp.path().join("gitconfig"); + // SAFETY: this test binary has a single test, so no other thread reads the environment. + unsafe { + std::env::set_var("GIT_CONFIG_GLOBAL", &global); + std::env::set_var("GIT_CONFIG_NOSYSTEM", "1"); + std::env::set_var("GIT_AUTHOR_DATE", "2026-01-01T00:00:00Z"); + std::env::set_var("GIT_COMMITTER_DATE", "2026-01-01T00:00:00Z"); + } + let run = |config: &[(&str, &str)]| { + std::fs::write( + &global, + "[user]\n\tname = Test\n\temail = test@example.com\n[core]\n\tautocrlf = false\n[advice]\n\taddEmbeddedRepo = false\n", + ) + .unwrap(); + for (key, value) in config { + git(temp.path(), &["config", "--global", key, value]); + } + let mut out = Results(Vec::new()); + create_and_apply(&mut out); + shelve(&mut out); + out.0 + }; + let expected = run(&[]); + let text = |step: &str| &expected.iter().rev().find(|(name, _)| *name == step).unwrap().1; + assert!(text("create").contains("Subproject commit"), "{}", text("create")); + for step in ["apply", "unshelve", "combined unshelve"] { + assert!(text(step).contains("changed ") && text(step).contains("new "), "{step}: {}", text(step)); + } + + let mut failures = Vec::new(); + for config in CONFIGS { + let actual = run(config); + let mut different: Vec<_> = + expected.iter().zip(&actual).filter(|(want, got)| want != got).map(|(want, _)| want.0).collect(); + different.dedup(); + if actual.len() != expected.len() || !different.is_empty() { + failures.push(format!("{config:?}: {different:?}")); + } + } + assert!(failures.is_empty(), "these configs change the result of:\n{}", failures.join("\n")); +}