дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
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 <[email protected]>
231 рядки
9.7 KiB
Rust
231 рядки
9.7 KiB
Rust
//! 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 = [email protected]\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"));
|
|
}
|