Skip to main content

grit_lib/worktree/
move_repair.rs

1//! Linked worktree move and repair (Git `worktree move` / `worktree repair`).
2
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6
7use crate::error::{Error, Result};
8use crate::git_path::{absolute_path_for_gitfile_stored_path, path_for_disk_compare};
9use crate::index::{Index, MODE_GITLINK};
10use crate::lockfile::{LockError, LockFile, LockWait};
11use crate::repo::Repository;
12
13use super::core::{common_git_dir, find_linked_worktree, list_worktrees, WorktreeEntry};
14use super::error::{LinkedWorktreeError, LinkedWorktreeOperation};
15
16/// Options for [`move_linked_worktree`].
17#[derive(Debug, Clone, Default)]
18pub struct MoveWorktreeOptions {
19    /// Allow move when the worktree is locked (Git requires `-f` twice; grit uses one `--force`).
20    pub force: bool,
21    /// Report the move without changing disk state.
22    pub dry_run: bool,
23}
24
25/// What [`repair_worktrees`] fixed for one worktree path.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum WorktreeRepairKind {
28    /// The worktree `.git` gitfile pointed at the wrong admin directory.
29    GitFileAdminDir,
30    /// `<admin>/gitdir` did not point at this worktree's `.git` file.
31    GitdirWorktreePath,
32    /// `.git` used a relative/absolute path where the other form was required.
33    GitFilePathStyle,
34    /// `gitdir` used a relative/absolute path where the other form was required.
35    GitdirPathStyle,
36}
37
38/// One repair action recorded by [`repair_worktrees`].
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct WorktreeRepair {
41    /// Working tree root that was repaired.
42    pub path: PathBuf,
43    /// Which link was rewritten.
44    pub kind: WorktreeRepairKind,
45}
46
47/// Move a linked worktree to a new path and rewrite `gitdir` / `.git` links.
48///
49/// # Errors
50///
51/// Returns [`LinkedWorktreeError::NotRegistered`] for an unknown `from`,
52/// [`LinkedWorktreeError::MainWorktree`] for the main worktree, [`LinkedWorktreeError::Locked`] unless
53/// [`MoveWorktreeOptions::force`] is set, [`LinkedWorktreeError::PathExists`] for an existing
54/// destination, [`LinkedWorktreeError::HasSubmodules`] for populated submodules, and I/O failures.
55pub(crate) fn move_linked_worktree(
56    repo: &Repository,
57    from: &Path,
58    to: &Path,
59    options: &MoveWorktreeOptions,
60) -> Result<()> {
61    let entry = find_linked_worktree(repo, from, LinkedWorktreeOperation::Move)?;
62    if entry.is_locked && !options.force {
63        return Err(LinkedWorktreeError::Locked {
64            reason: entry.lock_reason,
65        }
66        .into());
67    }
68
69    let dest = resolve_move_destination(&entry.path, to)?;
70    if dest.exists() {
71        return Err(LinkedWorktreeError::PathExists { path: dest }.into());
72    }
73
74    if worktree_has_blocking_submodules(&entry)? {
75        return Err(LinkedWorktreeError::HasSubmodules.into());
76    }
77
78    if options.dry_run {
79        return Ok(());
80    }
81
82    rename_worktree_directory(&entry.path, &dest)?;
83
84    let dotgit = dest.join(".git");
85    let gitdir_file = entry.admin_dir.join("gitdir");
86    write_worktree_linking_files(&dotgit, &gitdir_file, &dest, &entry.admin_dir)?;
87    Ok(())
88}
89
90/// Repair `.git` / `gitdir` links for linked worktrees.
91///
92/// When `paths` is empty, repairs every registered linked worktree from the open repository.
93/// Otherwise each path must be a linked worktree root (not the main worktree).
94///
95/// # Errors
96///
97/// Returns [`LinkedWorktreeError::PathNotFound`] or [`LinkedWorktreeError::NotADirectory`] for an invalid
98/// target, [`LinkedWorktreeError::DotGitIsDirectory`] or [`LinkedWorktreeError::BrokenGitFile`] when a
99/// target's `.git` cannot be traced to its registration, and I/O failures.
100pub(crate) fn repair_worktrees(
101    repo: &Repository,
102    paths: &[&Path],
103    dry_run: bool,
104) -> Result<Vec<WorktreeRepair>> {
105    let common = common_git_dir(repo.git_dir());
106    let mut repairs = Vec::new();
107    if paths.is_empty() {
108        for entry in list_worktrees(repo)? {
109            if entry.admin_dir == common {
110                continue;
111            }
112            let Some(wt_path) = locate_worktree_root_for_repair(&entry)? else {
113                continue;
114            };
115            repair_worktree_links(&wt_path, &entry.admin_dir, dry_run, &mut repairs)?;
116        }
117        return Ok(repairs);
118    }
119    for path in paths {
120        let wt_path = path_for_disk_compare(path);
121        if !wt_path.exists() {
122            return Err(LinkedWorktreeError::PathNotFound { path: wt_path }.into());
123        }
124        if !wt_path.is_dir() {
125            return Err(LinkedWorktreeError::NotADirectory { path: wt_path }.into());
126        }
127        repair_worktree_at_path(repo, &wt_path, dry_run, &mut repairs)?;
128    }
129    Ok(repairs)
130}
131
132/// Resolve the destination directory for [`move_linked_worktree`].
133///
134/// When `to` is an existing directory, the worktree basename is appended (Git behavior).
135///
136/// # Errors
137///
138/// Returns [`LinkedWorktreeError::NoFileName`] when `from` has no final path component and
139/// [`LinkedWorktreeError::NotADirectory`] when the destination's parent is not a directory.
140pub fn resolve_move_destination(from: &Path, to: &Path) -> Result<PathBuf> {
141    let dest = if to.is_dir() {
142        let base = from
143            .file_name()
144            .ok_or_else(|| LinkedWorktreeError::NoFileName {
145                path: from.to_path_buf(),
146            })?;
147        path_for_disk_compare(&to.join(base))
148    } else {
149        path_for_disk_compare(to)
150    };
151    if let Some(parent) = dest.parent() {
152        if parent.exists() && !parent.is_dir() {
153            return Err(LinkedWorktreeError::NotADirectory {
154                path: parent.to_path_buf(),
155            }
156            .into());
157        }
158    }
159    Ok(dest)
160}
161
162fn rename_worktree_directory(from: &Path, to: &Path) -> Result<()> {
163    if let Some(parent) = to.parent() {
164        fs::create_dir_all(parent).map_err(Error::Io)?;
165    }
166    match fs::rename(from, to) {
167        Ok(()) => Ok(()),
168        Err(err) if err.kind() == std::io::ErrorKind::CrossesDevices => {
169            match copy_dir_all(from, to) {
170                Ok(()) => {
171                    fs::remove_dir_all(from).map_err(Error::Io)?;
172                    Ok(())
173                }
174                Err(copy_err) => {
175                    let _ = fs::remove_dir_all(to);
176                    Err(copy_err)
177                }
178            }
179        }
180        Err(err) => Err(Error::Io(err)),
181    }
182}
183
184fn copy_dir_all(from: &Path, to: &Path) -> Result<()> {
185    fs::create_dir_all(to).map_err(Error::Io)?;
186    for entry in fs::read_dir(from).map_err(Error::Io)? {
187        let entry = entry.map_err(Error::Io)?;
188        let src = entry.path();
189        let dest = to.join(entry.file_name());
190        copy_tree_entry(&src, &dest)?;
191    }
192    Ok(())
193}
194
195fn copy_tree_entry(from: &Path, to: &Path) -> Result<()> {
196    let meta = fs::symlink_metadata(from).map_err(Error::Io)?;
197    let file_type = meta.file_type();
198    if file_type.is_symlink() || windows_mount_reparse_point(&meta) {
199        let target = fs::read_link(from).map_err(Error::Io)?;
200        create_symlink(&meta, &target, to)?;
201    } else if file_type.is_dir() {
202        copy_dir_all(from, to)?;
203    } else {
204        if let Some(parent) = to.parent() {
205            fs::create_dir_all(parent).map_err(Error::Io)?;
206        }
207        fs::copy(from, to).map_err(Error::Io)?;
208    }
209    Ok(())
210}
211
212/// Windows directory junctions (and other mount-point reparse points) look like directories
213/// to [`std::fs::FileType::is_dir`] but must not be descended into when copying.
214#[cfg(windows)]
215fn windows_mount_reparse_point(meta: &fs::Metadata) -> bool {
216    use std::os::windows::fs::MetadataExt;
217    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
218    meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
219}
220
221#[cfg(not(windows))]
222fn windows_mount_reparse_point(_meta: &fs::Metadata) -> bool {
223    false
224}
225
226fn create_symlink(source_meta: &fs::Metadata, target: &Path, link_path: &Path) -> Result<()> {
227    if let Some(parent) = link_path.parent() {
228        fs::create_dir_all(parent).map_err(Error::Io)?;
229    }
230    #[cfg(unix)]
231    {
232        let _ = source_meta;
233        use std::os::unix::fs::symlink;
234        symlink(target, link_path).map_err(Error::Io)?;
235    }
236    #[cfg(windows)]
237    {
238        use std::os::windows::fs::{symlink_dir, symlink_file, FileTypeExt};
239        // Preserve the source reparse-point kind. `Metadata::is_dir()` is false for every symlink
240        // on Windows; `FileTypeExt::is_symlink_dir()` reads the reparse-point kind directly.
241        // Junctions are directory reparse points but not symlinks.
242        if source_meta.file_type().is_symlink_dir() || windows_mount_reparse_point(source_meta) {
243            symlink_dir(target, link_path).map_err(Error::Io)?;
244        } else {
245            symlink_file(target, link_path).map_err(Error::Io)?;
246        }
247    }
248    Ok(())
249}
250
251#[cfg(all(test, windows))]
252mod windows_symlink_copy_tests {
253    use super::*;
254    use std::os::windows::fs::{symlink_dir, FileTypeExt};
255
256    #[test]
257    fn copy_tree_entry_preserves_dangling_directory_symlink_kind() {
258        let tmp = tempfile::tempdir().expect("tempdir");
259        let src_root = tmp.path().join("src");
260        fs::create_dir_all(&src_root).expect("srcdir");
261        let src_link = src_root.join("dirlink");
262        symlink_dir("missing-directory", &src_link).expect("symlink_dir");
263
264        let dest_link = tmp.path().join("dst").join("dirlink");
265        copy_tree_entry(&src_link, &dest_link).expect("copy");
266
267        let meta = fs::symlink_metadata(&dest_link).expect("dest meta");
268        assert!(meta.file_type().is_symlink());
269        assert!(
270            meta.file_type().is_symlink_dir(),
271            "directory reparse point must stay a directory link"
272        );
273        assert_eq!(
274            fs::read_link(&dest_link).expect("readlink"),
275            PathBuf::from("missing-directory")
276        );
277    }
278
279    #[test]
280    fn copy_tree_entry_preserves_relative_directory_symlink_kind() {
281        let tmp = tempfile::tempdir().expect("tempdir");
282        let src_root = tmp.path().join("src");
283        fs::create_dir_all(&src_root).expect("srcdir");
284        let src_link = src_root.join("dirlink");
285        symlink_dir("relative\\child", &src_link).expect("symlink_dir");
286
287        let dest_link = tmp.path().join("dst").join("dirlink");
288        copy_tree_entry(&src_link, &dest_link).expect("copy");
289
290        let meta = fs::symlink_metadata(&dest_link).expect("dest meta");
291        assert!(meta.file_type().is_symlink());
292        assert!(
293            meta.file_type().is_symlink_dir(),
294            "relative directory link must not become a file link"
295        );
296        assert_eq!(
297            fs::read_link(&dest_link).expect("readlink"),
298            PathBuf::from("relative\\child")
299        );
300    }
301}
302
303fn worktree_has_blocking_submodules(entry: &WorktreeEntry) -> Result<bool> {
304    let modules = entry.admin_dir.join("modules");
305    if modules.is_dir() && fs::read_dir(&modules).map_err(Error::Io)?.next().is_some() {
306        return Ok(true);
307    }
308    let index_path = entry.admin_dir.join("index");
309    if !index_path.is_file() {
310        return Ok(false);
311    }
312    let index = Index::load(&index_path)?;
313    for idx_entry in index.entries() {
314        if idx_entry.mode != MODE_GITLINK {
315            continue;
316        }
317        let name = std::str::from_utf8(&idx_entry.path).map_err(|_| {
318            LinkedWorktreeError::NonUtf8SubmodulePath {
319                path: idx_entry.path.clone(),
320            }
321        })?;
322        let sub_path = entry.path.join(name);
323        if is_submodule_populated(&sub_path) {
324            return Ok(true);
325        }
326    }
327    Ok(false)
328}
329
330fn is_submodule_populated(sub_path: &Path) -> bool {
331    let dot_git = sub_path.join(".git");
332    if dot_git.is_dir() {
333        return true;
334    }
335    if dot_git.is_file() {
336        if let Ok(content) = fs::read_to_string(&dot_git) {
337            if let Some(target) = parse_gitfile_target(&content, sub_path) {
338                return target.exists();
339            }
340        }
341    }
342    false
343}
344
345fn parse_gitfile_target(content: &str, base: &Path) -> Option<PathBuf> {
346    for line in content.lines() {
347        if let Some(rest) = line.strip_prefix("gitdir:") {
348            let rel = rest.trim();
349            let path = if Path::new(rel).is_absolute() {
350                PathBuf::from(rel)
351            } else {
352                base.join(rel)
353            };
354            return Some(path_for_disk_compare(&path));
355        }
356    }
357    None
358}
359
360fn write_worktree_linking_files(
361    dotgit: &Path,
362    gitdir_file: &Path,
363    wt_path: &Path,
364    admin_dir: &Path,
365) -> Result<()> {
366    let admin_abs = absolute_path_for_gitfile_stored_path(admin_dir);
367    let dotgit_abs = absolute_path_for_gitfile_stored_path(dotgit);
368    atomic_write_text(gitdir_file, &format!("{dotgit_abs}\n"))?;
369    atomic_write_text(dotgit, &format!("gitdir: {admin_abs}\n"))?;
370    let _ = wt_path;
371    Ok(())
372}
373
374fn atomic_write_text(path: &Path, content: &str) -> Result<()> {
375    let lock_path = lock_path_for(path);
376    let mut lock = LockFile::acquire(&lock_path, LockWait::Immediately).map_err(map_lock_err)?;
377    lock.write_all(content.as_bytes()).map_err(Error::Io)?;
378    lock.commit_to(path).map_err(map_lock_err)?;
379    Ok(())
380}
381
382fn lock_path_for(path: &Path) -> PathBuf {
383    let name = path
384        .file_name()
385        .map(|n| format!("{}.lock", n.to_string_lossy()))
386        .unwrap_or_else(|| "file.lock".to_owned());
387    path.parent()
388        .map(|p| p.join(&name))
389        .unwrap_or_else(|| PathBuf::from(name))
390}
391
392fn map_lock_err(err: LockError) -> Error {
393    match err {
394        LockError::Io { source, .. } => Error::Io(source),
395        LockError::Held { path } => LinkedWorktreeError::LockHeld { path }.into(),
396    }
397}
398
399/// Resolve the on-disk worktree root for a linked registration, including after a manual move
400/// left the admin `gitdir` pointing at a stale path.
401fn locate_worktree_root_for_repair(entry: &WorktreeEntry) -> Result<Option<PathBuf>> {
402    if linked_worktree_gitfile_at(&entry.path) {
403        return Ok(Some(entry.path.clone()));
404    }
405    if let Some(wt) = worktree_root_from_admin_gitdir(&entry.admin_dir) {
406        if linked_worktree_gitfile_at(&wt) {
407            return Ok(Some(wt));
408        }
409    }
410    discover_moved_worktree_sibling(entry)
411}
412
413fn linked_worktree_gitfile_at(wt_root: &Path) -> bool {
414    wt_root.is_dir() && wt_root.join(".git").is_file()
415}
416
417fn worktree_root_from_admin_gitdir(admin: &Path) -> Option<PathBuf> {
418    let gitdir_path = admin.join("gitdir");
419    let raw = fs::read_to_string(&gitdir_path).ok()?;
420    let trimmed = raw.trim();
421    if trimmed.is_empty() {
422        return None;
423    }
424    let mut dotgit = PathBuf::from(trimmed);
425    if dotgit.is_relative() {
426        dotgit = admin.join(dotgit);
427    }
428    let dotgit = path_for_disk_compare(&dotgit);
429    if !dotgit.is_file() {
430        return None;
431    }
432    dotgit.parent().map(path_for_disk_compare)
433}
434
435fn discover_moved_worktree_sibling(entry: &WorktreeEntry) -> Result<Option<PathBuf>> {
436    let stale = &entry.path;
437    let Some(parent) = stale.parent() else {
438        return Ok(None);
439    };
440    if !parent.is_dir() {
441        return Ok(None);
442    }
443    let expected_admin = absolute_path_for_gitfile_stored_path(&entry.admin_dir);
444    for child in fs::read_dir(parent).map_err(Error::Io)? {
445        let child = child.map_err(Error::Io)?;
446        let path = path_for_disk_compare(&child.path());
447        if path == *stale || !path.is_dir() {
448            continue;
449        }
450        let dotgit = path.join(".git");
451        if gitfile_refers_to_admin(&dotgit, &path, &expected_admin) {
452            return Ok(Some(path));
453        }
454    }
455    Ok(None)
456}
457
458fn gitfile_refers_to_admin(dotgit: &Path, wt_path: &Path, expected_admin: &str) -> bool {
459    if !dotgit.is_file() {
460        return false;
461    }
462    let content = fs::read_to_string(dotgit).unwrap_or_default();
463    match parse_gitfile_target(&content, wt_path) {
464        Some(admin) => absolute_path_for_gitfile_stored_path(&admin) == expected_admin,
465        None => false,
466    }
467}
468
469fn gitfile_repair_kind(
470    content: &str,
471    wt_path: &Path,
472    expected_admin: &str,
473) -> Option<WorktreeRepairKind> {
474    if content_contains_relative_gitdir(content) {
475        return Some(WorktreeRepairKind::GitFilePathStyle);
476    }
477    match parse_gitfile_target(content, wt_path) {
478        Some(current) => {
479            let current_admin = absolute_path_for_gitfile_stored_path(&current);
480            if current_admin != expected_admin {
481                Some(WorktreeRepairKind::GitFileAdminDir)
482            } else {
483                None
484            }
485        }
486        None => Some(WorktreeRepairKind::GitFileAdminDir),
487    }
488}
489
490fn content_contains_relative_gitdir(content: &str) -> bool {
491    content.lines().any(|line| {
492        line.strip_prefix("gitdir:")
493            .map(|rest| !Path::new(rest.trim()).is_absolute())
494            .unwrap_or(false)
495    })
496}
497
498fn repair_worktree_at_path(
499    repo: &Repository,
500    wt_path: &Path,
501    dry_run: bool,
502    repairs: &mut Vec<WorktreeRepair>,
503) -> Result<()> {
504    let dotgit = wt_path.join(".git");
505    if dotgit.is_dir() {
506        return Err(LinkedWorktreeError::DotGitIsDirectory { path: dotgit }.into());
507    }
508    let dotgit_content = fs::read_to_string(&dotgit).map_err(Error::Io)?;
509    let admin_dir = resolve_admin_from_gitfile(repo, &dotgit_content, wt_path)
510        .ok_or(LinkedWorktreeError::BrokenGitFile { path: dotgit })?;
511    repair_worktree_links(wt_path, &admin_dir, dry_run, repairs)
512}
513
514/// Rewrite `.git` / `gitdir` for `wt_path` using `admin_dir` as the authoritative registration.
515fn repair_worktree_links(
516    wt_path: &Path,
517    admin_dir: &Path,
518    dry_run: bool,
519    repairs: &mut Vec<WorktreeRepair>,
520) -> Result<()> {
521    let dotgit = wt_path.join(".git");
522    if dotgit.is_dir() {
523        return Err(LinkedWorktreeError::DotGitIsDirectory { path: dotgit }.into());
524    }
525    let dotgit_content = fs::read_to_string(&dotgit).unwrap_or_default();
526    let expected_admin = absolute_path_for_gitfile_stored_path(admin_dir);
527    if let Some(kind) = gitfile_repair_kind(&dotgit_content, wt_path, &expected_admin) {
528        repairs.push(WorktreeRepair {
529            path: wt_path.to_path_buf(),
530            kind,
531        });
532        if !dry_run {
533            let gitdir_file = admin_dir.join("gitdir");
534            write_worktree_linking_files(&dotgit, &gitdir_file, wt_path, admin_dir)?;
535        }
536    }
537
538    let gitdir_file = admin_dir.join("gitdir");
539    let expected_dotgit = absolute_path_for_gitfile_stored_path(&dotgit);
540    let gitdir_raw = fs::read_to_string(&gitdir_file).unwrap_or_default();
541    if let Some(kind) = gitdir_repair_kind(&gitdir_raw, admin_dir, &expected_dotgit) {
542        repairs.push(WorktreeRepair {
543            path: wt_path.to_path_buf(),
544            kind,
545        });
546        if !dry_run {
547            write_worktree_linking_files(&dotgit, &gitdir_file, wt_path, admin_dir)?;
548        }
549    }
550    Ok(())
551}
552
553fn gitdir_repair_kind(
554    raw: &str,
555    admin: &Path,
556    expected_dotgit: &str,
557) -> Option<WorktreeRepairKind> {
558    let trimmed = raw.trim();
559    if trimmed.is_empty() {
560        return Some(WorktreeRepairKind::GitdirWorktreePath);
561    }
562    if Path::new(trimmed).is_relative() {
563        return Some(WorktreeRepairKind::GitdirPathStyle);
564    }
565    let resolved = resolve_gitdir_target(trimmed, admin)?;
566    if resolved != expected_dotgit {
567        Some(WorktreeRepairKind::GitdirWorktreePath)
568    } else {
569        None
570    }
571}
572
573fn resolve_admin_from_gitfile(repo: &Repository, content: &str, wt_path: &Path) -> Option<PathBuf> {
574    parse_gitfile_target(content, wt_path)
575        .filter(|admin| admin.join("commondir").is_file() || admin.join("HEAD").is_file())
576        .or_else(|| infer_admin_from_gitfile_content(repo, content))
577}
578
579fn infer_admin_from_gitfile_content(repo: &Repository, content: &str) -> Option<PathBuf> {
580    let line = content.lines().find_map(|l| l.strip_prefix("gitdir:"))?;
581    let trimmed = line.trim();
582    let id = Path::new(trimmed).file_name()?.to_str()?;
583    let common = common_git_dir(repo.git_dir());
584    let candidate = common.join("worktrees").join(id);
585    if candidate.is_dir() {
586        Some(path_for_disk_compare(&candidate))
587    } else {
588        None
589    }
590}
591
592fn resolve_gitdir_target(trimmed: &str, admin: &Path) -> Option<String> {
593    if trimmed.is_empty() {
594        return None;
595    }
596    let path = if Path::new(trimmed).is_absolute() {
597        PathBuf::from(trimmed)
598    } else {
599        admin.join(trimmed)
600    };
601    Some(absolute_path_for_gitfile_stored_path(&path))
602}