Skip to main content

grit_lib/worktree/
core.rs

1//! Linked worktree registry: discovery, listing, and admin-dir layout.
2//!
3//! Git stores linked worktrees under `<common-git-dir>/worktrees/<id>/` with
4//! `gitdir`, `commondir`, `HEAD`, and optional `locked` / `prunable` files.
5//! This module reads that layout and implements linked worktree add/remove.
6
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use crate::branch_tracking::write_branch_upstream_config;
11use crate::check_ref_format::RefName;
12use crate::config::ConfigSet;
13#[cfg(test)]
14use crate::environment::RepositoryOptions;
15use crate::error::{Error, Result};
16use crate::git_path::{absolute_path_for_gitfile_stored_path, path_for_disk_compare};
17use crate::hooks::run_post_checkout;
18use crate::porcelain::branch::resolve_create_tracking;
19use crate::porcelain::branch_error::BranchError;
20use crate::porcelain::branch_error::TrackMode;
21use crate::porcelain::checkout::{checkout_between_trees_with_progress, CheckoutOutcome};
22use crate::porcelain::checkout_reflog::{
23    create_branch_ref_with_reflog, reset_branch_ref_with_reflog,
24};
25use crate::porcelain::status::{status, StatusOptions};
26use crate::progress::{CancelToken, NullProgress};
27use crate::refs;
28use crate::repo::{common_git_dir_for_config, Repository};
29use crate::rev_parse::resolve_revision;
30use crate::state::{resolve_head, resolve_linked_worktree_head, HeadState};
31
32use super::error::{LinkedWorktreeError, LinkedWorktreeOperation};
33
34#[cfg(test)]
35use super::error::WorktreeError;
36
37/// Why Git marks a linked worktree as `prunable` in `worktree list --porcelain`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
40#[cfg_attr(feature = "serde-models", serde(rename_all = "snake_case"))]
41pub enum PrunableReason {
42    /// Admin path is not a directory (`not a valid directory`).
43    AdminNotValidDirectory,
44    /// `<admin>/gitdir` is missing (`gitdir file does not exist`).
45    GitdirFileMissing,
46    /// Resolved gitdir target is missing (`gitdir file points to non-existent location`).
47    GitdirPointsElsewhere,
48    /// Working tree root directory is missing while the gitdir file still exists.
49    WorktreePathMissing,
50    /// `<admin>/gitdir` is empty or unreadable (`invalid gitdir file`).
51    InvalidGitdirFile,
52    /// `<admin>/prunable` exists (grit/Git admin marker forcing prune eligibility).
53    ExplicitMarker,
54}
55
56impl PrunableReason {
57    /// Message text after `prunable` in `git worktree list --porcelain`.
58    #[must_use]
59    pub fn porcelain_message(self) -> &'static str {
60        match self {
61            Self::AdminNotValidDirectory => "not a valid directory",
62            Self::GitdirFileMissing => "gitdir file does not exist",
63            Self::GitdirPointsElsewhere => "gitdir file points to non-existent location",
64            Self::WorktreePathMissing => "gitdir file points to non-existent location",
65            Self::InvalidGitdirFile => "invalid gitdir file",
66            Self::ExplicitMarker => "gitdir file points to non-existent location",
67        }
68    }
69}
70
71/// One row returned by [`list_worktrees`].
72#[derive(Debug, Clone, PartialEq, Eq)]
73#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
74pub struct WorktreeEntry {
75    /// Absolute path to the working tree (for bare main worktree, the common git dir).
76    pub path: PathBuf,
77    /// Resolved HEAD for this worktree.
78    pub head: HeadState,
79    /// Whether this worktree is bare (only the main entry can be bare).
80    pub is_bare: bool,
81    /// True when `<admin>/locked` exists.
82    pub is_locked: bool,
83    /// Contents of the `locked` file when non-empty.
84    pub lock_reason: Option<String>,
85    /// Administrative directory: common git dir for main, else `worktrees/<id>/`.
86    pub admin_dir: PathBuf,
87    /// True when [`Self::prunable_reason`] is set (Git `prunable` in `worktree list`).
88    pub is_prunable: bool,
89    /// Typed prune reason when [`Self::is_prunable`] is true.
90    pub prunable_reason: Option<PrunableReason>,
91    /// True when this row is the worktree [`Repository`] was opened from.
92    pub is_current: bool,
93}
94
95/// Shared git directory for `git_dir` (follows `commondir` for linked worktrees).
96#[must_use]
97pub(crate) fn common_git_dir(git_dir: &Path) -> PathBuf {
98    common_git_dir_for_config(git_dir)
99}
100
101/// Number of registered worktrees (main + linked entries under `worktrees/`).
102#[must_use]
103pub fn registered_worktree_count(common: &Path) -> usize {
104    let worktrees_dir = common.join("worktrees");
105    if !worktrees_dir.is_dir() {
106        return 1;
107    }
108    let linked = fs::read_dir(&worktrees_dir)
109        .into_iter()
110        .flatten()
111        .flatten()
112        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
113        .count();
114    1 + linked
115}
116
117/// Whether `common` is configured as a bare repository (`core.bare=true`).
118#[must_use]
119pub fn is_bare_repository(common: &Path) -> bool {
120    ConfigSet::load(
121        &crate::environment::Environment::empty(),
122        Some(common),
123        &crate::config::LoadConfigOptions::standard(
124            &crate::environment::Environment::empty(),
125            Some(common),
126        ),
127    )
128    .ok()
129    .and_then(|cfg| cfg.get_bool("core.bare").ok().flatten())
130    .unwrap_or_else(|| {
131        // Heuristic when config is missing: bare repos usually are not named `.git`.
132        !common.ends_with(".git") && common.join("config").is_file()
133    })
134}
135
136/// Where a local branch is checked out among registered worktrees.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct BranchWorktreeCheckout {
139    /// Short branch name (e.g. `feat`).
140    pub branch: String,
141    /// Working tree path for the checkout.
142    pub worktree_path: PathBuf,
143    /// Administrative git directory for that worktree.
144    pub admin_dir: PathBuf,
145}
146
147/// Administrative git directory for the worktree `repo` was opened from.
148#[must_use]
149pub(crate) fn worktree_admin_dir(repo: &Repository) -> PathBuf {
150    let common = common_git_dir(repo.git_dir());
151    if repo.git_dir().starts_with(common.join("worktrees")) {
152        repo.git_dir().to_path_buf()
153    } else {
154        common
155    }
156}
157
158fn head_is_branch(head: &HeadState, branch_short_name: &str) -> bool {
159    match head {
160        HeadState::Branch {
161            short_name,
162            refname,
163            ..
164        } => {
165            short_name == branch_short_name || refname == &format!("refs/heads/{branch_short_name}")
166        }
167        _ => false,
168    }
169}
170
171/// Whether a rebase or bisect in the worktree `entry` is working on
172/// `branch_short_name`: it detached `HEAD` and puts the branch back when it
173/// ends, so the branch counts as checked out there, as it does for Git.
174fn operation_holds_branch(entry: &WorktreeEntry, branch_short_name: &str) -> bool {
175    if !matches!(entry.head, HeadState::Detached { .. }) {
176        return false;
177    }
178    let refname = format!("refs/heads/{branch_short_name}");
179    let first_line = |file: &str| {
180        fs::read_to_string(entry.admin_dir.join(file))
181            .ok()
182            .and_then(|text| text.lines().next().map(|line| line.trim().to_owned()))
183    };
184    let rebasing = ["rebase-merge/head-name", "rebase-apply/head-name"]
185        .into_iter()
186        .any(|file| first_line(file).as_deref() == Some(refname.as_str()));
187    rebasing
188        || first_line("BISECT_START")
189            .is_some_and(|start| start == branch_short_name || start == refname)
190}
191
192pub(crate) fn admin_dirs_match(a: &Path, b: &Path) -> bool {
193    path_for_disk_compare(a) == path_for_disk_compare(b) || a == b
194}
195
196/// Find a worktree that has `branch_short_name` checked out, optionally skipping one admin dir.
197///
198/// A worktree has the branch checked out when its `HEAD` is the branch, or when a rebase or
199/// bisect there is working on it (with `HEAD` detached until it ends). Bare repository entries
200/// are skipped: their symbolic `HEAD` is not a checkout (same as Git `wt->is_bare`).
201///
202/// `exclude_admin_dir` is typically the current worktree's admin dir so a switch to the branch
203/// already checked out here is allowed.
204pub(crate) fn find_worktree_with_branch_checked_out(
205    repo: &Repository,
206    branch_short_name: &str,
207    exclude_admin_dir: Option<&Path>,
208) -> Result<Option<BranchWorktreeCheckout>> {
209    for entry in list_worktrees(repo)? {
210        if entry.is_bare {
211            continue;
212        }
213        if exclude_admin_dir.is_some_and(|ex| admin_dirs_match(&entry.admin_dir, ex)) {
214            continue;
215        }
216        if head_is_branch(&entry.head, branch_short_name)
217            || operation_holds_branch(&entry, branch_short_name)
218        {
219            return Ok(Some(BranchWorktreeCheckout {
220                branch: branch_short_name.to_owned(),
221                worktree_path: entry.path.clone(),
222                admin_dir: entry.admin_dir.clone(),
223            }));
224        }
225    }
226    Ok(None)
227}
228
229/// Refuse when another worktree already has `branch_short_name` checked out.
230///
231/// # Errors
232///
233/// Returns [`crate::porcelain::branch_error::BranchError::CheckedOut`] when a different worktree holds the branch.
234pub(crate) fn ensure_branch_not_checked_out_elsewhere(
235    repo: &Repository,
236    branch_short_name: &str,
237) -> Result<()> {
238    let exclude = worktree_admin_dir(repo);
239    if let Some(found) =
240        find_worktree_with_branch_checked_out(repo, branch_short_name, Some(&exclude))?
241    {
242        return Err(branch_checked_out_error(
243            branch_short_name,
244            &found.worktree_path,
245        ));
246    }
247    Ok(())
248}
249
250/// Refuse when any worktree (including linked) has `branch_short_name` checked out.
251///
252/// # Errors
253///
254/// Returns [`crate::porcelain::branch_error::BranchError::CheckedOut`] when any registered worktree holds the branch.
255pub(crate) fn ensure_branch_not_checked_out_in_any_worktree(
256    repo: &Repository,
257    branch_short_name: &str,
258) -> Result<()> {
259    if let Some(found) = find_worktree_with_branch_checked_out(repo, branch_short_name, None)? {
260        return Err(branch_checked_out_error(
261            branch_short_name,
262            &found.worktree_path,
263        ));
264    }
265    Ok(())
266}
267
268fn branch_checked_out_error(branch: &str, worktree_path: &Path) -> Error {
269    Error::Branch(BranchError::CheckedOut {
270        name: branch.to_owned(),
271        worktree: crate::git_path::path_for_error_message(worktree_path),
272    })
273}
274
275/// Whether the main worktree row in [`list_worktrees`] is marked bare (matches `git worktree list`).
276///
277/// Git sets this when `core.bare` is true or the repository has no work tree, even if the current
278/// handle was opened from a linked checkout with a work tree.
279fn main_worktree_list_is_bare(repo: &Repository) -> bool {
280    let core_bare = repo
281        .config()
282        .snapshot()
283        .ok()
284        .is_some_and(|cfg| cfg.bool_with_default("core.bare", false));
285    core_bare || repo.is_bare()
286}
287
288/// Enumerate the main and linked worktrees for `repo`.
289///
290/// Order matches Git: main worktree first, then linked worktrees sorted by admin id.
291pub(crate) fn list_worktrees(repo: &Repository) -> Result<Vec<WorktreeEntry>> {
292    let common = common_git_dir(repo.git_dir());
293    let git_dir = repo.git_dir();
294    let opened_from_linked = git_dir.starts_with(common.join("worktrees"));
295    let mut entries = Vec::new();
296
297    let bare = main_worktree_list_is_bare(repo);
298    let main_path = if bare {
299        path_for_disk_compare(&common)
300    } else if let Some(wt) = repo.work_tree() {
301        // When opened from the main worktree, use the discovered work tree path.
302        if repo.git_dir() == common || !repo.git_dir().starts_with(common.join("worktrees")) {
303            path_for_disk_compare(wt)
304        } else {
305            path_for_disk_compare(common.parent().unwrap_or(&common))
306        }
307    } else {
308        path_for_disk_compare(common.parent().unwrap_or(&common))
309    };
310
311    let main_head = if opened_from_linked || (repo.refs_on_disk() && git_dir != common) {
312        resolve_head(&common)
313    } else {
314        crate::state::resolve_head_for_repository(repo)
315    }
316    .unwrap_or(HeadState::Invalid);
317    entries.push(WorktreeEntry {
318        path: main_path,
319        head: main_head,
320        is_bare: bare,
321        is_locked: false,
322        lock_reason: None,
323        admin_dir: common.clone(),
324        is_prunable: false,
325        prunable_reason: None,
326        is_current: !opened_from_linked && repo_opened_from_admin(git_dir, &common),
327    });
328
329    let worktrees_dir = common.join("worktrees");
330    if !worktrees_dir.is_dir() {
331        return Ok(entries);
332    }
333
334    let mut names: Vec<String> = fs::read_dir(&worktrees_dir)
335        .map_err(Error::Io)?
336        .filter_map(|e| e.ok())
337        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
338        .map(|e| e.file_name().to_string_lossy().into_owned())
339        .collect();
340    names.sort();
341
342    for name in names {
343        let admin = worktrees_dir.join(&name);
344        let wt_head = resolve_linked_worktree_head(repo, &admin);
345        let wt_path = read_worktree_path(&admin)?;
346        let (is_locked, lock_reason) = read_lock_state(&admin)?;
347        let (is_prunable, prunable_reason) =
348            linked_worktree_prunable_state(&admin, is_locked, &wt_path);
349        let is_current = opened_from_linked && git_dir == admin.as_path();
350        entries.push(WorktreeEntry {
351            path: wt_path,
352            head: wt_head,
353            is_bare: false,
354            is_locked,
355            lock_reason,
356            admin_dir: admin,
357            is_prunable,
358            prunable_reason,
359            is_current,
360        });
361    }
362
363    Ok(entries)
364}
365
366#[inline]
367fn repo_opened_from_admin(git_dir: &Path, admin: &Path) -> bool {
368    git_dir == admin || path_for_disk_compare(git_dir) == path_for_disk_compare(admin)
369}
370
371/// Last path component of `path`, without trailing directory separators (Git `worktree_basename`).
372#[must_use]
373pub fn worktree_path_basename(path: &Path) -> String {
374    let s = path.to_string_lossy();
375    let trimmed = s.trim_end_matches(['/', '\\']);
376    trimmed
377        .rsplit(['/', '\\'])
378        .next()
379        .unwrap_or(trimmed)
380        .to_owned()
381}
382
383/// Sanitize a path basename for use as `worktrees/<id>/` (Git `sanitize_refname_component`).
384#[must_use]
385pub fn sanitize_worktree_id_component(name: &str) -> String {
386    if name == "@" {
387        return "-".to_owned();
388    }
389
390    let mut out = String::new();
391    let mut last = '\0';
392    let chars: Vec<char> = name.chars().collect();
393    let mut i = 0;
394    while i < chars.len() {
395        let ch = chars[i];
396        if ch.is_ascii_control()
397            || matches!(ch, ':' | '?' | '[' | '\\' | '^' | '~' | ' ' | '\t' | '*')
398        {
399            if (out.is_empty() && last != '-') || !out.is_empty() {
400                out.push('-');
401            }
402            last = '-';
403            i += 1;
404            continue;
405        }
406        if ch == '.' && i + 1 < chars.len() && chars[i + 1] == '.' {
407            if last == '.' {
408                out.pop();
409            } else {
410                out.push('.');
411                last = '.';
412            }
413            i += 2;
414            continue;
415        }
416        if ch == '@' && i + 1 < chars.len() && chars[i + 1] == '{' {
417            if let Some(last_ch) = out.pop() {
418                if last_ch != '-' {
419                    out.push('-');
420                }
421            }
422            last = '-';
423            i += 2;
424            continue;
425        }
426        if ch == '.' && out.is_empty() {
427            out.push('-');
428            last = '-';
429            i += 1;
430            continue;
431        }
432        out.push(ch);
433        last = ch;
434        i += 1;
435    }
436
437    const LOCK_SUFFIX: &str = ".lock";
438    while out.ends_with(LOCK_SUFFIX) {
439        out.truncate(out.len() - LOCK_SUFFIX.len());
440    }
441    while out.ends_with('.') {
442        out.pop();
443    }
444    out
445}
446
447/// Pick a unique `<common>/worktrees/<id>/` directory for a new linked worktree at `wt_path`.
448///
449/// Git uses the sanitized basename and appends `1`, `2`, … when the admin dir already exists.
450#[must_use]
451pub fn allocate_worktree_admin_dir(common: &Path, wt_path: &Path) -> PathBuf {
452    let worktrees_dir = common.join("worktrees");
453    let base = sanitize_worktree_id_component(&worktree_path_basename(wt_path));
454    let base = if base.is_empty() {
455        "worktree".to_owned()
456    } else {
457        base
458    };
459
460    let mut counter = 0u32;
461    loop {
462        let id = if counter == 0 {
463            base.clone()
464        } else {
465            format!("{base}{counter}")
466        };
467        let admin = worktrees_dir.join(&id);
468        if !admin.exists() {
469            return admin;
470        }
471        counter = counter.saturating_add(1);
472        if counter == 0 {
473            break;
474        }
475    }
476    worktrees_dir.join(format!("{base}{}", std::process::id()))
477}
478
479/// Copy `config.worktree` into a linked worktree admin dir, stripping keys Git omits
480/// when `extensions.worktreeConfig` is enabled (`core.bare`, `core.worktree`).
481pub(crate) fn copy_filtered_worktree_config(source_git_dir: &Path, admin_dir: &Path) -> Result<()> {
482    let src = source_git_dir.join("config.worktree");
483    if !src.is_file() {
484        return Ok(());
485    }
486    let dst = admin_dir.join("config.worktree");
487    fs::copy(&src, &dst).map_err(Error::Io)?;
488    strip_worktree_config_keys(&dst, &["core.bare", "core.worktree"])?;
489    Ok(())
490}
491
492fn strip_worktree_config_keys(path: &Path, keys: &[&str]) -> Result<()> {
493    let content = fs::read_to_string(path).map_err(Error::Io)?;
494    let mut kept = Vec::new();
495    let mut section: Option<String> = None;
496    for line in content.lines() {
497        let trimmed = line.trim();
498        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
499            kept.push(line);
500            continue;
501        }
502        if trimmed.starts_with('[') {
503            let end = trimmed.find(']').unwrap_or(trimmed.len());
504            let name = trimmed[1..end].trim().to_ascii_lowercase();
505            section = Some(name);
506            kept.push(line);
507            continue;
508        }
509        if let Some((key, _)) = trimmed.split_once('=') {
510            let key = key.trim().to_ascii_lowercase();
511            let full = match section.as_deref() {
512                Some(sec) => format!("{sec}.{key}"),
513                None => key.clone(),
514            };
515            if keys.iter().any(|k| full.eq_ignore_ascii_case(k)) {
516                continue;
517            }
518        } else if keys.iter().any(|k| trimmed.eq_ignore_ascii_case(k)) {
519            continue;
520        }
521        kept.push(line);
522    }
523    let mut out = kept.join("\n");
524    if !out.is_empty() {
525        out.push('\n');
526    }
527    fs::write(path, out).map_err(Error::Io)
528}
529
530/// How [`add_linked_worktree`] attaches `HEAD` to a branch.
531#[derive(Debug, Clone, PartialEq, Eq)]
532pub enum WorktreeBranch {
533    /// Check out an existing local branch (its tip must match the start commit).
534    Existing(String),
535    /// Create `refs/heads/<name>` at the start commit (fails when the branch exists).
536    Create(String),
537    /// Create or reset `refs/heads/<name>` to the start commit (`git worktree add -B`).
538    CreateOrReset(String),
539    /// Detached HEAD at the start commit.
540    Detach,
541    /// `HEAD` on the unborn branch `refs/heads/<name>`, with an empty working tree and
542    /// index (`git worktree add --orphan`). The start point is ignored and the repository
543    /// need not have any commits. Fails when the branch exists.
544    Orphan(String),
545}
546
547/// Options for [`add_linked_worktree`].
548#[derive(Debug, Clone)]
549pub struct AddLinkedWorktreeOptions {
550    /// Directory for the new working tree (created when missing).
551    pub path: PathBuf,
552    /// Branch mode. When `None`, a new branch named after the path basename is created.
553    pub branch: Option<WorktreeBranch>,
554    /// Start commit (revision spec). Defaults to the current `HEAD` commit.
555    pub start_point: Option<String>,
556    /// Replace a stale registration when the working tree directory is missing.
557    pub force: bool,
558    /// When set, write `locked` before checkout finishes (same order as Git).
559    pub lock: Option<LockWorktreeOptions>,
560    /// Register the worktree and set `HEAD` without populating the working tree or index.
561    pub no_checkout: bool,
562    /// When the start point is a remote-tracking branch, configure upstream for the new branch.
563    pub track: bool,
564}
565
566/// Options for locking during [`add_linked_worktree`] or
567/// [`Worktrees::lock`](crate::repo_handles::Worktrees::lock).
568#[derive(Debug, Clone, Default)]
569pub struct LockWorktreeOptions {
570    /// Optional reason stored in the `locked` file (shown by `git worktree list`).
571    pub reason: Option<String>,
572}
573
574/// Options for [`prune_linked_worktrees`].
575#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
576pub struct PruneWorktreesOptions {
577    /// List prunable worktrees without removing admin directories.
578    pub dry_run: bool,
579}
580
581/// One linked worktree removed or that would be removed by [`prune_linked_worktrees`].
582#[derive(Debug, Clone, PartialEq, Eq)]
583pub struct PrunedWorktreeEntry {
584    /// Working tree path from the registry.
585    pub path: PathBuf,
586    /// Why the entry is prunable (matches `git worktree prune` messaging).
587    pub reason: String,
588}
589
590/// Register and populate a linked worktree (Git `worktree add` layout).
591///
592/// On-disk stores initialize `HEAD` through the repository's selected ref backend.
593/// Reftable worktrees keep their symbolic or detached HEAD in a separate stack,
594/// with discovery placeholders in the admin directory. `no_checkout` still creates
595/// this ref metadata, but leaves the index and tracked files absent.
596///
597/// After a successful add with checkout, runs the `post-checkout` hook from the
598/// new worktree with a null old object id, the start commit, and flag `1` (same as
599/// Git `worktree add`). The hook is advisory: failures do not roll back the worktree.
600///
601/// # Errors
602///
603/// Fails when the path is occupied, the branch is already checked out in a non-bare
604/// worktree, or checkout cannot complete.
605pub(crate) fn add_linked_worktree(
606    repo: &Repository,
607    opts: &AddLinkedWorktreeOptions,
608) -> Result<WorktreeEntry> {
609    add_linked_worktree_with_cancel(repo, opts, &CancelToken::never())
610}
611
612/// Register and populate a linked worktree, stopping when `cancel` is set.
613///
614/// On cancel or any failure after registration begins, removes the new admin directory,
615/// removes the working tree directory when this call created it, and rolls back a newly
616/// created branch ([`add_linked_worktree`]).
617///
618/// # Errors
619///
620/// Same as [`add_linked_worktree`], plus [`Error::Cancelled`](crate::error::Error::Cancelled).
621pub(crate) fn add_linked_worktree_with_cancel(
622    repo: &Repository,
623    opts: &AddLinkedWorktreeOptions,
624    cancel: &CancelToken,
625) -> Result<WorktreeEntry> {
626    // Like Git, a bare repository can have linked worktrees.
627    let common = common_git_dir(repo.git_dir());
628
629    let wt_path = if opts.path.exists() {
630        path_for_disk_compare(&opts.path)
631    } else {
632        opts.path.clone()
633    };
634    let admin_plan = plan_admin_dir_for_add(&common, &wt_path, opts.force)?;
635    ensure_empty_or_missing(&wt_path)?;
636
637    // An orphan worktree has no start commit: HEAD is the unborn branch and nothing
638    // is checked out.
639    let (start_oid, tree_oid, plan) = if let Some(WorktreeBranch::Orphan(name)) = &opts.branch {
640        (None, None, plan_orphan_worktree_head(repo, name)?)
641    } else {
642        let (start_spec, start_oid) = resolve_worktree_start_commit(repo, opts)?;
643        let tree_oid = repo.odb().commit_tree(&start_oid)?;
644        let plan = plan_worktree_head(repo, opts, &wt_path, &start_spec, start_oid)?;
645        (Some(start_oid), Some(tree_oid), plan)
646    };
647    if let Some(ref branch_ref) = plan.head_ref {
648        let short = branch_ref
649            .strip_prefix("refs/heads/")
650            .unwrap_or(branch_ref.as_str());
651        ensure_branch_not_checked_out_in_any_worktree(repo, short)?;
652    }
653
654    let admin = admin_plan.admin_dir;
655    let worktree_absent_before = !wt_path.exists();
656    let mut stale_guard = admin_plan
657        .stale_admins
658        .map(StaleWorktreeAdminBackup::remove_and_backup)
659        .transpose()?;
660
661    let mut branch_rollback = None;
662    let mut add_rollback = LinkedWorktreeAddRollback::default();
663    let finish = (|| -> Result<WorktreeEntry> {
664        if let Some(ref bw) = plan.branch_write {
665            let branch_ref = format!("refs/heads/{}", bw.branch_short);
666            let previous_tip = repo.resolve_ref_oid(&branch_ref).ok();
667            branch_rollback = Some(BranchRefRollback {
668                repo,
669                branch_ref: branch_ref.clone(),
670                previous_tip,
671                committed: false,
672            });
673            create_worktree_branch(
674                repo,
675                &bw.branch_short,
676                &bw.start_spec,
677                bw.start_oid,
678                bw.force_reset,
679            )?;
680        }
681        if let (Some(branch_short), Some(bw)) = (&plan.track_branch, &plan.branch_write) {
682            maybe_track_new_branch(repo, opts, branch_short, &bw.start_spec, bw.start_oid)?;
683        }
684
685        fs::create_dir_all(&admin).map_err(Error::Io)?;
686        add_rollback.set_admin(&admin);
687        if let Some(guard) = stale_guard.as_mut() {
688            guard.set_new_admin(&admin);
689        }
690        fs::create_dir_all(&wt_path).map_err(Error::Io)?;
691        add_rollback.track_worktree(&wt_path, worktree_absent_before);
692        if let Some(guard) = stale_guard.as_mut() {
693            guard.track_replacement_worktree(&wt_path, worktree_absent_before);
694        }
695
696        let wt_git = wt_path.join(".git");
697        fs::write(
698            &wt_git,
699            format!(
700                "gitdir: {}\n",
701                absolute_path_for_gitfile_stored_path(&admin)
702            ),
703        )
704        .map_err(Error::Io)?;
705        let wt_git_abs = absolute_path_for_gitfile_stored_path(&wt_git);
706        fs::write(admin.join("commondir"), "../..\n").map_err(Error::Io)?;
707        fs::write(admin.join("gitdir"), format!("{wt_git_abs}\n")).map_err(Error::Io)?;
708
709        let head = match (&plan.head_ref, start_oid) {
710            (Some(target), _) => crate::refs::store::RawRef::Symbolic(target.clone()),
711            (None, Some(start_oid)) => crate::refs::store::RawRef::Direct(start_oid),
712            (None, None) => unreachable!("an orphan worktree has a HEAD branch"),
713        };
714        if repo.refs_on_disk() {
715            crate::refs::store::initialize_head(&admin, head)?;
716        } else {
717            // Injected stores share branches, with each linked HEAD kept in its admin file.
718            let content = match head {
719                crate::refs::store::RawRef::Symbolic(target) => format!("ref: {target}\n"),
720                crate::refs::store::RawRef::Direct(oid) => format!("{oid}\n"),
721            };
722            fs::write(admin.join("HEAD"), content).map_err(Error::Io)?;
723        }
724
725        copy_filtered_worktree_config(&common, &admin)?;
726
727        if let Some(lock) = &opts.lock {
728            write_admin_lock_file(&admin, lock.reason.as_deref())?;
729        }
730
731        if let (false, Some(tree_oid)) = (opts.no_checkout, tree_oid) {
732            let linked = repo.open_linked_worktree(&admin, &wt_path)?;
733            let _: CheckoutOutcome = checkout_between_trees_with_progress(
734                &linked,
735                None,
736                &tree_oid,
737                &mut NullProgress,
738                cancel,
739            )?;
740        }
741
742        linked_worktree_entry(repo, &admin)
743    })();
744
745    match finish {
746        Ok(entry) => {
747            add_rollback.commit();
748            if let Some(guard) = stale_guard.take() {
749                guard.commit();
750            }
751            if let Some(mut rollback) = branch_rollback {
752                rollback.commit();
753            }
754            if !opts.no_checkout {
755                if let Some(oid) = start_oid {
756                    let linked = repo.open_linked_worktree(&admin, &wt_path)?;
757                    run_post_checkout(&linked, None, oid, true);
758                }
759            }
760            Ok(entry)
761        }
762        Err(err) => Err(err),
763    }
764}
765
766/// Remove admin directories for linked worktrees whose working tree is gone.
767///
768/// Skips locked worktrees. Returns paths to pruned working trees (for reporting).
769///
770/// # Errors
771///
772/// Propagates I/O failures while reading or removing admin directories.
773pub(crate) fn prune_linked_worktrees(
774    repo: &Repository,
775    opts: &PruneWorktreesOptions,
776) -> Result<Vec<PrunedWorktreeEntry>> {
777    let common = common_git_dir(repo.git_dir());
778    let worktrees_dir = common.join("worktrees");
779    if !worktrees_dir.is_dir() {
780        return Ok(Vec::new());
781    }
782
783    let mut pruned = Vec::new();
784    for entry in list_worktrees(repo)? {
785        if entry.admin_dir == common || entry.is_locked || !entry.is_prunable {
786            continue;
787        }
788        let reason = prune_reason(&entry.admin_dir, &entry.path);
789        pruned.push(PrunedWorktreeEntry {
790            path: entry.path.clone(),
791            reason,
792        });
793        if !opts.dry_run {
794            fs::remove_dir_all(&entry.admin_dir).map_err(Error::Io)?;
795        }
796    }
797    Ok(pruned)
798}
799
800fn prune_reason(admin: &Path, wt_path: &Path) -> String {
801    let prunable_file = admin.join("prunable");
802    if prunable_file.is_file() {
803        if let Ok(content) = fs::read_to_string(&prunable_file) {
804            let trimmed = content.trim();
805            if !trimmed.is_empty() {
806                return trimmed.to_owned();
807            }
808        }
809    }
810    if !wt_path.exists() {
811        return "gitdir file points to non-existent location".into();
812    }
813    "prunable".into()
814}
815
816fn write_admin_lock_file(admin: &Path, reason: Option<&str>) -> Result<()> {
817    let body = reason.unwrap_or("");
818    fs::write(admin.join("locked"), body).map_err(Error::Io)
819}
820
821struct WorktreeHeadPlan {
822    head_ref: Option<String>,
823    branch_write: Option<BranchWritePlan>,
824    track_branch: Option<String>,
825}
826
827struct BranchWritePlan {
828    branch_short: String,
829    start_spec: String,
830    start_oid: crate::objects::ObjectId,
831    force_reset: bool,
832}
833
834struct BranchRefRollback<'a> {
835    repo: &'a Repository,
836    branch_ref: String,
837    previous_tip: Option<crate::objects::ObjectId>,
838    committed: bool,
839}
840
841impl BranchRefRollback<'_> {
842    fn commit(&mut self) {
843        self.committed = true;
844    }
845}
846
847impl Drop for BranchRefRollback<'_> {
848    fn drop(&mut self) {
849        if self.committed {
850            return;
851        }
852        let _ = match self.previous_tip {
853            None => refs::delete_ref_on_store(self.repo.ref_store(), &self.branch_ref),
854            Some(old) => refs::update_direct_ref_on_store(
855                self.repo.ref_store(),
856                self.repo.git_dir(),
857                &self.branch_ref,
858                &old,
859            ),
860        };
861    }
862}
863
864fn resolve_worktree_start_commit(
865    repo: &Repository,
866    opts: &AddLinkedWorktreeOptions,
867) -> Result<(String, crate::objects::ObjectId)> {
868    if let Some(WorktreeBranch::Existing(name)) = &opts.branch {
869        if opts.start_point.is_none() {
870            let oid = resolve_existing_branch_tip(repo, name)?;
871            return Ok((name.clone(), oid));
872        }
873    }
874    let start_spec = opts.start_point.as_deref().unwrap_or("HEAD").to_owned();
875    let start_oid = resolve_revision(repo, &start_spec)?;
876    Ok((start_spec, start_oid))
877}
878
879/// HEAD for [`WorktreeBranch::Orphan`]: the unborn branch `refs/heads/<name>`.
880fn plan_orphan_worktree_head(repo: &Repository, name: &str) -> Result<WorktreeHeadPlan> {
881    validate_branch_name(name)?;
882    let branch_ref = format!("refs/heads/{name}");
883    if repo.references().read_existing(&branch_ref)?.is_some() {
884        return Err(BranchError::AlreadyExists {
885            name: name.to_owned(),
886        }
887        .into());
888    }
889    Ok(WorktreeHeadPlan {
890        head_ref: Some(branch_ref),
891        branch_write: None,
892        track_branch: None,
893    })
894}
895
896fn plan_worktree_head(
897    repo: &Repository,
898    opts: &AddLinkedWorktreeOptions,
899    wt_path: &Path,
900    start_spec: &str,
901    start_oid: crate::objects::ObjectId,
902) -> Result<WorktreeHeadPlan> {
903    match &opts.branch {
904        Some(WorktreeBranch::Orphan(name)) => plan_orphan_worktree_head(repo, name),
905        Some(WorktreeBranch::Detach) => Ok(WorktreeHeadPlan {
906            head_ref: None,
907            branch_write: None,
908            track_branch: None,
909        }),
910        Some(WorktreeBranch::Existing(name)) => {
911            let branch_ref = prepare_existing_branch(repo, name, start_oid)?;
912            Ok(WorktreeHeadPlan {
913                head_ref: Some(branch_ref),
914                branch_write: None,
915                track_branch: None,
916            })
917        }
918        Some(WorktreeBranch::Create(name)) => Ok(WorktreeHeadPlan {
919            head_ref: Some(format!("refs/heads/{name}")),
920            branch_write: Some(BranchWritePlan {
921                branch_short: name.clone(),
922                start_spec: start_spec.to_owned(),
923                start_oid,
924                force_reset: false,
925            }),
926            track_branch: if opts.track { Some(name.clone()) } else { None },
927        }),
928        Some(WorktreeBranch::CreateOrReset(name)) => Ok(WorktreeHeadPlan {
929            head_ref: Some(format!("refs/heads/{name}")),
930            branch_write: Some(BranchWritePlan {
931                branch_short: name.clone(),
932                start_spec: start_spec.to_owned(),
933                start_oid,
934                force_reset: true,
935            }),
936            track_branch: if opts.track { Some(name.clone()) } else { None },
937        }),
938        None => {
939            if let Some(start) = opts.start_point.as_deref() {
940                if let Some(branch_ref) = resolve_existing_branch(repo, start) {
941                    let tip = repo.resolve_ref_oid(&branch_ref)?;
942                    if tip != start_oid {
943                        return Err(LinkedWorktreeError::BranchTipMismatch {
944                            branch: branch_ref
945                                .strip_prefix("refs/heads/")
946                                .unwrap_or(&branch_ref)
947                                .to_owned(),
948                        }
949                        .into());
950                    }
951                    return Ok(WorktreeHeadPlan {
952                        head_ref: Some(branch_ref),
953                        branch_write: None,
954                        track_branch: None,
955                    });
956                }
957                return Ok(WorktreeHeadPlan {
958                    head_ref: None,
959                    branch_write: None,
960                    track_branch: None,
961                });
962            }
963            let branch = worktree_path_basename(wt_path);
964            validate_branch_name(&branch)?;
965            Ok(WorktreeHeadPlan {
966                head_ref: Some(format!("refs/heads/{branch}")),
967                branch_write: Some(BranchWritePlan {
968                    branch_short: branch.clone(),
969                    start_spec: start_spec.to_owned(),
970                    start_oid,
971                    force_reset: false,
972                }),
973                track_branch: if opts.track { Some(branch) } else { None },
974            })
975        }
976    }
977}
978
979fn prepare_existing_branch(
980    repo: &Repository,
981    name: &str,
982    start_oid: crate::objects::ObjectId,
983) -> Result<String> {
984    let tip = resolve_existing_branch_tip(repo, name)?;
985    if tip != start_oid {
986        return Err(LinkedWorktreeError::BranchTipMismatch {
987            branch: name.to_owned(),
988        }
989        .into());
990    }
991    Ok(format!("refs/heads/{name}"))
992}
993
994fn validate_branch_name(name: &str) -> Result<()> {
995    RefName::branch(name).map(|_| ()).map_err(|reason| {
996        BranchError::InvalidName {
997            name: name.to_owned(),
998            reason: reason.to_string(),
999        }
1000        .into()
1001    })
1002}
1003
1004fn resolve_existing_branch_tip(repo: &Repository, name: &str) -> Result<crate::objects::ObjectId> {
1005    validate_branch_name(name)?;
1006    repo.resolve_ref_oid(&format!("refs/heads/{name}"))
1007        .map_err(|_| {
1008            BranchError::NotFound {
1009                name: name.to_owned(),
1010            }
1011            .into()
1012        })
1013}
1014
1015fn create_worktree_branch(
1016    repo: &Repository,
1017    name: &str,
1018    start_spec: &str,
1019    start_oid: crate::objects::ObjectId,
1020    force_reset: bool,
1021) -> Result<String> {
1022    validate_branch_name(name)?;
1023    let branch_ref = format!("refs/heads/{name}");
1024    let existing = repo.references().read_existing(&branch_ref)?;
1025    if existing.is_some() && !force_reset {
1026        return Err(BranchError::AlreadyExists {
1027            name: name.to_owned(),
1028        }
1029        .into());
1030    }
1031    if let Some(existing_ref) = existing {
1032        ensure_branch_not_checked_out_in_any_worktree(repo, name)?;
1033        reset_branch_ref_with_reflog(repo, &branch_ref, start_oid, start_spec, &existing_ref)?;
1034    } else {
1035        create_branch_ref_with_reflog(repo, &branch_ref, start_oid, start_spec)?;
1036    }
1037    Ok(branch_ref)
1038}
1039
1040fn maybe_track_new_branch(
1041    repo: &Repository,
1042    opts: &AddLinkedWorktreeOptions,
1043    branch_short: &str,
1044    start_spec: &str,
1045    start_oid: crate::objects::ObjectId,
1046) -> Result<()> {
1047    if !opts.track {
1048        return Ok(());
1049    }
1050    let mode = match opts.start_point.as_deref() {
1051        Some(s) if s != "HEAD" => TrackMode::Always,
1052        _ => TrackMode::Auto,
1053    };
1054    match resolve_create_tracking(repo, branch_short, start_spec, start_oid, mode) {
1055        Ok(Some((remote, merge))) => {
1056            write_branch_upstream_config(repo, branch_short, &remote, &merge)
1057        }
1058        Ok(None) => Ok(()),
1059        Err(Error::Branch(BranchError::UpstreamNotTracking { .. })) => Ok(()),
1060        Err(err) => Err(err),
1061    }
1062}
1063
1064fn linked_worktree_entry(repo: &Repository, admin: &Path) -> Result<WorktreeEntry> {
1065    let wt_path = read_worktree_path(admin)?;
1066    let wt_head = resolve_linked_worktree_head(repo, admin);
1067    let (is_locked, lock_reason) = read_lock_state(admin)?;
1068    let (is_prunable, prunable_reason) = linked_worktree_prunable_state(admin, is_locked, &wt_path);
1069    Ok(WorktreeEntry {
1070        path: wt_path,
1071        head: wt_head,
1072        is_bare: false,
1073        is_locked,
1074        lock_reason,
1075        admin_dir: admin.to_path_buf(),
1076        is_prunable,
1077        prunable_reason,
1078        is_current: admin_dirs_match(admin, &worktree_admin_dir(repo)),
1079    })
1080}
1081
1082/// Match [`worktree_entry_is_prunable`] syscall order; attach a reason only when prunable.
1083fn linked_worktree_prunable_state(
1084    admin: &Path,
1085    is_locked: bool,
1086    wt_path: &Path,
1087) -> (bool, Option<PrunableReason>) {
1088    if is_locked {
1089        return (false, None);
1090    }
1091    if admin.join("prunable").is_file() {
1092        return (true, Some(PrunableReason::ExplicitMarker));
1093    }
1094    // Like Git's `should_prune_worktree`, a worktree stays while the `.git` file its
1095    // `gitdir` names exists, even if the directory around it is still there.
1096    if linked_worktree_gitfile(admin).map_or_else(|| wt_path.exists(), |gitfile| gitfile.exists()) {
1097        return (false, None);
1098    }
1099    (
1100        true,
1101        Some(linked_worktree_prunable_reason_when_missing(admin)),
1102    )
1103}
1104
1105/// The worktree's `.git` file named by the admin directory's `gitdir` file.
1106fn linked_worktree_gitfile(admin: &Path) -> Option<PathBuf> {
1107    let raw = fs::read_to_string(admin.join("gitdir")).ok()?;
1108    let trimmed = raw.trim();
1109    if trimmed.is_empty() {
1110        return None;
1111    }
1112    let gitfile = PathBuf::from(trimmed);
1113    Some(if gitfile.is_relative() {
1114        admin.join(gitfile)
1115    } else {
1116        gitfile
1117    })
1118}
1119
1120fn linked_worktree_prunable_reason_when_missing(admin: &Path) -> PrunableReason {
1121    if !admin.is_dir() {
1122        return PrunableReason::AdminNotValidDirectory;
1123    }
1124    let gitdir_file = admin.join("gitdir");
1125    if !gitdir_file.is_file() {
1126        return PrunableReason::GitdirFileMissing;
1127    }
1128    let raw = fs::read_to_string(&gitdir_file).unwrap_or_default();
1129    let trimmed = raw.trim();
1130    if trimmed.is_empty() {
1131        return PrunableReason::InvalidGitdirFile;
1132    }
1133    let mut dotgit = PathBuf::from(trimmed);
1134    if dotgit.is_relative() {
1135        dotgit = admin.join(dotgit);
1136    }
1137    let dotgit = path_for_disk_compare(&dotgit);
1138    if !dotgit.is_file() {
1139        return PrunableReason::GitdirPointsElsewhere;
1140    }
1141    PrunableReason::WorktreePathMissing
1142}
1143
1144/// Resolve `path` for [`add_linked_worktree`].
1145///
1146/// Relative paths are interpreted from `relative_to` (typically the process working
1147/// directory at the CLI boundary). The result is absolute and stable for registry
1148/// comparison even when the leaf directory does not exist yet.
1149///
1150/// # Errors
1151///
1152/// Returns [`LinkedWorktreeError::NoFileName`] when `path` has no final component.
1153pub fn resolve_linked_worktree_add_path(path: &Path, relative_to: &Path) -> Result<PathBuf> {
1154    if path.exists() {
1155        return Ok(path_for_disk_compare(path));
1156    }
1157    let absolute = if path.is_absolute() {
1158        path.to_path_buf()
1159    } else {
1160        relative_to.join(path)
1161    };
1162    if let Some(parent) = absolute.parent().filter(|p| p.exists()) {
1163        let Some(name) = absolute.file_name() else {
1164            return Err(LinkedWorktreeError::NoFileName { path: absolute }.into());
1165        };
1166        let mut resolved = path_for_disk_compare(parent);
1167        resolved.push(name);
1168        return Ok(resolved);
1169    }
1170    Ok(absolute)
1171}
1172
1173struct WorktreeAdminAddPlan {
1174    admin_dir: PathBuf,
1175    stale_admins: Option<Vec<PathBuf>>,
1176}
1177
1178/// On failure after stale admin dirs were moved aside, restore them.
1179struct StaleWorktreeAdminBackup {
1180    moved_aside: Vec<(PathBuf, PathBuf)>,
1181    new_admin: Option<PathBuf>,
1182    replacement_worktree: Option<(PathBuf, bool)>,
1183}
1184
1185/// On failure, remove a linked worktree admin dir and a working tree this add created.
1186#[derive(Default)]
1187struct LinkedWorktreeAddRollback {
1188    admin: Option<PathBuf>,
1189    worktree: Option<(PathBuf, bool)>,
1190    committed: bool,
1191}
1192
1193impl LinkedWorktreeAddRollback {
1194    fn set_admin(&mut self, admin: &Path) {
1195        self.admin = Some(admin.to_path_buf());
1196    }
1197
1198    fn track_worktree(&mut self, path: &Path, absent_before: bool) {
1199        self.worktree = Some((path.to_path_buf(), absent_before));
1200    }
1201
1202    fn commit(&mut self) {
1203        self.committed = true;
1204    }
1205}
1206
1207impl Drop for LinkedWorktreeAddRollback {
1208    fn drop(&mut self) {
1209        if self.committed {
1210            return;
1211        }
1212        if let Some(admin) = self.admin.take() {
1213            let _ = fs::remove_dir_all(admin);
1214        }
1215        if let Some((wt_path, absent_before)) = self.worktree.take() {
1216            if absent_before {
1217                let _ = fs::remove_dir_all(&wt_path);
1218            } else if wt_path.join(".git").is_file() {
1219                let _ = fs::remove_file(wt_path.join(".git"));
1220            }
1221        }
1222    }
1223}
1224
1225impl StaleWorktreeAdminBackup {
1226    fn remove_and_backup(stale_admins: Vec<PathBuf>) -> Result<Self> {
1227        let mut moved_aside = Vec::new();
1228        for (i, admin) in stale_admins.into_iter().enumerate() {
1229            let id = admin
1230                .file_name()
1231                .map(|n| n.to_string_lossy().into_owned())
1232                .unwrap_or_else(|| "wt".to_owned());
1233            let aside = admin
1234                .parent()
1235                .ok_or_else(|| LinkedWorktreeError::InvalidAdminDir {
1236                    path: admin.clone(),
1237                })?
1238                .join(format!(".{id}-stale-backup-{i}"));
1239            if aside.exists() {
1240                fs::remove_dir_all(&aside).map_err(Error::Io)?;
1241            }
1242            fs::rename(&admin, &aside).map_err(Error::Io)?;
1243            moved_aside.push((admin, aside));
1244        }
1245        Ok(Self {
1246            moved_aside,
1247            new_admin: None,
1248            replacement_worktree: None,
1249        })
1250    }
1251
1252    fn set_new_admin(&mut self, admin: &Path) {
1253        self.new_admin = Some(admin.to_path_buf());
1254    }
1255
1256    fn track_replacement_worktree(&mut self, path: &Path, absent_before_replacement: bool) {
1257        self.replacement_worktree = Some((path.to_path_buf(), absent_before_replacement));
1258    }
1259
1260    fn commit(mut self) {
1261        for (_, aside) in self.moved_aside.drain(..) {
1262            let _ = fs::remove_dir_all(aside);
1263        }
1264    }
1265}
1266
1267impl Drop for StaleWorktreeAdminBackup {
1268    fn drop(&mut self) {
1269        if self.moved_aside.is_empty() {
1270            return;
1271        }
1272        if let Some((wt_path, absent_before)) = self.replacement_worktree.take() {
1273            if absent_before {
1274                let _ = fs::remove_dir_all(&wt_path);
1275            } else if wt_path.join(".git").is_file() {
1276                let _ = fs::remove_file(wt_path.join(".git"));
1277            }
1278        }
1279        if let Some(new_admin) = self.new_admin.take() {
1280            let _ = fs::remove_dir_all(new_admin);
1281        }
1282        for (admin, aside) in &self.moved_aside {
1283            let _ = fs::remove_dir_all(admin);
1284            let _ = fs::rename(aside, admin);
1285        }
1286    }
1287}
1288
1289fn linked_admins_for_worktree_path(common: &Path, wt_path: &Path) -> Result<Vec<PathBuf>> {
1290    let target = path_for_disk_compare(wt_path);
1291    let worktrees_dir = common.join("worktrees");
1292    if !worktrees_dir.is_dir() {
1293        return Ok(Vec::new());
1294    }
1295    let mut admins = Vec::new();
1296    for entry in fs::read_dir(&worktrees_dir).map_err(Error::Io)? {
1297        let entry = entry.map_err(Error::Io)?;
1298        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
1299            continue;
1300        }
1301        let admin = entry.path();
1302        let registered = read_worktree_path(&admin)?;
1303        if path_for_disk_compare(&registered) == target {
1304            admins.push(admin);
1305        }
1306    }
1307    Ok(admins)
1308}
1309
1310fn plan_admin_dir_for_add(
1311    common: &Path,
1312    wt_path: &Path,
1313    force: bool,
1314) -> Result<WorktreeAdminAddPlan> {
1315    let existing = linked_admins_for_worktree_path(common, wt_path)?;
1316    if existing.is_empty() {
1317        return Ok(WorktreeAdminAddPlan {
1318            admin_dir: allocate_worktree_admin_dir(common, wt_path),
1319            stale_admins: None,
1320        });
1321    }
1322
1323    if wt_path.exists() {
1324        return Err(LinkedWorktreeError::PathRegistered {
1325            path: wt_path.to_path_buf(),
1326        }
1327        .into());
1328    }
1329    if !force {
1330        return Err(LinkedWorktreeError::PathRegisteredMissing {
1331            path: wt_path.to_path_buf(),
1332        }
1333        .into());
1334    }
1335
1336    let worktrees_dir = common.join("worktrees");
1337    let base = sanitize_worktree_id_component(&worktree_path_basename(wt_path));
1338    let base = if base.is_empty() {
1339        "worktree".to_owned()
1340    } else {
1341        base
1342    };
1343    let preferred = worktrees_dir.join(&base);
1344    let admin_dir = existing
1345        .iter()
1346        .find(|admin| {
1347            admin
1348                .file_name()
1349                .is_some_and(|name| name.to_string_lossy() == base)
1350        })
1351        .cloned()
1352        .unwrap_or_else(|| {
1353            if preferred.exists() {
1354                allocate_worktree_admin_dir(common, wt_path)
1355            } else {
1356                preferred
1357            }
1358        });
1359    Ok(WorktreeAdminAddPlan {
1360        admin_dir,
1361        stale_admins: Some(existing),
1362    })
1363}
1364
1365/// Remove a linked worktree and its admin directory.
1366///
1367/// # Errors
1368///
1369/// Returns [`LinkedWorktreeError::NotRegistered`] for an unknown `path`,
1370/// [`LinkedWorktreeError::MainWorktree`] for the main worktree, and, unless `force` is set,
1371/// [`LinkedWorktreeError::Locked`] or [`LinkedWorktreeError::HasLocalChanges`].
1372pub(crate) fn remove_linked_worktree(repo: &Repository, path: &Path, force: bool) -> Result<()> {
1373    let entry = find_linked_worktree(repo, path, LinkedWorktreeOperation::Remove)?;
1374    if entry.is_locked && !force {
1375        return Err(LinkedWorktreeError::Locked {
1376            reason: entry.lock_reason,
1377        }
1378        .into());
1379    }
1380
1381    let linked = repo.open_linked_worktree(&entry.admin_dir, &entry.path)?;
1382    if !force && worktree_has_local_changes(&linked)? {
1383        return Err(LinkedWorktreeError::HasLocalChanges.into());
1384    }
1385
1386    fs::remove_dir_all(&entry.admin_dir).map_err(Error::Io)?;
1387    if entry.path.exists() {
1388        fs::remove_dir_all(&entry.path).map_err(Error::Io)?;
1389    }
1390    Ok(())
1391}
1392
1393/// The registered linked worktree whose root is `path`, for a mutation named by `operation`.
1394///
1395/// # Errors
1396///
1397/// [`LinkedWorktreeError::NotRegistered`] when no worktree is registered at `path`, and
1398/// [`LinkedWorktreeError::MainWorktree`] when `path` is the main working tree.
1399pub(crate) fn find_linked_worktree(
1400    repo: &Repository,
1401    path: &Path,
1402    operation: LinkedWorktreeOperation,
1403) -> Result<WorktreeEntry> {
1404    let target = path_for_disk_compare(path);
1405    let Some(entry) = list_worktrees(repo)?.into_iter().find(|e| e.path == target) else {
1406        return Err(LinkedWorktreeError::NotRegistered { path: target }.into());
1407    };
1408    if entry.admin_dir == common_git_dir(repo.git_dir()) {
1409        return Err(LinkedWorktreeError::MainWorktree { operation }.into());
1410    }
1411    Ok(entry)
1412}
1413
1414/// Write `<admin>/locked` for the linked worktree at `path`.
1415///
1416/// # Errors
1417///
1418/// Fails as [`find_linked_worktree`] does, with [`LinkedWorktreeError::AlreadyLocked`] when the
1419/// worktree is already locked, or with I/O errors writing the file.
1420pub(crate) fn lock_linked_worktree(
1421    repo: &Repository,
1422    path: &Path,
1423    reason: Option<&str>,
1424) -> Result<()> {
1425    let entry = find_linked_worktree(repo, path, LinkedWorktreeOperation::Lock)?;
1426    if entry.is_locked {
1427        return Err(LinkedWorktreeError::AlreadyLocked {
1428            reason: entry.lock_reason,
1429        }
1430        .into());
1431    }
1432    write_admin_lock_file(&entry.admin_dir, reason)
1433}
1434
1435/// Delete `<admin>/locked` for the linked worktree at `path`.
1436///
1437/// # Errors
1438///
1439/// Fails as [`find_linked_worktree`] does, with [`LinkedWorktreeError::NotLocked`] when the worktree
1440/// is not locked, or with I/O errors removing the file.
1441pub(crate) fn unlock_linked_worktree(repo: &Repository, path: &Path) -> Result<()> {
1442    let entry = find_linked_worktree(repo, path, LinkedWorktreeOperation::Unlock)?;
1443    if !entry.is_locked {
1444        return Err(LinkedWorktreeError::NotLocked.into());
1445    }
1446    fs::remove_file(entry.admin_dir.join("locked")).map_err(Error::Io)
1447}
1448
1449fn resolve_existing_branch(repo: &Repository, spec: &str) -> Option<String> {
1450    let full = if spec.starts_with("refs/heads/") {
1451        spec.to_owned()
1452    } else {
1453        format!("refs/heads/{spec}")
1454    };
1455    repo.resolve_ref_oid(&full).ok()?;
1456    Some(full)
1457}
1458
1459fn ensure_empty_or_missing(path: &Path) -> Result<()> {
1460    if !path.exists() {
1461        return Ok(());
1462    }
1463    if !path.is_dir() {
1464        return Err(LinkedWorktreeError::PathExistsNotDirectory {
1465            path: path.to_path_buf(),
1466        }
1467        .into());
1468    }
1469    let mut entries = fs::read_dir(path).map_err(Error::Io)?;
1470    if entries.next().is_some() {
1471        return Err(LinkedWorktreeError::PathExists {
1472            path: path.to_path_buf(),
1473        }
1474        .into());
1475    }
1476    Ok(())
1477}
1478
1479fn worktree_has_local_changes(repo: &Repository) -> Result<bool> {
1480    let model = status(
1481        repo,
1482        &StatusOptions::default(),
1483        &mut NullProgress,
1484        &crate::progress::CancelToken::never(),
1485    )?;
1486    Ok(!model.staged.is_empty()
1487        || !model.unstaged.is_empty()
1488        || !model.conflicts.is_empty()
1489        || !model.untracked.is_empty())
1490}
1491
1492/// Read the working tree path from `<admin>/gitdir` (parent of the worktree `.git` file).
1493pub fn read_worktree_path(admin: &Path) -> Result<PathBuf> {
1494    let gitdir_path = admin.join("gitdir");
1495    if !gitdir_path.is_file() {
1496        return Ok(admin.to_path_buf());
1497    }
1498    let raw = fs::read_to_string(&gitdir_path).map_err(Error::Io)?;
1499    let mut p = PathBuf::from(raw.trim());
1500    if p.is_relative() {
1501        p = admin.join(p);
1502    }
1503    let parent = p.parent().unwrap_or(&p).to_path_buf();
1504    Ok(path_for_disk_compare(&parent))
1505}
1506
1507fn read_lock_state(admin: &Path) -> Result<(bool, Option<String>)> {
1508    let locked_file = admin.join("locked");
1509    if !locked_file.is_file() {
1510        return Ok((false, None));
1511    }
1512    let content = fs::read_to_string(&locked_file).map_err(Error::Io)?;
1513    let reason = content.trim();
1514    if reason.is_empty() {
1515        Ok((true, None))
1516    } else {
1517        Ok((true, Some(reason.to_owned())))
1518    }
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523    use super::*;
1524    use crate::git_path::CanonicalizeExt;
1525    use crate::repo::Repository;
1526    use std::fs;
1527    use tempfile::TempDir;
1528
1529    #[test]
1530    fn list_main_worktree_only() {
1531        let tmp = TempDir::new().unwrap();
1532        let root = tmp.path().join("repo");
1533        fs::create_dir_all(root.join(".git")).unwrap();
1534        fs::write(root.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
1535        fs::create_dir_all(root.join(".git/objects")).unwrap();
1536        fs::write(
1537            root.join(".git/config"),
1538            "[core]\n\trepositoryformatversion = 0\n",
1539        )
1540        .unwrap();
1541
1542        let repo = Repository::open(
1543            &root.join(".git"),
1544            &RepositoryOptions::empty().with_work_tree(&root),
1545        )
1546        .unwrap();
1547        let list = repo.worktrees().list().unwrap();
1548        assert_eq!(list.len(), 1);
1549        assert_eq!(list[0].path, path_for_disk_compare(&root));
1550        assert!(!list[0].is_bare);
1551    }
1552
1553    #[cfg_attr(
1554        not(feature = "full-tests"),
1555        ignore = "starts system git or is heavy; run with --features full-tests"
1556    )]
1557    #[test]
1558    fn a_branch_being_rebased_or_bisected_in_a_worktree_is_checked_out_there() {
1559        let tmp = TempDir::new().unwrap();
1560        let main = tmp.path().join("main");
1561        fs::create_dir_all(&main).unwrap();
1562        let git = |dir: &Path, args: &[&str]| grit_test_support::git(dir, args);
1563        git(&main, &["init", "-q", "-b", "main"]);
1564        fs::write(main.join("f"), "base\n").unwrap();
1565        git(&main, &["add", "f"]);
1566        git(&main, &["commit", "-q", "-m", "base"]);
1567        git(&main, &["branch", "feature"]);
1568        git(&main, &["branch", "other"]);
1569        for n in 1..=3 {
1570            fs::write(main.join("f"), format!("main {n}\n")).unwrap();
1571            git(&main, &["commit", "-q", "-am", "main"]);
1572        }
1573        git(&main, &["switch", "-q", "feature"]);
1574        fs::write(main.join("f"), "feature\n").unwrap();
1575        git(&main, &["commit", "-q", "-am", "feature"]);
1576        git(&main, &["switch", "-q", "main"]);
1577        let linked = tmp.path().join("linked");
1578        git(
1579            &main,
1580            &["worktree", "add", "-q", linked.to_str().unwrap(), "feature"],
1581        );
1582        // The rebase stops on a conflict with HEAD detached.
1583        let rebase = grit_test_support::git_cmd(&["rebase", "main"])
1584            .in_dir(&linked)
1585            .exec();
1586        assert!(!rebase.ok(), "the rebase stops on a conflict");
1587        let repo = Repository::discover(Some(&main), &RepositoryOptions::empty()).unwrap();
1588        let found = find_worktree_with_branch_checked_out(&repo, "feature", None)
1589            .unwrap()
1590            .expect("the rebase holds feature");
1591        assert_eq!(found.worktree_path, path_for_disk_compare(&linked));
1592        assert!(matches!(
1593            ensure_branch_not_checked_out_in_any_worktree(&repo, "feature"),
1594            Err(Error::Branch(BranchError::CheckedOut { .. }))
1595        ));
1596        git(&linked, &["rebase", "--abort"]);
1597
1598        // A bisect started on a branch holds it too.
1599        git(&linked, &["switch", "-q", "other"]);
1600        git(&linked, &["bisect", "start", "main", "other"]);
1601        let head = repo.worktrees().list().unwrap().remove(1).head;
1602        assert!(matches!(head, HeadState::Detached { .. }), "{head:?}");
1603        assert!(find_worktree_with_branch_checked_out(&repo, "other", None)
1604            .unwrap()
1605            .is_some());
1606        git(&linked, &["bisect", "reset"]);
1607        git(&linked, &["switch", "-q", "--detach", "HEAD"]);
1608        assert_eq!(
1609            find_worktree_with_branch_checked_out(&repo, "other", None).unwrap(),
1610            None,
1611            "a plain detached HEAD holds nothing"
1612        );
1613        assert_eq!(
1614            find_worktree_with_branch_checked_out(&repo, "feature", None).unwrap(),
1615            None
1616        );
1617    }
1618
1619    #[cfg_attr(
1620        not(feature = "full-tests"),
1621        ignore = "starts system git or is heavy; run with --features full-tests"
1622    )]
1623    #[test]
1624    fn allocate_unique_worktree_id() {
1625        let tmp = TempDir::new().unwrap();
1626        let common = tmp.path().join("git");
1627        fs::create_dir_all(common.join("worktrees/here")).unwrap();
1628        let admin = allocate_worktree_admin_dir(&common, Path::new("/tmp/sub/here"));
1629        assert_eq!(admin, common.join("worktrees/here1"));
1630    }
1631
1632    #[test]
1633    fn strip_worktree_config_removes_core_bare_and_worktree() {
1634        let tmp = TempDir::new().unwrap();
1635        let path = tmp.path().join("config.worktree");
1636        fs::write(
1637            &path,
1638            "[core]\n\tbare = true\n\tworktree = /wt\n[bogus]\n\tkey = value\n",
1639        )
1640        .unwrap();
1641        strip_worktree_config_keys(&path, &["core.bare", "core.worktree"]).unwrap();
1642        let out = fs::read_to_string(&path).unwrap();
1643        assert!(out.contains("bogus"));
1644        assert!(!out.contains("bare"));
1645        assert!(!out.contains("worktree"));
1646    }
1647
1648    #[cfg_attr(
1649        not(feature = "full-tests"),
1650        ignore = "starts system git or is heavy; run with --features full-tests"
1651    )]
1652    #[test]
1653    fn sanitize_funny_worktree_name() {
1654        assert_eq!(
1655            sanitize_worktree_id_component(".  weird*..?.lock.lock"),
1656            "---weird-.-"
1657        );
1658    }
1659
1660    #[test]
1661    fn read_worktree_path_from_gitdir_file() {
1662        let tmp = TempDir::new().unwrap();
1663        let admin = tmp.path().join("wt-admin");
1664        fs::create_dir_all(&admin).unwrap();
1665        let wt = tmp.path().join("linked");
1666        fs::create_dir_all(wt.join(".git")).unwrap();
1667        fs::write(
1668            admin.join("gitdir"),
1669            format!("{}\n", wt.join(".git").display()),
1670        )
1671        .unwrap();
1672        let path = read_worktree_path(&admin).unwrap();
1673        assert_eq!(path, path_for_disk_compare(&wt));
1674    }
1675
1676    #[cfg_attr(
1677        not(feature = "full-tests"),
1678        ignore = "starts system git or is heavy; run with --features full-tests"
1679    )]
1680    #[test]
1681    fn add_and_remove_linked_worktree_via_library() {
1682        use std::process::Command;
1683        let tmp = TempDir::new().unwrap();
1684        let main = tmp.path().join("main");
1685        fs::create_dir_all(&main).unwrap();
1686        let git = |args: &[&str]| {
1687            let out = Command::new("git")
1688                .env("GIT_AUTHOR_NAME", "Test")
1689                .env("GIT_AUTHOR_EMAIL", "test@example.com")
1690                .env("GIT_COMMITTER_NAME", "Test")
1691                .env("GIT_COMMITTER_EMAIL", "test@example.com")
1692                .current_dir(&main)
1693                .args(args)
1694                .output()
1695                .unwrap();
1696            assert!(out.status.success(), "git {args:?}");
1697        };
1698        git(&["init", "-q", "-b", "main"]);
1699        fs::write(main.join("t"), b"1\n").unwrap();
1700        git(&["add", "t"]);
1701        git(&["commit", "-qm", "init"]);
1702
1703        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
1704        let linked = tmp.path().join("linked");
1705        repo.worktrees()
1706            .add(&AddLinkedWorktreeOptions {
1707                path: linked.clone(),
1708                branch: Some(WorktreeBranch::Create("wt".into())),
1709                start_point: Some("HEAD".into()),
1710                force: false,
1711                lock: None,
1712                no_checkout: false,
1713                track: false,
1714            })
1715            .unwrap();
1716        assert_eq!(repo.worktrees().list().unwrap().len(), 2);
1717        repo.worktrees().remove(&linked, false).unwrap();
1718        assert_eq!(repo.worktrees().list().unwrap().len(), 1);
1719    }
1720
1721    #[test]
1722    fn registered_worktree_count_and_basename() {
1723        let tmp = TempDir::new().unwrap();
1724        let common = tmp.path().join("git");
1725        fs::create_dir_all(common.join("worktrees/a")).unwrap();
1726        fs::create_dir_all(common.join("worktrees/b")).unwrap();
1727        assert_eq!(registered_worktree_count(&common), 3);
1728        assert_eq!(
1729            worktree_path_basename(Path::new("/tmp/my/project/")),
1730            "project"
1731        );
1732    }
1733
1734    #[test]
1735    fn registered_worktree_count_without_worktrees_dir() {
1736        let tmp = TempDir::new().unwrap();
1737        let common = tmp.path().join("only-main");
1738        fs::create_dir_all(&common).unwrap();
1739        assert_eq!(registered_worktree_count(&common), 1);
1740    }
1741
1742    #[test]
1743    fn common_git_dir_and_bare_detection() {
1744        let tmp = TempDir::new().unwrap();
1745        let git_dir = tmp.path().join("bare.git");
1746        fs::create_dir_all(&git_dir).unwrap();
1747        fs::write(
1748            git_dir.join("config"),
1749            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
1750        )
1751        .unwrap();
1752        assert!(is_bare_repository(&git_dir));
1753        assert_eq!(common_git_dir(&git_dir), git_dir);
1754    }
1755
1756    #[cfg_attr(
1757        not(feature = "full-tests"),
1758        ignore = "starts system git or is heavy; run with --features full-tests"
1759    )]
1760    #[test]
1761    fn sanitize_worktree_id_special_cases() {
1762        assert_eq!(sanitize_worktree_id_component("@"), "-");
1763        assert!(!sanitize_worktree_id_component("@{upstream}").contains('@'));
1764        assert_eq!(sanitize_worktree_id_component("..name"), ".name");
1765        assert_eq!(sanitize_worktree_id_component(".lock.lock"), "-lock");
1766        let tmp = TempDir::new().unwrap();
1767        let common = tmp.path().join("git");
1768        fs::create_dir_all(&common).unwrap();
1769        assert_eq!(
1770            allocate_worktree_admin_dir(&common, Path::new("/")),
1771            common.join("worktrees/worktree")
1772        );
1773    }
1774
1775    #[test]
1776    fn copy_filtered_worktree_config_no_source_is_ok() {
1777        let tmp = TempDir::new().unwrap();
1778        let admin = tmp.path().join("admin");
1779        fs::create_dir_all(&admin).unwrap();
1780        copy_filtered_worktree_config(tmp.path(), &admin).unwrap();
1781        assert!(!admin.join("config.worktree").exists());
1782    }
1783
1784    #[test]
1785    fn copy_filtered_worktree_config_copies_file() {
1786        let tmp = TempDir::new().unwrap();
1787        let common = tmp.path().join("common");
1788        let admin = tmp.path().join("admin");
1789        fs::create_dir_all(&common).unwrap();
1790        fs::create_dir_all(&admin).unwrap();
1791        fs::write(
1792            common.join("config.worktree"),
1793            "[core]\n\tbare = false\n\tworktree = /x\n[ext]\n\tk = v\n",
1794        )
1795        .unwrap();
1796        copy_filtered_worktree_config(&common, &admin).unwrap();
1797        let out = fs::read_to_string(admin.join("config.worktree")).unwrap();
1798        assert!(out.contains("[ext]"));
1799        assert!(!out.contains("worktree"));
1800    }
1801
1802    #[test]
1803    fn read_lock_state_and_missing_gitdir_path() {
1804        let tmp = TempDir::new().unwrap();
1805        let admin = tmp.path().join("admin");
1806        fs::create_dir_all(&admin).unwrap();
1807        assert_eq!(read_worktree_path(&admin).unwrap(), admin);
1808        fs::write(admin.join("locked"), "maintenance\n").unwrap();
1809        let (locked, reason) = read_lock_state(&admin).unwrap();
1810        assert!(locked);
1811        assert_eq!(reason.as_deref(), Some("maintenance"));
1812    }
1813
1814    #[test]
1815    fn ensure_empty_or_missing_rejects_nonempty_dir() {
1816        let tmp = TempDir::new().unwrap();
1817        let dir = tmp.path().join("occupied");
1818        fs::create_dir_all(&dir).unwrap();
1819        fs::write(dir.join("file"), b"x").unwrap();
1820        assert!(matches!(
1821            ensure_empty_or_missing(&dir),
1822            Err(Error::Worktree(WorktreeError::Linked(LinkedWorktreeError::PathExists {
1823                path
1824            }))) if path == dir
1825        ));
1826        assert!(matches!(
1827            ensure_empty_or_missing(&dir.join("file")),
1828            Err(Error::Worktree(WorktreeError::Linked(
1829                LinkedWorktreeError::PathExistsNotDirectory { .. }
1830            )))
1831        ));
1832        let missing = tmp.path().join("missing");
1833        assert!(ensure_empty_or_missing(&missing).is_ok());
1834    }
1835
1836    #[cfg_attr(
1837        not(feature = "full-tests"),
1838        ignore = "starts system git or is heavy; run with --features full-tests"
1839    )]
1840    #[test]
1841    fn add_linked_worktree_to_bare_repository() {
1842        let tmp = TempDir::new().unwrap();
1843        let bare = tmp.path().join("bare.git");
1844        fs::create_dir_all(bare.join("objects")).unwrap();
1845        fs::write(bare.join("HEAD"), "ref: refs/heads/main\n").unwrap();
1846        fs::write(
1847            bare.join("config"),
1848            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
1849        )
1850        .unwrap();
1851        let repo = Repository::open(&bare, &RepositoryOptions::empty()).unwrap();
1852        let wt = tmp.path().join("wt");
1853        let entry = repo
1854            .worktrees()
1855            .add(&AddLinkedWorktreeOptions {
1856                path: wt.clone(),
1857                branch: Some(WorktreeBranch::Orphan("wt".into())),
1858                start_point: None,
1859                force: false,
1860                lock: None,
1861                no_checkout: false,
1862                track: false,
1863            })
1864            .unwrap();
1865        assert_eq!(
1866            entry.admin_dir,
1867            fs::canonicalize(&bare)
1868                .unwrap()
1869                .join("worktrees")
1870                .join("wt")
1871        );
1872        assert_eq!(
1873            fs::read_to_string(entry.admin_dir.join("HEAD")).unwrap(),
1874            "ref: refs/heads/wt\n"
1875        );
1876        assert_eq!(
1877            fs::read_to_string(entry.admin_dir.join("commondir")).unwrap(),
1878            "../..\n"
1879        );
1880        assert!(wt.join(".git").is_file());
1881    }
1882
1883    #[cfg_attr(
1884        not(feature = "full-tests"),
1885        ignore = "starts system git or is heavy; run with --features full-tests"
1886    )]
1887    #[test]
1888    fn is_bare_matches_git_for_bare_repo_and_linked_worktree() {
1889        use std::process::Command;
1890        let tmp = TempDir::new().unwrap();
1891        let root = tmp.path();
1892        let bare = root.join("b.git");
1893        let wt = root.join("wt");
1894        let git = |dir: &Path, args: &[&str]| {
1895            assert!(
1896                Command::new("git")
1897                    .current_dir(dir)
1898                    .args(args)
1899                    .output()
1900                    .unwrap()
1901                    .status
1902                    .success(),
1903                "git {args:?} in {}",
1904                dir.display()
1905            );
1906        };
1907        git(root, &["init", "-q", "--bare", bare.to_str().unwrap()]);
1908        let tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
1909        let commit = Command::new("git")
1910            .current_dir(&bare)
1911            .env("GIT_AUTHOR_NAME", "a")
1912            .env("GIT_AUTHOR_EMAIL", "a@b")
1913            .env("GIT_COMMITTER_NAME", "a")
1914            .env("GIT_COMMITTER_EMAIL", "a@b")
1915            .args(["commit-tree", tree, "-m", "root"])
1916            .output()
1917            .unwrap();
1918        assert!(commit.status.success());
1919        let oid = String::from_utf8(commit.stdout).unwrap().trim().to_owned();
1920        git(&bare, &["update-ref", "refs/heads/main", oid.as_str()]);
1921        git(
1922            &bare,
1923            &["worktree", "add", "-q", wt.to_str().unwrap(), "main"],
1924        );
1925
1926        let git_is_bare = |dir: &Path| {
1927            Command::new("git")
1928                .current_dir(dir)
1929                .args(["rev-parse", "--is-bare-repository"])
1930                .output()
1931                .unwrap()
1932                .stdout
1933        };
1934        assert_eq!(git_is_bare(&wt), b"false\n");
1935
1936        let linked = Repository::discover(Some(wt.as_path()), &RepositoryOptions::empty()).unwrap();
1937        assert!(!linked.is_bare());
1938        assert!(linked.work_tree().is_some());
1939        assert!(linked
1940            .git_dir()
1941            .starts_with(bare.join("worktrees").as_path()));
1942
1943        let list = linked.worktrees().list().unwrap();
1944        assert_eq!(list.len(), 2);
1945        assert!(
1946            list[0].is_bare,
1947            "main row stays bare when core.bare is true"
1948        );
1949        assert!(!list[1].is_bare);
1950
1951        let bare_repo = Repository::open(&bare, &RepositoryOptions::empty()).unwrap();
1952        assert!(bare_repo.is_bare());
1953        assert!(bare_repo.work_tree().is_none());
1954        assert_eq!(git_is_bare(&bare), b"true\n");
1955
1956        let with_wt = Repository::open(
1957            &bare,
1958            &RepositoryOptions::empty().with_work_tree(wt.as_path()),
1959        )
1960        .unwrap();
1961        assert!(!with_wt.is_bare());
1962        assert_eq!(git_is_bare(&wt), b"false\n");
1963
1964        let non_bare_no_wt = tmp.path().join("nonbare.git");
1965        fs::create_dir_all(non_bare_no_wt.join("objects")).unwrap();
1966        fs::write(non_bare_no_wt.join("HEAD"), "ref: refs/heads/main\n").unwrap();
1967        fs::write(
1968            non_bare_no_wt.join("config"),
1969            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n",
1970        )
1971        .unwrap();
1972        let cfg_false = Repository::open(&non_bare_no_wt, &RepositoryOptions::empty()).unwrap();
1973        assert!(!cfg_false.is_bare());
1974    }
1975
1976    #[cfg_attr(
1977        not(feature = "full-tests"),
1978        ignore = "starts system git or is heavy; run with --features full-tests"
1979    )]
1980    #[test]
1981    fn list_worktrees_from_linked_checkout_normalizes_main_path() {
1982        use std::process::Command;
1983        let tmp = TempDir::new().unwrap();
1984        let main = tmp.path().join("main");
1985        fs::create_dir_all(&main).unwrap();
1986        let git = |args: &[&str]| {
1987            assert!(Command::new("git")
1988                .env("GIT_AUTHOR_NAME", "Test")
1989                .env("GIT_AUTHOR_EMAIL", "test@example.com")
1990                .env("GIT_COMMITTER_NAME", "Test")
1991                .env("GIT_COMMITTER_EMAIL", "test@example.com")
1992                .current_dir(&main)
1993                .args(args)
1994                .output()
1995                .unwrap()
1996                .status
1997                .success());
1998        };
1999        git(&["init", "-q", "-b", "main"]);
2000        fs::write(main.join("t"), b"1\n").unwrap();
2001        git(&["add", "t"]);
2002        git(&["commit", "-qm", "init"]);
2003
2004        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
2005        let linked = tmp.path().join("linked");
2006        repo.worktrees()
2007            .add(&AddLinkedWorktreeOptions {
2008                path: linked.clone(),
2009                branch: Some(WorktreeBranch::Create("wt".into())),
2010                start_point: Some("HEAD".into()),
2011                force: false,
2012                lock: None,
2013                no_checkout: false,
2014                track: false,
2015            })
2016            .unwrap();
2017
2018        let linked_repo =
2019            Repository::discover(Some(linked.as_path()), &RepositoryOptions::empty()).unwrap();
2020        let list = linked_repo.worktrees().list().unwrap();
2021        assert_eq!(list.len(), 2);
2022        let expected_main = path_for_disk_compare(&main);
2023        assert_eq!(list[0].path, expected_main);
2024        #[cfg(windows)]
2025        {
2026            let displayed = list[0].path.display().to_string();
2027            assert!(
2028                !displayed.starts_with(r"\\?\"),
2029                "main worktree path must not use the verbatim prefix: {displayed}"
2030            );
2031        }
2032    }
2033
2034    #[cfg_attr(
2035        not(feature = "full-tests"),
2036        ignore = "starts system git or is heavy; run with --features full-tests"
2037    )]
2038    #[test]
2039    fn branch_checkout_exclusivity_helpers() {
2040        use std::process::Command;
2041        let tmp = TempDir::new().unwrap();
2042        let main = tmp.path().join("main");
2043        fs::create_dir_all(&main).unwrap();
2044        let git = |args: &[&str]| {
2045            assert!(Command::new("git")
2046                .env("GIT_AUTHOR_NAME", "Test")
2047                .env("GIT_AUTHOR_EMAIL", "test@example.com")
2048                .env("GIT_COMMITTER_NAME", "Test")
2049                .env("GIT_COMMITTER_EMAIL", "test@example.com")
2050                .current_dir(&main)
2051                .args(args)
2052                .output()
2053                .unwrap()
2054                .status
2055                .success());
2056        };
2057        git(&["init", "-q", "-b", "main"]);
2058        fs::write(main.join("t"), b"1\n").unwrap();
2059        git(&["add", "t"]);
2060        git(&["commit", "-qm", "init"]);
2061
2062        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
2063        let linked = tmp.path().join("linked");
2064        repo.worktrees()
2065            .add(&AddLinkedWorktreeOptions {
2066                path: linked.clone(),
2067                branch: Some(WorktreeBranch::Create("feature".into())),
2068                start_point: Some("HEAD".into()),
2069                force: false,
2070                lock: None,
2071                no_checkout: false,
2072                track: false,
2073            })
2074            .unwrap();
2075
2076        let linked_repo =
2077            Repository::discover(Some(linked.as_path()), &RepositoryOptions::empty()).unwrap();
2078        let linked_admin = linked_repo
2079            .git_dir()
2080            .canonicalize_simplified()
2081            .unwrap_or_else(|_| linked_repo.git_dir().to_path_buf());
2082        assert_eq!(worktree_admin_dir(&linked_repo), linked_admin);
2083
2084        let found = find_worktree_with_branch_checked_out(&repo, "feature", None)
2085            .unwrap()
2086            .expect("linked checkout");
2087        assert_eq!(found.branch, "feature");
2088
2089        assert!(ensure_branch_not_checked_out_in_any_worktree(&repo, "feature").is_err());
2090        assert!(ensure_branch_not_checked_out_elsewhere(&linked_repo, "feature").is_ok());
2091        assert!(ensure_branch_not_checked_out_elsewhere(&repo, "feature").is_err());
2092    }
2093
2094    #[cfg_attr(
2095        not(feature = "full-tests"),
2096        ignore = "starts system git or is heavy; run with --features full-tests"
2097    )]
2098    #[test]
2099    fn missing_registered_path_rejects_add_without_force() {
2100        use std::process::Command;
2101        let tmp = TempDir::new().unwrap();
2102        let main = tmp.path().join("main");
2103        fs::create_dir_all(&main).unwrap();
2104        let git = |args: &[&str]| {
2105            assert!(Command::new("git")
2106                .current_dir(&main)
2107                .args(args)
2108                .output()
2109                .unwrap()
2110                .status
2111                .success());
2112        };
2113        git(&["init", "-q", "-b", "main"]);
2114        fs::write(main.join("t"), b"1\n").unwrap();
2115        git(&["add", "t"]);
2116        git(&["commit", "-qm", "init"]);
2117
2118        let repo =
2119            Repository::discover(Some(&main), &crate::environment::RepositoryOptions::empty())
2120                .unwrap();
2121        let linked = tmp.path().join("linked");
2122        repo.worktrees()
2123            .add(&AddLinkedWorktreeOptions {
2124                path: linked.clone(),
2125                branch: Some(WorktreeBranch::Create("a".into())),
2126                start_point: Some("HEAD".into()),
2127                force: false,
2128                lock: None,
2129                no_checkout: false,
2130                track: false,
2131            })
2132            .unwrap();
2133        fs::remove_dir_all(&linked).unwrap();
2134        assert!(matches!(
2135            repo.worktrees()
2136                .add(&AddLinkedWorktreeOptions {
2137                    path: linked.clone(),
2138                    branch: Some(WorktreeBranch::Create("b".into())),
2139                    start_point: Some("HEAD".into()),
2140                    force: false,
2141                    lock: None,
2142                    no_checkout: false,
2143                    track: false,
2144                },)
2145                .unwrap_err(),
2146            Error::Worktree(WorktreeError::Linked(
2147                LinkedWorktreeError::PathRegisteredMissing { .. }
2148            ))
2149        ));
2150    }
2151
2152    #[cfg_attr(
2153        not(feature = "full-tests"),
2154        ignore = "starts system git or is heavy; run with --features full-tests"
2155    )]
2156    #[test]
2157    fn remove_linked_worktree_refuses_main_and_locked() {
2158        use std::process::Command;
2159        let tmp = TempDir::new().unwrap();
2160        let main = tmp.path().join("main");
2161        fs::create_dir_all(&main).unwrap();
2162        let git = |args: &[&str]| {
2163            assert!(Command::new("git")
2164                .env("GIT_AUTHOR_NAME", "Test")
2165                .env("GIT_AUTHOR_EMAIL", "test@example.com")
2166                .env("GIT_COMMITTER_NAME", "Test")
2167                .env("GIT_COMMITTER_EMAIL", "test@example.com")
2168                .current_dir(&main)
2169                .args(args)
2170                .output()
2171                .unwrap()
2172                .status
2173                .success());
2174        };
2175        git(&["init", "-q", "-b", "main"]);
2176        fs::write(main.join("t"), b"1\n").unwrap();
2177        git(&["add", "t"]);
2178        git(&["commit", "-qm", "init"]);
2179
2180        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
2181        assert!(matches!(
2182            repo.worktrees().remove(&main, false),
2183            Err(Error::Worktree(WorktreeError::Linked(
2184                LinkedWorktreeError::MainWorktree {
2185                    operation: LinkedWorktreeOperation::Remove
2186                }
2187            )))
2188        ));
2189
2190        let linked = tmp.path().join("linked");
2191        repo.worktrees()
2192            .add(&AddLinkedWorktreeOptions {
2193                path: linked.clone(),
2194                branch: Some(WorktreeBranch::Create("wt".into())),
2195                start_point: Some("HEAD".into()),
2196                force: false,
2197                lock: None,
2198                no_checkout: false,
2199                track: false,
2200            })
2201            .unwrap();
2202        let common = common_git_dir(repo.git_dir());
2203        let admin = fs::read_dir(common.join("worktrees"))
2204            .unwrap()
2205            .find_map(|e| e.ok())
2206            .map(|e| e.path())
2207            .expect("admin");
2208        fs::write(admin.join("locked"), "hold\n").unwrap();
2209        assert!(matches!(
2210            repo.worktrees().remove( &linked, false),
2211            Err(Error::Worktree(WorktreeError::Linked(LinkedWorktreeError::Locked {
2212                reason: Some(r)
2213            }))) if r == "hold"
2214        ));
2215        assert!(repo.worktrees().remove(&linked, true).is_ok());
2216        assert!(matches!(
2217            repo.worktrees().remove(&linked, false),
2218            Err(Error::Worktree(WorktreeError::Linked(
2219                LinkedWorktreeError::NotRegistered { .. }
2220            )))
2221        ));
2222    }
2223}