дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
fix(vcs): keep the file when a case-only rename is rolled back, left out or shelved (#7769)
On a case-insensitive disk, after git mv readme.md README.md (or a folder renamed the same way), Rollback deleted the file, a commit leaving the rename out committed its deletion, and Shelve reported no changes, because both names resolved to the one the index has. Unstage, a commit's excluded files, Shelve and Create Patch now act on both names of a staged case-only rename; Rollback and Shelve restore the old name on disk, and Unshelve brings the rename back by removing the old file first and putting the new name in the index. Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
1 джерело
88eba9f3bd
коміт
1bdd5b4094
6 files changed
+475
-9
No files matched your search
@@ -0,0 +1,107 @@
|
||||
//! Renames that only change letter case on a worktree that ignores it (`core.ignoreCase`). The
|
||||
//! disk has one file for both names, so only the index can hold the rename, and Git's commands
|
||||
//! that go through the worktree take one name for the other.
|
||||
|
||||
use crate::cli::{run_env, run_paths_env};
|
||||
use crate::repo::ignores_case;
|
||||
use crate::{ChangeKind, Repo};
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) struct CaseRename {
|
||||
pub old: String,
|
||||
pub new: String,
|
||||
}
|
||||
|
||||
impl CaseRename {
|
||||
/// `rel` is either name, or a folder above one.
|
||||
fn is_in(&self, rel: &str) -> bool {
|
||||
let covers = |path: &str| {
|
||||
rel == "." || path.strip_prefix(rel).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
|
||||
};
|
||||
covers(&self.old) || covers(&self.new)
|
||||
}
|
||||
|
||||
/// Removes the file, and the folders renamed with it once they are empty, so that Git gives
|
||||
/// them their old names when it writes the file again.
|
||||
pub(crate) fn remove_file(&self, r: &Repo) -> std::io::Result<()> {
|
||||
std::fs::remove_file(r.abs_path(&self.new))?;
|
||||
let parents = |path: &str| Path::new(path).ancestors().skip(1).map(Path::to_path_buf).collect::<Vec<_>>();
|
||||
for (old, new) in parents(&self.old).into_iter().zip(parents(&self.new)) {
|
||||
if old == new || std::fs::remove_dir(r.root().join(new)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The case-only renames among `files`, a list of changes without rename detection.
|
||||
pub(crate) fn among<'a>(
|
||||
r: &Repo,
|
||||
files: impl Iterator<Item = (&'a str, ChangeKind)> + Clone,
|
||||
) -> IdeResult<Vec<CaseRename>> {
|
||||
if !ignores_case(&r.gix()?) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let of = |wanted| files.clone().filter(move |(_, kind)| *kind == wanted).map(|(path, _)| path);
|
||||
let added: HashMap<String, &str> = of(ChangeKind::Added).map(|path| (path.to_ascii_lowercase(), path)).collect();
|
||||
Ok(of(ChangeKind::Deleted)
|
||||
.filter_map(|old| {
|
||||
let new = *added.get(&old.to_ascii_lowercase())?;
|
||||
Some(CaseRename { old: old.to_owned(), new: new.to_owned() })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The staged case-only renames that `rels` name by either side.
|
||||
pub(crate) fn staged(r: &Repo, rels: &[String]) -> IdeResult<Vec<CaseRename>> {
|
||||
if rels.is_empty() || !ignores_case(&r.gix()?) || !r.has_head()? {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let args = ["diff", "--cached", "--name-status", "-z", "--no-renames", "--no-ext-diff", "HEAD", "--"];
|
||||
let changes = crate::ops::parse_name_status(&run_env(r.root(), &args, None, &[])?.stdout_str());
|
||||
let mut renames = among(r, changes.iter().map(|file| (file.path.as_str(), file.kind)))?;
|
||||
renames.retain(|rename| rels.iter().any(|rel| rename.is_in(rel)));
|
||||
Ok(renames)
|
||||
}
|
||||
|
||||
/// `rels` with both names of the staged case-only renames they name.
|
||||
pub(crate) fn with_both_names(r: &Repo, mut rels: Vec<String>) -> IdeResult<Vec<String>> {
|
||||
let renames = staged(r, &rels)?;
|
||||
rels.extend(renames.into_iter().flat_map(|rename| [rename.old, rename.new]));
|
||||
Ok(rels)
|
||||
}
|
||||
|
||||
/// The renames whose two names `paths` holds while the index has the old one only.
|
||||
pub(crate) fn unstaged(r: &Repo, paths: &[PathBuf]) -> IdeResult<Vec<CaseRename>> {
|
||||
let given = paths.iter().map(|path| r.given_rel_path(path)).collect::<IdeResult<Vec<_>>>()?;
|
||||
let mut renames = Vec::new();
|
||||
for (path, new) in paths.iter().zip(&given) {
|
||||
let old = r.rel_path(path)?;
|
||||
if old != *new && given.contains(&old) {
|
||||
renames.push(CaseRename { old, new: new.clone() });
|
||||
}
|
||||
}
|
||||
Ok(renames)
|
||||
}
|
||||
|
||||
/// Moves the index entries of `renames` from the old name to the new one.
|
||||
pub(crate) fn rename_in_index(r: &Repo, renames: &[CaseRename], env: &[(&str, &OsStr)]) -> IdeResult<()> {
|
||||
let old: Vec<String> = renames.iter().map(|rename| rename.old.clone()).collect();
|
||||
let args = ["--literal-pathspecs", "ls-files", "--stage", "-z", "--"];
|
||||
let entries = run_paths_env(r.root(), &args, &old, None, env)?.stdout_str();
|
||||
let null = r.gix()?.object_hash().null();
|
||||
let mut moves = String::new();
|
||||
for (entry, path) in entries.split('\0').filter_map(|line| line.split_once('\t')) {
|
||||
if let Some(rename) = renames.iter().find(|rename| rename.old == path) {
|
||||
moves.push_str(&format!("0 {null}\t{path}\0{entry}\t{}\0", rename.new));
|
||||
}
|
||||
}
|
||||
if moves.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
run_env(r.root(), &["update-index", "-z", "--index-info"], Some(moves.as_bytes()), env).map(|_| ())
|
||||
}
|
||||
@@ -1034,6 +1034,7 @@ mod backend;
|
||||
mod bek;
|
||||
mod blame;
|
||||
mod block_history;
|
||||
mod case_rename;
|
||||
pub mod changelists;
|
||||
mod cherry_pick_plan;
|
||||
mod cli;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! and applying them (falling back to a 3-way merge that leaves conflicts for the
|
||||
//! merge UI), as Create Patch / Apply Patch / Shelve do in IDEA.
|
||||
|
||||
use crate::case_rename::{self, CaseRename};
|
||||
use crate::cli::{self, TempIndex, run, run_env};
|
||||
use crate::repo::gx;
|
||||
use crate::{ApplyOutcome, ChangeKind, ChangedFile, PatchFile, Repo, Repos, StagingPatchEntry, StagingPatchSide};
|
||||
@@ -57,7 +58,13 @@ pub(crate) fn working_patch_with_prefix(
|
||||
} else {
|
||||
run_env(r.root(), &["read-tree", "--empty"], None, &env)?;
|
||||
}
|
||||
cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], rel_paths, None, &env)?;
|
||||
// `git add` updates the entry of the old name when only the case of a name differs.
|
||||
let renames = case_rename::staged(r, rel_paths)?;
|
||||
case_rename::rename_in_index(r, &renames, &env)?;
|
||||
let mut paths: Vec<_> =
|
||||
rel_paths.iter().filter(|rel| !renames.iter().any(|rename| rename.old == **rel)).cloned().collect();
|
||||
paths.extend(renames.into_iter().map(|rename| rename.new));
|
||||
cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], &paths, None, &env)?;
|
||||
let mut diff = vec!["diff", "--cached", "--binary", "--full-index"];
|
||||
diff.push(if detect_renames { "-M" } else { "--no-renames" });
|
||||
diff.extend(DIFF_FORMAT);
|
||||
@@ -383,6 +390,12 @@ fn preview_with_prefix(r: &Repo, patch: &str, prefix: &str) -> IdeResult<Vec<Pat
|
||||
// An error we could not attribute to a file: nothing applies cleanly.
|
||||
if files.iter().all(|f| f.applies) {
|
||||
files.iter_mut().for_each(|f| f.applies = false);
|
||||
} else {
|
||||
// The new name of such a rename is taken by the file it renames.
|
||||
for rename in case_rename::among(r, files.iter().map(|file| (file.path.as_str(), file.kind)))? {
|
||||
let applies = files.iter().any(|f| f.path == rename.old && f.applies);
|
||||
files.iter_mut().filter(|f| f.path == rename.new).for_each(|f| f.applies = applies);
|
||||
}
|
||||
}
|
||||
}
|
||||
for file in &mut files {
|
||||
@@ -590,6 +603,12 @@ fn apply_patch(r: &Repo, patch: &str, prefix: &str, identify_conflicts: bool) ->
|
||||
.ok_or_else(|| IdeError::invalid("The patch contains a path outside its repository"))
|
||||
})
|
||||
.collect::<IdeResult<Vec<_>>>()?;
|
||||
let renames = case_rename::among(r, files.iter().map(|file| (file.path.as_str(), file.kind)))?;
|
||||
if !renames.is_empty()
|
||||
&& let Some(outcome) = apply_case_renames(r, &patch, renames, prefix, identify_conflicts)?
|
||||
{
|
||||
return Ok(outcome);
|
||||
}
|
||||
let strip = strip_option(prefix);
|
||||
let mut args = APPLY.to_vec();
|
||||
args.extend(strip.as_deref());
|
||||
@@ -627,6 +646,50 @@ fn apply_patch(r: &Repo, patch: &str, prefix: &str, identify_conflicts: bool) ->
|
||||
Ok(ApplyOutcome { applied: clean, conflicts })
|
||||
}
|
||||
|
||||
/// Git does not add a file under a name the disk still has for the one being deleted, so the
|
||||
/// deletions go first, and come back if the rest fails. The index takes the new names, which a
|
||||
/// worktree that ignores case cannot show. `None` when the old files do not have their old content.
|
||||
fn apply_case_renames(
|
||||
r: &Repo,
|
||||
patch: &str,
|
||||
mut renames: Vec<CaseRename>,
|
||||
prefix: &str,
|
||||
identify_conflicts: bool,
|
||||
) -> IdeResult<Option<ApplyOutcome>> {
|
||||
let mut deletions = String::new();
|
||||
let mut rest = String::new();
|
||||
for (section, file) in sections(patch) {
|
||||
let renamed = renames.iter().any(|rename| rename.old == file.path);
|
||||
if renamed { &mut deletions } else { &mut rest }.push_str(section);
|
||||
}
|
||||
// Several commits can rename a file there and back; such a patch is Git's to apply in order.
|
||||
if rest.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let strip = strip_option(prefix);
|
||||
let mut args = APPLY.to_vec();
|
||||
args.extend(strip.as_deref());
|
||||
let deletions = deletions.as_bytes();
|
||||
let check = cli::run_raw(r.root(), &[args.as_slice(), &["--check", "-"]].concat(), Some(deletions))?;
|
||||
if check.code != Some(0) {
|
||||
return Ok(None);
|
||||
}
|
||||
run(r.root(), &[args.as_slice(), &["-"]].concat(), Some(deletions))?;
|
||||
let mut outcome = match apply_patch(r, &rest, prefix, identify_conflicts) {
|
||||
Ok(outcome) => outcome,
|
||||
Err(error) => {
|
||||
run(r.root(), &[args.as_slice(), &["-R", "-"]].concat(), Some(deletions))?;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
for name in renames.iter_mut().flat_map(|rename| [&mut rename.old, &mut rename.new]) {
|
||||
*name = name.strip_prefix(prefix).unwrap_or(name).to_owned();
|
||||
}
|
||||
case_rename::rename_in_index(r, &renames, &[])?;
|
||||
outcome.applied.extend(renames.into_iter().map(|rename| rename.old));
|
||||
Ok(Some(outcome))
|
||||
}
|
||||
|
||||
fn unmerged(r: &Repo) -> IdeResult<Vec<String>> {
|
||||
let out = run(r.root(), &["diff", "--name-only", "--diff-filter=U", "-z"], None)?;
|
||||
Ok(out.stdout_str().split('\0').filter(|s| !s.is_empty()).map(str::to_string).collect())
|
||||
|
||||
@@ -819,20 +819,26 @@ fn revert_files(r: &Repo, files: &[crate::ChangedFile]) -> IdeResult<()> {
|
||||
let has_head = r.has_head()?;
|
||||
let (in_head, new): (Vec<_>, Vec<_>) = files.iter().partition(|f| has_head && f.kind != ChangeKind::Added);
|
||||
let paths = |files: &[&crate::ChangedFile]| -> Vec<String> { files.iter().map(|f| f.path.clone()).collect() };
|
||||
if !in_head.is_empty() {
|
||||
let args = ["--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--"];
|
||||
run_paths(r.root(), &args, &paths(&in_head))?;
|
||||
}
|
||||
// Removed first: the new name of a case-only rename is the same file as the one to restore.
|
||||
if !new.is_empty() {
|
||||
let args = ["--literal-pathspecs", "rm", "--cached", "-q", "-r", "--ignore-unmatch", "--"];
|
||||
// Forced: the staged content may differ from the file's, which is on the shelf.
|
||||
let args = ["--literal-pathspecs", "rm", "--cached", "-f", "-q", "-r", "--ignore-unmatch", "--"];
|
||||
run_paths(r.root(), &args, &paths(&new))?;
|
||||
let renames = crate::case_rename::among(r, files.iter().map(|f| (f.path.as_str(), f.kind)))?;
|
||||
for f in new {
|
||||
let abs = r.abs_path(&f.path);
|
||||
if abs.is_file() || abs.is_symlink() {
|
||||
std::fs::remove_file(&abs)?;
|
||||
match renames.iter().find(|rename| rename.new == f.path) {
|
||||
Some(rename) => rename.remove_file(r)?,
|
||||
None => std::fs::remove_file(&abs)?,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !in_head.is_empty() {
|
||||
let args = ["--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--"];
|
||||
run_paths(r.root(), &args, &paths(&in_head))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Operations delegated to the git CLI (all writes, plus blame and textual diffs).
|
||||
|
||||
use crate::TextEncoding;
|
||||
use crate::case_rename;
|
||||
use crate::cli::{self, run};
|
||||
use crate::push_report;
|
||||
use crate::repo::{gx, resolve};
|
||||
@@ -356,7 +357,7 @@ pub(crate) fn restore_unstaged(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
pub(crate) fn unstage(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let rel = r.rel_paths(paths)?;
|
||||
let rel = case_rename::with_both_names(r, r.rel_paths(paths)?)?;
|
||||
if r.has_head()? {
|
||||
run_paths(r, &["restore", "--staged"], &rel)
|
||||
} else {
|
||||
@@ -474,6 +475,13 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Git leaves a file that has its content alone, so its old name would not come back.
|
||||
for rename in case_rename::unstaged(r, paths)? {
|
||||
let file = r.abs_path(&rename.new);
|
||||
if tracked.contains(&rename.old) && (file.is_file() || file.is_symlink()) {
|
||||
rename.remove_file(r)?;
|
||||
}
|
||||
}
|
||||
run_paths(r, &["restore", "--worktree"], &tracked)?;
|
||||
// A plain restore leaves a submodule alone. This one checks out the commit the index
|
||||
// records there and restores its tracked files, keeping its untracked ones.
|
||||
@@ -634,7 +642,7 @@ pub(crate) fn fill_commit_index(
|
||||
let paths: Vec<PathBuf> = paths.iter().map(|p| p.0.clone()).collect();
|
||||
r.rel_paths(&paths)
|
||||
};
|
||||
let exclude = rel_paths(&options.exclude)?;
|
||||
let exclude = case_rename::with_both_names(r, rel_paths(&options.exclude)?)?;
|
||||
if !exclude.is_empty() {
|
||||
let args: &[&str] = if r.has_head()? {
|
||||
&["--literal-pathspecs", "reset", "-q", "HEAD", "--"]
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Renames that only change letter case, staged on a disk that ignores case: both names are one file.
|
||||
|
||||
use ide_vcs::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
const HEAD_TEXT: &str = "one\ntwo\nthree\n";
|
||||
const EDITED: &str = "one\nTWO\nthree\n";
|
||||
|
||||
struct Rename {
|
||||
old: &'static str,
|
||||
new: &'static str,
|
||||
edited: bool,
|
||||
}
|
||||
|
||||
const RENAMES: [Rename; 4] = [
|
||||
Rename { old: "readme.md", new: "README.md", edited: false },
|
||||
Rename { old: "readme.md", new: "README.md", edited: true },
|
||||
Rename { old: "top/dir/sub/x.txt", new: "top/DIR/sub/x.txt", edited: false },
|
||||
Rename { old: "top/dir/sub/x.txt", new: "top/DIR/sub/x.txt", edited: true },
|
||||
];
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
base: PathBuf,
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// `None`, with a message, where the temporary folder is on a case-sensitive disk.
|
||||
fn new(rename: &Rename) -> Option<Self> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(base.join("probe"), "").unwrap();
|
||||
if !base.join("PROBE").exists() {
|
||||
eprintln!("the temporary folder is on a case-sensitive disk; skipping");
|
||||
return None;
|
||||
}
|
||||
let dir = base.join("work");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let fx = Fixture { _tmp: tmp, base, dir };
|
||||
fx.git(&["init", "-q", "-b", "main"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Test"),
|
||||
("user.email", "[email protected]"),
|
||||
("commit.gpgsign", "false"),
|
||||
("core.autocrlf", "false"),
|
||||
] {
|
||||
fx.git(&["config", key, value]);
|
||||
}
|
||||
fx.write(rename.old, HEAD_TEXT);
|
||||
fx.write("other.txt", "other\n");
|
||||
fx.git(&["add", "."]);
|
||||
fx.git(&["commit", "-q", "-m", "base"]);
|
||||
// `git mv dir DIR` fails on such a disk, and a file's rename would keep the folder's spelling.
|
||||
let top = |path: &'static str| if path.contains('/') { &path[..7] } else { path };
|
||||
fx.git(&["mv", top(rename.old), "moving"]);
|
||||
fx.git(&["mv", "moving", top(rename.new)]);
|
||||
if rename.edited {
|
||||
fx.write(rename.new, EDITED);
|
||||
}
|
||||
fx.write("other.txt", "changed\n");
|
||||
Some(fx)
|
||||
}
|
||||
fn git(&self, args: &[&str]) -> String {
|
||||
let out = Command::new("git").current_dir(&self.dir).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim_end().to_owned()
|
||||
}
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
std::fs::create_dir_all(self.path(rel).parent().unwrap()).unwrap();
|
||||
std::fs::write(self.path(rel), text).unwrap();
|
||||
}
|
||||
fn path(&self, rel: &str) -> PathBuf {
|
||||
self.dir.join(rel)
|
||||
}
|
||||
fn repo(&self) -> Repo {
|
||||
let repo = Repo::discover(&self.dir).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
repo
|
||||
}
|
||||
fn both(&self, rename: &Rename) -> [PathBuf; 2] {
|
||||
[self.path(rename.new), self.path(rename.old)]
|
||||
}
|
||||
fn index(&self) -> Vec<String> {
|
||||
self.git(&["ls-files"]).lines().map(str::to_owned).collect()
|
||||
}
|
||||
fn spelled(&self, rel: &str) -> bool {
|
||||
let mut dir = self.dir.clone();
|
||||
rel.split('/').all(|part| {
|
||||
let found = std::fs::read_dir(&dir).unwrap().any(|entry| entry.unwrap().file_name() == part);
|
||||
dir.push(part);
|
||||
found
|
||||
})
|
||||
}
|
||||
fn assert_as_in_head(&self, rename: &Rename, step: &str) {
|
||||
let Rename { old, edited, .. } = rename;
|
||||
assert_eq!(self.git(&["status", "--short"]), " M other.txt", "{step}: {old}, edited {edited}");
|
||||
assert_eq!(std::fs::read_to_string(self.path(old)).unwrap(), HEAD_TEXT, "{step}: {old}");
|
||||
assert!(self.spelled(old), "{step}: {old} has its old name on disk again");
|
||||
}
|
||||
fn assert_renamed(&self, rename: &Rename, step: &str) {
|
||||
let Rename { old, new, edited } = rename;
|
||||
let state = if *edited { "RM" } else { "R " };
|
||||
let expected = format!("{state} {old} -> {new}");
|
||||
let status = self.git(&["status", "--short"]);
|
||||
assert!(status.lines().any(|line| line == expected), "{step}: want {expected:?}, got {status:?}");
|
||||
let text = if *edited { EDITED } else { HEAD_TEXT };
|
||||
assert_eq!(std::fs::read_to_string(self.path(new)).unwrap(), text, "{step}: {new}");
|
||||
assert!(self.spelled(new), "{step}: {new} has its new name on disk");
|
||||
}
|
||||
}
|
||||
|
||||
fn for_each(test: impl Fn(&Fixture, &Rename)) {
|
||||
for rename in &RENAMES {
|
||||
if let Some(fx) = Fixture::new(rename) {
|
||||
fx.assert_renamed(rename, "fixture");
|
||||
test(&fx, rename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_restores_the_file_and_its_name() {
|
||||
for_each(|fx, rename| {
|
||||
let repo = fx.repo();
|
||||
let paths = fx.both(rename);
|
||||
repo.unstage(&paths).unwrap();
|
||||
repo.discard(&paths).unwrap();
|
||||
fx.assert_as_in_head(rename, "rollback");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_of_one_file_of_a_renamed_folder_leaves_the_others_renamed() {
|
||||
let Some(fx) = Fixture::new(&RENAMES[2]) else { return };
|
||||
fx.write("top/DIR/second.txt", "second\n");
|
||||
fx.git(&["add", "top/DIR/second.txt", "other.txt"]);
|
||||
fx.git(&["commit", "-q", "-m", "second"]);
|
||||
fx.git(&["mv", "top/DIR", "moving"]);
|
||||
fx.git(&["mv", "moving", "top/dir"]);
|
||||
let repo = fx.repo();
|
||||
let paths = [fx.path("top/dir/second.txt"), fx.path("top/DIR/second.txt")];
|
||||
repo.unstage(&paths).unwrap();
|
||||
repo.discard(&paths).unwrap();
|
||||
assert_eq!(fx.git(&["status", "--short"]), "R top/DIR/sub/x.txt -> top/dir/sub/x.txt");
|
||||
assert_eq!(std::fs::read_to_string(fx.path("top/dir/second.txt")).unwrap(), "second\n");
|
||||
assert_eq!(std::fs::read_to_string(fx.path("top/dir/sub/x.txt")).unwrap(), HEAD_TEXT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_before_unstaging_never_deletes_the_file() {
|
||||
for_each(|fx, rename| {
|
||||
fx.repo().discard(&fx.both(rename)).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(fx.path(rename.new)).unwrap(), HEAD_TEXT);
|
||||
assert_eq!(
|
||||
fx.git(&["diff", "--cached", "--name-status", "-M"]),
|
||||
format!("R100\t{}\t{}", rename.old, rename.new)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unstage_takes_both_names_back_to_head() {
|
||||
for names in [&[0, 1][..], &[0], &[1]] {
|
||||
for_each(|fx, rename| {
|
||||
let paths: Vec<_> = names.iter().map(|&name| fx.both(rename)[name].clone()).collect();
|
||||
fx.repo().unstage(&paths).unwrap();
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-status"]), "", "{paths:?}");
|
||||
let text = if rename.edited { EDITED } else { HEAD_TEXT };
|
||||
assert_eq!(std::fs::read_to_string(fx.path(rename.new)).unwrap(), text);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commit_without_the_rename_leaves_it_staged() {
|
||||
for_each(|fx, rename| {
|
||||
for exclude in [fx.both(rename).to_vec(), vec![fx.path(rename.new)]] {
|
||||
fx.write("other.txt", &format!("changed {}\n", exclude.len()));
|
||||
let options = CommitOptions {
|
||||
run_hooks: true,
|
||||
stage: vec![fx.path("other.txt").into()],
|
||||
exclude: exclude.iter().map(Into::into).collect(),
|
||||
..CommitOptions::default()
|
||||
};
|
||||
fx.repo().commit_with("other", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap();
|
||||
assert_eq!(fx.git(&["show", "--format=", "--name-status", "--no-renames", "HEAD"]), "M\tother.txt");
|
||||
assert_eq!(fx.git(&["ls-tree", "-r", "--name-only", "HEAD", rename.old]), rename.old);
|
||||
fx.assert_renamed(rename, "commit");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shelve_and_unshelve_take_the_rename_along() {
|
||||
for_each(|fx, rename| {
|
||||
for paths in [fx.both(rename).to_vec(), vec![fx.path(rename.new)]] {
|
||||
let repo = fx.repo();
|
||||
let shelf = fx.base.join("shelf");
|
||||
let entry = repo.shelve(&shelf, "rename", &paths).unwrap();
|
||||
fx.assert_as_in_head(rename, "shelve");
|
||||
let outcome = repo.unshelve(&shelf, &entry.id, true).unwrap();
|
||||
assert!(outcome.conflicts.is_empty());
|
||||
fx.assert_renamed(rename, "unshelve");
|
||||
assert!(shelf::list(&shelf).unwrap().is_empty());
|
||||
assert_eq!(fx.git(&["diff", "--name-only", "--", "other.txt"]), "other.txt");
|
||||
}
|
||||
|
||||
let repo = fx.repo();
|
||||
let shelf = fx.base.join("combined");
|
||||
let part = shelf::ShelfCapture::capture(&repo, &fx.base, &fx.both(rename)).unwrap();
|
||||
let entry = shelf::save_combined(&shelf, &fx.base, "rename", std::slice::from_ref(&part)).unwrap();
|
||||
part.revert(&repo).unwrap();
|
||||
fx.assert_as_in_head(rename, "combined shelve");
|
||||
for selection in shelf::selections(&shelf, &entry.id, None).unwrap() {
|
||||
selection.apply(&repo).unwrap();
|
||||
}
|
||||
fx.assert_renamed(rename, "combined unshelve");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unshelve_that_fails_leaves_the_file_and_the_shelf() {
|
||||
for_each(|fx, rename| {
|
||||
let repo = fx.repo();
|
||||
let shelf = fx.base.join("shelf");
|
||||
fx.write("new.txt", "shelved\n");
|
||||
let mut paths = fx.both(rename).to_vec();
|
||||
paths.push(fx.path("new.txt"));
|
||||
let entry = repo.shelve(&shelf, "rename", &paths).unwrap();
|
||||
fx.write("new.txt", "in the way\n");
|
||||
repo.unshelve(&shelf, &entry.id, true).unwrap_err();
|
||||
assert_eq!(std::fs::read_to_string(fx.path(rename.old)).unwrap(), HEAD_TEXT);
|
||||
assert_eq!(std::fs::read_to_string(fx.path("new.txt")).unwrap(), "in the way\n");
|
||||
assert_eq!(shelf::list(&shelf).unwrap().len(), 1);
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-status"]), "");
|
||||
|
||||
// The file the rename starts from has local edits, so its old content cannot be taken away.
|
||||
std::fs::remove_file(fx.path("new.txt")).unwrap();
|
||||
fx.write(rename.old, "one\ntwo\nlocal\n");
|
||||
repo.unshelve(&shelf, &entry.id, true).unwrap_err();
|
||||
assert_eq!(std::fs::read_to_string(fx.path(rename.old)).unwrap(), "one\ntwo\nlocal\n");
|
||||
assert_eq!(shelf::list(&shelf).unwrap().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_patch_has_the_rename_and_its_preview_applies() {
|
||||
for_each(|fx, rename| {
|
||||
let repo = fx.repo();
|
||||
let shelf = fx.base.join("shelf");
|
||||
let patch = repo.create_patch(&fx.both(rename), false).unwrap();
|
||||
for name in [rename.old, rename.new] {
|
||||
assert!(patch.contains(name), "{name}: {patch}");
|
||||
}
|
||||
let entry = repo.shelve(&shelf, "rename", &fx.both(rename)).unwrap();
|
||||
let patch = shelf::patch_of(&shelf, &entry.id).unwrap();
|
||||
let preview = repo.patch_preview(&patch).unwrap();
|
||||
assert_eq!(preview.len(), 2);
|
||||
assert!(preview.iter().all(|file| file.applies), "{preview:#?}");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_git_has_not_been_told_about_stays_the_file_of_the_index() {
|
||||
for_each(|fx, rename| {
|
||||
fx.git(&["reset", "-q", "HEAD"]);
|
||||
let repo = fx.repo();
|
||||
let on_disk = fx.path(rename.new);
|
||||
if rename.edited {
|
||||
let status = repo.status().unwrap();
|
||||
let file = status.iter().find(|file| file.rel_path == rename.old).unwrap();
|
||||
assert_eq!((file.path.0.as_path(), file.unstaged), (Path::new(&on_disk), Some(ChangeKind::Modified)));
|
||||
repo.discard(&[on_disk]).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(fx.path(rename.old)).unwrap(), HEAD_TEXT);
|
||||
assert_eq!(fx.git(&["status", "--short"]), " M other.txt");
|
||||
assert!(fx.index().contains(&rename.old.to_owned()));
|
||||
});
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача