|
| 1 | +//! read-only listing of git worktrees |
| 2 | +
|
| 3 | +use std::path::{Path, PathBuf}; |
| 4 | + |
| 5 | +use git2::{Repository, WorktreeLockStatus}; |
| 6 | +use scopetime::scope_time; |
| 7 | + |
| 8 | +use super::{repo, RepoPath}; |
| 9 | +use crate::error::Result; |
| 10 | + |
| 11 | +/// name reported for the primary working tree |
| 12 | +const MAIN_WORKTREE_NAME: &str = "(main)"; |
| 13 | + |
| 14 | +/// Information about one git worktree (the primary tree or a linked one). |
| 15 | +#[derive(Debug, Clone)] |
| 16 | +pub struct WorktreeInfo { |
| 17 | + /// Linked-worktree name; "(main)" for the primary working tree. |
| 18 | + pub name: String, |
| 19 | + /// Absolute path to the worktree's working directory. |
| 20 | + pub path: PathBuf, |
| 21 | + /// Short name of the checked-out branch (HEAD), or None if |
| 22 | + /// detached/unborn. |
| 23 | + pub branch: Option<String>, |
| 24 | + /// Whether the worktree's working directory is present/valid. |
| 25 | + pub is_valid: bool, |
| 26 | + /// Whether the worktree is locked. |
| 27 | + pub is_locked: bool, |
| 28 | + /// Whether this is the worktree gitui is currently operating in. |
| 29 | + pub is_current: bool, |
| 30 | +} |
| 31 | + |
| 32 | +/// Lists the worktrees of the repo at `repo_path`, returning the |
| 33 | +/// primary working tree first followed by any linked worktrees. |
| 34 | +pub fn get_worktrees( |
| 35 | + repo_path: &RepoPath, |
| 36 | +) -> Result<Vec<WorktreeInfo>> { |
| 37 | + scope_time!("get_worktrees"); |
| 38 | + |
| 39 | + let repo = repo(repo_path)?; |
| 40 | + |
| 41 | + // working dir gitui is currently operating in, used to flag the |
| 42 | + // matching entry as `is_current`. |
| 43 | + let current = repo.workdir(); |
| 44 | + |
| 45 | + let mut worktrees = Vec::new(); |
| 46 | + |
| 47 | + if let Some(main) = main_worktree_info(&repo, current) { |
| 48 | + worktrees.push(main); |
| 49 | + } |
| 50 | + |
| 51 | + // `iter()` yields `Result<Option<&str>, Error>`; the two |
| 52 | + // flattens drop unreadable/non-utf8 names, leaving `&str`. |
| 53 | + for name in repo.worktrees()?.iter().flatten().flatten() { |
| 54 | + worktrees.push(linked_worktree_info(&repo, name, current)?); |
| 55 | + } |
| 56 | + |
| 57 | + Ok(worktrees) |
| 58 | +} |
| 59 | + |
| 60 | +/// synthesizes the entry for the primary working tree, which is not |
| 61 | +/// part of `Repository::worktrees`. returns `None` for bare repos |
| 62 | +/// (no working tree) or when the primary workdir cannot be located. |
| 63 | +fn main_worktree_info( |
| 64 | + repo: &Repository, |
| 65 | + current: Option<&Path>, |
| 66 | +) -> Option<WorktreeInfo> { |
| 67 | + if repo.is_bare() { |
| 68 | + return None; |
| 69 | + } |
| 70 | + |
| 71 | + // primary working dir and the repo handle used to read its branch. |
| 72 | + let (main_workdir, branch) = if repo.is_worktree() { |
| 73 | + // gitui is operating inside a linked worktree; the primary |
| 74 | + // tree sits next to the shared common git dir. |
| 75 | + let workdir = |
| 76 | + repo.commondir().parent().map(Path::to_path_buf)?; |
| 77 | + |
| 78 | + let branch = Repository::open(&workdir) |
| 79 | + .ok() |
| 80 | + .and_then(|r| head_branch(&r)); |
| 81 | + |
| 82 | + (workdir, branch) |
| 83 | + } else { |
| 84 | + let workdir = repo.workdir()?; |
| 85 | + |
| 86 | + (workdir.to_path_buf(), head_branch(repo)) |
| 87 | + }; |
| 88 | + |
| 89 | + Some(WorktreeInfo { |
| 90 | + is_current: same_workdir(&main_workdir, current), |
| 91 | + name: MAIN_WORKTREE_NAME.to_string(), |
| 92 | + path: main_workdir, |
| 93 | + branch, |
| 94 | + is_valid: true, |
| 95 | + is_locked: false, |
| 96 | + }) |
| 97 | +} |
| 98 | + |
| 99 | +/// builds the entry for a single linked worktree. |
| 100 | +fn linked_worktree_info( |
| 101 | + repo: &Repository, |
| 102 | + name: &str, |
| 103 | + current: Option<&Path>, |
| 104 | +) -> Result<WorktreeInfo> { |
| 105 | + let wt = repo.find_worktree(name)?; |
| 106 | + |
| 107 | + let branch = Repository::open_from_worktree(&wt) |
| 108 | + .ok() |
| 109 | + .and_then(|r| head_branch(&r)); |
| 110 | + |
| 111 | + let is_locked = wt.is_locked().is_ok_and(|status| { |
| 112 | + matches!(status, WorktreeLockStatus::Locked(_)) |
| 113 | + }); |
| 114 | + |
| 115 | + Ok(WorktreeInfo { |
| 116 | + is_current: same_workdir(wt.path(), current), |
| 117 | + name: name.to_string(), |
| 118 | + path: wt.path().to_path_buf(), |
| 119 | + branch, |
| 120 | + is_valid: wt.validate().is_ok(), |
| 121 | + is_locked, |
| 122 | + }) |
| 123 | +} |
| 124 | + |
| 125 | +/// short name of the branch a repo's HEAD points at, or `None` when |
| 126 | +/// HEAD is unborn or detached. |
| 127 | +fn head_branch(repo: &Repository) -> Option<String> { |
| 128 | + // a detached HEAD points at a commit, not a branch, and its |
| 129 | + // shorthand is "HEAD" rather than a branch name. |
| 130 | + if repo.head_detached().unwrap_or(false) { |
| 131 | + return None; |
| 132 | + } |
| 133 | + |
| 134 | + repo.head() |
| 135 | + .ok() |
| 136 | + .as_ref() |
| 137 | + .and_then(|head| head.shorthand().ok().map(String::from)) |
| 138 | +} |
| 139 | + |
| 140 | +/// whether `path` and `current` refer to the same working directory, |
| 141 | +/// comparing canonicalized paths and falling back to raw equality when |
| 142 | +/// canonicalization fails. |
| 143 | +fn same_workdir(path: &Path, current: Option<&Path>) -> bool { |
| 144 | + current.is_some_and(|current| { |
| 145 | + let canon = |p: &Path| std::fs::canonicalize(p).ok(); |
| 146 | + match (canon(path), canon(current)) { |
| 147 | + (Some(a), Some(b)) => a == b, |
| 148 | + _ => path == current, |
| 149 | + } |
| 150 | + }) |
| 151 | +} |
| 152 | + |
| 153 | +#[cfg(test)] |
| 154 | +mod tests { |
| 155 | + use super::{get_worktrees, WorktreeInfo}; |
| 156 | + use crate::sync::{tests::repo_init, RepoPath}; |
| 157 | + use pretty_assertions::assert_eq; |
| 158 | + |
| 159 | + fn find<'a>( |
| 160 | + list: &'a [WorktreeInfo], |
| 161 | + name: &str, |
| 162 | + ) -> &'a WorktreeInfo { |
| 163 | + list.iter().find(|w| w.name == name).unwrap() |
| 164 | + } |
| 165 | + |
| 166 | + #[test] |
| 167 | + fn test_lists_primary_and_linked() { |
| 168 | + let (_td, repo) = repo_init().unwrap(); |
| 169 | + |
| 170 | + let root = repo.path().parent().unwrap(); |
| 171 | + let repo_path: RepoPath = root.to_str().unwrap().into(); |
| 172 | + |
| 173 | + // linked worktree kept outside the main workdir to avoid |
| 174 | + // nesting; `wt_dir` must stay alive for the whole test. |
| 175 | + let wt_dir = tempfile::TempDir::new().unwrap(); |
| 176 | + let wt_path = wt_dir.path().join("wt1"); |
| 177 | + repo.worktree("wt1", &wt_path, None).unwrap(); |
| 178 | + |
| 179 | + let list = get_worktrees(&repo_path).unwrap(); |
| 180 | + |
| 181 | + assert_eq!(list.len(), 2); |
| 182 | + |
| 183 | + let linked = find(&list, "wt1"); |
| 184 | + assert!(linked.path.is_absolute()); |
| 185 | + assert!(linked.path.ends_with("wt1")); |
| 186 | + // git names the branch after the worktree by default. |
| 187 | + assert!(linked.branch.is_some()); |
| 188 | + assert!(!linked.is_current); |
| 189 | + |
| 190 | + let primary = find(&list, "(main)"); |
| 191 | + assert!(primary.is_current); |
| 192 | + } |
| 193 | + |
| 194 | + #[test] |
| 195 | + fn test_primary_only() { |
| 196 | + let (_td, repo) = repo_init().unwrap(); |
| 197 | + |
| 198 | + let root = repo.path().parent().unwrap(); |
| 199 | + let repo_path: RepoPath = root.to_str().unwrap().into(); |
| 200 | + |
| 201 | + let list = get_worktrees(&repo_path).unwrap(); |
| 202 | + |
| 203 | + assert_eq!(list.len(), 1); |
| 204 | + assert_eq!(list[0].name, "(main)"); |
| 205 | + assert!(list[0].is_current); |
| 206 | + assert!(list[0].is_valid); |
| 207 | + assert!(!list[0].is_locked); |
| 208 | + } |
| 209 | + |
| 210 | + #[test] |
| 211 | + fn test_detached_head_has_no_branch() { |
| 212 | + let (_td, repo) = repo_init().unwrap(); |
| 213 | + |
| 214 | + let root = repo.path().parent().unwrap(); |
| 215 | + let repo_path: RepoPath = root.to_str().unwrap().into(); |
| 216 | + |
| 217 | + let oid = repo.head().unwrap().target().unwrap(); |
| 218 | + repo.set_head_detached(oid).unwrap(); |
| 219 | + |
| 220 | + let list = get_worktrees(&repo_path).unwrap(); |
| 221 | + |
| 222 | + assert_eq!(list.len(), 1); |
| 223 | + assert_eq!(list[0].name, "(main)"); |
| 224 | + assert!(list[0].branch.is_none()); |
| 225 | + } |
| 226 | +} |
0 commit comments