Skip to main content

grit_lib/porcelain/
paths.rs

1//! Remove and rename paths in the working tree and index (`git rm` / `git mv` semantics).
2
3use crate::diff::{
4    diff_index_to_tree, diff_index_to_worktree_with_options, DiffIndexToWorktreeOptions, DiffStatus,
5};
6use crate::error::{Error, ErrorSummary, PathOutsideRepoError, Result};
7use crate::git_path::CanonicalizeExt;
8use crate::index::{index_file_mtime, Index, IndexEntry, MODE_GITLINK, MODE_TREE};
9use crate::objects::ObjectId;
10use crate::path_icase::{paths_equal, worktree_filesystem_case_insensitive};
11use crate::path_validate::{validate_path, EntryMode, PathValidationKind, ProtectOptions};
12use crate::pathspec::{
13    is_plain_literal_pathspec, literal_spec_for_lookup, matches_pathspec_list_with_context,
14    pathspec_is_exclude, PathspecMatchContext,
15};
16use crate::porcelain::checkout::remove_empty_parent_dirs_batch;
17use crate::porcelain::pathspec_match::{
18    index_stage0_path_modes, RepositoryPathspecFilter, REGULAR_FILE_MODE,
19};
20use crate::progress::{poll_cancel, CancelToken, NullProgress};
21use crate::repo::{Repository, RepositoryError};
22use crate::worktree::WorktreeError;
23use std::collections::{BTreeSet, HashSet};
24use std::fs;
25use std::path::{Component, Path, PathBuf};
26use std::sync::{Arc, Mutex};
27
28/// Options for [`remove_paths`].
29#[derive(Debug, Clone, Default)]
30pub struct RemoveOptions {
31    /// Resolved pathspec patterns (repository-relative).
32    pub pathspecs: Vec<String>,
33    /// Original pathspec argv fragments for errors (defaults to `pathspecs` when empty).
34    pub pathspec_sources: Vec<String>,
35    /// Remove from the index only; leave the working tree file in place.
36    pub cached: bool,
37    /// Remove even when the path has staged or unstaged local modifications.
38    pub force: bool,
39    /// Allow removing directories (all tracked paths under a directory prefix).
40    pub recursive: bool,
41    /// Run every check and report [`RemoveOutcome::removed`] without writing the index or work tree.
42    pub dry_run: bool,
43    /// Treat non-matching pathspecs as success with an empty removal list.
44    pub ignore_unmatch: bool,
45}
46
47impl RemoveOptions {
48    /// When `recursive` is false, infer directory removal from trailing slashes or existing directories.
49    ///
50    /// # Errors
51    ///
52    /// Returns [`RepositoryError::RequiresWorkTree`] when the repository has no work tree.
53    pub fn resolve_recursive(&mut self, repo: &Repository) -> Result<()> {
54        if self.recursive {
55            return Ok(());
56        }
57        self.recursive = infer_remove_recursive(repo, &self.pathspec_sources, &self.pathspecs)?;
58        Ok(())
59    }
60}
61
62/// Result of [`remove_paths`].
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct RemoveOutcome {
65    /// Repository-relative paths removed from the index (and usually the work tree).
66    pub removed: Vec<String>,
67}
68
69/// Why [`remove_paths`] refused to remove a path without [`RemoveOptions::force`].
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum RemoveBlockReason {
72    /// The index entry differs from `HEAD` (or there is no `HEAD` commit yet) while the work
73    /// tree file matches the index. Deleting the file would lose the staged content;
74    /// [`RemoveOptions::cached`] keeps it on disk.
75    StagedChanges,
76    /// The work tree file differs from the index while the index matches `HEAD`. Deleting
77    /// the file would lose the edits; [`RemoveOptions::cached`] keeps it on disk.
78    LocalModifications,
79    /// The index entry differs from both `HEAD` and the work tree file, so the staged
80    /// content exists nowhere else. Refused even with [`RemoveOptions::cached`].
81    StagedAndLocal,
82}
83
84impl RemoveBlockReason {
85    /// Decide whether a path is refused, given how its index entry compares.
86    ///
87    /// # Parameters
88    ///
89    /// - `staged`: the index entry differs from `HEAD`, or there is no `HEAD` commit.
90    /// - `local`: the work tree file differs from the index entry.
91    /// - `cached`: the removal keeps the work tree file ([`RemoveOptions::cached`]).
92    ///
93    /// # Returns
94    ///
95    /// `None` when the path may be removed without `force`.
96    #[must_use]
97    pub fn classify(staged: bool, local: bool, cached: bool) -> Option<Self> {
98        match (staged, local) {
99            (true, true) => Some(Self::StagedAndLocal),
100            (true, false) if !cached => Some(Self::StagedChanges),
101            (false, true) if !cached => Some(Self::LocalModifications),
102            _ => None,
103        }
104    }
105
106    /// Whether retrying with [`RemoveOptions::cached`] would remove the path.
107    #[must_use]
108    pub fn allowed_with_cached(self) -> bool {
109        !matches!(self, Self::StagedAndLocal)
110    }
111}
112
113impl std::fmt::Display for RemoveBlockReason {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str(match self {
116            Self::StagedChanges => "staged changes",
117            Self::LocalModifications => "local modifications",
118            Self::StagedAndLocal => "staged content differs from both HEAD and the working tree",
119        })
120    }
121}
122
123/// A path [`remove_paths`] refused to remove, carried by [`crate::worktree::WorktreeError::RemoveBlocked`].
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct BlockedRemoval {
126    /// Repository-relative path that was not removed.
127    pub path: String,
128    /// Why removing it would lose content.
129    pub reason: RemoveBlockReason,
130}
131
132impl std::fmt::Display for BlockedRemoval {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "{} ({})", self.path, self.reason)
135    }
136}
137
138/// One tracked path rename performed by [`move_paths`].
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct PathMove {
141    /// Source path before the move.
142    pub from: String,
143    /// Destination path after the move.
144    pub to: String,
145}
146
147/// Options for [`move_paths`].
148#[derive(Debug, Clone)]
149pub struct MoveOptions {
150    /// Tracked source paths to move (repository-relative).
151    pub sources: Vec<String>,
152    /// Destination path or existing directory.
153    pub destination: String,
154    /// Replace an existing destination in the work tree and index.
155    pub force: bool,
156    /// Validate and report [`MoveOutcome::moves`] without writing the index or work tree.
157    pub dry_run: bool,
158}
159
160/// Result of [`move_paths`] and [`move_path`].
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct MoveOutcome {
163    /// Individual renames applied (or that would be applied when `dry_run`).
164    pub moves: Vec<PathMove>,
165}
166
167/// Remove paths matching `opts.pathspecs` from the index and (unless `cached`) the work tree.
168///
169/// Unless `force` is set, refuses paths whose removal would lose content that exists
170/// nowhere else (see [`RemoveBlockReason`]):
171///
172/// - Without `cached`, a path is refused when its index entry differs from `HEAD` (every
173///   entry counts as staged before the first commit) or its work tree file differs from
174///   the index.
175/// - With `cached`, a path is refused only when its index entry differs from both `HEAD`
176///   and the work tree file, so a committed file edited since (or a freshly added file)
177///   can always be untracked while keeping the file on disk.
178/// - A path whose work tree file is already gone (or replaced by a directory) is never
179///   refused.
180///
181/// Directory prefixes require `recursive`. Empty parent directories are removed after
182/// deleting files. Cache-tree entries for touched paths are invalidated before the index
183/// is written atomically after the index lock is acquired ([`IndexFile::begin_update`](crate::index::IndexFile::begin_update)).
184///
185/// # Errors
186///
187/// Returns [`crate::worktree::WorktreeError::PathspecNoMatch`], [`crate::worktree::WorktreeError::RemoveBlocked`],
188/// [`crate::worktree::WorktreeError::NotRemovingRecursively`], or I/O / object-store failures.
189pub(crate) fn remove_paths(
190    repo: &Repository,
191    opts: &RemoveOptions,
192    cancel: &CancelToken,
193) -> Result<RemoveOutcome> {
194    let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
195
196    if opts.pathspecs.is_empty() {
197        return Err(Error::Worktree(WorktreeError::RemovePathsRequired));
198    }
199
200    let mut opts = opts.clone();
201    opts.resolve_recursive(repo)?;
202
203    let mut index = repo.load_index()?;
204    let head_tree = repo.head_tree()?;
205
206    let to_remove = collect_removal_paths(repo, &index, work_tree, &opts)?;
207
208    if !opts.force {
209        let blocked = blocked_removals(
210            repo,
211            &mut index,
212            head_tree.as_ref(),
213            work_tree,
214            &to_remove,
215            opts.cached,
216        )?;
217        if !blocked.is_empty() {
218            return Err(Error::Worktree(WorktreeError::RemoveBlocked {
219                paths: blocked,
220            }));
221        }
222    }
223
224    if to_remove.is_empty() || opts.dry_run {
225        return Ok(RemoveOutcome { removed: to_remove });
226    }
227
228    let mut lock = repo.begin_index_update()?;
229    poll_cancel(&mut NullProgress, cancel)?;
230    index = repo.load_index()?;
231    let path_bytes: Vec<&[u8]> = to_remove.iter().map(|p| p.as_bytes()).collect();
232
233    let mut worktree_backups: Vec<WorktreePathBackup> = Vec::new();
234    if !opts.cached {
235        for path in &to_remove {
236            poll_remove_cancel(work_tree, &worktree_backups, cancel)?;
237            match snapshot_worktree_path(work_tree, path) {
238                Ok(Some(backup)) => {
239                    if let Err(err) = remove_backed_up_worktree_path(work_tree, &backup) {
240                        return Err(abort_failed_remove_worktree(
241                            work_tree,
242                            &worktree_backups,
243                            err,
244                        ));
245                    }
246                    worktree_backups.push(backup);
247                }
248                Ok(None) => {}
249                Err(err) => {
250                    return Err(abort_failed_remove_worktree(
251                        work_tree,
252                        &worktree_backups,
253                        err,
254                    ));
255                }
256            }
257        }
258        let removed_abs: Vec<PathBuf> = worktree_backups
259            .iter()
260            .map(|backup| work_tree.join(backup.rel()))
261            .collect();
262        remove_empty_parent_dirs_batch(work_tree, &removed_abs);
263    }
264
265    index.remove_paths(path_bytes);
266    poll_remove_cancel(work_tree, &worktree_backups, cancel)?;
267    if let Err(err) = repo.commit_index_update(&mut lock, &mut index, !opts.cached) {
268        return Err(abort_failed_remove_worktree(
269            work_tree,
270            &worktree_backups,
271            err,
272        ));
273    }
274
275    Ok(RemoveOutcome { removed: to_remove })
276}
277
278/// Rename `src` to `dst` in the working tree and index, preserving stat data and object ids.
279///
280/// Thin wrapper around [`move_paths`] for a single source path.
281///
282/// # Errors
283///
284/// Same as [`move_paths`].
285pub(crate) fn move_path(
286    repo: &Repository,
287    src: &str,
288    dst: &str,
289    force: bool,
290    cancel: &CancelToken,
291) -> Result<MoveOutcome> {
292    move_paths(
293        repo,
294        &MoveOptions {
295            sources: vec![src.to_owned()],
296            destination: dst.to_owned(),
297            force,
298            dry_run: false,
299        },
300        cancel,
301    )
302}
303
304/// Move one or more tracked sources into `opts.destination`, updating the index once.
305///
306/// When multiple sources are given, `destination` must name an existing directory; each
307/// source is moved under that directory using its final path component. On
308/// case-insensitive volumes with `core.ignorecase=true`, renaming a tracked directory
309/// to a case-only spelling (for example `Dir` to `dir`) renames every indexed path
310/// under that tree and updates the worktree dentry spelling. With `dry_run`, every
311/// validation runs but the index and work tree are left unchanged.
312///
313/// # Errors
314///
315/// Returns [`crate::worktree::WorktreeError::InvalidPath`], [`crate::worktree::WorktreeError::MoveSourceNotTracked`], [`crate::worktree::WorktreeError::MoveDestinationExists`],
316/// and related move errors, or I/O failures.
317pub(crate) fn move_paths(
318    repo: &Repository,
319    opts: &MoveOptions,
320    cancel: &CancelToken,
321) -> Result<MoveOutcome> {
322    let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
323    if opts.sources.is_empty() {
324        return Err(Error::Worktree(WorktreeError::MoveNothingToMove {
325            src: opts.destination.clone(),
326        }));
327    }
328
329    let ignorecase = repo
330        .config()
331        .snapshot()
332        .ok()
333        .is_some_and(|cfg| cfg.ignore_case());
334
335    let mut index = repo.load_index()?;
336    let dst_had_trailing_slash = destination_had_trailing_separator(&opts.destination);
337    let dst = normalize_and_validate_repo_relative(repo, work_tree, &opts.destination)?;
338
339    let mut planned: Vec<SingleMovePlan> = Vec::new();
340    let mut simulated = index.clone();
341
342    for src_raw in &opts.sources {
343        let src = normalize_and_validate_repo_relative(repo, work_tree, src_raw)?;
344        let plan = plan_single_move(PlanSingleMoveParams {
345            repo,
346            work_tree,
347            index: &simulated,
348            src: &src,
349            dst: &dst,
350            dst_had_trailing_slash,
351            multi_source: opts.sources.len() > 1,
352            force: opts.force,
353            ignorecase,
354        })?;
355        apply_renames_to_index(&mut simulated, &plan.renames)?;
356        planned.push(plan);
357    }
358
359    let moves: Vec<PathMove> = planned
360        .iter()
361        .flat_map(|plan| {
362            plan.renames.iter().map(|(from, to)| PathMove {
363                from: from.clone(),
364                to: to.clone(),
365            })
366        })
367        .collect();
368
369    validate_unique_move_destinations(&moves)?;
370
371    if opts.dry_run {
372        return Ok(MoveOutcome { moves });
373    }
374
375    let mut lock = repo.begin_index_update()?;
376    poll_cancel(&mut NullProgress, cancel)?;
377    index = repo.load_index()?;
378
379    let mut force_clear_worktree: Vec<String> = Vec::new();
380    if opts.force {
381        for plan in &planned {
382            force_clear_worktree.extend(worktree_paths_to_clear(
383                work_tree,
384                &index,
385                &plan.final_dst,
386            ));
387        }
388        force_clear_worktree.sort();
389        force_clear_worktree.dedup();
390    }
391
392    let cleared_backup = if !force_clear_worktree.is_empty() {
393        backup_and_remove_worktree_paths(work_tree, &force_clear_worktree)?
394    } else {
395        Vec::new()
396    };
397
398    let mut completed_worktree_renames: Vec<(String, String)> = Vec::new();
399    for plan in &planned {
400        if cancel.poll().is_err() {
401            return Err(abort_failed_move_worktree(
402                work_tree,
403                &completed_worktree_renames,
404                &cleared_backup,
405                ignorecase,
406                Error::Cancelled,
407            ));
408        }
409        if opts.force {
410            clear_destination_index(&mut index, &plan.final_dst);
411        }
412        if let Err(err) = rename_worktree_paths(
413            work_tree,
414            &plan.src,
415            &plan.final_dst,
416            &plan.renames,
417            ignorecase,
418        ) {
419            return Err(abort_failed_move_worktree(
420                work_tree,
421                &completed_worktree_renames,
422                &cleared_backup,
423                ignorecase,
424                err,
425            ));
426        }
427        completed_worktree_renames.extend(plan.renames.clone());
428    }
429
430    let all_renames: Vec<(String, String)> = planned
431        .iter()
432        .flat_map(|plan| plan.renames.clone())
433        .collect();
434    if let Err(err) = apply_renames_to_index(&mut index, &all_renames) {
435        return Err(abort_failed_move_worktree(
436            work_tree,
437            &completed_worktree_renames,
438            &cleared_backup,
439            ignorecase,
440            err,
441        ));
442    }
443
444    if let Err(err) = poll_cancel(&mut NullProgress, cancel) {
445        return Err(abort_failed_move_worktree(
446            work_tree,
447            &completed_worktree_renames,
448            &cleared_backup,
449            ignorecase,
450            err,
451        ));
452    }
453
454    repo.flush_index_update(&mut lock, &mut index)?;
455    if let Err(err) = poll_cancel(&mut NullProgress, cancel) {
456        return Err(abort_failed_move_worktree(
457            work_tree,
458            &completed_worktree_renames,
459            &cleared_backup,
460            ignorecase,
461            err,
462        ));
463    }
464    repo.finish_index_update(&mut lock, true)?;
465
466    Ok(MoveOutcome { moves })
467}
468
469fn poll_remove_cancel(
470    work_tree: &Path,
471    backups: &[WorktreePathBackup],
472    cancel: &CancelToken,
473) -> Result<()> {
474    if let Err(err) = poll_cancel(&mut NullProgress, cancel) {
475        return Err(abort_failed_remove_worktree(work_tree, backups, err));
476    }
477    Ok(())
478}
479
480/// Put work-tree files back after a failed [`remove_paths`] once some paths were deleted.
481fn abort_failed_remove_worktree(
482    work_tree: &Path,
483    backups: &[WorktreePathBackup],
484    original: Error,
485) -> Error {
486    if backups.is_empty() {
487        return original;
488    }
489    let unrestored = restore_worktree_backups_best_effort(work_tree, backups);
490    if unrestored.is_empty() {
491        original
492    } else {
493        Error::Worktree(WorktreeError::CheckoutRollbackIncomplete {
494            source: ErrorSummary::from(original),
495            unrestored,
496        })
497    }
498}
499
500fn restore_worktree_backups_best_effort(
501    work_tree: &Path,
502    backups: &[WorktreePathBackup],
503) -> Vec<String> {
504    let mut unrestored = Vec::new();
505    for backup in backups {
506        if restore_worktree_backups(work_tree, std::slice::from_ref(backup)).is_err() {
507            unrestored.push(backup.rel().to_string());
508        }
509    }
510    unrestored.sort_unstable();
511    unrestored.dedup();
512    unrestored
513}
514
515fn validate_unique_move_destinations(moves: &[PathMove]) -> Result<()> {
516    let mut seen = HashSet::new();
517    for mv in moves {
518        if !seen.insert(mv.to.clone()) {
519            return Err(Error::Worktree(WorktreeError::MoveDuplicateDestination {
520                destination: mv.to.clone(),
521            }));
522        }
523    }
524    Ok(())
525}
526
527struct WorktreeRenameRollback {
528    /// Destination paths whose move was successfully reversed during rollback.
529    rolled_back_destinations: HashSet<String>,
530    /// Reverse-rename failures encountered while rolling back (newest first).
531    failures: Vec<(String, String, Error)>,
532}
533
534fn rollback_worktree_renames(
535    work_tree: &Path,
536    applied: &[(String, String)],
537    ignorecase: bool,
538) -> WorktreeRenameRollback {
539    let mut rolled_back_destinations = HashSet::new();
540    let mut failures = Vec::new();
541    for (from, to) in applied.iter().rev() {
542        match reverse_worktree_rename(work_tree, from, to, ignorecase) {
543            Ok(()) => {
544                rolled_back_destinations.insert(to.clone());
545            }
546            Err(err) => failures.push((from.clone(), to.clone(), err)),
547        }
548    }
549    WorktreeRenameRollback {
550        rolled_back_destinations,
551        failures,
552    }
553}
554
555fn reverse_worktree_rename(work_tree: &Path, from: &str, to: &str, ignorecase: bool) -> Result<()> {
556    let from_abs = work_tree.join(from);
557    let to_abs = work_tree.join(to);
558    if !to_abs.exists() {
559        return Err(Error::Worktree(WorktreeError::Path {
560            detail: format!("rollback skipped missing destination '{to}'"),
561        }));
562    }
563    if let Some(parent) = from_abs.parent() {
564        fs::create_dir_all(parent).map_err(|e| {
565            Error::Worktree(WorktreeError::Path {
566                detail: format!("creating parent for rollback '{from}': {e}"),
567            })
568        })?;
569    }
570    rename_worktree_entry(&to_abs, &from_abs, ignorecase).map_err(|e| {
571        Error::Worktree(WorktreeError::Path {
572            detail: format!("rolling back rename '{to}' -> '{from}': {e}"),
573        })
574    })?;
575    Ok(())
576}
577
578fn backup_path_preserves_moved_content(backup_rel: &str, preserve_roots: &HashSet<String>) -> bool {
579    preserve_roots
580        .iter()
581        .any(|root| backup_rel == root || backup_rel.starts_with(&format!("{root}/")))
582}
583
584/// Undo completed worktree renames, then restore force-cleared destination backups.
585///
586/// Backups for destinations whose reverse rename failed are skipped so moved source bytes
587/// are not overwritten by pre-move destination snapshots.
588fn abort_failed_move_worktree(
589    work_tree: &Path,
590    completed_renames: &[(String, String)],
591    force_backups: &[WorktreePathBackup],
592    ignorecase: bool,
593    original: Error,
594) -> Error {
595    let rollback = rollback_worktree_renames(work_tree, completed_renames, ignorecase);
596    let moved_destinations: HashSet<String> =
597        completed_renames.iter().map(|(_, to)| to.clone()).collect();
598    let preserve_destination_content: HashSet<String> = moved_destinations
599        .difference(&rollback.rolled_back_destinations)
600        .cloned()
601        .collect();
602    let backups_to_restore: Vec<WorktreePathBackup> = force_backups
603        .iter()
604        .filter(|backup| {
605            !backup_path_preserves_moved_content(backup.rel(), &preserve_destination_content)
606        })
607        .cloned()
608        .collect();
609    let restore_err = restore_worktree_backups(work_tree, &backups_to_restore).err();
610
611    if rollback.failures.is_empty() && restore_err.is_none() {
612        return original;
613    }
614
615    WorktreeError::MoveRollbackIncomplete {
616        source: ErrorSummary::from(original),
617        unreversed: rollback.failures.len(),
618        backup_restore: restore_err.map(ErrorSummary::from),
619    }
620    .into()
621}
622
623struct SingleMovePlan {
624    src: String,
625    final_dst: String,
626    renames: Vec<(String, String)>,
627}
628
629struct PlanSingleMoveParams<'a> {
630    repo: &'a Repository,
631    work_tree: &'a Path,
632    index: &'a Index,
633    src: &'a str,
634    dst: &'a str,
635    dst_had_trailing_slash: bool,
636    multi_source: bool,
637    force: bool,
638    ignorecase: bool,
639}
640
641fn plan_single_move(params: PlanSingleMoveParams<'_>) -> Result<SingleMovePlan> {
642    let PlanSingleMoveParams {
643        repo,
644        work_tree,
645        index,
646        src,
647        dst,
648        dst_had_trailing_slash,
649        multi_source,
650        force,
651        ignorecase,
652    } = params;
653    let src_entries = index_paths_under(index, src, true);
654    if src_entries.is_empty() {
655        return Err(Error::Worktree(WorktreeError::MoveSourceNotTracked {
656            src: src.to_owned(),
657        }));
658    }
659
660    let (final_dst, dst_is_dir_target) = resolve_move_destination(
661        work_tree,
662        index,
663        src,
664        dst,
665        dst_had_trailing_slash,
666        !multi_source,
667        ignorecase,
668    )?;
669    let final_dst = normalize_and_validate_repo_relative(repo, work_tree, &final_dst)?;
670
671    if multi_source && !dst_is_dir_target {
672        let dest_exists =
673            work_tree.join(&final_dst).exists() || index.get(final_dst.as_bytes(), 0).is_some();
674        if dest_exists {
675            return Err(Error::Worktree(WorktreeError::MoveDestinationExists {
676                src: src.to_owned(),
677                destination: final_dst,
678            }));
679        }
680        return Err(WorktreeError::MoveDestinationNotDirectory {
681            destination: final_dst,
682        }
683        .into());
684    }
685
686    if is_subdirectory(&final_dst, src, ignorecase) {
687        return Err(Error::Worktree(WorktreeError::MoveIntoSubdirectory {
688            src: src.to_owned(),
689            destination: final_dst,
690        }));
691    }
692
693    if final_dst == *src {
694        return Err(Error::Worktree(WorktreeError::MoveIntoSelf {
695            src: src.to_owned(),
696            destination: final_dst,
697        }));
698    }
699
700    let renames = plan_index_renames(index, src, &final_dst)?;
701    if renames.is_empty() {
702        return Err(Error::Worktree(WorktreeError::MoveNothingToMove {
703            src: src.to_owned(),
704        }));
705    }
706
707    ensure_worktree_move_sources_exist(work_tree, &renames)?;
708
709    if !force
710        && destination_exists(
711            work_tree,
712            index,
713            &final_dst,
714            dst_is_dir_target,
715            ignorecase,
716            &renames,
717        )
718    {
719        return Err(Error::Worktree(WorktreeError::MoveDestinationExists {
720            src: src.to_owned(),
721            destination: final_dst,
722        }));
723    }
724
725    Ok(SingleMovePlan {
726        src: src.to_owned(),
727        final_dst,
728        renames,
729    })
730}
731
732fn apply_renames_to_index(index: &mut Index, renames: &[(String, String)]) -> Result<()> {
733    if renames.is_empty() {
734        return Ok(());
735    }
736    let old_paths: Vec<Vec<u8>> = renames
737        .iter()
738        .map(|(from, _)| from.as_bytes().to_vec())
739        .collect();
740    let mut new_entries = Vec::with_capacity(renames.len());
741    for (from, to) in renames {
742        let old = index.get(from.as_bytes(), 0).ok_or_else(|| {
743            Error::Worktree(WorktreeError::MoveMissingIndexEntry { path: from.clone() })
744        })?;
745        new_entries.push(entry_with_relpath(old.clone(), to));
746    }
747    let old_refs: Vec<&[u8]> = old_paths.iter().map(|p| p.as_slice()).collect();
748    index.remove_paths_and_insert(old_refs, new_entries);
749    Ok(())
750}
751
752fn infer_remove_recursive(repo: &Repository, sources: &[String], specs: &[String]) -> Result<bool> {
753    let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
754    let source_labels = if sources.is_empty() { specs } else { sources };
755    for (sel, spec) in source_labels.iter().zip(specs.iter()) {
756        if sel.ends_with('/') || sel.ends_with('\\') {
757            return Ok(true);
758        }
759        if work_tree.join(spec).is_dir() {
760            return Ok(true);
761        }
762    }
763    Ok(false)
764}
765
766fn collect_removal_paths(
767    repo: &Repository,
768    index: &Index,
769    _work_tree: &Path,
770    opts: &RemoveOptions,
771) -> Result<Vec<String>> {
772    let pathspec_ctx = repo.pathspec_match_context();
773    let path_modes = index_stage0_path_modes(index);
774    let sources = if opts.pathspec_sources.is_empty() {
775        &opts.pathspecs
776    } else {
777        &opts.pathspec_sources
778    };
779
780    let mut selected: BTreeSet<String> = BTreeSet::new();
781    for (label, resolved) in sources.iter().zip(opts.pathspecs.iter()) {
782        if pathspec_is_exclude(label) {
783            continue;
784        }
785        let matched = if is_plain_literal_pathspec(resolved, pathspec_ctx) && index.entries_sorted {
786            collect_plain_literal_removal(index, resolved, pathspec_ctx, opts, &mut selected)?
787        } else {
788            let filter = RepositoryPathspecFilter::try_new(repo, std::slice::from_ref(resolved))?;
789            collect_pathspec_matched_removal(
790                index,
791                &filter,
792                pathspec_ctx,
793                resolved,
794                &path_modes,
795                opts,
796                &mut selected,
797            )?
798        };
799        if !matched {
800            if opts.ignore_unmatch {
801                continue;
802            }
803            return Err(Error::Worktree(WorktreeError::PathspecNoMatch {
804                spec: label.clone(),
805            }));
806        }
807    }
808
809    let mut out: Vec<String> = selected.into_iter().collect();
810    out.sort();
811    Ok(out)
812}
813
814/// Collect removals for one plain literal pathspec using sorted-index range queries.
815fn collect_plain_literal_removal(
816    index: &Index,
817    resolved: &str,
818    ctx: PathspecMatchContext,
819    opts: &RemoveOptions,
820    selected: &mut BTreeSet<String>,
821) -> Result<bool> {
822    let spec = resolved.trim_end_matches('/');
823    let spec_lookup = literal_spec_for_lookup(spec, ctx);
824    let spec_bytes = spec_lookup.as_ref().as_bytes();
825    let mut matches: Vec<String> = Vec::new();
826
827    if index.sorted_contains_path(spec_bytes).unwrap_or(false) {
828        if let Some(stored) = sorted_index_exact_stored_path(index, spec_bytes) {
829            matches.push(stored);
830        }
831    }
832
833    let under = index.sorted_entries_under(spec_bytes).unwrap_or(&[]);
834
835    if matches.is_empty() && under.is_empty() && ctx.precompose_paths {
836        push_precompose_literal_alternate_matches(index, resolved, ctx, &mut matches);
837    }
838
839    if matches.is_empty() && under.is_empty() {
840        return Ok(false);
841    }
842
843    if matches.is_empty() {
844        if !opts.recursive {
845            return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
846                path: resolved.to_string(),
847            }));
848        }
849        for entry in under {
850            selected.insert(String::from_utf8_lossy(&entry.path).into_owned());
851        }
852        return Ok(true);
853    }
854
855    if !opts.recursive && index.has_stage0_descendant_under(spec_lookup.as_ref()) {
856        let prefix = format!("{}/", spec_lookup.as_ref());
857        if matches.iter().any(|path| path.starts_with(&prefix)) {
858            return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
859                path: resolved.to_string(),
860            }));
861        }
862    }
863
864    for path in matches {
865        insert_match_and_descendants(index, &path, opts, selected)?;
866    }
867    Ok(true)
868}
869
870fn sorted_index_exact_stored_path(index: &Index, path_bytes: &[u8]) -> Option<String> {
871    if !index.entries_sorted {
872        return None;
873    }
874    let at = index
875        .entries
876        .partition_point(|e| e.path.as_slice() < path_bytes);
877    index.entries.get(at).and_then(|e| {
878        (e.path.as_slice() == path_bytes).then(|| String::from_utf8_lossy(&e.path).into_owned())
879    })
880}
881
882/// Paths stored in a non-NFC spelling that still match a plain literal under precompose rules.
883fn push_precompose_literal_alternate_matches(
884    index: &Index,
885    resolved: &str,
886    ctx: PathspecMatchContext,
887    matches: &mut Vec<String>,
888) {
889    let spec_list = [resolved.to_string()];
890    let mut last_path: Option<Vec<u8>> = None;
891    for entry in &index.entries {
892        if last_path.as_deref() == Some(entry.path.as_slice()) {
893            continue;
894        }
895        last_path = Some(entry.path.clone());
896        let path = String::from_utf8_lossy(&entry.path);
897        if path.is_ascii() {
898            continue;
899        }
900        if matches_pathspec_list_with_context(path.as_ref(), &spec_list, ctx) {
901            matches.push(path.into_owned());
902        }
903    }
904}
905
906/// Collect removals for one pathspec by scanning the index once with a prepared filter.
907fn collect_pathspec_matched_removal(
908    index: &Index,
909    filter: &RepositoryPathspecFilter<'_>,
910    pathspec_ctx: PathspecMatchContext,
911    resolved: &str,
912    path_modes: &std::collections::HashMap<String, u32>,
913    opts: &RemoveOptions,
914    selected: &mut BTreeSet<String>,
915) -> Result<bool> {
916    let spec = resolved.trim_end_matches('/');
917    let mut matches: Vec<String> = Vec::new();
918    let mut last_path: Option<Vec<u8>> = None;
919    for entry in &index.entries {
920        if last_path.as_deref() == Some(entry.path.as_slice()) {
921            continue;
922        }
923        last_path = Some(entry.path.clone());
924        let path = String::from_utf8_lossy(&entry.path);
925        let mode = path_modes
926            .get(path.as_ref())
927            .copied()
928            .unwrap_or(REGULAR_FILE_MODE);
929        if filter.matches_entry(path.as_ref(), mode) {
930            matches.push(path.into_owned());
931        }
932    }
933
934    if matches.is_empty() {
935        let prefix = format!("{spec}/");
936        if index.entries_sorted {
937            let spec_lookup = literal_spec_for_lookup(spec, pathspec_ctx);
938            if let Some(under) = index.sorted_entries_under(spec_lookup.as_ref().as_bytes()) {
939                if under.is_empty() {
940                    return Ok(false);
941                }
942                if !opts.recursive {
943                    return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
944                        path: resolved.to_string(),
945                    }));
946                }
947                for entry in under {
948                    selected.insert(String::from_utf8_lossy(&entry.path).into_owned());
949                }
950                return Ok(true);
951            }
952        }
953        let mut under_prefix = false;
954        for entry in &index.entries {
955            let path = String::from_utf8_lossy(&entry.path);
956            if path.starts_with(&prefix) {
957                under_prefix = true;
958                if !opts.recursive {
959                    return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
960                        path: resolved.to_string(),
961                    }));
962                }
963                selected.insert(path.into_owned());
964            }
965        }
966        return Ok(under_prefix);
967    }
968
969    if !opts.recursive && index.has_stage0_descendant_under(spec) {
970        let prefix = format!("{spec}/");
971        if matches.iter().any(|path| path.starts_with(&prefix)) {
972            return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
973                path: resolved.to_string(),
974            }));
975        }
976    }
977
978    for path in matches {
979        insert_match_and_descendants(index, &path, opts, selected)?;
980    }
981    Ok(true)
982}
983
984fn insert_match_and_descendants(
985    index: &Index,
986    path: &str,
987    opts: &RemoveOptions,
988    selected: &mut BTreeSet<String>,
989) -> Result<()> {
990    if !opts.recursive && index.has_stage0_descendant_under(path) {
991        return Err(Error::Worktree(WorktreeError::NotRemovingRecursively {
992            path: path.to_string(),
993        }));
994    }
995    selected.insert(path.to_string());
996    if !opts.recursive {
997        return Ok(());
998    }
999    if index.entries_sorted {
1000        if let Some(run) = index.sorted_entries_under(path.as_bytes()) {
1001            for entry in run {
1002                selected.insert(String::from_utf8_lossy(&entry.path).into_owned());
1003            }
1004        }
1005        return Ok(());
1006    }
1007    let prefix = format!("{path}/");
1008    for entry in &index.entries {
1009        let p = String::from_utf8_lossy(&entry.path);
1010        if p.starts_with(&prefix) {
1011            selected.insert(p.into_owned());
1012        }
1013    }
1014    Ok(())
1015}
1016
1017/// Classify every path in `to_remove` and return the ones removal must refuse.
1018///
1019/// Only paths that could still be blocked are compared against the work tree: all of
1020/// `to_remove` normally, but just the staged ones with `cached`.
1021fn blocked_removals(
1022    repo: &Repository,
1023    index: &mut Index,
1024    head_tree: Option<&ObjectId>,
1025    work_tree: &Path,
1026    to_remove: &[String],
1027    cached: bool,
1028) -> Result<Vec<BlockedRemoval>> {
1029    let staged: HashSet<String> = diff_index_to_tree(repo.odb(), index, head_tree, false)?
1030        .into_iter()
1031        .filter(|entry| entry.status != DiffStatus::Unmerged)
1032        .map(|entry| entry.path().to_string())
1033        .collect();
1034    let compare: BTreeSet<String> = to_remove
1035        .iter()
1036        .filter(|path| !cached || staged.contains(*path))
1037        .cloned()
1038        .collect();
1039    let local = if compare.is_empty() {
1040        HashSet::new()
1041    } else {
1042        paths_differing_from_worktree(repo, index, work_tree, compare)?
1043    };
1044
1045    Ok(to_remove
1046        .iter()
1047        .filter_map(|path| {
1048            let reason =
1049                RemoveBlockReason::classify(staged.contains(path), local.contains(path), cached)?;
1050            let entry = index.get(path.as_bytes(), 0)?;
1051            if cached && entry.intent_to_add() {
1052                return None;
1053            }
1054            worktree_still_has_file(work_tree, path, entry.mode).then(|| BlockedRemoval {
1055                path: path.clone(),
1056                reason,
1057            })
1058        })
1059        .collect())
1060}
1061
1062/// A tracked file that has vanished from the work tree, or turned into a directory, has
1063/// nothing left on disk to lose, so its removal is never refused.
1064fn worktree_still_has_file(work_tree: &Path, path: &str, mode: u32) -> bool {
1065    match fs::symlink_metadata(work_tree.join(path)) {
1066        Ok(meta) => !meta.is_dir() || mode == MODE_GITLINK,
1067        Err(_) => false,
1068    }
1069}
1070
1071/// Index paths in `paths` whose work tree file differs from the index entry.
1072fn paths_differing_from_worktree(
1073    repo: &Repository,
1074    index: &mut Index,
1075    work_tree: &Path,
1076    paths: BTreeSet<String>,
1077) -> Result<HashSet<String>> {
1078    let index_mtime = index_file_mtime(&repo.index_path());
1079    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
1080    let rules_arc = Arc::new(Mutex::new(worktree_rules));
1081    let diff_opts = DiffIndexToWorktreeOptions {
1082        index_mtime,
1083        repository_git_dir: Some(repo.git_dir().to_path_buf()),
1084        refresh_index_stat_in_pass: true,
1085        config: repo.config().snapshot().ok(),
1086        worktree_rules: Some(Arc::clone(&rules_arc)),
1087        command_runner: Some(repo.command_runner()),
1088        restrict_to_paths: Some(Arc::new(paths)),
1089        ..Default::default()
1090    };
1091    let (unstaged, _) =
1092        diff_index_to_worktree_with_options(repo.odb(), index, work_tree, diff_opts)?;
1093    Ok(unstaged
1094        .into_iter()
1095        .filter(|entry| entry.status != DiffStatus::Unmerged)
1096        .map(|entry| entry.path().to_string())
1097        .collect())
1098}
1099
1100#[derive(Debug, Clone)]
1101enum WorktreePathBackup {
1102    File {
1103        rel: String,
1104        bytes: Vec<u8>,
1105        #[cfg(unix)]
1106        mode: u32,
1107    },
1108    Symlink {
1109        rel: String,
1110        target: PathBuf,
1111    },
1112}
1113
1114impl WorktreePathBackup {
1115    fn rel(&self) -> &str {
1116        match self {
1117            Self::File { rel, .. } | Self::Symlink { rel, .. } => rel,
1118        }
1119    }
1120}
1121
1122fn snapshot_worktree_path(work_tree: &Path, path: &str) -> Result<Option<WorktreePathBackup>> {
1123    let abs = work_tree.join(path);
1124    if abs.is_symlink() {
1125        let target = fs::read_link(&abs).map_err(|e| {
1126            Error::Worktree(WorktreeError::Path {
1127                detail: format!("reading symlink '{path}': {e}"),
1128            })
1129        })?;
1130        return Ok(Some(WorktreePathBackup::Symlink {
1131            rel: path.to_string(),
1132            target,
1133        }));
1134    }
1135    if abs.is_file() {
1136        let bytes = fs::read(&abs).map_err(|e| {
1137            Error::Worktree(WorktreeError::Path {
1138                detail: format!("reading '{path}': {e}"),
1139            })
1140        })?;
1141        #[cfg(unix)]
1142        {
1143            use std::os::unix::fs::PermissionsExt;
1144            let mode = fs::metadata(&abs)
1145                .map_err(|e| {
1146                    Error::Worktree(WorktreeError::Path {
1147                        detail: format!("reading metadata for '{path}': {e}"),
1148                    })
1149                })?
1150                .permissions()
1151                .mode()
1152                & 0o7777;
1153            return Ok(Some(WorktreePathBackup::File {
1154                rel: path.to_string(),
1155                bytes,
1156                mode,
1157            }));
1158        }
1159        #[cfg(not(unix))]
1160        {
1161            return Ok(Some(WorktreePathBackup::File {
1162                rel: path.to_string(),
1163                bytes,
1164            }));
1165        }
1166    }
1167    Ok(None)
1168}
1169
1170fn remove_backed_up_worktree_path(work_tree: &Path, backup: &WorktreePathBackup) -> Result<()> {
1171    let path = backup.rel();
1172    let abs = work_tree.join(path);
1173    fs::remove_file(&abs).map_err(|e| {
1174        Error::Worktree(WorktreeError::Path {
1175            detail: format!("removing '{path}': {e}"),
1176        })
1177    })?;
1178    Ok(())
1179}
1180
1181fn backup_and_remove_worktree_paths(
1182    work_tree: &Path,
1183    paths: &[String],
1184) -> Result<Vec<WorktreePathBackup>> {
1185    let mut snapshots = Vec::with_capacity(paths.len());
1186    for path in paths {
1187        if let Some(backup) = snapshot_worktree_path(work_tree, path)? {
1188            snapshots.push(backup);
1189        }
1190    }
1191
1192    let mut removed: Vec<WorktreePathBackup> = Vec::new();
1193    for backup in &snapshots {
1194        match remove_backed_up_worktree_path(work_tree, backup) {
1195            Ok(()) => removed.push(backup.clone()),
1196            Err(err) => {
1197                let _ = restore_worktree_backups(work_tree, &removed);
1198                return Err(err);
1199            }
1200        }
1201    }
1202    Ok(snapshots)
1203}
1204
1205fn restore_worktree_backups(work_tree: &Path, backups: &[WorktreePathBackup]) -> Result<()> {
1206    for backup in backups {
1207        match backup {
1208            WorktreePathBackup::File {
1209                rel,
1210                bytes,
1211                #[cfg(unix)]
1212                mode,
1213            } => {
1214                let abs = work_tree.join(rel);
1215                if let Some(parent) = abs.parent() {
1216                    fs::create_dir_all(parent).map_err(|e| {
1217                        Error::Worktree(WorktreeError::Path {
1218                            detail: format!("creating parent for '{rel}': {e}"),
1219                        })
1220                    })?;
1221                }
1222                fs::write(&abs, bytes).map_err(|e| {
1223                    Error::Worktree(WorktreeError::Path {
1224                        detail: format!("restoring '{rel}': {e}"),
1225                    })
1226                })?;
1227                #[cfg(unix)]
1228                {
1229                    use std::os::unix::fs::PermissionsExt;
1230                    let mut perms = fs::metadata(&abs)
1231                        .map_err(|e| {
1232                            Error::Worktree(WorktreeError::Path {
1233                                detail: format!("reading metadata for '{rel}': {e}"),
1234                            })
1235                        })?
1236                        .permissions();
1237                    perms.set_mode(*mode);
1238                    fs::set_permissions(&abs, perms).map_err(|e| {
1239                        Error::Worktree(WorktreeError::Path {
1240                            detail: format!("restoring mode for '{rel}': {e}"),
1241                        })
1242                    })?;
1243                }
1244            }
1245            WorktreePathBackup::Symlink { rel, target } => {
1246                let abs = work_tree.join(rel);
1247                if let Some(parent) = abs.parent() {
1248                    fs::create_dir_all(parent).map_err(|e| {
1249                        Error::Worktree(WorktreeError::Path {
1250                            detail: format!("creating parent for '{rel}': {e}"),
1251                        })
1252                    })?;
1253                }
1254                crate::worktree::create_worktree_symlink(&abs, target.as_ref()).map_err(|e| {
1255                    Error::Worktree(WorktreeError::Path {
1256                        detail: format!("restoring symlink '{rel}': {e}"),
1257                    })
1258                })?;
1259            }
1260        }
1261    }
1262    Ok(())
1263}
1264
1265/// Normalize a repository-relative path for rm/mv, rejecting escapes and absolutes.
1266///
1267/// Absolute paths (including paths inside the work tree) and any `..` segment
1268/// are rejected before normalization so callers cannot bypass prefix checks.
1269///
1270/// # Errors
1271///
1272/// Returns [`crate::worktree::WorktreeError::InvalidPath`] when `path` is empty, absolute, or contains `..`.
1273fn destination_had_trailing_separator(path: &str) -> bool {
1274    let trimmed = path.trim_end_matches([' ', '\t']);
1275    trimmed.ends_with('/') || trimmed.ends_with('\\')
1276}
1277
1278fn normalize_repo_relative_slashes(raw: &str) -> String {
1279    let with_slashes = raw.replace('\\', "/");
1280    let trimmed = with_slashes.trim_start_matches("./");
1281    trimmed
1282        .split('/')
1283        .filter(|component| !component.is_empty())
1284        .collect::<Vec<_>>()
1285        .join("/")
1286}
1287
1288fn path_outside_work_tree(path: &str, work_tree: &Path) -> Error {
1289    let repo_root = work_tree
1290        .canonicalize_simplified()
1291        .map(|p| p.display().to_string())
1292        .unwrap_or_else(|_| work_tree.display().to_string());
1293    Error::Worktree(WorktreeError::OutsideRepo(
1294        PathOutsideRepoError::OutsideRepository {
1295            path: path.to_owned(),
1296            subpath: path.to_owned(),
1297            repo_root,
1298        },
1299    ))
1300}
1301
1302fn normalize_and_validate_repo_relative(
1303    repo: &Repository,
1304    work_tree: &Path,
1305    path: &str,
1306) -> Result<String> {
1307    if path.is_empty() {
1308        return Err(Error::Worktree(WorktreeError::InvalidPath {
1309            path: "empty path".into(),
1310        }));
1311    }
1312    if Path::new(path).is_absolute() {
1313        return Err(Error::Worktree(WorktreeError::InvalidPath {
1314            path: format!("'{path}' is outside repository"),
1315        }));
1316    }
1317    let with_slashes = path.replace('\\', "/");
1318    if with_slashes.starts_with('/') {
1319        return Err(path_outside_work_tree(path, work_tree));
1320    }
1321    for component in Path::new(&with_slashes).components() {
1322        if matches!(component, Component::ParentDir) {
1323            return Err(path_outside_work_tree(path, work_tree));
1324        }
1325    }
1326    let rel = normalize_repo_relative_slashes(path);
1327    if rel.is_empty() {
1328        return Err(Error::Worktree(WorktreeError::InvalidPath {
1329            path: "empty path".into(),
1330        }));
1331    }
1332    let opts = ProtectOptions::from_config(&*repo.config().snapshot()?);
1333    validate_path(
1334        rel.as_bytes(),
1335        EntryMode::new(0o100644),
1336        opts,
1337        PathValidationKind::Worktree,
1338    )
1339    .map_err(|reason| Error::invalid_path_component(rel.clone(), reason))?;
1340    Ok(rel)
1341}
1342
1343fn index_paths_under(index: &Index, prefix: &str, include_exact: bool) -> Vec<String> {
1344    let plen = prefix.len();
1345    let mut paths: Vec<String> = index
1346        .entries
1347        .iter()
1348        .filter(|e| e.stage() == 0)
1349        .filter_map(|e| {
1350            let p = String::from_utf8_lossy(&e.path);
1351            if p == prefix {
1352                return include_exact.then(|| p.into_owned());
1353            }
1354            if p.len() > plen && p.starts_with(prefix) && p.as_bytes()[plen] == b'/' {
1355                return Some(p.into_owned());
1356            }
1357            None
1358        })
1359        .collect();
1360    paths.sort();
1361    paths.dedup();
1362    paths
1363}
1364
1365fn resolve_move_destination(
1366    work_tree: &Path,
1367    index: &Index,
1368    src: &str,
1369    dst: &str,
1370    dst_had_trailing_slash: bool,
1371    single_source: bool,
1372    _ignorecase: bool,
1373) -> Result<(String, bool)> {
1374    let src_is_dir = worktree_dentry_is_directory(work_tree, src)
1375        || index
1376            .get(src.as_bytes(), 0)
1377            .is_some_and(|e| e.mode == MODE_TREE)
1378        || !index_paths_under(index, src, false).is_empty();
1379
1380    let same_case_directory = src_is_dir
1381        && src != dst
1382        && paths_equal(src.as_bytes(), dst.as_bytes(), true)
1383        && (worktree_filesystem_case_insensitive(work_tree)
1384            || worktree_paths_same_identity(work_tree, src, dst));
1385
1386    let dst_abs = work_tree.join(dst);
1387    let dst_is_dir = !same_case_directory
1388        && (dst_abs.is_dir()
1389            || index_has_paths_under(index, dst, false)
1390            || index
1391                .get(dst.as_bytes(), 0)
1392                .is_some_and(|e| e.mode == MODE_TREE));
1393
1394    if dst_had_trailing_slash && !dst_is_dir {
1395        if single_source && src_is_dir {
1396            return Ok((dst.to_string(), false));
1397        }
1398        return Err(Error::Worktree(
1399            WorktreeError::MoveDestinationNotDirectory {
1400                destination: dst.to_owned(),
1401            },
1402        ));
1403    }
1404
1405    Ok(resolve_move_destination_path(
1406        src,
1407        dst,
1408        dst_is_dir,
1409        same_case_directory,
1410    ))
1411}
1412
1413/// Pure destination resolution for a single tracked source (unit-tested on all platforms).
1414#[must_use]
1415fn resolve_move_destination_path(
1416    src: &str,
1417    dst: &str,
1418    dst_is_dir: bool,
1419    same_case_directory: bool,
1420) -> (String, bool) {
1421    if same_case_directory {
1422        return (dst.to_string(), false);
1423    }
1424    if dst_is_dir {
1425        let base = Path::new(src)
1426            .file_name()
1427            .and_then(|s| s.to_str())
1428            .unwrap_or(src);
1429        (format!("{dst}/{base}"), true)
1430    } else {
1431        (dst.to_string(), false)
1432    }
1433}
1434
1435fn index_has_paths_under(index: &Index, prefix: &str, ignorecase: bool) -> bool {
1436    if ignorecase {
1437        return index.entries.iter().filter(|e| e.stage() == 0).any(|e| {
1438            let path = String::from_utf8_lossy(&e.path);
1439            index_path_at_destination(&path, prefix, true) && path != prefix
1440        });
1441    }
1442    !index_paths_under(index, prefix, false).is_empty()
1443}
1444
1445fn worktree_dentry_is_directory(work_tree: &Path, rel: &str) -> bool {
1446    fs::symlink_metadata(work_tree.join(rel))
1447        .map(|meta| meta.is_dir())
1448        .unwrap_or(false)
1449}
1450
1451#[cfg(unix)]
1452fn worktree_paths_same_identity(work_tree: &Path, a: &str, b: &str) -> bool {
1453    use std::os::unix::fs::MetadataExt;
1454
1455    let a_abs = work_tree.join(a);
1456    let b_abs = work_tree.join(b);
1457    let (Ok(ma), Ok(mb)) = (fs::symlink_metadata(&a_abs), fs::symlink_metadata(&b_abs)) else {
1458        return false;
1459    };
1460    if !ma.is_dir() || !mb.is_dir() {
1461        return false;
1462    }
1463    ma.dev() == mb.dev() && ma.ino() == mb.ino()
1464}
1465
1466#[cfg(not(unix))]
1467fn worktree_paths_same_identity(_work_tree: &Path, _a: &str, _b: &str) -> bool {
1468    false
1469}
1470
1471fn destination_exists(
1472    work_tree: &Path,
1473    index: &Index,
1474    dst: &str,
1475    _dst_was_dir: bool,
1476    ignorecase: bool,
1477    renames: &[(String, String)],
1478) -> bool {
1479    if ignorecase
1480        && (case_only_rename_to(renames, dst) || renames_are_case_only_tree_to(renames, dst))
1481    {
1482        return index_has_unrelated_entries(index, dst, ignorecase, renames);
1483    }
1484
1485    let abs = work_tree.join(dst);
1486    if abs.exists() {
1487        if ignorecase
1488            && (rename_sources_cover_path(renames, dst)
1489                || renames_are_case_only_tree_to(renames, dst))
1490        {
1491            return index_has_unrelated_entries(index, dst, ignorecase, renames);
1492        }
1493        return true;
1494    }
1495
1496    index_has_unrelated_entries(index, dst, ignorecase, renames)
1497}
1498
1499fn case_only_rename_to(renames: &[(String, String)], dst: &str) -> bool {
1500    renames.iter().any(|(from, to)| {
1501        to == dst && from != to && paths_equal(from.as_bytes(), to.as_bytes(), true)
1502    })
1503}
1504
1505fn renames_are_case_only_tree_to(renames: &[(String, String)], dst: &str) -> bool {
1506    !renames.is_empty()
1507        && renames
1508            .iter()
1509            .all(|(from, to)| case_only_rename_under_dst(from, to, dst))
1510}
1511
1512fn case_only_rename_under_dst(from: &str, to: &str, dst: &str) -> bool {
1513    if from == to || !paths_equal(from.as_bytes(), to.as_bytes(), true) {
1514        return false;
1515    }
1516    if to == dst {
1517        return paths_equal(from.as_bytes(), dst.as_bytes(), true);
1518    }
1519    let plen = dst.len();
1520    if to.len() <= plen || to.as_bytes().get(plen) != Some(&b'/') {
1521        return false;
1522    }
1523    if !paths_equal(&to.as_bytes()[..plen], dst.as_bytes(), true) {
1524        return false;
1525    }
1526    from.len() > plen
1527        && from.as_bytes().get(plen) == Some(&b'/')
1528        && paths_equal(&from.as_bytes()[..plen], &to.as_bytes()[..plen], true)
1529}
1530
1531fn rename_sources_cover_path(renames: &[(String, String)], path: &str) -> bool {
1532    renames
1533        .iter()
1534        .any(|(from, _)| paths_equal(from.as_bytes(), path.as_bytes(), true))
1535}
1536
1537fn index_has_unrelated_entries(
1538    index: &Index,
1539    dst: &str,
1540    ignorecase: bool,
1541    renames: &[(String, String)],
1542) -> bool {
1543    let rename_from: HashSet<&str> = renames.iter().map(|(from, _)| from.as_str()).collect();
1544
1545    if ignorecase {
1546        return index.entries.iter().filter(|e| e.stage() == 0).any(|e| {
1547            let path = String::from_utf8_lossy(&e.path);
1548            if !index_path_at_destination(&path, dst, true) {
1549                return false;
1550            }
1551            !rename_from.contains(path.as_ref())
1552        });
1553    }
1554
1555    let mut paths = index_paths_under(index, dst, true);
1556    if paths.is_empty() && index.get(dst.as_bytes(), 0).is_some() {
1557        paths.push(dst.to_string());
1558    }
1559    paths.iter().any(|p| !rename_from.contains(p.as_str()))
1560}
1561
1562fn index_path_at_destination(path: &str, dst: &str, ignorecase: bool) -> bool {
1563    if paths_equal(path.as_bytes(), dst.as_bytes(), ignorecase) {
1564        return true;
1565    }
1566    if !ignorecase && path == dst {
1567        return true;
1568    }
1569    let plen = dst.len();
1570    if path.len() <= plen || path.as_bytes().get(plen) != Some(&b'/') {
1571        return false;
1572    }
1573    let prefix = &path[..plen];
1574    if ignorecase {
1575        paths_equal(prefix.as_bytes(), dst.as_bytes(), true)
1576    } else {
1577        prefix == dst
1578    }
1579}
1580
1581fn worktree_paths_to_clear(work_tree: &Path, index: &Index, dst: &str) -> Vec<String> {
1582    let mut paths = index_paths_under(index, dst, true);
1583    if paths.is_empty() {
1584        let abs = work_tree.join(dst);
1585        if abs.is_file() || abs.is_symlink() {
1586            paths.push(dst.to_string());
1587        }
1588    }
1589    paths
1590}
1591
1592fn clear_destination_index(index: &mut Index, dst: &str) {
1593    let paths = index_paths_under(index, dst, true);
1594    if paths.is_empty() {
1595        index.remove(dst.as_bytes());
1596    } else {
1597        index.remove_paths(paths.iter().map(|p| p.as_bytes()));
1598    }
1599}
1600
1601fn is_subdirectory(candidate: &str, parent_dir: &str, ignorecase: bool) -> bool {
1602    if paths_equal(candidate.as_bytes(), parent_dir.as_bytes(), ignorecase) {
1603        return false;
1604    }
1605    let plen = parent_dir.len();
1606    if candidate.len() <= plen || candidate.as_bytes().get(plen) != Some(&b'/') {
1607        return false;
1608    }
1609    let prefix = &candidate[..plen];
1610    if ignorecase {
1611        paths_equal(prefix.as_bytes(), parent_dir.as_bytes(), true)
1612    } else {
1613        prefix == parent_dir
1614    }
1615}
1616
1617fn ensure_worktree_move_sources_exist(
1618    work_tree: &Path,
1619    renames: &[(String, String)],
1620) -> Result<()> {
1621    for (from, to) in renames {
1622        let abs = work_tree.join(from);
1623        if abs.is_file() || abs.is_symlink() {
1624            continue;
1625        }
1626        if abs.is_dir() {
1627            continue;
1628        }
1629        return Err(Error::Worktree(WorktreeError::MoveBadSource {
1630            src: from.clone(),
1631            destination: to.clone(),
1632        }));
1633    }
1634    Ok(())
1635}
1636
1637fn rename_worktree_entry(from: &Path, to: &Path, ignorecase: bool) -> std::io::Result<()> {
1638    if from == to {
1639        return Ok(());
1640    }
1641    let from_name = from.to_string_lossy();
1642    let to_name = to.to_string_lossy();
1643    if ignorecase && from_name.eq_ignore_ascii_case(to_name.as_ref()) && from != to {
1644        case_only_worktree_rename(from, to)
1645    } else {
1646        fs::rename(from, to)
1647    }
1648}
1649
1650pub(crate) fn case_only_worktree_rename(from: &Path, to: &Path) -> std::io::Result<()> {
1651    use std::sync::atomic::{AtomicU64, Ordering};
1652
1653    static CASE_MV_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
1654    let parent = to.parent().unwrap_or_else(|| Path::new("."));
1655    let salt = CASE_MV_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1656    for attempt in 0..64 {
1657        let temp_path = parent.join(format!(
1658            ".grit-mv-{}-{}-{}",
1659            std::process::id(),
1660            salt,
1661            attempt
1662        ));
1663        if temp_path.exists() {
1664            continue;
1665        }
1666        match fs::rename(from, &temp_path) {
1667            Ok(()) => match fs::rename(&temp_path, to) {
1668                Ok(()) => return Ok(()),
1669                Err(e) => {
1670                    if fs::rename(&temp_path, from).is_err() {
1671                        return Err(std::io::Error::new(
1672                            e.kind(),
1673                            format!(
1674                                "renaming back to '{}' after failed final case-only step: \
1675                                 source may be at '{}'",
1676                                from.display(),
1677                                temp_path.display()
1678                            ),
1679                        ));
1680                    }
1681                    return Err(e);
1682                }
1683            },
1684            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1685            Err(e) => return Err(e),
1686        }
1687    }
1688    Err(std::io::Error::other(
1689        "could not allocate a unique temporary path for case-only rename",
1690    ))
1691}
1692
1693fn plan_index_renames(index: &Index, src: &str, final_dst: &str) -> Result<Vec<(String, String)>> {
1694    let src_paths = index_paths_under(index, src, true);
1695    let mut renames = Vec::with_capacity(src_paths.len());
1696    for from in src_paths {
1697        let suffix = from.strip_prefix(src).unwrap_or("");
1698        let to = if suffix.is_empty() {
1699            final_dst.to_string()
1700        } else if let Some(stripped) = suffix.strip_prefix('/') {
1701            format!("{final_dst}/{stripped}")
1702        } else {
1703            format!("{final_dst}{suffix}")
1704        };
1705        renames.push((from, to));
1706    }
1707    Ok(renames)
1708}
1709
1710fn rename_worktree_paths(
1711    work_tree: &Path,
1712    src: &str,
1713    final_dst: &str,
1714    renames: &[(String, String)],
1715    ignorecase: bool,
1716) -> Result<()> {
1717    if renames.len() == 1 && renames[0].0 == src {
1718        let from = work_tree.join(&renames[0].0);
1719        let to = work_tree.join(&renames[0].1);
1720        if let Some(parent) = to.parent() {
1721            fs::create_dir_all(parent).map_err(|e| {
1722                Error::Worktree(WorktreeError::Path {
1723                    detail: format!("creating parent for '{}': {e}", renames[0].1),
1724                })
1725            })?;
1726        }
1727        rename_worktree_entry(&from, &to, ignorecase).map_err(|e| {
1728            Error::Worktree(WorktreeError::Path {
1729                detail: format!("renaming '{}' -> '{}': {e}", renames[0].0, renames[0].1),
1730            })
1731        })?;
1732        return Ok(());
1733    }
1734
1735    let src_abs = work_tree.join(src);
1736    let dst_abs = work_tree.join(final_dst);
1737    if src_abs.is_dir() {
1738        if let Some(parent) = dst_abs.parent() {
1739            fs::create_dir_all(parent).map_err(|e| {
1740                Error::Worktree(WorktreeError::Path {
1741                    detail: format!("creating parent for '{final_dst}': {e}"),
1742                })
1743            })?;
1744        }
1745        rename_worktree_entry(&src_abs, &dst_abs, ignorecase).map_err(|e| {
1746            Error::Worktree(WorktreeError::Path {
1747                detail: format!("renaming directory '{src}' -> '{final_dst}': {e}"),
1748            })
1749        })?;
1750        return Ok(());
1751    }
1752
1753    for (from, to) in renames {
1754        let from_abs = work_tree.join(from);
1755        let to_abs = work_tree.join(to);
1756        if let Some(parent) = to_abs.parent() {
1757            fs::create_dir_all(parent).map_err(|e| {
1758                Error::Worktree(WorktreeError::Path {
1759                    detail: format!("creating parent for '{to}': {e}"),
1760                })
1761            })?;
1762        }
1763        if from_abs.exists() {
1764            rename_worktree_entry(&from_abs, &to_abs, ignorecase).map_err(|e| {
1765                Error::Worktree(WorktreeError::Path {
1766                    detail: format!("renaming '{from}' -> '{to}': {e}"),
1767                })
1768            })?;
1769        }
1770    }
1771    Ok(())
1772}
1773
1774fn entry_with_relpath(mut entry: IndexEntry, path: &str) -> IndexEntry {
1775    entry.path = path.as_bytes().to_vec();
1776    let path_len = entry.path.len().min(0xFFF) as u16;
1777    entry.flags = (entry.flags & !0x0FFF) | path_len;
1778    entry
1779}
1780
1781#[cfg(test)]
1782mod remove_block_reason_tests {
1783    use super::{worktree_still_has_file, BlockedRemoval, RemoveBlockReason};
1784    use crate::index::{MODE_GITLINK, MODE_REGULAR};
1785
1786    #[test]
1787    fn classify_without_cached_refuses_any_difference() {
1788        assert_eq!(RemoveBlockReason::classify(false, false, false), None);
1789        assert_eq!(
1790            RemoveBlockReason::classify(true, false, false),
1791            Some(RemoveBlockReason::StagedChanges)
1792        );
1793        assert_eq!(
1794            RemoveBlockReason::classify(false, true, false),
1795            Some(RemoveBlockReason::LocalModifications)
1796        );
1797        assert_eq!(
1798            RemoveBlockReason::classify(true, true, false),
1799            Some(RemoveBlockReason::StagedAndLocal)
1800        );
1801    }
1802
1803    #[test]
1804    fn classify_with_cached_refuses_only_staged_and_local() {
1805        assert_eq!(RemoveBlockReason::classify(false, false, true), None);
1806        assert_eq!(RemoveBlockReason::classify(true, false, true), None);
1807        assert_eq!(RemoveBlockReason::classify(false, true, true), None);
1808        assert_eq!(
1809            RemoveBlockReason::classify(true, true, true),
1810            Some(RemoveBlockReason::StagedAndLocal)
1811        );
1812    }
1813
1814    #[test]
1815    fn allowed_with_cached_matches_classify() {
1816        for reason in [
1817            RemoveBlockReason::StagedChanges,
1818            RemoveBlockReason::LocalModifications,
1819            RemoveBlockReason::StagedAndLocal,
1820        ] {
1821            let (staged, local) = match reason {
1822                RemoveBlockReason::StagedChanges => (true, false),
1823                RemoveBlockReason::LocalModifications => (false, true),
1824                RemoveBlockReason::StagedAndLocal => (true, true),
1825            };
1826            assert_eq!(
1827                reason.allowed_with_cached(),
1828                RemoveBlockReason::classify(staged, local, true).is_none()
1829            );
1830        }
1831    }
1832
1833    #[test]
1834    fn blocked_removal_display_names_path_and_reason() {
1835        let blocked = BlockedRemoval {
1836            path: "dir/a.txt".into(),
1837            reason: RemoveBlockReason::LocalModifications,
1838        };
1839        assert_eq!(blocked.to_string(), "dir/a.txt (local modifications)");
1840    }
1841
1842    #[test]
1843    fn worktree_presence_ignores_missing_files_and_directories() {
1844        let tmp = tempfile::tempdir().expect("tempdir");
1845        let wt = tmp.path();
1846        std::fs::write(wt.join("file"), b"x\n").unwrap();
1847        std::fs::create_dir(wt.join("dir")).unwrap();
1848        assert!(worktree_still_has_file(wt, "file", MODE_REGULAR));
1849        assert!(!worktree_still_has_file(wt, "missing", MODE_REGULAR));
1850        assert!(!worktree_still_has_file(wt, "dir", MODE_REGULAR));
1851        assert!(worktree_still_has_file(wt, "dir", MODE_GITLINK));
1852    }
1853}
1854
1855#[cfg(test)]
1856mod collect_removal_paths_tests {
1857    use std::fs;
1858
1859    use crate::porcelain::add::{stage, StageOptions};
1860    use crate::progress::{CancelToken, NullProgress};
1861    use crate::repo::{init_repository, Repository};
1862
1863    use crate::index::Index;
1864    use crate::pathspec::{matches_pathspec_list_with_context, PathspecMatchContext};
1865
1866    use super::{remove_paths, RemoveOptions};
1867
1868    fn init_repo(root: &std::path::Path) -> Repository {
1869        init_repository(root, false, "main", None, Default::default()).expect("init")
1870    }
1871
1872    fn rm_collect(repo: &Repository, specs: &[&str], recursive: bool) -> Vec<String> {
1873        remove_paths(
1874            repo,
1875            &RemoveOptions {
1876                pathspecs: specs.iter().map(|s| (*s).to_string()).collect(),
1877                pathspec_sources: specs.iter().map(|s| (*s).to_string()).collect(),
1878                recursive,
1879                dry_run: true,
1880                force: true,
1881                ..Default::default()
1882            },
1883            &crate::progress::CancelToken::never(),
1884        )
1885        .expect("dry-run rm")
1886        .removed
1887    }
1888
1889    #[test]
1890    fn literal_directory_removal_selects_all_tracked_descendants() {
1891        let tmp = tempfile::tempdir().expect("tempdir");
1892        let root = tmp.path();
1893        let repo = init_repo(root);
1894        fs::create_dir_all(root.join("d000/s00")).unwrap();
1895        fs::write(root.join("d000/s00/a.txt"), b"a\n").unwrap();
1896        fs::write(root.join("d000/s00/b.txt"), b"b\n").unwrap();
1897        fs::create_dir_all(root.join("d001")).unwrap();
1898        fs::write(root.join("d001/x.txt"), b"x\n").unwrap();
1899        stage(
1900            &repo,
1901            &StageOptions::default(),
1902            &mut NullProgress,
1903            &CancelToken::never(),
1904        )
1905        .unwrap();
1906
1907        let mut removed = rm_collect(&repo, &["d000"], true);
1908        removed.sort();
1909        assert_eq!(
1910            removed,
1911            vec!["d000/s00/a.txt".to_string(), "d000/s00/b.txt".to_string()]
1912        );
1913    }
1914
1915    #[test]
1916    fn literal_file_does_not_remove_prefix_collision_path() {
1917        let tmp = tempfile::tempdir().expect("tempdir");
1918        let root = tmp.path();
1919        let repo = init_repo(root);
1920        fs::write(root.join("file"), b"1\n").unwrap();
1921        fs::write(root.join("file2.txt"), b"2\n").unwrap();
1922        stage(
1923            &repo,
1924            &StageOptions::default(),
1925            &mut NullProgress,
1926            &CancelToken::never(),
1927        )
1928        .unwrap();
1929
1930        let removed = rm_collect(&repo, &["file"], false);
1931        assert_eq!(removed, vec!["file".to_string()]);
1932    }
1933
1934    #[test]
1935    fn glob_pathspec_selects_matching_paths() {
1936        let tmp = tempfile::tempdir().expect("tempdir");
1937        let root = tmp.path();
1938        let repo = init_repo(root);
1939        fs::write(root.join("a.txt"), b"a\n").unwrap();
1940        fs::write(root.join("b.rs"), b"b\n").unwrap();
1941        fs::write(root.join("c.rs"), b"c\n").unwrap();
1942        stage(
1943            &repo,
1944            &StageOptions::default(),
1945            &mut NullProgress,
1946            &CancelToken::never(),
1947        )
1948        .unwrap();
1949
1950        let mut removed = rm_collect(&repo, &["*.rs"], false);
1951        removed.sort();
1952        assert_eq!(removed, vec!["b.rs".to_string(), "c.rs".to_string()]);
1953    }
1954
1955    #[test]
1956    fn ignore_unmatch_skips_unknown_spec() {
1957        let tmp = tempfile::tempdir().expect("tempdir");
1958        let root = tmp.path();
1959        let repo = init_repo(root);
1960        fs::write(root.join("keep.txt"), b"k\n").unwrap();
1961        stage(
1962            &repo,
1963            &StageOptions::default(),
1964            &mut NullProgress,
1965            &CancelToken::never(),
1966        )
1967        .unwrap();
1968
1969        let outcome = remove_paths(
1970            &repo,
1971            &RemoveOptions {
1972                pathspecs: vec!["keep.txt".into(), "missing.txt".into()],
1973                pathspec_sources: vec!["keep.txt".into(), "missing.txt".into()],
1974                dry_run: true,
1975                force: true,
1976                ignore_unmatch: true,
1977                ..Default::default()
1978            },
1979            &crate::progress::CancelToken::never(),
1980        )
1981        .expect("ignore unmatch");
1982        assert_eq!(outcome.removed, vec!["keep.txt".to_string()]);
1983    }
1984
1985    fn bruteforce_literal_dir_removal(
1986        index: &Index,
1987        spec: &str,
1988        ctx: PathspecMatchContext,
1989        recursive: bool,
1990    ) -> Vec<String> {
1991        let mut tracked: std::collections::BTreeSet<String> = index
1992            .entries
1993            .iter()
1994            .map(|e| String::from_utf8_lossy(&e.path).into_owned())
1995            .collect();
1996        let resolved = spec.to_string();
1997        let spec_trim = resolved.trim_end_matches('/');
1998        let matches: Vec<String> = tracked
1999            .iter()
2000            .filter(|path| {
2001                matches_pathspec_list_with_context(path, std::slice::from_ref(&resolved), ctx)
2002            })
2003            .cloned()
2004            .collect();
2005        let mut selected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
2006        if matches.is_empty() {
2007            let prefix = format!("{spec_trim}/");
2008            let under: Vec<String> = tracked
2009                .iter()
2010                .filter(|path| path.starts_with(&prefix))
2011                .cloned()
2012                .collect();
2013            assert!(!under.is_empty());
2014            assert!(recursive);
2015            selected.extend(under);
2016        } else {
2017            for path in matches {
2018                selected.insert(path.clone());
2019                if recursive {
2020                    let prefix = format!("{path}/");
2021                    for child in tracked.iter().filter(|p| p.starts_with(&prefix)) {
2022                        selected.insert((*child).clone());
2023                    }
2024                }
2025            }
2026        }
2027        let mut out: Vec<String> = selected.into_iter().collect();
2028        out.sort();
2029        out
2030    }
2031
2032    #[test]
2033    fn literal_directory_removal_matches_bruteforce_on_large_index() {
2034        let tmp = tempfile::tempdir().expect("tempdir");
2035        let root = tmp.path();
2036        let repo = init_repo(root);
2037        for d in 0..100 {
2038            fs::create_dir_all(root.join(format!("d{d:03}"))).unwrap();
2039            for f in 0..50 {
2040                let rel = format!("d{d:03}/f{f:02}.txt");
2041                fs::write(root.join(&rel), b"x\n").unwrap();
2042            }
2043        }
2044        stage(
2045            &repo,
2046            &StageOptions::default(),
2047            &mut NullProgress,
2048            &CancelToken::never(),
2049        )
2050        .unwrap();
2051
2052        let index = repo.load_index().expect("index");
2053        let ctx = repo.pathspec_match_context();
2054        let removed = rm_collect(&repo, &["d000"], true);
2055        let expected = bruteforce_literal_dir_removal(&index, "d000", ctx, true);
2056        assert_eq!(removed, expected);
2057        assert_eq!(removed.len(), 50);
2058        assert_eq!(index.entries.len(), 5000);
2059    }
2060
2061    #[test]
2062    fn precomposed_nfc_literal_removes_nfc_index_path() {
2063        let tmp = tempfile::tempdir().expect("tempdir");
2064        let root = tmp.path();
2065        let repo = init_repo(root);
2066        repo.force_pathspec_precompose_for_test();
2067        let nfd = "cafe\u{301}.txt";
2068        let nfc = "caf\u{e9}.txt";
2069        fs::write(root.join(nfd), b"x\n").unwrap();
2070        stage(
2071            &repo,
2072            &StageOptions::default(),
2073            &mut NullProgress,
2074            &CancelToken::never(),
2075        )
2076        .unwrap();
2077
2078        let index = repo.load_index().expect("index");
2079        let stored = String::from_utf8_lossy(
2080            &index
2081                .entries
2082                .iter()
2083                .find(|e| e.stage() == 0)
2084                .expect("stage-0 entry")
2085                .path,
2086        )
2087        .into_owned();
2088
2089        let removed = rm_collect(&repo, &[nfc], false);
2090        assert_eq!(removed, vec![stored]);
2091    }
2092
2093    #[test]
2094    fn exclude_pathspec_label_does_not_select_paths() {
2095        let tmp = tempfile::tempdir().expect("tempdir");
2096        let root = tmp.path();
2097        let repo = init_repo(root);
2098        fs::write(root.join("a.txt"), b"a\n").unwrap();
2099        fs::write(root.join("b.txt"), b"b\n").unwrap();
2100        stage(
2101            &repo,
2102            &StageOptions::default(),
2103            &mut NullProgress,
2104            &CancelToken::never(),
2105        )
2106        .unwrap();
2107
2108        let outcome = remove_paths(
2109            &repo,
2110            &RemoveOptions {
2111                pathspecs: vec!["*.txt".into(), ":(exclude)a.txt".into()],
2112                pathspec_sources: vec!["*.txt".into(), ":(exclude)a.txt".into()],
2113                dry_run: true,
2114                force: true,
2115                ..Default::default()
2116            },
2117            &crate::progress::CancelToken::never(),
2118        )
2119        .expect("dry-run rm");
2120        assert_eq!(outcome.removed.len(), 2);
2121        assert!(outcome.removed.contains(&"a.txt".to_string()));
2122        assert!(outcome.removed.contains(&"b.txt".to_string()));
2123    }
2124}
2125
2126#[cfg(test)]
2127mod path_validation_tests {
2128    use super::normalize_and_validate_repo_relative;
2129    use crate::error::Error;
2130    use crate::repo::{InitOptions, Repository};
2131    use crate::worktree::WorktreeError;
2132
2133    fn test_repo() -> (tempfile::TempDir, Repository) {
2134        let dir = tempfile::tempdir().expect("tempdir");
2135        let (repo, _) = Repository::init(dir.path(), &InitOptions::default()).expect("init");
2136        (dir, repo)
2137    }
2138
2139    #[test]
2140    fn rejects_absolute_paths() {
2141        let (_dir, repo) = test_repo();
2142        let wt = repo.work_tree().expect("worktree");
2143        let err = normalize_and_validate_repo_relative(&repo, wt, "/tmp/repo/destination")
2144            .expect_err("abs");
2145        assert!(matches!(
2146            err,
2147            Error::Worktree(WorktreeError::InvalidPath { .. })
2148        ));
2149    }
2150
2151    #[test]
2152    fn rejects_internal_parent_components() {
2153        let (_dir, repo) = test_repo();
2154        let wt = repo.work_tree().expect("worktree");
2155        let err = normalize_and_validate_repo_relative(&repo, wt, "dir/../source").expect_err("..");
2156        assert!(matches!(
2157            err,
2158            Error::Worktree(WorktreeError::OutsideRepo(_))
2159        ));
2160    }
2161
2162    #[test]
2163    fn accepts_simple_relative_paths() {
2164        let (_dir, repo) = test_repo();
2165        let wt = repo.work_tree().expect("worktree");
2166        assert_eq!(
2167            normalize_and_validate_repo_relative(&repo, wt, "./nested/file.txt").expect("ok"),
2168            "nested/file.txt"
2169        );
2170    }
2171
2172    #[test]
2173    fn strips_trailing_directory_separators_before_validation() {
2174        let (_dir, repo) = test_repo();
2175        let wt = repo.work_tree().expect("worktree");
2176        for path in ["dir/", "dir//", "./dir/"] {
2177            assert_eq!(
2178                normalize_and_validate_repo_relative(&repo, wt, path).expect("ok"),
2179                "dir",
2180                "path {path}"
2181            );
2182        }
2183    }
2184}
2185
2186#[cfg(test)]
2187mod is_subdirectory_tests {
2188    use super::is_subdirectory;
2189
2190    #[test]
2191    fn ignorecase_rejects_move_into_case_folded_subdirectory() {
2192        assert!(is_subdirectory("dir/nested", "Dir", true));
2193        assert!(!is_subdirectory("dir/nested", "Dir", false));
2194    }
2195}
2196
2197#[cfg(test)]
2198mod index_has_paths_under_tests {
2199    use super::index_has_paths_under;
2200
2201    use crate::index::{Index, IndexEntry};
2202    use crate::objects::ObjectId;
2203
2204    fn dummy_entry(path: &str) -> IndexEntry {
2205        IndexEntry {
2206            ctime_sec: 0,
2207            ctime_nsec: 0,
2208            mtime_sec: 0,
2209            mtime_nsec: 0,
2210            dev: 0,
2211            ino: 0,
2212            mode: 0o100644,
2213            uid: 0,
2214            gid: 0,
2215            size: 0,
2216            oid: ObjectId::from_bytes(&[0u8; 20]).unwrap(),
2217            flags: 0,
2218            flags_extended: None,
2219            path: path.as_bytes().to_vec(),
2220            base_index_pos: 0,
2221        }
2222    }
2223
2224    #[test]
2225    fn ignorecase_prefix_for_collision_not_destination_directory() {
2226        let mut index = Index::new();
2227        index.push_entry_unsorted(dummy_entry("Docs/a.txt"));
2228        assert!(
2229            index_has_paths_under(&index, "docs", true),
2230            "icase prefix match is for collision detection"
2231        );
2232        assert!(
2233            !index_has_paths_under(&index, "docs", false),
2234            "destination-directory classification stays case-sensitive"
2235        );
2236    }
2237}
2238
2239#[cfg(test)]
2240mod resolve_move_destination_tests {
2241    use super::resolve_move_destination_path;
2242
2243    #[test]
2244    fn case_only_directory_rename_uses_destination_spelling() {
2245        assert_eq!(
2246            resolve_move_destination_path("Dir", "dir", true, true),
2247            ("dir".into(), false)
2248        );
2249    }
2250
2251    #[test]
2252    fn real_directory_destination_appends_basename() {
2253        assert_eq!(
2254            resolve_move_destination_path("Dir", "other", true, false),
2255            ("other/Dir".into(), true)
2256        );
2257    }
2258}
2259
2260#[cfg(test)]
2261mod destination_exists_tests {
2262    use super::{
2263        case_only_rename_to, case_only_rename_under_dst, destination_exists,
2264        index_has_unrelated_entries, rename_sources_cover_path, renames_are_case_only_tree_to,
2265    };
2266    use crate::index::Index;
2267    use crate::index::IndexEntry;
2268    use crate::objects::ObjectId;
2269
2270    fn dummy_entry(path: &str) -> IndexEntry {
2271        IndexEntry {
2272            ctime_sec: 0,
2273            ctime_nsec: 0,
2274            mtime_sec: 0,
2275            mtime_nsec: 0,
2276            dev: 0,
2277            ino: 0,
2278            mode: 0o100644,
2279            uid: 0,
2280            gid: 0,
2281            size: 0,
2282            oid: ObjectId::from_bytes(&[0u8; 20]).unwrap(),
2283            flags: 0,
2284            flags_extended: None,
2285            path: path.as_bytes().to_vec(),
2286            base_index_pos: 0,
2287        }
2288    }
2289
2290    #[test]
2291    fn case_only_rename_helpers() {
2292        let renames = vec![
2293            ("README.md".into(), "readme.md".into()),
2294            ("src/A.rs".into(), "src/a.rs".into()),
2295        ];
2296        assert!(case_only_rename_to(&renames, "readme.md"));
2297        assert!(!case_only_rename_to(&renames, "other.md"));
2298        assert!(rename_sources_cover_path(&renames, "README.md"));
2299        assert!(!rename_sources_cover_path(&renames, "missing.md"));
2300    }
2301
2302    #[test]
2303    fn ignorecase_index_collision_allows_case_only_target() {
2304        let tmp = tempfile::tempdir().expect("tempdir");
2305        let wt = tmp.path();
2306        std::fs::write(wt.join("README.md"), b"x\n").unwrap();
2307        let mut index = Index::new();
2308        index.push_entry_unsorted(dummy_entry("README.md"));
2309        let renames = vec![("README.md".into(), "readme.md".into())];
2310        assert!(
2311            !destination_exists(wt, &index, "readme.md", false, true, &renames),
2312            "case-only rename must not treat the source path as a blocking destination"
2313        );
2314    }
2315
2316    #[test]
2317    fn ignorecase_index_blocks_unrelated_destination() {
2318        let mut index = Index::new();
2319        index.push_entry_unsorted(dummy_entry("README.md"));
2320        index.push_entry_unsorted(dummy_entry("readme.md"));
2321        let renames = vec![("README.md".into(), "readme.md".into())];
2322        assert!(
2323            index_has_unrelated_entries(&index, "readme.md", true, &renames),
2324            "distinct index spellings at the same icase path must block"
2325        );
2326    }
2327
2328    #[test]
2329    fn case_only_tree_rename_helpers() {
2330        let renames = vec![
2331            ("Dir/x.txt".into(), "dir/x.txt".into()),
2332            ("Dir/y.txt".into(), "dir/y.txt".into()),
2333        ];
2334        assert!(renames_are_case_only_tree_to(&renames, "dir"));
2335        assert!(case_only_rename_under_dst("Dir/x.txt", "dir/x.txt", "dir"));
2336        assert!(!renames_are_case_only_tree_to(&renames, "other"));
2337    }
2338
2339    #[test]
2340    fn ignorecase_tree_collision_allows_case_only_destination() {
2341        let tmp = tempfile::tempdir().expect("tempdir");
2342        let wt = tmp.path();
2343        std::fs::create_dir_all(wt.join("Dir")).unwrap();
2344        std::fs::write(wt.join("Dir/x.txt"), b"x\n").unwrap();
2345        let mut index = Index::new();
2346        index.push_entry_unsorted(dummy_entry("Dir/x.txt"));
2347        let renames = vec![("Dir/x.txt".into(), "dir/x.txt".into())];
2348        assert!(
2349            !destination_exists(wt, &index, "dir", false, true, &renames),
2350            "case-only directory tree must not collide with itself on a folding volume"
2351        );
2352    }
2353
2354    #[test]
2355    fn ignorecase_tree_blocks_distinct_destination_directory() {
2356        let tmp = tempfile::tempdir().expect("tempdir");
2357        let wt = tmp.path();
2358        std::fs::create_dir_all(wt.join("Dir")).unwrap();
2359        std::fs::create_dir_all(wt.join("dir")).unwrap();
2360        std::fs::write(wt.join("Dir/x.txt"), b"x\n").unwrap();
2361        std::fs::write(wt.join("dir/extra.txt"), b"y\n").unwrap();
2362        let mut index = Index::new();
2363        index.push_entry_unsorted(dummy_entry("Dir/x.txt"));
2364        index.push_entry_unsorted(dummy_entry("dir/extra.txt"));
2365        let renames = vec![("Dir/x.txt".into(), "dir/x.txt".into())];
2366        assert!(
2367            destination_exists(wt, &index, "dir", false, true, &renames),
2368            "unrelated tracked paths under the destination must still block"
2369        );
2370    }
2371}
2372
2373#[cfg(test)]
2374mod move_rollback_tests {
2375    use crate::worktree::WorktreeError;
2376    use std::fs;
2377
2378    use crate::error::Error;
2379
2380    use super::{
2381        abort_failed_move_worktree, restore_worktree_backups, rollback_worktree_renames,
2382        snapshot_worktree_path,
2383    };
2384
2385    #[test]
2386    fn abort_failed_move_rolls_back_before_restoring_force_backups() {
2387        let tmp = tempfile::tempdir().expect("tempdir");
2388        let wt = tmp.path();
2389        fs::create_dir_all(wt.join("src")).expect("src dir");
2390        fs::create_dir_all(wt.join("dest")).expect("dest dir");
2391        fs::write(wt.join("dest/a.txt"), b"old-dest\n").expect("dest file");
2392        let backup = snapshot_worktree_path(wt, "dest/a.txt")
2393            .expect("snapshot")
2394            .expect("backup bytes");
2395        fs::write(wt.join("dest/a.txt"), b"from-source\n").expect("simulated completed rename");
2396        let completed = vec![("src/a.txt".to_string(), "dest/a.txt".to_string())];
2397        let original = crate::error::Error::Worktree(WorktreeError::Path {
2398            detail: "simulated rename failure".into(),
2399        });
2400
2401        let _ = abort_failed_move_worktree(
2402            wt,
2403            &completed,
2404            std::slice::from_ref(&backup),
2405            false,
2406            original,
2407        );
2408
2409        assert_eq!(
2410            fs::read(wt.join("src/a.txt")).expect("source restored"),
2411            b"from-source\n",
2412            "source bytes must survive rollback before backup restore"
2413        );
2414        assert_eq!(
2415            fs::read(wt.join("dest/a.txt")).expect("dest restored"),
2416            b"old-dest\n",
2417            "force backup must restore pre-move destination content"
2418        );
2419
2420        fs::write(wt.join("dest/a.txt"), b"from-source\n").expect("post-move dest");
2421        restore_worktree_backups(wt, std::slice::from_ref(&backup)).expect("restore first");
2422        let _rollback = rollback_worktree_renames(wt, &completed, false);
2423        let wrong_source = fs::read(wt.join("src/a.txt")).expect("wrong-order source");
2424        assert_ne!(
2425            wrong_source, b"from-source\n",
2426            "restoring backups before rollback must not preserve moved source bytes"
2427        );
2428    }
2429
2430    #[test]
2431    fn abort_failed_move_restores_multi_source_force_batch() {
2432        let tmp = tempfile::tempdir().expect("tempdir");
2433        let wt = tmp.path();
2434        fs::create_dir_all(wt.join("src")).expect("src");
2435        fs::create_dir_all(wt.join("dest")).expect("dest");
2436        fs::write(wt.join("dest/f0.txt"), b"old0\n").expect("old dest0");
2437        fs::write(wt.join("dest/f1.txt"), b"old1\n").expect("old dest1");
2438        let backup0 = snapshot_worktree_path(wt, "dest/f0.txt")
2439            .expect("snap0")
2440            .expect("b0");
2441        let backup1 = snapshot_worktree_path(wt, "dest/f1.txt")
2442            .expect("snap1")
2443            .expect("b1");
2444        fs::write(wt.join("dest/f0.txt"), b"source0\n").expect("moved0");
2445        fs::write(wt.join("dest/f1.txt"), b"source1\n").expect("moved1");
2446        let completed = vec![
2447            ("src/f0.txt".to_string(), "dest/f0.txt".to_string()),
2448            ("src/f1.txt".to_string(), "dest/f1.txt".to_string()),
2449        ];
2450        let backups = vec![backup0, backup1];
2451        let _ = abort_failed_move_worktree(
2452            wt,
2453            &completed,
2454            &backups,
2455            false,
2456            crate::error::Error::Worktree(WorktreeError::Path {
2457                detail: "simulated later rename failure".into(),
2458            }),
2459        );
2460        assert_eq!(fs::read(wt.join("src/f0.txt")).unwrap(), b"source0\n");
2461        assert_eq!(fs::read(wt.join("src/f1.txt")).unwrap(), b"source1\n");
2462        assert_eq!(fs::read(wt.join("dest/f0.txt")).unwrap(), b"old0\n");
2463        assert_eq!(fs::read(wt.join("dest/f1.txt")).unwrap(), b"old1\n");
2464    }
2465
2466    #[test]
2467    fn abort_failed_move_preserves_destination_when_reverse_rename_fails() {
2468        use super::backup_and_remove_worktree_paths;
2469
2470        let tmp = tempfile::tempdir().expect("tempdir");
2471        let wt = tmp.path();
2472        fs::create_dir_all(wt.join("src")).expect("src dir");
2473        fs::create_dir_all(wt.join("dest")).expect("dest dir");
2474        fs::write(wt.join("src/f0000"), b"SOURCE-0\n").expect("source 0");
2475        fs::write(wt.join("src/f0001"), b"SOURCE-1\n").expect("source 1");
2476        fs::write(wt.join("dest/f0000"), b"OLDDEST-0\n").expect("old dest 0");
2477        fs::write(wt.join("dest/f0001"), b"OLDDEST-1\n").expect("old dest 1");
2478
2479        let cleared = backup_and_remove_worktree_paths(
2480            wt,
2481            &["dest/f0000".to_owned(), "dest/f0001".to_owned()],
2482        )
2483        .expect("backup dest");
2484        fs::create_dir_all(wt.join("dest")).expect("dest dir after clear");
2485
2486        fs::rename(wt.join("src/f0000"), wt.join("dest/f0000")).expect("move 0");
2487        fs::rename(wt.join("src/f0001"), wt.join("dest/f0001")).expect("move 1");
2488        fs::create_dir_all(wt.join("src/f0000")).expect("block rollback for f0000");
2489
2490        let applied = vec![
2491            ("src/f0000".to_owned(), "dest/f0000".to_owned()),
2492            ("src/f0001".to_owned(), "dest/f0001".to_owned()),
2493        ];
2494        let err = abort_failed_move_worktree(
2495            wt,
2496            &applied,
2497            &cleared,
2498            false,
2499            Error::Worktree(WorktreeError::MoveBadSource {
2500                src: "src/f0001".to_owned(),
2501                destination: "dest/f0001".to_owned(),
2502            }),
2503        );
2504        assert!(
2505            matches!(
2506                err,
2507                Error::Worktree(WorktreeError::MoveRollbackIncomplete { unreversed: 1, .. })
2508            ),
2509            "expected aggregated incomplete rollback error, got {err:?}"
2510        );
2511        assert_eq!(
2512            fs::read_to_string(wt.join("dest/f0000")).expect("dest f0000"),
2513            "SOURCE-0\n",
2514            "must not overwrite moved bytes with forced-destination backup when rollback failed"
2515        );
2516        assert_eq!(
2517            fs::read_to_string(wt.join("dest/f0001")).expect("dest f0001"),
2518            "OLDDEST-1\n",
2519            "successful rollback should restore cleared destination backup"
2520        );
2521    }
2522
2523    #[test]
2524    fn abort_failed_move_preserves_directory_destination_descendants() {
2525        use super::WorktreePathBackup;
2526
2527        let tmp = tempfile::tempdir().expect("tempdir");
2528        let wt = tmp.path();
2529        fs::create_dir_all(wt.join("dest/srcdir")).expect("dest tree");
2530        fs::write(wt.join("dest/srcdir/file"), b"SOURCE-DIR\n").expect("moved file");
2531        fs::create_dir_all(wt.join("srcdir")).expect("srcdir");
2532        fs::write(wt.join("srcdir/blocker"), b"x\n").expect("block directory rollback");
2533
2534        let cleared = vec![WorktreePathBackup::File {
2535            rel: "dest/srcdir/file".to_owned(),
2536            bytes: b"OLDDEST-DIR\n".to_vec(),
2537            #[cfg(unix)]
2538            mode: 0o100644,
2539        }];
2540
2541        let applied = vec![("srcdir".to_owned(), "dest/srcdir".to_owned())];
2542        let err = abort_failed_move_worktree(
2543            wt,
2544            &applied,
2545            &cleared,
2546            false,
2547            Error::Worktree(WorktreeError::MoveBadSource {
2548                src: "srcdir/missing".to_owned(),
2549                destination: "dest/srcdir/missing".to_owned(),
2550            }),
2551        );
2552        assert!(
2553            matches!(
2554                err,
2555                Error::Worktree(WorktreeError::MoveRollbackIncomplete { .. })
2556            ),
2557            "unexpected error: {err:?}"
2558        );
2559        assert_eq!(
2560            fs::read_to_string(wt.join("dest/srcdir/file")).expect("dest file"),
2561            "SOURCE-DIR\n",
2562            "must not restore descendant backup when directory rollback failed"
2563        );
2564    }
2565}
2566
2567#[cfg(test)]
2568mod cancel_regression_tests {
2569    use crate::error::Error;
2570    use crate::porcelain::add::{stage, StageOptions};
2571    use crate::progress::CancelToken;
2572    use crate::progress::NullProgress;
2573    use crate::repo::{init_repository, Repository};
2574    use std::fs;
2575
2576    use super::{move_path, remove_paths, RemoveOptions};
2577
2578    fn init_repo(root: &std::path::Path) -> Repository {
2579        init_repository(root, false, "main", None, Default::default()).expect("init")
2580    }
2581
2582    #[cfg(unix)]
2583    #[test]
2584    fn remove_paths_worktree_failure_on_second_path_restores_first_and_index() {
2585        use std::os::unix::fs::PermissionsExt;
2586
2587        let tmp = tempfile::tempdir().expect("tempdir");
2588        let root = tmp.path();
2589        let repo = init_repo(root);
2590        fs::create_dir_all(root.join("locked")).unwrap();
2591        fs::write(root.join("a.txt"), b"a\n").unwrap();
2592        fs::write(root.join("locked/b.txt"), b"b\n").unwrap();
2593        stage(
2594            &repo,
2595            &StageOptions::default(),
2596            &mut NullProgress,
2597            &crate::progress::CancelToken::never(),
2598        )
2599        .unwrap();
2600        fs::set_permissions(root.join("locked"), fs::Permissions::from_mode(0o555)).unwrap();
2601        let index_before = fs::read(repo.index_path()).expect("read index");
2602
2603        let err = remove_paths(
2604            &repo,
2605            &RemoveOptions {
2606                pathspecs: vec!["a.txt".into(), "locked/b.txt".into()],
2607                force: true,
2608                ..RemoveOptions::default()
2609            },
2610            &crate::progress::CancelToken::never(),
2611        )
2612        .expect_err("unlink under read-only directory must fail");
2613
2614        assert!(
2615            !matches!(err, Error::Cancelled),
2616            "unexpected cancel: {err:?}"
2617        );
2618        assert_eq!(
2619            fs::read(repo.index_path()).expect("read index"),
2620            index_before,
2621            "index must still list every path"
2622        );
2623        assert!(root.join("a.txt").is_file(), "first path must be restored");
2624        assert!(
2625            root.join("locked/b.txt").is_file(),
2626            "second path must remain"
2627        );
2628        assert!(
2629            repo.load_index()
2630                .expect("load index")
2631                .get(b"a.txt", 0)
2632                .is_some(),
2633            "index must still track a.txt"
2634        );
2635        assert!(
2636            repo.load_index()
2637                .expect("load index")
2638                .get(b"locked/b.txt", 0)
2639                .is_some(),
2640            "index must still track locked/b.txt"
2641        );
2642    }
2643
2644    #[test]
2645    fn remove_paths_cancel_during_worktree_removal_restores_files_and_index() {
2646        let tmp = tempfile::tempdir().expect("tempdir");
2647        let root = tmp.path();
2648        let repo = init_repo(root);
2649        fs::write(root.join("a.txt"), b"a\n").unwrap();
2650        fs::write(root.join("b.txt"), b"b\n").unwrap();
2651        stage(
2652            &repo,
2653            &StageOptions::default(),
2654            &mut NullProgress,
2655            &crate::progress::CancelToken::never(),
2656        )
2657        .unwrap();
2658        let index_before = fs::read(repo.index_path()).expect("read index");
2659
2660        // After lock poll, cancel while removing the second worktree file.
2661        let cancel = CancelToken::after_polls(4);
2662        let err = remove_paths(
2663            &repo,
2664            &RemoveOptions {
2665                pathspecs: vec!["a.txt".into(), "b.txt".into()],
2666                force: true,
2667                ..RemoveOptions::default()
2668            },
2669            &cancel,
2670        )
2671        .expect_err("cancelled rm");
2672        assert!(matches!(err, Error::Cancelled));
2673        assert_eq!(
2674            fs::read(repo.index_path()).expect("read index"),
2675            index_before
2676        );
2677        assert!(root.join("a.txt").is_file());
2678        assert!(root.join("b.txt").is_file());
2679    }
2680
2681    #[test]
2682    fn move_paths_cancel_after_worktree_rename_rolls_back() {
2683        let tmp = tempfile::tempdir().expect("tempdir");
2684        let root = tmp.path();
2685        let repo = init_repo(root);
2686        fs::write(root.join("a.txt"), b"a\n").unwrap();
2687        stage(
2688            &repo,
2689            &StageOptions::default(),
2690            &mut NullProgress,
2691            &crate::progress::CancelToken::never(),
2692        )
2693        .unwrap();
2694        let index_before = fs::read(repo.index_path()).expect("read index");
2695
2696        // After lock poll and loop guard, cancel at the final pre-commit poll.
2697        let cancel = CancelToken::after_polls(3);
2698        let err = move_path(&repo, "a.txt", "b.txt", false, &cancel).expect_err("cancelled mv");
2699        assert!(matches!(err, Error::Cancelled));
2700        assert_eq!(
2701            fs::read(repo.index_path()).expect("read index"),
2702            index_before
2703        );
2704        assert!(root.join("a.txt").is_file());
2705        assert!(!root.join("b.txt").exists());
2706    }
2707}
2708
2709#[cfg(test)]
2710mod index_lock_transaction_tests {
2711    use std::fs;
2712
2713    use crate::porcelain::add::{stage, StageOptions};
2714    use crate::progress::NullProgress;
2715    use crate::repo::{init_repository, Repository};
2716    use crate::test_support::inject::set_test_inject_index_write_fail;
2717
2718    use super::{move_path, remove_paths, RemoveOptions};
2719
2720    fn init_repo(root: &std::path::Path) -> Repository {
2721        init_repository(root, false, "main", None, Default::default()).expect("init")
2722    }
2723
2724    #[test]
2725    fn remove_paths_injected_index_write_failure_leaves_worktree() {
2726        let tmp = tempfile::tempdir().expect("tempdir");
2727        let root = tmp.path();
2728        let repo = init_repo(root);
2729        fs::write(root.join("a.txt"), b"1\n").unwrap();
2730        stage(
2731            &repo,
2732            &StageOptions::default(),
2733            &mut NullProgress,
2734            &crate::progress::CancelToken::never(),
2735        )
2736        .unwrap();
2737
2738        set_test_inject_index_write_fail(true);
2739        let err = remove_paths(
2740            &repo,
2741            &RemoveOptions {
2742                pathspecs: vec!["a.txt".into()],
2743                pathspec_sources: vec!["a.txt".into()],
2744                force: true,
2745                ..Default::default()
2746            },
2747            &crate::progress::CancelToken::never(),
2748        )
2749        .expect_err("injected write failure");
2750        set_test_inject_index_write_fail(false);
2751        assert!(matches!(
2752            err,
2753            crate::error::Error::Io(_)
2754                | crate::error::Error::Repository(crate::repo::RepositoryError::GitDirPathIo(_))
2755                | crate::error::Error::Index(_)
2756        ));
2757        assert!(root.join("a.txt").is_file());
2758    }
2759
2760    #[test]
2761    fn move_path_injected_index_write_failure_leaves_worktree() {
2762        let tmp = tempfile::tempdir().expect("tempdir");
2763        let root = tmp.path();
2764        let repo = init_repo(root);
2765        fs::write(root.join("a.txt"), b"1\n").unwrap();
2766        stage(
2767            &repo,
2768            &StageOptions::default(),
2769            &mut NullProgress,
2770            &crate::progress::CancelToken::never(),
2771        )
2772        .unwrap();
2773
2774        set_test_inject_index_write_fail(true);
2775        let err = move_path(
2776            &repo,
2777            "a.txt",
2778            "b.txt",
2779            false,
2780            &crate::progress::CancelToken::never(),
2781        )
2782        .expect_err("injected write failure");
2783        set_test_inject_index_write_fail(false);
2784        assert!(matches!(
2785            err,
2786            crate::error::Error::Io(_)
2787                | crate::error::Error::Repository(crate::repo::RepositoryError::GitDirPathIo(_))
2788                | crate::error::Error::Index(_)
2789        ));
2790        assert!(root.join("a.txt").is_file());
2791        assert!(!root.join("b.txt").exists());
2792    }
2793}
2794
2795#[cfg(test)]
2796mod trailing_slash_move_tests {
2797    use crate::worktree::WorktreeError;
2798    use std::fs;
2799
2800    use crate::error::Error;
2801    use crate::porcelain::add::{stage, StageOptions};
2802    use crate::progress::NullProgress;
2803    use crate::repo::{init_repository, Repository};
2804
2805    use super::move_path;
2806
2807    fn init_repo(root: &std::path::Path) -> Repository {
2808        init_repository(root, false, "main", None, Default::default()).expect("init")
2809    }
2810
2811    fn stage_all(repo: &Repository) {
2812        stage(
2813            repo,
2814            &StageOptions::default(),
2815            &mut NullProgress,
2816            &crate::progress::CancelToken::never(),
2817        )
2818        .expect("stage");
2819    }
2820
2821    #[test]
2822    fn move_file_into_existing_directory_with_trailing_slash() {
2823        let tmp = tempfile::tempdir().expect("tempdir");
2824        let root = tmp.path();
2825        let repo = init_repo(root);
2826        fs::create_dir_all(root.join("dir")).unwrap();
2827        fs::write(root.join("c"), b"c\n").unwrap();
2828        stage_all(&repo);
2829        move_path(
2830            &repo,
2831            "c",
2832            "dir/",
2833            false,
2834            &crate::progress::CancelToken::never(),
2835        )
2836        .expect("mv");
2837        assert!(root.join("dir/c").is_file());
2838        assert!(!root.join("c").exists());
2839    }
2840
2841    #[test]
2842    fn move_file_to_missing_directory_with_trailing_slash_refused() {
2843        let tmp = tempfile::tempdir().expect("tempdir");
2844        let root = tmp.path();
2845        let repo = init_repo(root);
2846        fs::write(root.join("c"), b"c\n").unwrap();
2847        stage_all(&repo);
2848        let err = move_path(
2849            &repo,
2850            "c",
2851            "missing/",
2852            false,
2853            &crate::progress::CancelToken::never(),
2854        )
2855        .expect_err("mv");
2856        assert!(matches!(
2857            err,
2858            Error::Worktree(WorktreeError::MoveDestinationNotDirectory { .. })
2859        ));
2860        assert!(root.join("c").is_file());
2861    }
2862
2863    #[test]
2864    fn move_directory_to_missing_directory_with_trailing_slash_renames() {
2865        let tmp = tempfile::tempdir().expect("tempdir");
2866        let root = tmp.path();
2867        let repo = init_repo(root);
2868        fs::create_dir_all(root.join("src/nested")).unwrap();
2869        fs::write(root.join("src/nested/file"), b"x\n").unwrap();
2870        stage_all(&repo);
2871        move_path(
2872            &repo,
2873            "src",
2874            "dest/",
2875            false,
2876            &crate::progress::CancelToken::never(),
2877        )
2878        .expect("mv");
2879        assert!(root.join("dest/nested/file").is_file());
2880        assert!(!root.join("src").exists());
2881    }
2882}