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 identify(path: &Path) -> Identity {
44 let common_dir = git_path(path, "--git-common-dir");
45 let worktree_path = git_path(path, "--show-toplevel");
46 if common_dir.is_none() || worktree_path.is_none() {
47 return Identity::default();
48 }
49 let branch = git(path, &["symbolic-ref", "--quiet", "--short", "HEAD"]).map(|bytes| {
50 crate::platform::output_text(crate::platform::fingerprint_line_ending(&bytes).0)
51 .into_owned()
52 });
53 Identity {
54 common_dir,
55 worktree_path,
56 branch,
57 }
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Worktree {
62 pub path: PathBuf,
63 pub branch: Option<String>,
64}
65
66pub fn worktrees(common_dir: &Path) -> Vec<Worktree> {
70 let args = [OsStr::new("--git-dir"), common_dir.as_os_str()]
71 .into_iter()
72 .chain(["worktree", "list", "--porcelain", "-z"].map(OsStr::new));
73 crate::process::tool_output("git", args)
74 .map(|output| parse_worktrees(&output))
75 .unwrap_or_default()
76 .into_iter()
77 .filter(|tree| crate::platform::paths::target_exists(&tree.path).unwrap_or(false))
78 .collect()
79}
80
81fn parse_worktrees(bytes: &[u8]) -> Vec<Worktree> {
82 let mut trees: Vec<(Worktree, bool)> = Vec::new();
83 for field in bytes.split(|byte| *byte == 0) {
84 if let Some(path) = field.strip_prefix(b"worktree ") {
85 let path = crate::platform::path_from_bytes(path);
86 trees.push((Worktree { path, branch: None }, false));
87 } else if let Some((tree, _)) = trees.last_mut()
88 && let Some(branch) = field.strip_prefix(b"branch refs/heads/")
89 {
90 tree.branch = Some(crate::platform::output_text(branch).into_owned());
91 } else if let Some((_, prunable)) = trees.last_mut()
92 && (field == b"prunable" || field.starts_with(b"prunable "))
93 {
94 *prunable = true;
95 }
96 }
97 trees
98 .into_iter()
99 .filter_map(|(tree, prunable)| (!prunable).then_some(tree))
100 .collect()
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn git_identity_preserves_supported_path_characters() {
109 let root = crate::test_os::tempdir();
110 for path in crate::test_os::git_path_cases(root.path()) {
111 crate::test_os::git(&path, &["init", "--quiet"]);
112 let identity = identify(&path);
113 assert_eq!(
114 identity.common_dir,
115 Some(crate::test_os::canonical(&path.join(".git"))),
116 "{path:?}"
117 );
118 assert_eq!(
119 identity.worktree_path,
120 Some(crate::test_os::canonical(&path)),
121 "{path:?}"
122 );
123 }
124 }
125
126 #[test]
127 fn porcelain_paths_are_not_split_on_whitespace() {
128 let root = crate::test_os::tempdir();
129 let named = root.path().join("a space\nline");
131 let detached = root.path().join("detached");
132 let wire = format!(
133 "worktree {}\0HEAD abc\0branch refs/heads/main\0\0worktree {}\0HEAD def\0detached\0\0",
134 crate::platform::path_text(&named),
135 crate::platform::path_text(&detached),
136 );
137 let trees = parse_worktrees(wire.as_bytes());
138 assert_eq!(trees[0].path, named);
139 assert_eq!(trees[0].branch.as_deref(), Some("main"));
140 assert_eq!(trees[1].path, detached);
141 assert_eq!(trees[1].branch, None);
142 }
143
144 #[test]
145 fn prunable_worktrees_are_not_listed() {
146 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";
147 let trees = parse_worktrees(wire.as_bytes());
148 assert_eq!(trees.len(), 1);
149 assert_eq!(trees[0].branch.as_deref(), Some("main"));
150 }
151
152 #[test]
153 fn a_removed_worktree_folder_is_not_listed() {
154 let root = crate::test_os::tempdir();
155 let main = root.path().join("main");
156 std::fs::create_dir(&main).unwrap();
157 crate::test_os::git(&main, &["init", "--quiet", "--initial-branch=main"]);
158 crate::test_os::git(
159 &main,
160 &[
161 "-c",
162 "user.name=artifactize",
163 "-c",
164 "user.email=artifactize@example.invalid",
165 "commit",
166 "--quiet",
167 "--allow-empty",
168 "-m",
169 "first",
170 ],
171 );
172 let other = root.path().join("other");
173 crate::test_os::git(
174 &main,
175 &[
176 "worktree",
177 "add",
178 "--quiet",
179 "-b",
180 "other",
181 &crate::platform::path_text(&other),
182 ],
183 );
184 let common = crate::test_os::canonical(&main.join(".git"));
185 let branches = |trees: Vec<Worktree>| -> Vec<Option<String>> {
186 trees.into_iter().map(|tree| tree.branch).collect()
187 };
188 assert_eq!(
189 branches(worktrees(&common)),
190 [Some("main".into()), Some("other".into())]
191 );
192 std::fs::remove_dir_all(&other).unwrap();
193 assert_eq!(branches(worktrees(&common)), [Some("main".into())]);
194 }
195}