1mod removal;
3pub use removal::{remove, validate_removal};
4
5use anyhow::{bail, Context, Result};
6use serde::Serialize;
7use std::{
8 io::Read,
9 path::{Component, Path, PathBuf},
10};
11
12use super::{cli_process, path_guard, project_paths, skill_store::SkillStore};
13
14#[derive(Clone, Debug, Serialize)]
15pub struct ProjectWorktree {
16 pub path: String,
17 pub branch: Option<String>,
18 pub head: Option<String>,
19 pub is_main: bool,
20 pub locked: bool,
21 pub available: bool,
22}
23
24#[derive(Serialize)]
25pub struct WorktreeFileEntry {
26 pub name: String,
27 pub path: String,
28 pub is_dir: bool,
29 pub is_symlink: bool,
30 pub is_ignored: bool,
31}
32
33pub fn list(store: &SkillStore, project_id: &str) -> Result<Vec<ProjectWorktree>> {
34 let project = store
35 .get_project_by_id(project_id)?
36 .context("Project is no longer registered")?;
37 let path = Path::new(&project.path);
38 let available = match path.metadata() {
39 Ok(metadata) => metadata.is_dir(),
40 Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
41 Err(error) => return Err(error.into()),
42 };
43 if !available {
44 return Ok(vec![plain_directory(path, false)]);
47 }
48 list_directory(&project_paths::project_directory(store, project_id)?)
49}
50
51fn plain_directory(directory: &Path, available: bool) -> ProjectWorktree {
52 ProjectWorktree {
53 path: directory.to_string_lossy().into_owned(),
54 branch: None,
55 head: None,
56 is_main: true,
57 locked: false,
58 available,
59 }
60}
61
62fn list_directory(directory: &Path) -> Result<Vec<ProjectWorktree>> {
63 match git2::Repository::open_ext(
66 directory,
67 git2::RepositoryOpenFlags::NO_SEARCH,
68 &[] as &[&Path],
69 ) {
70 Ok(repo) if repo.workdir().is_some() => {}
71 Ok(_) => bail!("A bare repository has no workspace directory"),
72 Err(error) if error.code() == git2::ErrorCode::NotFound => {
73 return Ok(vec![plain_directory(directory, true)]);
74 }
75 Err(error) => return Err(error.into()),
76 }
77 let output = cli_process::run(
78 "git",
79 &[
80 "--no-optional-locks",
81 "worktree",
82 "list",
83 "--porcelain",
84 "-z",
85 ],
86 &[],
87 15,
88 Some(directory),
89 None,
90 )
91 .map_err(anyhow::Error::msg)?;
92 let worktrees = parse_worktrees(&output);
93 if worktrees.is_empty() {
94 bail!("Git returned no workspace directories");
95 }
96 Ok(worktrees)
97}
98
99fn parse_worktrees(output: &str) -> Vec<ProjectWorktree> {
100 output
101 .split("\0\0")
102 .enumerate()
103 .filter_map(|(index, record)| {
104 let fields: Vec<_> = record.split('\0').collect();
105 let path = fields.first()?.strip_prefix("worktree ")?;
106 if fields.contains(&"bare") {
107 return None;
108 }
109 Some(ProjectWorktree {
110 path: path.to_owned(),
111 branch: fields
112 .iter()
113 .find_map(|field| field.strip_prefix("branch refs/heads/").map(str::to_owned)),
114 head: fields
115 .iter()
116 .find_map(|field| field.strip_prefix("HEAD ").map(str::to_owned)),
117 is_main: index == 0,
118 locked: fields
119 .iter()
120 .any(|field| *field == "locked" || field.starts_with("locked ")),
121 available: Path::new(path).is_dir()
122 && !fields
123 .iter()
124 .any(|field| *field == "prunable" || field.starts_with("prunable ")),
125 })
126 })
127 .collect()
128}
129
130pub fn directory(
133 store: &SkillStore,
134 project_id: &str,
135 worktree_path: Option<&str>,
136) -> Result<PathBuf> {
137 let root = project_paths::project_directory(store, project_id)?;
138 let Some(requested) = worktree_path else {
139 return Ok(root);
140 };
141 let candidate = Path::new(requested)
142 .canonicalize()
143 .context("Worktree directory is unavailable")?;
144 let allowed = list_directory(&root)?.into_iter().any(|entry| {
145 entry.available && Path::new(&entry.path).canonicalize().ok().as_ref() == Some(&candidate)
146 });
147 if !allowed {
148 bail!("Worktree does not belong to this registered project");
149 }
150 Ok(candidate)
151}
152
153pub fn create(
156 store: &SkillStore,
157 project_id: &str,
158 source_path: &str,
159 branch: &str,
160 destination: &str,
161) -> Result<ProjectWorktree> {
162 let source = directory(store, project_id, Some(source_path))?;
163 let repo = git2::Repository::open_ext(
164 &source,
165 git2::RepositoryOpenFlags::NO_SEARCH,
166 &[] as &[&Path],
167 )?;
168 let head = repo
169 .head()
170 .context("Create a commit before creating a worktree")?
171 .peel_to_commit()?
172 .id()
173 .to_string();
174 super::project_git::validate_branch_name(branch)?;
175 if repo.find_branch(branch, git2::BranchType::Local).is_ok() {
176 bail!("Branch already exists; enter a new branch name");
177 }
178 let target = Path::new(destination);
179 if !target.is_absolute()
180 || target
181 .components()
182 .any(|part| matches!(part, Component::ParentDir))
183 {
184 bail!("Enter an absolute destination path without parent traversal");
185 }
186 let parent = target
187 .parent()
188 .context("Select a destination directory")?
189 .canonicalize()
190 .context("Destination parent directory must exist")?;
191 let target = parent.join(
192 target
193 .file_name()
194 .context("Select a new destination directory")?,
195 );
196 if target.components().any(|part| {
197 part.as_os_str()
198 .to_str()
199 .is_some_and(|name| name.eq_ignore_ascii_case(".git"))
200 }) {
201 bail!("Destination cannot be inside Git metadata");
202 }
203 if target.symlink_metadata().is_ok() {
204 bail!("Destination already exists; choose a new directory");
205 }
206 #[cfg(windows)]
207 let git_target = dunce::simplified(&target);
208 #[cfg(not(windows))]
209 let git_target = target.as_path();
210 let target_str = git_target
211 .to_str()
212 .context("Destination must be valid UTF-8")?;
213 super::project_git::run_git(
214 &source,
215 &["worktree", "add", "-b", branch, "--", target_str, &head],
216 )?;
217 Ok(ProjectWorktree {
218 path: target_str.to_owned(),
219 branch: Some(branch.to_owned()),
220 head: Some(head),
221 is_main: false,
222 locked: false,
223 available: true,
224 })
225}
226
227pub(crate) fn file_path(root: &Path, relative: &str) -> Result<PathBuf> {
228 if Path::new(relative)
229 .components()
230 .any(|part| !matches!(part, Component::Normal(_)))
231 {
232 bail!("Invalid workspace file path");
233 }
234 let path = root.join(relative);
235 if !path_guard::is_path_safe(root, &path) {
236 bail!("File is outside the selected worktree");
237 }
238 Ok(path)
239}
240
241pub fn entries(root: &Path, relative: &str) -> Result<Vec<WorktreeFileEntry>> {
242 let directory = file_path(root, relative)?;
243 let mut entries = Vec::new();
244 for entry in std::fs::read_dir(directory)? {
245 let entry = entry?;
246 if entry.file_name() == ".git" {
247 continue;
248 }
249 if entries.len() >= 4000 {
250 bail!("Directory exceeds the 4000 entry limit");
251 }
252 let kind = entry.file_type()?;
253 let path = entry
254 .path()
255 .strip_prefix(root)?
256 .to_string_lossy()
257 .replace('\\', "/");
258 entries.push(WorktreeFileEntry {
259 name: entry.file_name().to_string_lossy().into_owned(),
260 path,
261 is_dir: kind.is_dir(),
262 is_symlink: kind.is_symlink(),
263 is_ignored: false,
264 });
265 }
266 mark_ignored(root, &mut entries);
267 entries.sort_by(|a, b| {
268 b.is_dir
269 .cmp(&a.is_dir)
270 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
271 .then(a.name.cmp(&b.name))
272 });
273 Ok(entries)
274}
275
276fn mark_ignored(root: &Path, entries: &mut [WorktreeFileEntry]) {
278 let Ok(repo) = git2::Repository::discover(root) else {
279 return;
280 };
281 let Some(workdir) = repo.workdir() else {
282 return;
283 };
284 let Ok(workdir) = workdir.canonicalize() else {
285 return;
286 };
287 let Ok(root) = root.canonicalize() else {
288 return;
289 };
290 let Ok(prefix) = root.strip_prefix(&workdir) else {
291 return;
292 };
293 let Ok(index) = repo.index() else { return };
294 let tracked: std::collections::HashSet<String> = index
295 .iter()
296 .flat_map(|entry| {
297 let path = String::from_utf8_lossy(&entry.path).into_owned();
298 let mut paths = vec![path.clone()];
299 let mut parent = Path::new(&path).parent();
300 while let Some(directory) = parent {
301 paths.push(directory.to_string_lossy().replace('\\', "/"));
302 parent = directory.parent();
303 }
304 paths
305 })
306 .collect();
307 for entry in entries {
308 let path = prefix.join(&entry.path);
309 let key = path.to_string_lossy().replace('\\', "/");
310 entry.is_ignored = !tracked.contains(&key) && repo.is_path_ignored(&path).unwrap_or(false);
311 }
312}
313
314pub fn read_file(root: &Path, relative: &str) -> Result<String> {
315 let path = file_path(root, relative)?;
316 if !path.is_file() {
317 bail!("Select a regular text file");
318 }
319 let file = std::fs::File::open(path)?;
320 let mut bytes = Vec::new();
321 file.take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
322 if bytes.len() > 1024 * 1024 {
323 bail!("File exceeds the 1 MiB preview limit");
324 }
325 if bytes.contains(&0) {
326 bail!("Binary files cannot be previewed");
327 }
328 String::from_utf8(bytes).context("File is not UTF-8 text")
329}
330
331#[cfg(test)]
332mod tests;