Skip to main content

vitrify_cli/cmd/
mod.rs

1//! Command implementations and the shared invocation context.
2
3pub mod audit;
4pub mod brief;
5pub mod change;
6pub mod check;
7pub mod claim;
8pub mod init;
9pub mod journal;
10pub mod ledger;
11pub mod lint;
12pub mod locate;
13pub mod new;
14pub mod pin;
15pub mod probe;
16pub mod questions;
17pub mod readset;
18pub mod run;
19pub mod run_status;
20pub mod schema;
21pub mod trace;
22
23use std::path::{Path, PathBuf};
24use std::process::Command;
25
26use vitrify_core::CoreError;
27use vitrify_core::audit as core_audit;
28use vitrify_core::config::{self, Config, Overrides};
29use vitrify_core::contract::{self, Peers};
30use vitrify_core::graph::UnitGraph;
31use vitrify_core::model::{self, Instance, SddHandle};
32
33/// The governed files under the SDD's `scope_roots` — what git would commit
34/// at `root` — or `None` outside a git work tree, where callers walk the
35/// filesystem instead ([`core_audit::walk_scope`]).
36pub fn governed_files(root: &Path, inst: &Instance) -> Option<Vec<String>> {
37    crate::git::Git::new(root)
38        .committable_files(&inst.meta.get_list("scope_roots"))
39        .ok()
40}
41
42/// Every file git would commit at `root` — `None` outside a git work tree.
43fn committable_files(root: &Path) -> Option<Vec<String>> {
44    crate::git::Git::new(root)
45        .committable_files(&[".".to_string()])
46        .ok()
47}
48
49/// SDD resolution ([`model::resolve_sdd`]) whose repo-wide search covers
50/// only what git would commit, so git's ignore rules decide where an SDD
51/// can be found. Every verb resolves through here.
52pub fn resolve_sdd(root: &Path, sdd_arg: Option<&str>, cwd: &Path) -> Result<SddHandle, CoreError> {
53    if sdd_arg.is_some() {
54        // an explicit --sdd never searches
55        return model::resolve_sdd(root, sdd_arg, cwd);
56    }
57    model::resolve_sdd_with(root, None, cwd, committable_files(root).as_deref())
58}
59
60/// Every SDD in the repository ([`model::discover`]), searched the same way.
61pub fn discover(root: &Path) -> Vec<SddHandle> {
62    model::discover_with(root, committable_files(root).as_deref())
63}
64
65/// The SDDs of the repository at `root`, as the place an external
66/// contract's authority is looked up in — found only if something asks.
67pub fn peers(root: &Path) -> Peers<'_> {
68    Peers::new(move || discover(root))
69}
70
71/// The SDDs of the repository at `root` that load, each with the error of
72/// one that does not (a schema version this vitrify does not read), in
73/// discovery order. `own`, loaded already, stands in for its discovered
74/// copy, or joins them when discovery does not find it.
75pub fn loaded(root: &Path, own: Option<&Instance>) -> (Vec<Instance>, Vec<(SddHandle, CoreError)>) {
76    let mut insts: Vec<Instance> = Vec::new();
77    let mut refused: Vec<(SddHandle, CoreError)> = Vec::new();
78    for h in discover(root) {
79        if let Some(own) = own
80            && same_root(&h.root, &own.root)
81        {
82            insts.push(own.clone());
83            continue;
84        }
85        match Instance::load(h.clone()) {
86            Ok(inst) => insts.push(inst),
87            Err(e) => refused.push((h, e)),
88        }
89    }
90    if let Some(own) = own
91        && !insts.iter().any(|i| same_root(&i.root, &own.root))
92    {
93        insts.push(own.clone());
94    }
95    (insts, refused)
96}
97
98fn same_root(a: &Path, b: &Path) -> bool {
99    a == b || matches!((a.canonicalize(), b.canonicalize()), (Ok(x), Ok(y)) if x == y)
100}
101
102/// The repository's unit graph over every SDD that loads ([`loaded`]):
103/// what pins in `depends_on` resolve against.
104pub fn repo_graph(root: &Path, own: Option<&Instance>) -> Result<UnitGraph, CoreError> {
105    UnitGraph::build(&loaded(root, own).0)
106}
107
108/// Whether a unit of `inst` names, in `depends_on`, anything but a unit of
109/// its own SDD — so its claimability needs the repository's graph.
110pub fn reaches_out(inst: &Instance) -> bool {
111    inst.units.iter().any(|u| {
112        u.meta
113            .get_list("depends_on")
114            .iter()
115            .any(|d| inst.unit(d).is_none())
116    })
117}
118
119/// The SDDs a verb acts on: the one `--sdd` names, or the repository's only
120/// one; with `--all`, every SDD of the repository in discovery order. None
121/// found is exit 4 either way.
122pub fn targets(
123    root: &Path,
124    sdd_arg: Option<&str>,
125    all: bool,
126    cwd: &Path,
127) -> Result<Vec<SddHandle>, CoreError> {
128    if !all {
129        return Ok(vec![resolve_sdd(root, sdd_arg, cwd)?]);
130    }
131    let found = discover(root);
132    if found.is_empty() {
133        return Err(CoreError::refusal(4, model::NO_SDD));
134    }
135    Ok(found)
136}
137
138/// `path` as output names it: from the repository root when it lies under
139/// it, as it is otherwise.
140pub fn shown(root: &Path, path: &Path) -> String {
141    let rel = path
142        .strip_prefix(root)
143        .ok()
144        .map(Path::to_path_buf)
145        .or_else(|| {
146            let (root, path) = (root.canonicalize().ok()?, path.canonicalize().ok()?);
147            path.strip_prefix(&root).ok().map(Path::to_path_buf)
148        });
149    match rel {
150        Some(rel) if rel.as_os_str().is_empty() => ".".to_string(),
151        Some(rel) => rel.to_string_lossy().replace('\\', "/"),
152        None => path.display().to_string(),
153    }
154}
155
156/// How one SDD is named where a verb reports on several: its slug, or —
157/// when it has none — where it lies.
158pub fn label(sdd: &SddHandle, root: &Path) -> String {
159    match contract::slug(sdd) {
160        "" => shown(root, &sdd.root),
161        slug => slug.to_string(),
162    }
163}
164
165/// One verb run over several SDDs: `one` is run for each — an error from
166/// one is reported under its name and the rest still run — and the exit
167/// code is the worst of theirs: an unexpected error before any refusal or
168/// finding.
169pub fn each(
170    root: &Path,
171    sdds: &[SddHandle],
172    mut one: impl FnMut(&SddHandle) -> Result<u8, CoreError>,
173) -> u8 {
174    let mut codes: Vec<u8> = Vec::new();
175    for sdd in sdds {
176        codes.push(match one(sdd) {
177            Ok(code) => code,
178            Err(e) => {
179                let text = e.to_string();
180                crate::out::diag(&format!(
181                    "{}: {}",
182                    label(sdd, root),
183                    text.strip_prefix("error: ").unwrap_or(&text)
184                ));
185                e.exit_code()
186            }
187        });
188    }
189    if codes.contains(&1) {
190        1
191    } else {
192        codes.into_iter().max().unwrap_or(0)
193    }
194}
195
196/// An SDD's root relative to the root of the checkout it was resolved in —
197/// the one name for it that holds in every checkout of the repository (the
198/// primary, a unit worktree, the integration checkout, a transaction).
199/// `None` when the SDD lies outside that checkout.
200pub fn sdd_rel(checkout: &Path, sdd_root: &Path) -> Option<PathBuf> {
201    if let Ok(rel) = sdd_root.strip_prefix(checkout) {
202        return Some(rel.to_path_buf());
203    }
204    let checkout = checkout.canonicalize().ok()?;
205    let sdd_root = sdd_root.canonicalize().ok()?;
206    sdd_root.strip_prefix(&checkout).ok().map(Path::to_path_buf)
207}
208
209/// Resolve the SDD at `rel` ([`sdd_rel`]) inside `checkout`. Never searches:
210/// a repository with several SDDs resolves the same one everywhere.
211pub fn resolve_sdd_in(checkout: &Path, rel: &Path) -> Result<SddHandle, CoreError> {
212    let at = checkout.join(rel);
213    model::resolve_sdd(checkout, Some(&at.to_string_lossy()), checkout)
214}
215
216/// `rel` as a `--sdd` argument that works from any checkout's root.
217pub fn sdd_arg(rel: &Path) -> String {
218    let s = rel.to_string_lossy().replace('\\', "/");
219    if s.is_empty() { ".".to_string() } else { s }
220}
221
222/// `opts` with the governed-file listing filled in from git — every audit
223/// call goes through here, so the orphan scan follows git's ignore rules.
224pub fn audit_options(
225    mut opts: core_audit::Options,
226    root: &Path,
227    inst: &Instance,
228) -> core_audit::Options {
229    opts.scope_files = governed_files(root, inst);
230    opts
231}
232
233/// The repository containing the current working directory:
234/// `git rev-parse --show-toplevel`, else cwd.
235pub fn repo_root() -> PathBuf {
236    let out = Command::new("git")
237        .args(["rev-parse", "--show-toplevel"])
238        .output();
239    if let Ok(o) = out
240        && o.status.success()
241        && let Ok(s) = String::from_utf8(o.stdout)
242    {
243        let trimmed = s.trim();
244        if !trimmed.is_empty() {
245            return PathBuf::from(trimmed);
246        }
247    }
248    cwd()
249}
250
251pub fn cwd() -> PathBuf {
252    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
253}
254
255/// Home-dir resolution: `$VITRIFY_HOME` if set, else `$HOME/.vitrify`.
256pub fn home_dir() -> Option<PathBuf> {
257    if let Ok(h) = std::env::var("VITRIFY_HOME")
258        && !h.is_empty()
259    {
260        return Some(PathBuf::from(h));
261    }
262    std::env::var("HOME")
263        .ok()
264        .filter(|h| !h.is_empty())
265        .map(|h| PathBuf::from(h).join(".vitrify"))
266}
267
268/// Load configuration with its precedence: environment, the repository's
269/// `.vitrify/config.toml`, `~/.vitrify/config.toml`, the default.
270pub fn load_config(overrides: &Overrides) -> Result<Config, CoreError> {
271    let env: Vec<(String, String)> = std::env::vars()
272        .filter(|(k, _)| k.starts_with("VITRIFY_"))
273        .collect();
274    config::load(Some(&repo_root()), home_dir().as_deref(), &env, overrides)
275}