1use std::path::{Path, PathBuf};
19
20use vitrify_core::CoreError;
21use vitrify_core::model::{Instance, Meta, Shape};
22use vitrify_core::trace::hash12;
23
24use crate::git::Git;
25
26#[derive(Debug, Clone)]
28pub struct Layout {
29 pub primary: PathBuf,
31 pub scratch: PathBuf,
33 pub wt_root: PathBuf,
35}
36
37impl Layout {
38 pub fn resolve(
42 primary: &Path,
43 home: Option<&Path>,
44 worktree_dir: &str,
45 ) -> Result<Layout, CoreError> {
46 let wt_root = if worktree_dir.trim().is_empty() {
47 let Some(home) = home else {
48 return Err(CoreError::refusal(
49 1,
50 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
51 ));
52 };
53 let name = primary
54 .file_name()
55 .map(|n| ref_part(&n.to_string_lossy()))
56 .unwrap_or_else(|| "repo".to_string());
57 let key = hash12(&primary.to_string_lossy());
58 home.join("worktrees").join(format!("{name}-{}", &key[..8]))
59 } else {
60 let p = PathBuf::from(worktree_dir.trim());
61 if p.is_absolute() { p } else { primary.join(p) }
62 };
63 Ok(Layout::at(primary, &wt_root))
64 }
65
66 pub fn at(primary: &Path, wt_root: &Path) -> Layout {
68 Layout {
69 primary: primary.to_path_buf(),
70 scratch: primary.join(".vitrify"),
71 wt_root: normalize(wt_root),
72 }
73 }
74
75 pub fn mainline(&self, slug: &str) -> PathBuf {
78 self.wt_root.join(format!("mainline-{slug}"))
79 }
80
81 pub fn mainline_lock(&self, slug: &str) -> PathBuf {
85 self.wt_root.join(format!("mainline-{slug}.lock"))
86 }
87
88 pub fn base_checkout(&self, slug: &str) -> PathBuf {
91 self.wt_root.join(format!("base-{slug}"))
92 }
93
94 pub fn head_checkout(&self, slug: &str) -> PathBuf {
97 self.scratch
98 .join(format!("tx-{}-{slug}-head", std::process::id()))
99 }
100
101 pub fn job_logs(&self, job: &str) -> PathBuf {
104 self.scratch.join("logs").join(job)
105 }
106
107 pub fn lane_logs(&self, job: &str, slug: &str) -> PathBuf {
110 self.job_logs(job).join(slug)
111 }
112
113 pub fn unit_worktree(&self, slug: &str, unit: &str, seq: i64) -> PathBuf {
115 self.wt_root.join(format!("{slug}-{unit}-c{seq}"))
116 }
117
118 pub fn in_tree(&self) -> Option<PathBuf> {
121 self.wt_root
122 .strip_prefix(&self.primary)
123 .ok()
124 .map(Path::to_path_buf)
125 }
126
127 pub fn ensure_scratch(&self) -> Result<(), CoreError> {
131 ensure_scratch(&self.primary).map(|_| ())
132 }
133
134 pub fn ensure_worktree_root(&self, primary: &Git) -> Result<(), CoreError> {
139 std::fs::create_dir_all(&self.wt_root).map_err(|source| CoreError::Io {
140 path: self.wt_root.clone(),
141 source,
142 })?;
143 let Some(rel) = self.in_tree() else {
144 return Ok(());
145 };
146 let rel = rel.to_string_lossy().replace('\\', "/");
147 if rel.is_empty() {
148 return Err(CoreError::refusal(
149 2,
150 "error: run.worktree_dir is the repository root itself — name a directory",
151 ));
152 }
153 primary
154 .exclude_locally(&format!("/{rel}/"))
155 .map_err(CoreError::from)?;
156 if let Some(source) = primary
157 .ignored_by(&format!("{rel}/probe"))
158 .map_err(CoreError::from)?
159 && !source.contains("info/exclude")
160 {
161 return Err(CoreError::refusal(
162 2,
163 format!(
164 "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"
165 ),
166 ));
167 }
168 Ok(())
169 }
170}
171
172fn normalize(path: &Path) -> PathBuf {
176 use std::path::Component;
177 let mut out = PathBuf::new();
178 for part in path.components() {
179 match part {
180 Component::CurDir => {}
181 Component::ParentDir => {
182 if !out.pop() {
183 out.push("..");
184 }
185 }
186 other => out.push(other.as_os_str()),
187 }
188 }
189 out
190}
191
192pub fn ensure_scratch(primary: &Path) -> Result<PathBuf, CoreError> {
194 let scratch = primary.join(".vitrify");
195 std::fs::create_dir_all(&scratch).map_err(|source| CoreError::Io {
196 path: scratch.clone(),
197 source,
198 })?;
199 let _ = std::fs::write(scratch.join(".gitignore"), "*\n");
200 Ok(scratch)
201}
202
203pub fn ref_part(s: &str) -> String {
207 let mut out: String = s
208 .chars()
209 .map(|c| {
210 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
211 c
212 } else {
213 '-'
214 }
215 })
216 .collect();
217 while out.contains("..") {
218 out = out.replace("..", ".");
219 }
220 let mut out = out
221 .trim_start_matches(['.', '-'])
222 .trim_end_matches('.')
223 .to_string();
224 if out.ends_with(".lock") {
225 out.push('-');
226 }
227 if out.is_empty() {
228 out.push_str("sdd");
229 }
230 out
231}
232
233pub fn slug_of(meta: &Meta, root: &Path, shape: Shape) -> String {
236 let named = meta.get_str("sdd").map(str::trim).unwrap_or("");
237 if !named.is_empty() {
238 return ref_part(named);
239 }
240 let stem = match shape {
241 Shape::Bundle => root.file_name().map(|n| n.to_string_lossy().to_string()),
242 Shape::Single => root.file_name().map(|n| {
243 let n = n.to_string_lossy();
244 n.strip_suffix(".sdd.md")
245 .or_else(|| n.strip_suffix(".md"))
246 .unwrap_or(&n)
247 .to_string()
248 }),
249 };
250 ref_part(&stem.unwrap_or_default())
251}
252
253pub fn sdd_slug(inst: &Instance) -> String {
254 slug_of(&inst.meta, &inst.root, inst.shape)
255}
256
257pub fn branch_prefix(slug: &str, unit: &str) -> String {
259 format!("sdd/{slug}/{}/", ref_part(unit))
260}
261
262pub fn unit_branch(slug: &str, unit: &str, seq: i64) -> String {
264 format!("{}c{seq}", branch_prefix(slug, unit))
265}
266
267pub fn branch_seq(branch: &str) -> Option<i64> {
269 branch.rsplit('/').next()?.strip_prefix('c')?.parse().ok()
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn names_carry_the_slug_and_the_token() {
278 assert_eq!(
279 unit_branch("shop-cart", "U-001", 3),
280 "sdd/shop-cart/U-001/c3"
281 );
282 assert_eq!(branch_seq("sdd/shop-cart/U-001/c3"), Some(3));
283 assert_eq!(branch_seq("sdd/shop-cart/U-001/x3"), None);
284 let l = Layout::at(Path::new("/r"), Path::new("/w"));
285 assert_eq!(
286 l.unit_worktree("shop-cart", "U-001", 3),
287 PathBuf::from("/w/shop-cart-U-001-c3")
288 );
289 assert_eq!(
290 l.mainline("shop-cart"),
291 PathBuf::from("/w/mainline-shop-cart")
292 );
293 assert_eq!(
294 l.mainline_lock("shop-cart"),
295 PathBuf::from("/w/mainline-shop-cart.lock")
296 );
297 assert_eq!(
298 l.lane_logs("run-x", "shop-cart"),
299 PathBuf::from("/r/.vitrify/logs/run-x/shop-cart")
300 );
301 assert_eq!(
302 l.head_checkout("shop-cart"),
303 PathBuf::from(format!(
304 "/r/.vitrify/tx-{}-shop-cart-head",
305 std::process::id()
306 ))
307 );
308 assert!(l.in_tree().is_none());
309 assert_eq!(
310 Layout::at(Path::new("/r"), Path::new("/r/wt")).in_tree(),
311 Some(PathBuf::from("wt"))
312 );
313 }
314
315 #[test]
316 fn ref_part_is_always_a_legal_component() {
317 assert_eq!(ref_part("shop-cart"), "shop-cart");
318 assert_eq!(ref_part("my sdd/v2"), "my-sdd-v2");
319 assert_eq!(ref_part("..hidden"), "hidden");
320 assert_eq!(ref_part("a..b"), "a.b");
321 assert_eq!(ref_part("x.lock"), "x.lock-");
322 assert_eq!(ref_part("~^:"), "sdd");
323 }
324
325 #[test]
326 fn default_root_is_outside_the_working_tree_and_keyed_by_repository() {
327 let a = Layout::resolve(Path::new("/src/app"), Some(Path::new("/h")), "").unwrap();
328 let b = Layout::resolve(Path::new("/other/app"), Some(Path::new("/h")), "").unwrap();
329 assert!(a.wt_root.starts_with("/h/worktrees"));
330 assert!(a.in_tree().is_none());
331 assert_ne!(a.wt_root, b.wt_root, "same name, different repository");
332 let c = Layout::resolve(Path::new("/src/app"), None, "/big/disk").unwrap();
334 assert_eq!(c.wt_root, PathBuf::from("/big/disk"));
335 let d = Layout::resolve(Path::new("/src/app"), None, "vitrify-wt").unwrap();
336 assert_eq!(d.in_tree(), Some(PathBuf::from("vitrify-wt")));
337 let e = Layout::resolve(Path::new("/src/app"), None, "../app-wt").unwrap();
339 assert_eq!(e.wt_root, PathBuf::from("/src/app-wt"));
340 assert!(e.in_tree().is_none());
341 let f = Layout::resolve(Path::new("/src/app"), None, "./a/../wt").unwrap();
342 assert_eq!(f.in_tree(), Some(PathBuf::from("wt")));
343 assert!(Layout::resolve(Path::new("/src/app"), None, "").is_err());
345 }
346}