Skip to main content

vgi_cli/
report.rs

1//! What `vgi repo init` prints for each step.
2
3use std::io::Write;
4
5/// What a step did — or, under `--dry-run`, would do.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Change {
8    /// Already as the plan wants it; nothing sent.
9    Unchanged,
10    /// Absent; created.
11    Create,
12    /// Present but different; rewritten.
13    Update,
14    /// Present and no longer wanted; removed.
15    Remove,
16}
17
18impl Change {
19    fn label(self, dry_run: bool) -> &'static str {
20        match (self, dry_run) {
21            (Change::Unchanged, _) => "unchanged",
22            (Change::Create, false) => "created",
23            (Change::Update, false) => "updated",
24            (Change::Remove, false) => "removed",
25            (Change::Create, true) => "would create",
26            (Change::Update, true) => "would update",
27            (Change::Remove, true) => "would remove",
28        }
29    }
30}
31
32/// Where step lines go, and whether they describe changes made or planned.
33pub struct Report<'w> {
34    out: &'w mut dyn Write,
35    dry_run: bool,
36    changes: usize,
37}
38
39impl<'w> Report<'w> {
40    /// A report to `out`.
41    pub fn new(out: &'w mut dyn Write, dry_run: bool) -> Self {
42        Report {
43            out,
44            dry_run,
45            changes: 0,
46        }
47    }
48
49    /// Whether nothing is being written.
50    pub fn dry_run(&self) -> bool {
51        self.dry_run
52    }
53
54    /// How many steps changed (or would change) something.
55    pub fn changes(&self) -> usize {
56        self.changes
57    }
58
59    /// A free-form line.
60    pub fn line(&mut self, text: impl AsRef<str>) {
61        // A closed stdout is not worth failing a half-applied plan over.
62        let _ = writeln!(self.out, "{}", text.as_ref());
63    }
64
65    /// One step's outcome. `preview` — the file or request body — is shown
66    /// only for a change under `--dry-run`, so the person sees every byte
67    /// that would be written before anything is.
68    pub fn step(&mut self, id: &str, subject: &str, change: Change, preview: Option<&str>) {
69        if change != Change::Unchanged {
70            self.changes += 1;
71        }
72        self.line(format!(
73            "  [{:<12}] {id:<36} {subject}",
74            change.label(self.dry_run)
75        ));
76        if self.dry_run
77            && change != Change::Unchanged
78            && let Some(p) = preview
79        {
80            for l in p.lines() {
81                self.line(format!("      | {l}"));
82            }
83        }
84    }
85}