fix(vcs): keep a deleted new file deleted after Pull, checkout, merge (#7343)

A new file staged and then deleted came back after Pull, checkout or merge: preserving local changes stashed and restored it. The deletions are now recorded and reapplied after the restore, across every batch of Git path queries; pre-existing empty folders are recreated, and a restore Git blocks keeps its marker and deletion record for the retry.

Closes #7333

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-02 14:47:00 +08:00
1 джерело 44ccaaef26
коміт 300424658a
7 files changed
+511 -18

No files matched your search

+5 -2
Переглянути файл
@@ -355,11 +355,14 @@ pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> Id
let wanted = undo.paths();
let skipped = project.history.restore_deletion_undo(undo);
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
// takes that back, keeping the restored content. Git records deletions at commit time.
// takes that back, keeping the restored content. Git records deletions at commit time
// (a file it dropped from the index because it was only added comes back unversioned).
// One call per working copy: its first folder takes the tree below with it anyway.
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
let Some(backend) = project.backend_of(path) else { continue };
let Some(backend) = project.backend_of(path).filter(|b| b.kind() != ide_vcs::VcsKind::Git) else {
continue;
};
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, paths)) => paths.push(path.clone()),
None => by_backend.push((backend, vec![path.clone()])),
+79
Переглянути файл
@@ -0,0 +1,79 @@
//! #7333: Delete of a file that was only added to Git also drops it from the index, as IDEA
//! does, so it does not linger as `AD`; Undo brings the content back without touching the index.
mod common;
use ide_host::{Host, Project};
use std::{
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::Duration,
};
fn git(root: &Path, args: &[&str]) -> String {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim_end().to_owned()
}
fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
(temp, base, root)
}
async fn open(base: &Path, root: &Path) -> (Host, Arc<Project>) {
let host = Host::new(common::host_config(base));
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
(host, project)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deleting_an_added_file_drops_it_from_the_index_and_undo_keeps_the_index() {
let (_temp, base, root) = repo();
std::fs::write(root.join("staged.txt"), "base\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "base"]);
std::fs::create_dir(root.join("dir")).unwrap();
std::fs::write(root.join("dir/new file.txt"), "new\n").unwrap();
std::fs::write(root.join("staged.txt"), "staged\n").unwrap();
git(&root, &["add", "."]);
let (host, project) = open(&base, &root).await;
// What Delete does (`delete_recorded`: the same paths, history, removal and backend hook),
// without the system Trash `fs_delete_with_undo` moves things to.
let delete = |path: &Path| {
let paths = ide_workspace::file_ops::deletion_paths(path).unwrap();
let undo = project.history.capture_deletion_undo(&paths, 1 << 20);
if path.is_dir() {
std::fs::remove_dir_all(path).unwrap()
} else {
std::fs::remove_file(path).unwrap()
}
project.with_backend_of(path, |b| b.files_deleted(&paths)).unwrap();
undo
};
let undo_dir = delete(&root.join("dir"));
let undo_staged = delete(&root.join("staged.txt"));
assert_eq!(git(&root, &["status", "--porcelain"]), "MD staged.txt");
ide_host::ops::fs::fs_undo_delete(&host, "main", undo_dir).await.unwrap();
ide_host::ops::fs::fs_undo_delete(&host, "main", undo_staged).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("dir/new file.txt")).unwrap(), "new\n");
// The staged edit stays staged; the added file comes back unversioned.
assert_eq!(git(&root, &["status", "--porcelain", "-uall"]), "M staged.txt\n?? \"dir/new file.txt\"");
}
+7 -2
Переглянути файл
@@ -308,8 +308,8 @@ pub trait Backend: Send + Sync + Any {
/// Files or folders the IDE deleted (project tree Delete, refactorings).
/// A checkout backend opens them for delete (`p4 delete`); Git records the
/// deletion at commit time, so this is a no-op. Called after they are gone
/// from disk.
/// deletion at commit time, but drops files that were only added from the
/// index. Called after they are gone from disk.
fn files_deleted(&self, _paths: &[PathBuf]) -> IdeResult<()> {
Ok(())
}
@@ -456,6 +456,11 @@ impl Backend for Repo {
Repo::unstage(self, paths)
}
fn files_deleted(&self, paths: &[PathBuf]) -> IdeResult<()> {
let _scope = self.execution_scope();
crate::write::forget_deleted_added(self, paths)
}
fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
Repo::discard(self, paths)
}
+5 -2
Переглянути файл
@@ -218,7 +218,7 @@ pub(crate) fn batch_paths(base_len: usize, paths: &[String], limit: usize) -> Ve
/// [`run`] with a list of paths appended after `--`, split into as many invocations as
/// the platform's command-line limit needs (a large rollback would otherwise fail with
/// `os error 206` on Windows). `args` must already carry `--literal-pathspecs` and
/// end with `--`; the first error stops the remaining batches.
/// end with `--`; the output joins every batch's, and the first error stops the rest.
pub(crate) fn run_paths_env(
root: &Path,
args: &[&str],
@@ -234,7 +234,10 @@ pub(crate) fn run_paths_env(
for batch in batch_paths(base_len, paths, command_line_limit()) {
let mut full: Vec<&str> = args.to_vec();
full.extend(batch.iter().map(String::as_str));
out = run_env(root, &full, stdin, env)?;
let batch = run_env(root, &full, stdin, env)?;
out.stdout.extend(batch.stdout);
out.stderr.extend(batch.stderr);
out.code = batch.code;
}
Ok(out)
}
+142 -12
Переглянути файл
@@ -9,12 +9,15 @@ use crate::write::{drop_restored_stash, selected_stash_index, unmerged_paths};
use crate::{Repo, Stash};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::io::Write;
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};
/// `.git/<MARKER>` holds the saved entry to restore. Older versions stored only a stash commit id.
const MARKER: &str = "openidea-saved-changes";
/// `.git/<DELETED>` lists the [`deleted_files`] of the saved entry and, ending in `/`, the
/// folders above them that existed, NUL-separated.
const DELETED: &str = "openidea-saved-deletions";
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
@@ -42,7 +45,16 @@ fn save_locked(r: &Repo, message: &str) -> IdeResult<Option<Saved>> {
if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() {
return Ok(None);
}
let mut deleted = deleted_files(r)?;
// The stash removes a folder that only held such files: it was there before.
deleted.extend(existing_folders(r, &deleted));
let Some(stash) = stash_local_changes(r, message)? else { return Ok(None) };
let deleted_list = r.git_dir.join(DELETED);
if deleted.is_empty() {
remove_if_exists(&deleted_list)?;
} else if let Err(error) = std::fs::write(&deleted_list, deleted.join("\0")) {
return Err(rolled_back(error.into(), restore_entry(r, Saved::Stash(stash), false)));
}
let saved = Saved::Stash(stash);
write_marker(r, &saved)?;
let options = r.automatic_shelf.read().unwrap_or_else(|poison| poison.into_inner()).clone();
@@ -169,6 +181,85 @@ fn apply_snapshot(r: &Repo, snapshot: &str, allow_unstaged: bool) -> IdeResult<V
Ok(Vec::new())
}
/// Staged files deleted from the working tree. A stash records no such deletion when HEAD lacks
/// the path (`AD`, `RD`): its working tree keeps the staged file, which comes back on restore.
fn deleted_files(r: &Repo) -> IdeResult<Vec<String>> {
let out = run(r.root(), &["diff", "--name-only", "--no-renames", "--diff-filter=D", "-z"], None)?;
Ok(out.stdout_str().split('\0').filter(|p| !p.is_empty()).map(str::to_owned).collect())
}
/// Folders above [`deleted_files`] that exist, relative and ending in `/`.
fn existing_folders(r: &Repo, gone: &[String]) -> Vec<String> {
gone.iter()
.flat_map(|path| path.match_indices('/').map(move |(end, _)| &path[..=end]))
.filter(|folder| r.abs_path(folder).is_dir())
.collect::<BTreeSet<_>>()
.into_iter()
.map(str::to_owned)
.collect()
}
/// The stash apply itself can remove an empty directory when replaying a tracked deletion.
/// Parents come first. Stop at a file or symlink the operation put in place of a directory.
fn restore_folders(r: &Repo, folders: &BTreeSet<PathBuf>) -> IdeResult<()> {
let mut directories = HashSet::from([r.root()]);
for folder in folders {
if !folder.parent().is_some_and(|parent| directories.contains(parent)) {
continue;
}
match std::fs::create_dir(folder) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
if !std::fs::symlink_metadata(folder)?.is_dir() {
continue;
}
}
Err(error) => return Err(error.into()),
}
directories.insert(folder.as_path());
}
Ok(())
}
/// The restored [`deleted_files`] that came back on disk are deleted again, unless the operation
/// changed the path, or the index entry or file differs from the saved index.
fn delete_again(r: &Repo, snapshot: &str, gone: &[String], existing: &BTreeSet<PathBuf>) -> IdeResult<()> {
if gone.is_empty() {
return Ok(());
}
let base = format!("{snapshot}^1");
let saved_index = format!("{snapshot}^2");
let names = |args: &[&str], paths: &[String]| -> IdeResult<HashSet<String>> {
let mut full = vec!["--literal-pathspecs"];
full.extend_from_slice(args);
full.extend(["--name-only", "--no-renames", "-z", "--"]);
let out = cli::run_paths(r.root(), &full, paths)?;
Ok(out.stdout_str().split('\0').filter(|p| !p.is_empty()).map(str::to_owned).collect())
};
let keep: HashSet<String> = [
names(&["diff", "--no-ext-diff", &base, "HEAD"], gone)?,
names(&["diff", "--no-ext-diff", "--cached", &saved_index], gone)?,
// Also lists a path whose file is missing, which leaves nothing to delete.
names(&["diff", "--no-ext-diff", &saved_index], gone)?,
]
.into_iter()
.flatten()
.collect();
for path in gone.iter().filter(|path| !keep.contains(*path)) {
let file = r.abs_path(path);
std::fs::remove_file(&file)?;
// A folder the restore created for the deleted files only does not stay behind empty.
let mut dir = file.parent();
while let Some(parent) = dir.filter(|dir| *dir != r.root() && !existing.contains(*dir)) {
if std::fs::remove_dir(parent).is_err() {
break;
}
dir = parent.parent();
}
}
Ok(())
}
/// `stash apply --index` applies a patch without a three-way fallback. The patch
/// can fail on context even when both the staged and working changes merge cleanly.
fn merge_saved_index(r: &Repo, snapshot: &str) -> IdeResult<Option<(String, String)>> {
@@ -187,18 +278,57 @@ fn merge_saved_index(r: &Repo, snapshot: &str) -> IdeResult<Option<(String, Stri
Ok((before != merged).then_some((before, merged)))
}
fn remove_if_exists(path: &Path) -> IdeResult<()> {
match std::fs::remove_file(path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
fn restore_entry(r: &Repo, saved: Saved, allow_unstaged: bool) -> IdeResult<Vec<String>> {
std::fs::remove_file(r.git_dir.join(MARKER))?;
let deleted_list = r.git_dir.join(DELETED);
let record = match std::fs::read(&deleted_list) {
Ok(record) => record,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(error) => return Err(error.into()),
};
let (folders, deleted): (Vec<_>, Vec<_>) = String::from_utf8_lossy(&record)
.split('\0')
.filter(|p| !p.is_empty())
.map(str::to_owned)
.partition(|path| path.ends_with('/'));
let snapshot = match &saved {
Saved::Stash(stash) => &stash.id,
Saved::Shelf { snapshot, .. } => snapshot,
Saved::Shelves(shelves) => &shelves.snapshot,
};
// A restore that did not run keeps the record along with the saved changes.
let conflicts = restore_entry_files(r, &saved, allow_unstaged)?;
remove_if_exists(&r.git_dir.join(MARKER))?;
// With conflicts elsewhere, the other files were still restored.
let deleted: Vec<String> = deleted.into_iter().filter(|path| !conflicts.contains(path)).collect();
let existing = folders
.iter()
.filter(|folder| Path::new(folder).components().all(|part| matches!(part, Component::Normal(_))))
.map(|folder| r.abs_path(folder.trim_end_matches('/')))
.collect();
if let Err(error) = delete_again(r, snapshot, &deleted, &existing).and_then(|()| restore_folders(r, &existing)) {
tracing::warn!(%error, "could not restore the deleted files and their folders");
}
remove_if_exists(&deleted_list)?;
if conflicts.is_empty()
&& let Saved::Stash(stash) = saved
{
drop_restored_stash(r, &stash)?;
}
Ok(conflicts)
}
fn restore_entry_files(r: &Repo, saved: &Saved, allow_unstaged: bool) -> IdeResult<Vec<String>> {
match saved {
Saved::Stash(stash) => {
let conflicts = apply_snapshot(r, &stash.id, allow_unstaged)?;
if conflicts.is_empty() {
drop_restored_stash(r, &stash)?;
}
Ok(conflicts)
}
Saved::Stash(stash) => apply_snapshot(r, &stash.id, allow_unstaged),
Saved::Shelf { directory, entry, snapshot } => {
let restored = restore_shelf(r, &directory, &entry, &snapshot, allow_unstaged);
let restored = restore_shelf(r, directory, entry, snapshot, allow_unstaged);
if restored.as_ref().is_ok_and(|files| !files.is_empty()) {
crate::conflict_resolution::record_conflicts(
r,
@@ -208,7 +338,7 @@ fn restore_entry(r: &Repo, saved: Saved, allow_unstaged: bool) -> IdeResult<Vec<
restored
}
Saved::Shelves(shelves) => {
let restored = restore_shelves(r, &shelves, allow_unstaged);
let restored = restore_shelves(r, shelves, allow_unstaged);
if restored.is_ok() {
shelves.remove_archive();
}
+16
Переглянути файл
@@ -364,6 +364,22 @@ pub(crate) fn unstage(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
}
}
/// IDEA: a deleted file that was only added (not yet committed) also leaves the index, rather
/// than staying staged as added while gone from disk (`AD`).
pub(crate) fn forget_deleted_added(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
let rel = r.rel_paths(paths)?;
let args =
["--literal-pathspecs", "diff", "--cached", "--name-only", "--no-renames", "--diff-filter=A", "-z", "--"];
let out = cli::run_paths(r.root(), &args, &rel)?;
let added: Vec<String> = out
.stdout_str()
.split('\0')
.filter(|path| !path.is_empty() && std::fs::symlink_metadata(r.abs_path(path)).is_err())
.map(str::to_owned)
.collect();
run_paths(r, &["rm", "--cached", "-q", "--ignore-unmatch"], &added)
}
pub(crate) fn stage_patch(r: &Repo, patch: &str, encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>) -> IdeResult<()> {
if patch.trim().is_empty() {
return Ok(());
+257
Переглянути файл
@@ -74,6 +74,7 @@ impl Fixture {
configure(&other);
}
git_in(&other, &["pull", "-q", "--rebase"]);
std::fs::create_dir_all(other.join(rel).parent().unwrap()).unwrap();
std::fs::write(other.join(rel), content).unwrap();
git_in(&other, &["add", "-A"]);
git_in(&other, &["commit", "-q", "-m", &format!("remote {rel}")]);
@@ -3570,3 +3571,259 @@ fn local_changes_come_back_after_a_conflicting_merge_is_committed() {
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt");
assert!(fx.git(&["stash", "list"]).is_empty());
}
// #7333: a file added to the index and then deleted (`AD`) stays deleted around operations
// that put local changes aside.
/// `with_origin` plus local changes: `rel` added then deleted, a staged and an unstaged edit.
fn added_then_deleted(fx: &Fixture, rel: &str) {
fx.write("staged.txt", "base\n");
fx.write("unstaged.txt", "base\n");
fx.commit_all("more");
fx.git(&["push", "-q", "origin", "main"]);
fx.write(rel, "new\n");
fx.git(&["add", "--", rel]);
std::fs::remove_file(fx.path(rel)).unwrap();
fx.write("staged.txt", "staged\n");
fx.git(&["add", "staged.txt"]);
fx.write("unstaged.txt", "unstaged\n");
}
fn porcelain(fx: &Fixture) -> String {
fx.git(&["status", "--porcelain", "--untracked-files=no"])
}
fn assert_ad_kept(fx: &Fixture, rel: &str, before: &str) {
assert!(!fx.exists(rel), "{rel} came back");
assert_eq!(porcelain(fx), before);
assert_eq!(fx.git(&["show", &format!(":{rel}")]), "new");
assert!(fx.repo().stashes().unwrap().is_empty());
}
#[test]
fn pull_keeps_an_added_then_deleted_file_deleted() {
for automatic_shelf in [false, true] {
let (fx, bare) = Fixture::with_origin();
added_then_deleted(&fx, "new.txt");
let before = porcelain(&fx);
assert!(before.contains("AD new.txt"), "{before}");
fx.push_from_other(&bare, "remote.txt", "remote\n");
let repo = fx.repo();
if automatic_shelf {
repo.set_automatic_shelf(Some(fx.tmp.path().join("shelf")), None);
}
let (cancel, out) = quiet();
repo.pull(false, &cancel, &out).unwrap();
assert_eq!(fx.read("remote.txt"), "remote\n");
assert_ad_kept(&fx, "new.txt", &before);
}
}
#[test]
fn pull_keeps_a_deleted_new_file_in_nested_unicode_folders_deleted() {
let (fx, bare) = Fixture::with_origin();
let rel = "dir one/子目录/新 file.txt";
added_then_deleted(&fx, rel);
std::fs::remove_dir_all(fx.path("dir one")).unwrap();
let before = porcelain(&fx);
fx.push_from_other(&bare, "remote.txt", "remote\n");
let (cancel, out) = quiet();
fx.repo().pull(true, &cancel, &out).unwrap();
assert_ad_kept(&fx, rel, &before);
assert!(!fx.exists("dir one"), "the folder came back empty");
}
#[test]
fn pull_keeps_a_renamed_then_deleted_file_deleted() {
let (fx, bare) = Fixture::with_origin();
fx.git(&["mv", "a.txt", "renamed.txt"]);
std::fs::remove_file(fx.path("renamed.txt")).unwrap();
let before = porcelain(&fx);
assert!(before.contains("RD a.txt -> renamed.txt"), "{before}");
fx.push_from_other(&bare, "remote.txt", "remote\n");
let (cancel, out) = quiet();
fx.repo().pull(false, &cancel, &out).unwrap();
assert!(!fx.exists("renamed.txt"));
assert_eq!(porcelain(&fx), before);
}
#[test]
fn pull_keeps_the_file_a_pulled_commit_adds_at_the_same_path() {
let (fx, bare) = Fixture::with_origin();
added_then_deleted(&fx, "new.txt");
fx.push_from_other(&bare, "new.txt", "new\n");
let (cancel, out) = quiet();
fx.repo().pull(false, &cancel, &out).unwrap();
// Now tracked by the pulled commit: never deleted from under it.
assert_eq!(fx.read("new.txt"), "new\n");
assert_eq!(fx.git(&["show", "HEAD:new.txt"]), "new");
assert!(fx.repo().stashes().unwrap().is_empty());
}
#[test]
fn a_conflicting_restore_leaves_the_added_then_deleted_file_alone() {
let (fx, bare) = Fixture::with_origin();
added_then_deleted(&fx, "new.txt");
fx.push_from_other(&bare, "staged.txt", "remote\n");
let (cancel, out) = quiet();
assert!(fx.repo().pull(false, &cancel, &out).is_err());
assert!(!fx.git(&["diff", "--name-only", "--diff-filter=U"]).is_empty());
// The rest of the restore ran: the deleted file stays deleted, the stash keeps a copy.
assert_eq!(fx.repo().stashes().unwrap().len(), 1);
assert!(!fx.exists("new.txt"), "new.txt came back");
assert!(!fx.exists(".git/openidea-saved-deletions"));
fx.write("staged.txt", "resolved\n");
fx.git(&["add", "staged.txt"]);
assert!(!fx.exists("new.txt"));
assert!(fx.git(&["status", "--porcelain", "--", "new.txt"]).starts_with("AD"));
}
#[test]
fn blocked_restore_keeps_the_deletion_record_for_the_next_attempt() {
let (fx, _) = Fixture::with_origin();
fx.git(&["switch", "-qc", "side"]);
fx.write("a.txt", "side\n");
fx.commit_all("side");
fx.git(&["switch", "-q", "main"]);
fx.write("a.txt", "main\n");
fx.commit_all("main");
added_then_deleted(&fx, "new.txt");
let before = porcelain(&fx);
let repo = fx.repo();
assert!(repo.merge("side").is_err());
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("merge"));
fx.write("a.txt", "resolved\n");
fx.git(&["add", "a.txt"]);
fx.write("new.txt", "untracked blocker\n");
let (cancel, out) = quiet();
assert!(repo.continue_operation(&cancel, &out).is_err());
assert_eq!(repo.branch_info().unwrap().operation, None);
assert_eq!(fx.read("new.txt"), "untracked blocker\n");
assert!(fx.exists(".git/openidea-saved-changes"));
assert!(fx.exists(".git/openidea-saved-deletions"));
std::fs::remove_file(fx.path("new.txt")).unwrap();
repo.merge("side").unwrap();
assert_ad_kept(&fx, "new.txt", &before);
assert!(!fx.exists(".git/openidea-saved-changes"));
assert!(!fx.exists(".git/openidea-saved-deletions"));
}
#[test]
fn pull_keeps_more_deleted_new_files_than_one_command_line_holds_deleted() {
let (fx, bare) = Fixture::with_origin();
let folder = "f".repeat(100);
let paths: Vec<String> = (0..700).map(|i| format!("{folder}/{i:04}-{}.txt", "n".repeat(110))).collect();
for path in &paths {
fx.write(path, "new\n");
}
fx.git(&["add", "-A"]);
std::fs::remove_dir_all(fx.path(&folder)).unwrap();
assert_eq!(porcelain(&fx).lines().count(), 700);
// The pulled commit adds the first path, which lands in the first batch of path arguments.
fx.push_from_other(&bare, &paths[0], "new\n");
let (cancel, out) = quiet();
fx.repo().pull(false, &cancel, &out).unwrap();
assert_eq!(fx.read(&paths[0]), "new\n", "a file the pulled commit tracks was deleted");
assert!(paths[1..].iter().all(|path| !fx.exists(path)), "deleted files came back");
assert_eq!(porcelain(&fx).lines().count(), 699);
}
#[test]
fn pull_keeps_a_folder_that_existed_empty_before_saving() {
let (fx, bare) = Fixture::with_origin();
added_then_deleted(&fx, "dir/new.txt");
assert!(fx.path("dir").is_dir());
fx.push_from_other(&bare, "remote.txt", "remote\n");
let (cancel, out) = quiet();
fx.repo().pull(false, &cancel, &out).unwrap();
assert!(!fx.exists("dir/new.txt"));
assert!(fx.path("dir").is_dir(), "the empty folder was removed");
}
#[test]
fn pull_recreates_an_existing_empty_folder_removed_by_stash_apply() {
let (fx, bare) = Fixture::with_origin();
let folder = "dir/empty";
let file = "dir/empty/tracked.txt";
fx.write(file, "tracked\n");
fx.commit_all("track nested file");
fx.git(&["push", "-q", "origin", "main"]);
std::fs::remove_file(fx.path(file)).unwrap();
fx.push_from_other(&bare, "remote.txt", "remote\n");
let (cancel, out) = quiet();
fx.repo().pull(false, &cancel, &out).unwrap();
assert_eq!(porcelain(&fx), "D dir/empty/tracked.txt");
assert!(fx.path(folder).is_dir(), "stash apply removed the existing empty folder");
}
#[test]
fn deleting_more_added_files_than_one_command_line_holds_drops_them_all() {
let fx = Fixture::new();
fx.write("base.txt", "base\n");
fx.commit_all("base");
let folder = "f".repeat(100);
let paths: Vec<PathBuf> = (0..700).map(|i| fx.path(&format!("{folder}/{i:04}-{}.txt", "n".repeat(110)))).collect();
for path in &paths {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "new\n").unwrap();
}
fx.git(&["add", "-A"]);
std::fs::remove_dir_all(fx.path(&folder)).unwrap();
Backend::files_deleted(&fx.repo(), &paths).unwrap();
assert_eq!(porcelain(&fx), "");
}
#[test]
fn checkout_merge_and_rebase_keep_an_added_then_deleted_file_deleted() {
for op in ["checkout", "merge", "rebase"] {
let (fx, _bare) = Fixture::with_origin();
fx.write("staged.txt", "base\n");
fx.write("unstaged.txt", "base\n");
fx.commit_all("more");
fx.git(&["switch", "-qc", "other"]);
fx.write("other.txt", "other\n");
fx.commit_all("other");
fx.git(&["switch", "-q", "main"]);
if op == "rebase" {
fx.write("main.txt", "main\n");
fx.commit_all("main");
}
fx.write("new.txt", "new\n");
fx.git(&["add", "new.txt"]);
std::fs::remove_file(fx.path("new.txt")).unwrap();
fx.write("staged.txt", "staged\n");
fx.git(&["add", "staged.txt"]);
fx.write("unstaged.txt", "unstaged\n");
let before = porcelain(&fx);
let repo = fx.repo();
match op {
"checkout" => repo.checkout("other", false).unwrap(),
"merge" => repo.merge("other").unwrap(),
_ => repo.rebase("other").unwrap(),
}
assert!(fx.exists("other.txt"), "{op}");
assert_ad_kept(&fx, "new.txt", &before);
}
}
#[test]
fn deleting_an_added_file_drops_it_from_the_index() {
let fx = Fixture::new();
fx.write("tracked.txt", "base\n");
fx.write("staged.txt", "base\n");
fx.commit_all("base");
fx.write("dir/new one.txt", "new\n");
fx.write("dir/kept.txt", "kept\n");
fx.write("staged.txt", "staged\n");
fx.git(&["add", "-A"]);
for rel in ["dir/new one.txt", "tracked.txt", "staged.txt"] {
std::fs::remove_file(fx.path(rel)).unwrap();
}
let repo = fx.repo();
let paths = ["dir/new one.txt", "tracked.txt", "staged.txt", "dir/kept.txt"].map(|rel| fx.path(rel));
Backend::files_deleted(&repo, &paths).unwrap();
// Only the added file that is gone leaves the index; committed files stay deletions.
assert_eq!(porcelain(&fx), "A dir/kept.txt\nMD staged.txt\n D tracked.txt");
}