Skip to main content

vitrify_cli/cmd/
ledger.rs

1//! `vitrify ledger regen|progress` — derived ledger output.
2//! Regen message on stderr, progress line on stdout. `regen --check`
3//! writes nothing: it compares the ledger on disk with a fresh derivation
4//! and exits 3 when they differ.
5
6use std::path::Path;
7
8use vitrify_core::ledger::Check;
9use vitrify_core::model::{Instance, SddHandle, UtcTime};
10use vitrify_core::{CoreError, ledger};
11
12use crate::out::{diag, emit};
13
14/// Run `one` over the SDDs the flags name; with `--all` every line it
15/// prints is given the SDD's name (`one` receives the prefix).
16fn over(
17    sdd: Option<&str>,
18    all: bool,
19    one: impl Fn(&Path, &Instance, &str) -> Result<u8, CoreError>,
20) -> Result<u8, CoreError> {
21    let root = super::repo_root();
22    let sdds = super::targets(&root, sdd, all, &super::cwd())?;
23    if !all {
24        return one(&root, &Instance::load(sdds[0].clone())?, "");
25    }
26    Ok(super::each(&root, &sdds, |sdd: &SddHandle| {
27        let under = format!("{}: ", super::label(sdd, &root));
28        one(&root, &Instance::load(sdd.clone())?, &under)
29    }))
30}
31
32/// `regen --check` for one SDD, printing nothing: `None` when the ledger on
33/// disk is what a regeneration would write — or, unless `required`, when
34/// there is none — else `(subject, cause)`, the subject the ledger's file
35/// from the SDD's root.
36pub fn mismatch(inst: &Instance, required: bool) -> Result<Option<(String, String)>, CoreError> {
37    let today = UtcTime::now().format_date();
38    let name = |path: &Path| {
39        let rel = path
40            .strip_prefix(&inst.root)
41            .ok()
42            .filter(|r| !r.as_os_str().is_empty())
43            .or_else(|| path.file_name().map(Path::new))
44            .unwrap_or(path);
45        rel.to_string_lossy().replace('\\', "/")
46    };
47    Ok(match ledger::check(inst, &today)? {
48        Check::Current(_) => None,
49        Check::Missing(_) if !required => None,
50        Check::Missing(path) => Some((name(&path), "holds no ledger".to_string())),
51        Check::Differs {
52            path,
53            line,
54            derived,
55            found,
56        } => Some((
57            name(&path),
58            format!(
59                "line {line} differs from its derivation (derived `{derived}`, on disk `{found}`)"
60            ),
61        )),
62    })
63}
64
65pub fn regen(sdd: Option<&str>, all: bool, check: bool) -> Result<u8, CoreError> {
66    let today = UtcTime::now().format_date();
67    over(sdd, all, |root, inst, under| {
68        if check {
69            return Ok(match ledger::check(inst, &today)? {
70                Check::Current(path) => {
71                    emit(&format!(
72                        "{under}ledger current ({})",
73                        super::shown(root, &path)
74                    ));
75                    0
76                }
77                Check::Missing(path) => {
78                    emit(&format!(
79                        "{under}ledger missing: {} holds none — run `vitrify ledger regen`",
80                        super::shown(root, &path)
81                    ));
82                    3
83                }
84                Check::Differs {
85                    path,
86                    line,
87                    derived,
88                    found,
89                } => {
90                    emit(&format!(
91                        "{under}ledger differs from its derivation at {}:{line} — run `vitrify ledger regen`",
92                        super::shown(root, &path)
93                    ));
94                    emit(&format!("{under}  derived: {derived}"));
95                    emit(&format!("{under}  on disk: {found}"));
96                    3
97                }
98            });
99        }
100        let (_, msg) = ledger::regen(inst, &today)?;
101        diag(&msg);
102        emit(&format!("{under}{}", ledger::progress_line(&inst.units)));
103        Ok(0)
104    })
105}
106
107pub fn progress(sdd: Option<&str>, all: bool) -> Result<u8, CoreError> {
108    over(sdd, all, |_, inst, under| {
109        emit(&format!("{under}{}", ledger::progress_line(&inst.units)));
110        Ok(0)
111    })
112}