1use std::path::Path;
11
12use vitrify_core::audit::{self, Options, StateEdit};
13use vitrify_core::changelog::{self, Bump};
14use vitrify_core::contract::{self, State};
15use vitrify_core::journal::{self, Event};
16use vitrify_core::model::{self, Instance, SddHandle, Shape, UtcTime};
17use vitrify_core::{CoreError, ledger, yamlish};
18
19use crate::out::{J, diag, emit};
20
21pub struct ApplyFlags {
22 pub sdd: Option<String>,
23 pub all: bool,
25 pub dry_run: bool,
27 pub commit: Option<String>,
29 pub json: bool,
30}
31
32#[derive(Clone, Copy, PartialEq, Eq)]
34enum Action {
35 Applied,
36 AlreadyRecorded,
37 NotActive,
39 NoEntry,
40}
41
42impl Action {
43 fn as_str(self) -> &'static str {
44 match self {
45 Action::Applied => "applied",
46 Action::AlreadyRecorded => "already-recorded",
47 Action::NotActive => "draft",
48 Action::NoEntry => "no-entry",
49 }
50 }
51}
52
53struct Report {
55 label: String,
56 root: String,
57 status: String,
59 action: Action,
60 entry: Option<String>,
61 from: Option<String>,
62 to: Option<String>,
63 bump: Option<Bump>,
64 restamped: Vec<String>,
65 stale: Vec<String>,
66 changelog: String,
68}
69
70impl Report {
71 fn staleness(&self) -> String {
72 if self.stale.is_empty() {
73 "- Staleness applied: —".to_string()
74 } else {
75 format!("- Staleness applied: {} → Stale", self.stale.join(", "))
76 }
77 }
78
79 fn transition(&self) -> String {
80 let mut t = match (&self.from, &self.to) {
81 (Some(from), Some(to)) => format!("{from} → {to}"),
82 (None, Some(to)) => format!("→ {to}"),
83 (Some(from), None) => format!("{from} →"),
84 (None, None) => String::new(),
85 };
86 if let Some(b) = self.bump {
87 t.push_str(&format!(" ({})", b.as_str()));
88 }
89 t
90 }
91
92 fn lines(&self) -> Vec<String> {
93 let at = &self.label;
94 let entry = self.entry.as_deref().unwrap_or("");
95 match self.action {
96 Action::NotActive => vec![format!("{at}: {} — nothing to apply", self.status)],
97 Action::NoEntry => vec![format!("{at}: no change entry — nothing to apply")],
98 Action::AlreadyRecorded => {
99 vec![format!("{at}: {entry} already recorded — nothing to apply")]
100 }
101 Action::Applied => {
102 let what = if self.bump == Some(Bump::Patch) {
103 if self.restamped.is_empty() {
104 "no trace to re-record".to_string()
105 } else {
106 format!("traces of {} re-recorded", self.restamped.join(", "))
107 }
108 } else if self.stale.is_empty() {
109 "no unit marked Stale".to_string()
110 } else {
111 format!("{} marked Stale", self.stale.join(", "))
112 };
113 let head = match self.transition() {
114 t if t.is_empty() => format!("{at}: {entry}: {what}"),
115 t => format!("{at}: {entry} {t}: {what}"),
116 };
117 vec![head, format!("{at}: {}", self.staleness())]
118 }
119 }
120 }
121
122 fn json(&self, dry_run: bool) -> J {
123 let units = |us: &[String]| J::Arr(us.iter().map(|u| J::s(u.clone())).collect());
124 J::Obj(vec![
125 ("sdd".into(), J::s(self.label.clone())),
126 ("root".into(), J::s(self.root.clone())),
127 ("entry".into(), J::opt_str(self.entry.clone())),
128 ("from".into(), J::opt_str(self.from.clone())),
129 ("to".into(), J::opt_str(self.to.clone())),
130 (
131 "bump".into(),
132 J::opt_str(self.bump.map(|b| b.as_str().to_string())),
133 ),
134 ("action".into(), J::s(self.action.as_str())),
135 ("restamped".into(), units(&self.restamped)),
136 ("stale".into(), units(&self.stale)),
137 (
138 "staleness_line".into(),
139 J::opt_str((self.action == Action::Applied).then(|| self.staleness())),
140 ),
141 ("dry_run".into(), J::Bool(dry_run)),
142 ])
143 }
144}
145
146struct Refused(Vec<String>);
148
149fn event(inst: &Instance, events: &[Event], kind: &str, commit: Option<&str>) -> Event {
150 Event {
151 seq: journal::next_seq(events),
152 at: UtcTime::now().format(),
153 event: kind.to_string(),
154 sdd: inst.meta.get_str_or("version", "0.0.0").to_string(),
155 commit: commit.map(str::to_string),
156 ..Default::default()
157 }
158}
159
160fn append(inst: &Instance, e: Event) -> Result<(), CoreError> {
161 journal::append_line(&inst.handle(), &journal::render_line(&e))?;
162 Ok(())
163}
164
165fn moved(root: &Path, inst: &Instance) -> Result<Vec<(String, String)>, CoreError> {
170 let opts = super::audit_options(
171 Options {
172 skip_rotten: true,
173 apply_stale: true,
174 ..Default::default()
175 },
176 root,
177 inst,
178 );
179 let (_, edits) = audit::run(inst, root, &opts, &crate::gate::ShRunner, UtcTime::now())?;
180 Ok(edits
181 .into_iter()
182 .filter_map(|edit| match edit {
183 StateEdit::ApplyStale { unit, cause } => Some((unit, cause)),
184 StateEdit::FixLease { .. } => None,
185 })
186 .filter(|(unit, _)| {
187 inst.unit(unit)
188 .and_then(|u| u.meta.get_map("trace"))
189 .is_some_and(|t| !t.is_empty())
190 })
191 .collect())
192}
193
194fn apply_one(
195 root: &Path,
196 sdd: &SddHandle,
197 flags: &ApplyFlags,
198) -> Result<Result<Report, Refused>, CoreError> {
199 let inst = Instance::load(sdd.clone())?;
200 let handle = inst.handle();
201 let label = super::label(sdd, root);
202 let shown_root = super::shown(root, &sdd.root);
203 let changelog_path = match handle.shape {
204 Shape::Bundle => handle.root.join("changelog.md"),
205 Shape::Single => handle.file.clone(),
206 };
207 let mut report = Report {
208 label: label.clone(),
209 root: shown_root.clone(),
210 status: inst.meta.get_str_or("status", "Draft").trim().to_string(),
211 action: Action::NotActive,
212 entry: None,
213 from: None,
214 to: None,
215 bump: None,
216 restamped: Vec::new(),
217 stale: Vec::new(),
218 changelog: super::shown(root, &changelog_path),
219 };
220 if report.status != "Active" {
221 return Ok(Ok(report));
222 }
223 let misplaced = changelog::misplaced(&handle)?;
226 if !misplaced.is_empty() {
227 return Ok(Err(Refused(
228 misplaced
229 .iter()
230 .map(|(id, hashes)| {
231 let (cause, fix) = changelog::misplaced_finding(id, *hashes);
232 format!(
233 "error: {label}: {id}: {cause} → {fix}, then run vitrify change apply --sdd {shown_root}"
234 )
235 })
236 .collect(),
237 )));
238 }
239 let entries = changelog::entries(&handle)?;
240 let Some(last) = changelog::last(&entries) else {
241 report.action = Action::NoEntry;
242 return Ok(Ok(report));
243 };
244 report.entry = Some(last.id.clone());
245 report.from = changelog::from_version(&entries, last);
246 report.to = last.to.clone();
247 report.bump = match (&report.from, &report.to) {
248 (Some(from), Some(to)) => changelog::bump(from, to),
249 _ => None,
250 };
251 let (events, _) = journal::read(&handle)?;
252 if journal::records_change(&events, &last.id) {
253 report.action = Action::AlreadyRecorded;
254 return Ok(Ok(report));
255 }
256
257 let mut refused = Vec::new();
259 let version = inst.meta.get_str_or("version", "");
260 let updated = inst.meta.get_str_or("updated", "");
261 for (subject, cause) in changelog::findings(&entries, version, updated) {
262 if subject == "version" || subject == "updated" {
263 refused.push(format!(
264 "error: {label}: {subject}: {cause} → set version and updated to {}'s, then run vitrify change apply --sdd {shown_root}",
265 last.id
266 ));
267 }
268 }
269 for ext in contract::examine(&inst, &super::peers(root))? {
270 if ext.state == State::Stale {
271 refused.push(format!(
272 "error: {label}: {}'s pin is stale → vitrify pin sync --sdd {shown_root} first",
273 ext.id
274 ));
275 }
276 }
277 let moved = moved(root, &inst)?;
278 if report.bump.is_none() && !moved.is_empty() {
279 refused.push(format!(
280 "error: {label}: {}'s heading names no version bump ({}) and traces moved → write its transition, <from> → <to>, in the heading",
281 last.id,
282 match report.transition() {
283 t if t.is_empty() => "no →".to_string(),
284 t => t,
285 }
286 ));
287 }
288 if !refused.is_empty() {
289 return Ok(Err(Refused(refused)));
290 }
291
292 report.action = Action::Applied;
293 let commit = flags.commit.as_deref();
294 let mut change = event(&inst, &events, "change", commit);
295 change.entry = Some(last.id.clone());
296 if report.bump == Some(Bump::Patch) {
297 let mut traces = Vec::new();
300 for (unit, _) in &moved {
301 let Some(u) = inst.unit(unit) else { continue };
302 traces.push((u.clone(), super::trace::current(&inst, u)?));
303 }
304 report.restamped = traces.iter().map(|(u, _)| u.unit.clone()).collect();
305 if !flags.dry_run {
306 for (u, t) in &traces {
307 super::trace::restamp(&inst, u, t)?;
308 }
309 append(&inst, change)?;
310 }
311 } else {
312 report.stale = moved.iter().map(|(u, _)| u.clone()).collect();
313 if !flags.dry_run {
314 if !report.stale.is_empty() {
315 change.stale = Some(report.stale.clone());
316 }
317 append(&inst, change)?;
318 for (unit, cause) in &moved {
319 let Some(u) = inst.unit(unit) else { continue };
320 model::rewrite_unit_meta(&handle, u, |inner| {
321 yamlish::set_scalar_in_place(inner, "status", "Stale")
322 })?;
323 let (events, _) = journal::read(&handle)?;
324 let mut stale = event(&inst, &events, "stale", commit);
326 stale.unit = Some(unit.clone());
327 stale.actor = Some("audit".to_string());
328 stale.cause = Some(cause.clone());
329 append(&inst, stale)?;
330 }
331 }
332 }
333 if !flags.dry_run {
334 let fresh = Instance::load(inst.handle())?;
335 ledger::regen(&fresh, &UtcTime::now().format_date())?;
336 }
337 Ok(Ok(report))
338}
339
340fn report_one(
343 root: &Path,
344 sdd: &SddHandle,
345 flags: &ApplyFlags,
346 json_out: &mut Vec<J>,
347) -> Result<u8, CoreError> {
348 match apply_one(root, sdd, flags)? {
349 Err(Refused(lines)) => {
350 for line in lines {
351 diag(&line);
352 }
353 Ok(2)
354 }
355 Ok(report) => {
356 if flags.json {
357 json_out.push(report.json(flags.dry_run));
358 } else {
359 for line in report.lines() {
360 emit(&line);
361 }
362 }
363 if report.action == Action::Applied && !flags.dry_run {
364 diag(&format!(
365 "next: copy the Staleness applied line into {} ({}), then run vitrify check",
366 report.entry.as_deref().unwrap_or(""),
367 report.changelog
368 ));
369 }
370 Ok(0)
371 }
372 }
373}
374
375pub fn apply(flags: ApplyFlags) -> Result<u8, CoreError> {
376 let root = super::repo_root();
377 let sdds = super::targets(&root, flags.sdd.as_deref(), flags.all, &super::cwd())?;
378 let mut json_out: Vec<J> = Vec::new();
379 let code = if flags.all {
380 let code = super::each(&root, &sdds, |sdd| {
381 report_one(&root, sdd, &flags, &mut json_out)
382 });
383 if flags.json {
384 emit(&J::Arr(json_out).dumps_indent2());
385 }
386 code
387 } else {
388 let code = report_one(&root, &sdds[0], &flags, &mut json_out)?;
389 if let Some(obj) = json_out.pop() {
390 emit(&obj.dumps_indent2());
391 }
392 code
393 };
394 if flags.dry_run {
395 diag("dry run: nothing written");
396 }
397 Ok(code)
398}