1use std::path::{Path, PathBuf};
16
17use vitrify_core::CoreError;
18use vitrify_core::model::{Instance, Meta, Shape};
19use vitrify_core::trace::hash12;
20
21use crate::git::Git;
22
23#[derive(Debug, Clone)]
25pub struct Layout {
26 pub primary: PathBuf,
28 pub scratch: PathBuf,
30 pub wt_root: PathBuf,
32}
33
34impl Layout {
35 pub fn resolve(
39 primary: &Path,
40 home: Option<&Path>,
41 worktree_dir: &str,
42 ) -> Result<Layout, CoreError> {
43 let wt_root = if worktree_dir.trim().is_empty() {
44 let Some(home) = home else {
45 return Err(CoreError::refusal(
46 1,
47 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
48 ));
49 };
50 let name = primary
51 .file_name()
52 .map(|n| ref_part(&n.to_string_lossy()))
53 .unwrap_or_else(|| "repo".to_string());
54 let key = hash12(&primary.to_string_lossy());
55 home.join("worktrees").join(format!("{name}-{}", &key[..8]))
56 } else {
57 let p = PathBuf::from(worktree_dir.trim());
58 if p.is_absolute() { p } else { primary.join(p) }
59 };
60 Ok(Layout::at(primary, &wt_root))
61 }
62
63 pub fn at(primary: &Path, wt_root: &Path) -> Layout {
65 Layout {
66 primary: primary.to_path_buf(),
67 scratch: primary.join(".vitrify"),
68 wt_root: normalize(wt_root),
69 }
70 }
71
72 pub fn mainline(&self) -> PathBuf {
74 self.wt_root.join("mainline")
75 }
76
77 pub fn mainline_lock(&self) -> PathBuf {
79 self.wt_root.join("mainline.lock")
80 }
81
82 pub fn unit_worktree(&self, slug: &str, unit: &str, seq: i64) -> PathBuf {
84 self.wt_root.join(format!("{slug}-{unit}-c{seq}"))
85 }
86
87 pub fn in_tree(&self) -> Option<PathBuf> {
90 self.wt_root
91 .strip_prefix(&self.primary)
92 .ok()
93 .map(Path::to_path_buf)
94 }
95
96 pub fn ensure_scratch(&self) -> Result<(), CoreError> {
100 ensure_scratch(&self.primary).map(|_| ())
101 }
102
103 pub fn ensure_worktree_root(&self, primary: &Git) -> Result<(), CoreError> {
108 std::fs::create_dir_all(&self.wt_root).map_err(|source| CoreError::Io {
109 path: self.wt_root.clone(),
110 source,
111 })?;
112 let Some(rel) = self.in_tree() else {
113 return Ok(());
114 };
115 let rel = rel.to_string_lossy().replace('\\', "/");
116 if rel.is_empty() {
117 return Err(CoreError::refusal(
118 2,
119 "error: run.worktree_dir is the repository root itself — name a directory",
120 ));
121 }
122 primary
123 .exclude_locally(&format!("/{rel}/"))
124 .map_err(CoreError::from)?;
125 if let Some(source) = primary
126 .ignored_by(&format!("{rel}/probe"))
127 .map_err(CoreError::from)?
128 && !source.contains("info/exclude")
129 {
130 return Err(CoreError::refusal(
131 2,
132 format!(
133 "error: the worktree directory {rel}/ is ignored by {source} — tools that honour parent ignore files would check nothing in vitrify's worktrees; remove that pattern, or point run.worktree_dir elsewhere"
134 ),
135 ));
136 }
137 Ok(())
138 }
139}
140
141fn normalize(path: &Path) -> PathBuf {
145 use std::path::Component;
146 let mut out = PathBuf::new();
147 for part in path.components() {
148 match part {
149 Component::CurDir => {}
150 Component::ParentDir => {
151 if !out.pop() {
152 out.push("..");
153 }
154 }
155 other => out.push(other.as_os_str()),
156 }
157 }
158 out
159}
160
161pub fn ensure_scratch(primary: &Path) -> Result<PathBuf, CoreError> {
163 let scratch = primary.join(".vitrify");
164 std::fs::create_dir_all(&scratch).map_err(|source| CoreError::Io {
165 path: scratch.clone(),
166 source,
167 })?;
168 let _ = std::fs::write(scratch.join(".gitignore"), "*\n");
169 Ok(scratch)
170}
171
172pub fn ref_part(s: &str) -> String {
176 let mut out: String = s
177 .chars()
178 .map(|c| {
179 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
180 c
181 } else {
182 '-'
183 }
184 })
185 .collect();
186 while out.contains("..") {
187 out = out.replace("..", ".");
188 }
189 let mut out = out
190 .trim_start_matches(['.', '-'])
191 .trim_end_matches('.')
192 .to_string();
193 if out.ends_with(".lock") {
194 out.push('-');
195 }
196 if out.is_empty() {
197 out.push_str("sdd");
198 }
199 out
200}
201
202pub fn slug_of(meta: &Meta, root: &Path, shape: Shape) -> String {
205 let named = meta.get_str("sdd").map(str::trim).unwrap_or("");
206 if !named.is_empty() {
207 return ref_part(named);
208 }
209 let stem = match shape {
210 Shape::Bundle => root.file_name().map(|n| n.to_string_lossy().to_string()),
211 Shape::Single => root.file_name().map(|n| {
212 let n = n.to_string_lossy();
213 n.strip_suffix(".sdd.md")
214 .or_else(|| n.strip_suffix(".md"))
215 .unwrap_or(&n)
216 .to_string()
217 }),
218 };
219 ref_part(&stem.unwrap_or_default())
220}
221
222pub fn sdd_slug(inst: &Instance) -> String {
223 slug_of(&inst.meta, &inst.root, inst.shape)
224}
225
226pub fn branch_prefix(slug: &str, unit: &str) -> String {
228 format!("sdd/{slug}/{}/", ref_part(unit))
229}
230
231pub fn unit_branch(slug: &str, unit: &str, seq: i64) -> String {
233 format!("{}c{seq}", branch_prefix(slug, unit))
234}
235
236pub fn branch_seq(branch: &str) -> Option<i64> {
238 branch.rsplit('/').next()?.strip_prefix('c')?.parse().ok()
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn names_carry_the_slug_and_the_token() {
247 assert_eq!(
248 unit_branch("shop-cart", "U-001", 3),
249 "sdd/shop-cart/U-001/c3"
250 );
251 assert_eq!(branch_seq("sdd/shop-cart/U-001/c3"), Some(3));
252 assert_eq!(branch_seq("sdd/shop-cart/U-001/x3"), None);
253 let l = Layout::at(Path::new("/r"), Path::new("/w"));
254 assert_eq!(
255 l.unit_worktree("shop-cart", "U-001", 3),
256 PathBuf::from("/w/shop-cart-U-001-c3")
257 );
258 assert_eq!(l.mainline(), PathBuf::from("/w/mainline"));
259 assert!(l.in_tree().is_none());
260 assert_eq!(
261 Layout::at(Path::new("/r"), Path::new("/r/wt")).in_tree(),
262 Some(PathBuf::from("wt"))
263 );
264 }
265
266 #[test]
267 fn ref_part_is_always_a_legal_component() {
268 assert_eq!(ref_part("shop-cart"), "shop-cart");
269 assert_eq!(ref_part("my sdd/v2"), "my-sdd-v2");
270 assert_eq!(ref_part("..hidden"), "hidden");
271 assert_eq!(ref_part("a..b"), "a.b");
272 assert_eq!(ref_part("x.lock"), "x.lock-");
273 assert_eq!(ref_part("~^:"), "sdd");
274 }
275
276 #[test]
277 fn default_root_is_outside_the_working_tree_and_keyed_by_repository() {
278 let a = Layout::resolve(Path::new("/src/app"), Some(Path::new("/h")), "").unwrap();
279 let b = Layout::resolve(Path::new("/other/app"), Some(Path::new("/h")), "").unwrap();
280 assert!(a.wt_root.starts_with("/h/worktrees"));
281 assert!(a.in_tree().is_none());
282 assert_ne!(a.wt_root, b.wt_root, "same name, different repository");
283 let c = Layout::resolve(Path::new("/src/app"), None, "/big/disk").unwrap();
285 assert_eq!(c.wt_root, PathBuf::from("/big/disk"));
286 let d = Layout::resolve(Path::new("/src/app"), None, "vitrify-wt").unwrap();
287 assert_eq!(d.in_tree(), Some(PathBuf::from("vitrify-wt")));
288 let e = Layout::resolve(Path::new("/src/app"), None, "../app-wt").unwrap();
290 assert_eq!(e.wt_root, PathBuf::from("/src/app-wt"));
291 assert!(e.in_tree().is_none());
292 let f = Layout::resolve(Path::new("/src/app"), None, "./a/../wt").unwrap();
293 assert_eq!(f.in_tree(), Some(PathBuf::from("wt")));
294 assert!(Layout::resolve(Path::new("/src/app"), None, "").is_err());
296 }
297}