1use serde::{Deserialize, Serialize};
4use std::{
5 ffi::OsStr,
6 path::{Path, PathBuf},
7};
8
9#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Identity {
12 #[serde(
13 default,
14 skip_serializing_if = "Option::is_none",
15 with = "crate::platform::path_serde::option"
16 )]
17 pub common_dir: Option<PathBuf>,
18 #[serde(
19 default,
20 skip_serializing_if = "Option::is_none",
21 with = "crate::platform::path_serde::option"
22 )]
23 pub worktree_path: Option<PathBuf>,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub branch: Option<String>,
26}
27
28fn git(path: &Path, args: &[&str]) -> Option<Vec<u8>> {
29 let args = [OsStr::new("-C"), path.as_os_str()]
30 .into_iter()
31 .chain(args.iter().map(OsStr::new));
32 crate::process::tool_output("git", args)
33}
34
35fn git_path(path: &Path, arg: &str) -> Option<PathBuf> {
36 let output = git(path, &["rev-parse", "--path-format=absolute", arg])?;
37 let path = crate::platform::path_from_line(&output);
39 crate::platform::canonicalize(&path).ok()
40}
41
42pub fn checked_out_branch(path: &Path) -> Option<String> {
44 git(path, &["symbolic-ref", "--quiet", "--short", "HEAD"]).map(|bytes| {
45 crate::platform::output_text(crate::platform::fingerprint_line_ending(&bytes).0)
46 .into_owned()
47 })
48}
49
50pub fn identify(path: &Path) -> Identity {
52 let common_dir = git_path(path, "--git-common-dir");
53 let worktree_path = git_path(path, "--show-toplevel");
54 if common_dir.is_none() || worktree_path.is_none() {
55 return Identity::default();
56 }
57 let branch = checked_out_branch(path);
58 Identity {
59 common_dir,
60 worktree_path,
61 branch,
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Worktree {
67 pub path: PathBuf,
68 pub branch: Option<String>,
69}
70
71pub fn worktrees(common_dir: &Path) -> Vec<Worktree> {
75 let args = [OsStr::new("--git-dir"), common_dir.as_os_str()]
76 .into_iter()
77 .chain(["worktree", "list", "--porcelain", "-z"].map(OsStr::new));
78 crate::process::tool_output("git", args)
79 .map(|output| parse_worktrees(&output))
80 .unwrap_or_default()
81 .into_iter()
82 .filter(|tree| crate::platform::paths::target_exists(&tree.path).unwrap_or(false))
83 .collect()
84}
85
86fn parse_worktrees(bytes: &[u8]) -> Vec<Worktree> {
87 let mut trees: Vec<(Worktree, bool)> = Vec::new();
88 for field in bytes.split(|byte| *byte == 0) {
89 if let Some(path) = field.strip_prefix(b"worktree ") {
90 let path = crate::platform::path_from_bytes(path);
91 trees.push((Worktree { path, branch: None }, false));
92 } else if let Some((tree, _)) = trees.last_mut()
93 && let Some(branch) = field.strip_prefix(b"branch refs/heads/")
94 {
95 tree.branch = Some(crate::platform::output_text(branch).into_owned());
96 } else if let Some((_, prunable)) = trees.last_mut()
97 && (field == b"prunable" || field.starts_with(b"prunable "))
98 {
99 *prunable = true;
100 }
101 }
102 trees
103 .into_iter()
104 .filter_map(|(tree, prunable)| (!prunable).then_some(tree))
105 .collect()
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[test]
113 fn git_identity_preserves_supported_path_characters() {
114 let root = crate::test_os::tempdir();
115 for path in crate::test_os::git_path_cases(root.path()) {
116 crate::test_os::git(&path, &["init", "--quiet"]);
117 let identity = identify(&path);
118 assert_eq!(
119 identity.common_dir,
120 Some(crate::test_os::canonical(&path.join(".git"))),
121 "{path:?}"
122 );
123 assert_eq!(
124 identity.worktree_path,
125 Some(crate::test_os::canonical(&path)),
126 "{path:?}"
127 );
128 }
129 }
130
131 #[test]
132 fn porcelain_paths_are_not_split_on_whitespace() {
133 let root = crate::test_os::tempdir();
134 let named = root.path().join("a space\nline");
136 let detached = root.path().join("detached");
137 let wire = format!(
138 "worktree {}\0HEAD abc\0branch refs/heads/main\0\0worktree {}\0HEAD def\0detached\0\0",
139 crate::platform::path_text(&named),
140 crate::platform::path_text(&detached),
141 );
142 let trees = parse_worktrees(wire.as_bytes());
143 assert_eq!(trees[0].path, named);
144 assert_eq!(trees[0].branch.as_deref(), Some("main"));
145 assert_eq!(trees[1].path, detached);
146 assert_eq!(trees[1].branch, None);
147 }
148
149 #[test]
150 fn prunable_worktrees_are_not_listed() {
151 let wire = "worktree /work/main\0HEAD abc\0branch refs/heads/main\0\0worktree /work/gone\0HEAD def\0branch refs/heads/gone\0prunable gitdir file points to non-existent location\0\0";
152 let trees = parse_worktrees(wire.as_bytes());
153 assert_eq!(trees.len(), 1);
154 assert_eq!(trees[0].branch.as_deref(), Some("main"));
155 }
156
157 #[test]
158 fn a_removed_worktree_folder_is_not_listed() {
159 let root = crate::test_os::tempdir();
160 let main = root.path().join("main");
161 std::fs::create_dir(&main).unwrap();
162 crate::test_os::git(&main, &["init", "--quiet", "--initial-branch=main"]);
163 crate::test_os::git(
164 &main,
165 &[
166 "-c",
167 "user.name=artifactize",
168 "-c",
169 "user.email=artifactize@example.invalid",
170 "commit",
171 "--quiet",
172 "--allow-empty",
173 "-m",
174 "first",
175 ],
176 );
177 let other = root.path().join("other");
178 crate::test_os::git(
179 &main,
180 &[
181 "worktree",
182 "add",
183 "--quiet",
184 "-b",
185 "other",
186 &crate::platform::path_text(&other),
187 ],
188 );
189 let common = crate::test_os::canonical(&main.join(".git"));
190 let branches = |trees: Vec<Worktree>| -> Vec<Option<String>> {
191 trees.into_iter().map(|tree| tree.branch).collect()
192 };
193 assert_eq!(
194 branches(worktrees(&common)),
195 [Some("main".into()), Some("other".into())]
196 );
197 std::fs::remove_dir_all(&other).unwrap();
198 assert_eq!(branches(worktrees(&common)), [Some("main".into())]);
199 }
200}