Skip to main content

bynk/
report.rs

1//! Render a [`Report`] in one of three shapes.
2//!
3//! The default human table is for a person at a terminal; `--format short` (one
4//! `capability: level (remedy)` line) and `--format json` are the **pinned
5//! scriptable surface** (golden-tested), siblings to `bynk check --format
6//! short` (ADR 0071).
7
8use crate::doctor::{Capability, CapabilityReport, Level, Report};
9
10/// Output selector.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum Format {
13    #[default]
14    Human,
15    Short,
16    Json,
17}
18
19/// The displayed status word for a capability. Optional capabilities show
20/// `note` instead of `fail` when their tool is merely absent — a missing editor
21/// is a note, not a failure.
22fn level_word(cap: &CapabilityReport) -> &'static str {
23    match cap.level {
24        Level::Ok => "ok",
25        Level::Warn => "warn",
26        Level::Fail if cap.optional => "note",
27        Level::Fail => "fail",
28    }
29}
30
31pub fn render(report: &Report, format: Format) -> String {
32    render_coloured(report, format, false)
33}
34
35/// [`render`], with the human table's marks coloured when `colour` is on: an
36/// ok capability green, a warning yellow, a failure red. `short` and `json`
37/// are never coloured.
38pub fn render_coloured(report: &Report, format: Format, colour: bool) -> String {
39    match format {
40        Format::Human => human(report, colour),
41        Format::Short => short(report),
42        Format::Json => json(report),
43    }
44}
45
46fn short(report: &Report) -> String {
47    let mut out = String::new();
48    for cap in &report.capabilities {
49        let word = level_word(cap);
50        // The first non-ok row's remedy is the actionable hint for the line.
51        let remedy = cap
52            .rows
53            .iter()
54            .find(|r| r.level != Level::Ok)
55            .and_then(|r| r.remedy.as_deref());
56        match remedy {
57            Some(r) => out.push_str(&format!("{}: {word} ({r})\n", cap.capability.token())),
58            None => out.push_str(&format!("{}: {word}\n", cap.capability.token())),
59        }
60    }
61    out
62}
63
64fn human(report: &Report, colour: bool) -> String {
65    use bynk_driver::colour::{Style, paint};
66    let mut out = String::new();
67    let header = if report.is_all_ok() {
68        "bynk doctor — your environment is ready".to_string()
69    } else {
70        "bynk doctor — environment report".to_string()
71    };
72    out.push_str(&header);
73    out.push('\n');
74    out.push_str(&format!("driver: bynk {}\n", report.driver_version));
75    out.push_str("compiler: in-process\n");
76    out.push('\n');
77
78    for cap in &report.capabilities {
79        let mark = match cap.level {
80            Level::Ok => "✓",
81            Level::Warn => "!",
82            Level::Fail if cap.optional => "·",
83            Level::Fail => "✗",
84        };
85        let style = match cap.level {
86            Level::Ok => Some(Style::Green),
87            Level::Warn => Some(Style::Amber),
88            Level::Fail if cap.optional => None,
89            Level::Fail => Some(Style::Red),
90        };
91        let paint = |text: &str| match style {
92            Some(style) => paint(colour, style, text),
93            None => paint(colour, Style::Blue, text),
94        };
95        out.push_str(&format!(
96            "{} {} [{}]{}\n",
97            paint(mark),
98            cap.capability.token(),
99            paint(level_word(cap)),
100            if cap.optional { " (optional)" } else { "" }
101        ));
102        for row in &cap.rows {
103            out.push_str(&format!("    {} — {}\n", row.label, row.detail));
104            if let Some(remedy) = &row.remedy {
105                out.push_str(&format!("      ↳ fix: {remedy}\n"));
106            }
107        }
108    }
109    out
110}
111
112// The JSON surface is built from `#[derive(Serialize)]` structs (not the
113// `json!` macro): serde emits struct fields in declaration order regardless of
114// serde_json's `preserve_order` feature (no workspace crate enables it now) —
115// a map-based value would otherwise reorder under feature unification and
116// break the golden. Field order here *is* the pinned contract.
117#[derive(serde::Serialize)]
118struct JsonReport<'a> {
119    driver: &'a str,
120    compiler: JsonCompiler<'a>,
121    all_ok: bool,
122    capabilities: Vec<JsonCap<'a>>,
123}
124
125#[derive(serde::Serialize)]
126struct JsonCompiler<'a> {
127    resolved: bool,
128    path: Option<String>,
129    version: &'a str,
130    origin: &'static str,
131    skew: Option<&'static str>,
132}
133
134#[derive(serde::Serialize)]
135struct JsonCap<'a> {
136    capability: &'static str,
137    optional: bool,
138    level: &'static str,
139    rows: Vec<JsonRow<'a>>,
140}
141
142#[derive(serde::Serialize)]
143struct JsonRow<'a> {
144    label: &'a str,
145    level: &'static str,
146    detail: &'a str,
147    remedy: Option<&'a str>,
148}
149
150fn json(report: &Report) -> String {
151    let value = JsonReport {
152        driver: &report.driver_version,
153        // #2998: the compiler is `bynk` itself. The keys are the ones editors
154        // already read (vscode-bynk's doctor view); `path` and `skew` are
155        // always null now, there being no second binary to point at or drift from.
156        compiler: JsonCompiler {
157            resolved: true,
158            path: None,
159            version: &report.driver_version,
160            origin: "in-process",
161            skew: None,
162        },
163        all_ok: report.is_all_ok(),
164        capabilities: report
165            .capabilities
166            .iter()
167            .map(|cap| JsonCap {
168                capability: cap.capability.token(),
169                optional: cap.optional,
170                level: level_word(cap),
171                rows: cap
172                    .rows
173                    .iter()
174                    .map(|r| JsonRow {
175                        label: &r.label,
176                        level: level_token(r.level),
177                        detail: &r.detail,
178                        remedy: r.remedy.as_deref(),
179                    })
180                    .collect(),
181            })
182            .collect(),
183    };
184    // Pretty-printed and trailing-newline-terminated for a stable golden.
185    let mut s = serde_json::to_string_pretty(&value).expect("Report serialises");
186    s.push('\n');
187    s
188}
189
190fn level_token(level: Level) -> &'static str {
191    match level {
192        Level::Ok => "ok",
193        Level::Warn => "warn",
194        Level::Fail => "fail",
195    }
196}
197
198/// Parse a `--only <capability>` token (shared with the CLI layer).
199pub fn parse_capability(token: &str) -> Option<Capability> {
200    match token {
201        "compile" => Some(Capability::Compile),
202        "test" => Some(Capability::Test),
203        "deploy" => Some(Capability::Deploy),
204        "editor" => Some(Capability::Editor),
205        "build" => Some(Capability::BuildFromSource),
206        _ => None,
207    }
208}