Skip to main content

vitrify_cli/
layout.rs

1//! Where vitrify keeps its working copies, and what it calls them.
2//!
3//! Two places. `<repo>/.vitrify/` is scratch nothing is ever built in:
4//! transaction worktrees, logs, `run.json`, the repo-level config. The unit
5//! worktrees and the integration checkout — where workers build and gate
6//! commands run — live **outside the working tree**, by default under the
7//! vitrify home, so that no ignore file of the repository (its own
8//! `.gitignore`, or the `*` vitrify writes into `.vitrify/`) is an ancestor
9//! of the files being checked. Tools that honour parent ignore files would
10//! otherwise treat every source file as ignored and pass without looking.
11//!
12//! Branch and worktree names carry the SDD's slug: several SDDs in one
13//! repository all have a `U-001`, and their work must never share a name.
14
15use 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/// The directories of one repository's vitrify state.
24#[derive(Debug, Clone)]
25pub struct Layout {
26    /// The primary checkout.
27    pub primary: PathBuf,
28    /// `<primary>/.vitrify` — transactions, logs, `run.json`.
29    pub scratch: PathBuf,
30    /// Root of the unit worktrees and the integration checkout.
31    pub wt_root: PathBuf,
32}
33
34impl Layout {
35    /// The layout for `primary`. `worktree_dir` is `run.worktree_dir`: empty
36    /// puts the worktrees under the vitrify home (`home`), keyed by the
37    /// repository; a relative path is taken from the repository root.
38    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    /// An explicit layout (tests, and callers that already know the root).
64    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    /// The integration checkout: a detached worktree of the mainline head.
73    pub fn mainline(&self) -> PathBuf {
74        self.wt_root.join("mainline")
75    }
76
77    /// The lock that makes integration serial across processes.
78    pub fn mainline_lock(&self) -> PathBuf {
79        self.wt_root.join("mainline.lock")
80    }
81
82    /// One claim's worktree.
83    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    /// The worktree root relative to the primary checkout, when it lies
88    /// inside it.
89    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    /// Create `.vitrify/` with the ignore file that keeps it out of the
97    /// repository. Nothing is built under it, so the `*` hides nothing a
98    /// tool needs to see.
99    pub fn ensure_scratch(&self) -> Result<(), CoreError> {
100        ensure_scratch(&self.primary).map(|_| ())
101    }
102
103    /// Create the worktree root. A root inside the working tree is added to
104    /// `.git/info/exclude`, and refused when one of the repository's own
105    /// ignore files already covers it — the case in which ignore-aware
106    /// tools check nothing there.
107    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
141/// `path` with `.` and `..` resolved by name alone (the directory need not
142/// exist yet): `../repo-wt` beside the repository is outside it, whatever
143/// the spelling.
144fn 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
161/// Create `<primary>/.vitrify` and its ignore file; returns the directory.
162pub 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
172/// `s` as one component of a git ref or a directory name: anything outside
173/// `[A-Za-z0-9._-]` becomes `-`, leading dots and dashes go, and a `.lock`
174/// suffix (which git forbids) is defused.
175pub 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
202/// The SDD's name in branch and worktree names: its `sdd:` slug, else the
203/// name of its directory (bundle) or file (single).
204pub 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
226/// `sdd/<slug>/<unit>/` — every attempt branch of one unit.
227pub fn branch_prefix(slug: &str, unit: &str) -> String {
228    format!("sdd/{slug}/{}/", ref_part(unit))
229}
230
231/// `sdd/<slug>/<unit>/c<seq>` — the branch name carries the fencing token.
232pub fn unit_branch(slug: &str, unit: &str, seq: i64) -> String {
233    format!("{}c{seq}", branch_prefix(slug, unit))
234}
235
236/// The claim sequence a branch name carries (`…/c<seq>`).
237pub 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        // an explicit directory: absolute as given, relative from the root
284        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        // beside the repository is outside it, however it is spelled
289        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        // no home and no directory: nowhere to put them
295        assert!(Layout::resolve(Path::new("/src/app"), None, "").is_err());
296    }
297}