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::model::{self, Instance, SddHandle};
31
32/// The governed files under the SDD's `scope_roots` — what git would commit
33/// at `root` — or `None` outside a git work tree, where callers walk the
34/// filesystem instead ([`core_audit::walk_scope`]).
35pub fn governed_files(root: &Path, inst: &Instance) -> Option<Vec<String>> {
36    crate::git::Git::new(root)
37        .committable_files(&inst.meta.get_list("scope_roots"))
38        .ok()
39}
40
41/// Every file git would commit at `root` — `None` outside a git work tree.
42fn committable_files(root: &Path) -> Option<Vec<String>> {
43    crate::git::Git::new(root)
44        .committable_files(&[".".to_string()])
45        .ok()
46}
47
48/// SDD resolution ([`model::resolve_sdd`]) whose repo-wide search covers
49/// only what git would commit, so git's ignore rules decide where an SDD
50/// can be found. Every verb resolves through here.
51pub fn resolve_sdd(root: &Path, sdd_arg: Option<&str>, cwd: &Path) -> Result<SddHandle, CoreError> {
52    if sdd_arg.is_some() {
53        // an explicit --sdd never searches
54        return model::resolve_sdd(root, sdd_arg, cwd);
55    }
56    model::resolve_sdd_with(root, None, cwd, committable_files(root).as_deref())
57}
58
59/// Every SDD in the repository ([`model::discover`]), searched the same way.
60pub fn discover(root: &Path) -> Vec<SddHandle> {
61    model::discover_with(root, committable_files(root).as_deref())
62}
63
64/// The SDDs of the repository at `root`, as the place an external
65/// contract's authority is looked up in — found only if something asks.
66pub fn peers(root: &Path) -> Peers<'_> {
67    Peers::new(move || discover(root))
68}
69
70/// The SDDs a verb acts on: the one `--sdd` names, or the repository's only
71/// one; with `--all`, every SDD of the repository in discovery order. None
72/// found is exit 4 either way.
73pub fn targets(
74    root: &Path,
75    sdd_arg: Option<&str>,
76    all: bool,
77    cwd: &Path,
78) -> Result<Vec<SddHandle>, CoreError> {
79    if !all {
80        return Ok(vec![resolve_sdd(root, sdd_arg, cwd)?]);
81    }
82    let found = discover(root);
83    if found.is_empty() {
84        return Err(CoreError::refusal(4, model::NO_SDD));
85    }
86    Ok(found)
87}
88
89/// `path` as output names it: from the repository root when it lies under
90/// it, as it is otherwise.
91pub fn shown(root: &Path, path: &Path) -> String {
92    let rel = path
93        .strip_prefix(root)
94        .ok()
95        .map(Path::to_path_buf)
96        .or_else(|| {
97            let (root, path) = (root.canonicalize().ok()?, path.canonicalize().ok()?);
98            path.strip_prefix(&root).ok().map(Path::to_path_buf)
99        });
100    match rel {
101        Some(rel) if rel.as_os_str().is_empty() => ".".to_string(),
102        Some(rel) => rel.to_string_lossy().replace('\\', "/"),
103        None => path.display().to_string(),
104    }
105}
106
107/// How one SDD is named where a verb reports on several: its slug, or —
108/// when it has none — where it lies.
109pub fn label(sdd: &SddHandle, root: &Path) -> String {
110    match contract::slug(sdd) {
111        "" => shown(root, &sdd.root),
112        slug => slug.to_string(),
113    }
114}
115
116/// One verb run over several SDDs: `one` is run for each — an error from
117/// one is reported under its name and the rest still run — and the exit
118/// code is the worst of theirs: an unexpected error before any refusal or
119/// finding.
120pub fn each(
121    root: &Path,
122    sdds: &[SddHandle],
123    mut one: impl FnMut(&SddHandle) -> Result<u8, CoreError>,
124) -> u8 {
125    let mut codes: Vec<u8> = Vec::new();
126    for sdd in sdds {
127        codes.push(match one(sdd) {
128            Ok(code) => code,
129            Err(e) => {
130                let text = e.to_string();
131                crate::out::diag(&format!(
132                    "{}: {}",
133                    label(sdd, root),
134                    text.strip_prefix("error: ").unwrap_or(&text)
135                ));
136                e.exit_code()
137            }
138        });
139    }
140    if codes.contains(&1) {
141        1
142    } else {
143        codes.into_iter().max().unwrap_or(0)
144    }
145}
146
147/// An SDD's root relative to the root of the checkout it was resolved in —
148/// the one name for it that holds in every checkout of the repository (the
149/// primary, a unit worktree, the integration checkout, a transaction).
150/// `None` when the SDD lies outside that checkout.
151pub fn sdd_rel(checkout: &Path, sdd_root: &Path) -> Option<PathBuf> {
152    if let Ok(rel) = sdd_root.strip_prefix(checkout) {
153        return Some(rel.to_path_buf());
154    }
155    let checkout = checkout.canonicalize().ok()?;
156    let sdd_root = sdd_root.canonicalize().ok()?;
157    sdd_root.strip_prefix(&checkout).ok().map(Path::to_path_buf)
158}
159
160/// Resolve the SDD at `rel` ([`sdd_rel`]) inside `checkout`. Never searches:
161/// a repository with several SDDs resolves the same one everywhere.
162pub fn resolve_sdd_in(checkout: &Path, rel: &Path) -> Result<SddHandle, CoreError> {
163    let at = checkout.join(rel);
164    model::resolve_sdd(checkout, Some(&at.to_string_lossy()), checkout)
165}
166
167/// `rel` as a `--sdd` argument that works from any checkout's root.
168pub fn sdd_arg(rel: &Path) -> String {
169    let s = rel.to_string_lossy().replace('\\', "/");
170    if s.is_empty() { ".".to_string() } else { s }
171}
172
173/// `opts` with the governed-file listing filled in from git — every audit
174/// call goes through here, so the orphan scan follows git's ignore rules.
175pub fn audit_options(
176    mut opts: core_audit::Options,
177    root: &Path,
178    inst: &Instance,
179) -> core_audit::Options {
180    opts.scope_files = governed_files(root, inst);
181    opts
182}
183
184/// The repository containing the current working directory:
185/// `git rev-parse --show-toplevel`, else cwd.
186pub fn repo_root() -> PathBuf {
187    let out = Command::new("git")
188        .args(["rev-parse", "--show-toplevel"])
189        .output();
190    if let Ok(o) = out
191        && o.status.success()
192        && let Ok(s) = String::from_utf8(o.stdout)
193    {
194        let trimmed = s.trim();
195        if !trimmed.is_empty() {
196            return PathBuf::from(trimmed);
197        }
198    }
199    cwd()
200}
201
202pub fn cwd() -> PathBuf {
203    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
204}
205
206/// Home-dir resolution: `$VITRIFY_HOME` if set, else `$HOME/.vitrify`.
207pub fn home_dir() -> Option<PathBuf> {
208    if let Ok(h) = std::env::var("VITRIFY_HOME")
209        && !h.is_empty()
210    {
211        return Some(PathBuf::from(h));
212    }
213    std::env::var("HOME")
214        .ok()
215        .filter(|h| !h.is_empty())
216        .map(|h| PathBuf::from(h).join(".vitrify"))
217}
218
219/// Load configuration with its precedence: environment, the repository's
220/// `.vitrify/config.toml`, `~/.vitrify/config.toml`, the default.
221pub fn load_config(overrides: &Overrides) -> Result<Config, CoreError> {
222    let env: Vec<(String, String)> = std::env::vars()
223        .filter(|(k, _)| k.starts_with("VITRIFY_"))
224        .collect();
225    config::load(Some(&repo_root()), home_dir().as_deref(), &env, overrides)
226}