1pub 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
33pub 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
42fn committable_files(root: &Path) -> Option<Vec<String>> {
44 crate::git::Git::new(root)
45 .committable_files(&[".".to_string()])
46 .ok()
47}
48
49pub fn resolve_sdd(root: &Path, sdd_arg: Option<&str>, cwd: &Path) -> Result<SddHandle, CoreError> {
53 if sdd_arg.is_some() {
54 return model::resolve_sdd(root, sdd_arg, cwd);
56 }
57 model::resolve_sdd_with(root, None, cwd, committable_files(root).as_deref())
58}
59
60pub fn discover(root: &Path) -> Vec<SddHandle> {
62 model::discover_with(root, committable_files(root).as_deref())
63}
64
65pub fn peers(root: &Path) -> Peers<'_> {
68 Peers::new(move || discover(root))
69}
70
71pub 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
102pub fn repo_graph(root: &Path, own: Option<&Instance>) -> Result<UnitGraph, CoreError> {
105 UnitGraph::build(&loaded(root, own).0)
106}
107
108pub 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
119pub 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
138pub 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
156pub 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
165pub 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
196pub 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
209pub 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
216pub 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
222pub 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
233pub 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
255pub 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
268pub 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}