wsb 0.258.6441

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! The pre-action analysis table, and the verdict under it.
//!
//! Seven shell commands print this before doing anything irreversible: a fixed
//! three-column table of what was found, colour-coded by status, followed by
//! one line saying whether the run is going ahead. It is the project's answer
//! to a real problem — an operator about to sign, publish or delete something
//! should see what the tool believes BEFORE it acts, not afterwards in a
//! traceback — and it is worth having exactly once rather than once per
//! command.
//!
//! The widths, the rules and the status vocabulary are fixed here because they
//! are the vocabulary: a table whose columns move between commands is one an
//! operator has to re-read every time.

use std::fmt::Write as _;

/// The ANSI escapes the shell's `common.sh` defines, and the same rule for
/// when they apply: colour is for a terminal, and a captured log gets none.
pub struct Style {
    pub bold: &'static str,
    pub dim: &'static str,
    pub red: &'static str,
    pub green: &'static str,
    pub yellow: &'static str,
    pub cyan: &'static str,
    pub reset: &'static str,
}

impl Style {
    pub const PLAIN: Style = Style {
        bold: "",
        dim: "",
        red: "",
        green: "",
        yellow: "",
        cyan: "",
        reset: "",
    };

    pub const COLOUR: Style = Style {
        bold: "\u{1b}[1m",
        dim: "\u{1b}[2m",
        red: "\u{1b}[0;31m",
        green: "\u{1b}[0;32m",
        yellow: "\u{1b}[1;33m",
        cyan: "\u{1b}[0;36m",
        reset: "\u{1b}[0m",
    };

    /// Colour when stdout is a terminal, plain otherwise.
    pub fn detect() -> &'static Style {
        // `IsTerminal` rather than `isatty`: the same question, asked
        // through std, which every platform answers.
        let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
        if is_tty {
            &Style::COLOUR
        } else {
            &Style::PLAIN
        }
    }
}

const COL1: usize = 26;
const COL2: usize = 10;
const COL3: usize = 44;

/// One line of the table: a component, its status, and the detail behind it.
pub enum Row {
    Entry {
        label: String,
        status: String,
        detail: String,
    },
    /// A horizontal rule, for grouping.
    Rule,
}

impl Row {
    pub fn new(label: impl Into<String>, status: impl Into<String>, detail: impl Into<String>) -> Self {
        Row::Entry {
            label: label.into(),
            status: status.into(),
            detail: detail.into(),
        }
    }
}

/// The colour a status word carries.
///
/// The vocabulary is closed on purpose: a status outside it is dim rather than
/// green, so a typo reads as "not asserted" instead of as "fine".
fn status_colour<'a>(status: &str, style: &'a Style) -> &'a str {
    match status.to_ascii_uppercase().as_str() {
        "OK" | "VALID" | "PRESENT" | "SIGNED" | "FRESH" | "FOUND" | "YES" | "MATCH" | "CLEAN"
        | "UP-TO-DATE" => style.green,
        "MISSING" | "INVALID" | "CHANGED" | "NO" | "FAIL" | "UNSIGNED" | "STALE" | "ABSENT"
        | "ERROR" | "NONE" => style.red,
        "WARN" | "UNKNOWN" | "SKIP" | "PARTIAL" | "OUTDATED" => style.yellow,
        _ => style.dim,
    }
}

/// Show a table: drawn for a terminal, or emitted as its rows.
///
/// Every table in wsb goes through here. The rows are the same object in both
/// renderings, so a consumer of the packaged stream sees exactly what a person
/// at a terminal sees — the same rows, the same status words, the same order,
/// and none of the box characters that made it unreadable to anything but an
/// eye.
pub fn show(title: &str, rows: &[Row], verdict_line: Option<(&str, Verdict)>) {
    if crate::output::is_jsonl() {
        crate::output::emit(crate::output::Record::Table {
            title: title.to_string(),
            columns: vec![
                "Component".to_string(),
                "Status".to_string(),
                "Detail".to_string(),
            ],
            rows: rows
                .iter()
                .filter_map(|row| match row {
                    // A rule is typography. A reader of the data groups by what
                    // the rows say, not by where a line was drawn.
                    Row::Rule => None,
                    Row::Entry {
                        label,
                        status,
                        detail,
                    } => Some(vec![label.clone(), status.clone(), detail.clone()]),
                })
                .collect(),
            verdict: verdict_line.map(|(message, level)| crate::output::record::Verdict {
                message: message.to_string(),
                level: level.as_level(),
            }),
        });
        return;
    }

    let style = Style::detect();
    crate::out!("{}", analysis_table(title, rows, style));
    if let Some((message, level)) = verdict_line {
        crate::outln!("{}", verdict(message, level, style));
    }
}

/// [`show`], on stderr: for a report ABOUT a command's run — a preflight —
/// whose stdout is the command's product. `publish --plan` prints its plan as
/// a JSON document, and a table in front of it made that document unreadable to
/// everything that consumes it.
pub fn show_diagnostic(title: &str, rows: &[Row], verdict_line: Option<(&str, Verdict)>) {
    if crate::output::is_jsonl() {
        // A record stream has no second channel; the record says what it is.
        show(title, rows, verdict_line);
        return;
    }
    let style = if std::io::IsTerminal::is_terminal(&std::io::stderr()) {
        &Style::COLOUR
    } else {
        &Style::PLAIN
    };
    crate::errln!("{}", analysis_table(title, rows, style).trim_end_matches('\n'));
    if let Some((message, level)) = verdict_line {
        crate::errln!("{}", verdict(message, level, style));
    }
}

/// Render the table. Returned rather than printed so it can be compared.
pub fn analysis_table(title: &str, rows: &[Row], style: &Style) -> String {
    let width = COL1 + COL2 + COL3 + 6;
    let rule: String = "─".repeat(width);
    let mut out = String::new();

    let _ = write!(out, "\n{}{}  {title}{}\n", style.bold, style.cyan, style.reset);
    let _ = write!(out, "  {}{rule}{}\n", style.dim, style.reset);
    let _ = write!(
        out,
        "  {}{:<COL1$}  {:<COL2$}  {:<COL3$}{}\n",
        style.bold, "Component", "Status", "Detail", style.reset
    );
    let _ = write!(out, "  {}{rule}{}\n", style.dim, style.reset);

    for row in rows {
        match row {
            Row::Rule => {
                let _ = write!(out, "  {}{rule}{}\n", style.dim, style.reset);
            }
            Row::Entry {
                label,
                status,
                detail,
            } => {
                let colour = status_colour(status, style);
                // Both columns are TRUNCATED, not wrapped. A long value must not
                // push the table into a second shape — and the label overflows
                // as readily as the detail: a phase title is a sentence, and one
                // long enough shifted every column after it on that row alone.
                let label: String = label.chars().take(COL1).collect();
                let detail: String = detail.chars().take(COL3).collect();
                let _ = write!(
                    out,
                    "  {label:<COL1$}  {colour}{status:<COL2$}{}  {}{detail:<COL3$}{}\n",
                    style.reset, style.dim, style.reset
                );
            }
        }
    }

    let _ = write!(out, "  {}{rule}{}\n", style.dim, style.reset);
    out
}

/// The same table, as data.
///
/// The table is what an operator is shown before anything irreversible happens,
/// and a UI about to sign or publish needs exactly that — the same rows, the
/// same status words, the same order. Rendering it to text and parsing the text
/// back would make the columns a wire format; this is the one structure, with
/// two renderings.
pub fn analysis_json(title: &str, rows: &[Row], verdict: Option<(&str, Verdict)>) -> serde_json::Value {
    serde_json::json!({
        "title": title,
        "rows": rows
            .iter()
            .filter_map(|row| match row {
                // A rule is typography. A reader of the data groups by what the
                // rows say, not by where a line was drawn.
                Row::Rule => None,
                Row::Entry { label, status, detail } => Some(serde_json::json!({
                    "label": label,
                    "status": status,
                    "detail": detail,
                })),
            })
            .collect::<Vec<_>>(),
        "verdict": verdict.map(|(message, level)| serde_json::json!({
            "message": message,
            "level": level.as_str(),
        })),
    })
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    Ok,
    Warn,
    Fail,
}

impl Verdict {
    /// How much this matters, in the vocabulary every record uses.
    pub fn as_level(self) -> crate::output::Level {
        match self {
            Verdict::Ok => crate::output::Level::Info,
            Verdict::Warn => crate::output::Level::Warn,
            Verdict::Fail => crate::output::Level::Error,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Verdict::Ok => "ok",
            Verdict::Warn => "warn",
            Verdict::Fail => "fail",
        }
    }
}

/// The one line under the table saying what happens next.
pub fn verdict(message: &str, level: Verdict, style: &Style) -> String {
    let colour = match level {
        Verdict::Ok => style.green,
        Verdict::Warn => style.yellow,
        Verdict::Fail => style.red,
    };
    format!("  {}{colour}→ {message}{}\n\n", style.bold, style.reset)
}

/// A human-readable age, from a unix timestamp.
pub fn age(timestamp: Option<u64>, now: u64) -> String {
    let Some(timestamp) = timestamp else {
        return "unknown".to_string();
    };
    let delta = now.saturating_sub(timestamp);
    if delta < 60 {
        format!("{delta}s ago")
    } else if delta < 3_600 {
        format!("{}m ago", delta / 60)
    } else if delta < 86_400 {
        format!("{}h ago", delta / 3_600)
    } else {
        format!("{}d ago", delta / 86_400)
    }
}

/// Whether a tool is on PATH, as a (status, detail) pair for one row.
pub fn tool(name: &str) -> (String, String) {
    match which(name) {
        Some(path) => ("FOUND".to_string(), path),
        None => ("MISSING".to_string(), "not in PATH".to_string()),
    }
}

/// The first executable named `name` on PATH.
///
/// The NAMES come from the platform as well as the directories: `which("cargo")`
/// on Windows has to find `cargo.exe`, because that is the file, and a search
/// that only tried the bare name reported every tool on the machine missing.
pub fn which(name: &str) -> Option<String> {
    let paths = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&paths) {
        for candidate in crate::platform::command_file_names(name) {
            let candidate = dir.join(candidate);
            if crate::platform::is_executable(&candidate) {
                return Some(candidate.display().to_string());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    /// TEST8830: the table is the fixed shape every command shares.
    #[test]
    fn test8830_the_table_has_one_shape() {
        let rows = vec![
            Row::new("Binary", "PRESENT", "/opt/thing"),
            Row::Rule,
            Row::new("jq", "MISSING", "not in PATH"),
        ];
        let text = analysis_table("Analysis", &rows, &Style::PLAIN);
        let lines: Vec<&str> = text.lines().collect();
        // blank, title, rule, header, rule, entry, rule, entry, rule
        assert_eq!(lines.len(), 9, "{text}");
        let width = COL1 + COL2 + COL3 + 6;
        for index in [2, 4, 6, 8] {
            assert_eq!(
                lines[index].trim().chars().count(),
                width,
                "line {index} is not a full-width rule: {:?}",
                lines[index]
            );
        }
        // Every entry line puts its columns at the same offsets, which is the
        // whole reason the widths are fixed.
        for index in [3, 5, 7] {
            assert!(
                lines[index].starts_with("  "),
                "line {index} is not indented: {:?}",
                lines[index]
            );
        }
        assert!(lines[5].contains("Binary"));
        assert!(lines[5].contains("PRESENT"));
    }

    /// TEST8831: a long detail is truncated, never wrapped.
    #[test]
    fn test8831_a_long_detail_does_not_reshape_the_table() {
        let long = "x".repeat(COL3 * 2);
        let text = analysis_table("A", &[Row::new("L", "OK", &long)], &Style::PLAIN);
        let entry = text.lines().nth(5).expect("an entry line");
        assert_eq!(
            entry.chars().count(),
            2 + COL1 + 2 + COL2 + 2 + COL3,
            "the entry line is not the fixed width: {entry:?}"
        );
        assert_eq!(text.lines().count(), 7, "the detail wrapped onto another line");
    }

    /// TEST8832: a status outside the vocabulary is not green.
    ///
    /// Dim reads as "not asserted"; green reads as "fine". A typo must not
    /// become an assurance.
    #[test]
    fn test8832_an_unknown_status_is_not_reassuring() {
        assert_eq!(status_colour("OK", &Style::COLOUR), Style::COLOUR.green);
        assert_eq!(status_colour("ok", &Style::COLOUR), Style::COLOUR.green);
        assert_eq!(status_colour("MISSING", &Style::COLOUR), Style::COLOUR.red);
        assert_eq!(status_colour("WARN", &Style::COLOUR), Style::COLOUR.yellow);
        assert_eq!(status_colour("OKAY", &Style::COLOUR), Style::COLOUR.dim);
        assert_eq!(status_colour("", &Style::COLOUR), Style::COLOUR.dim);
    }

    /// TEST8833: a captured log carries no escapes.
    #[test]
    fn test8833_plain_output_has_no_escapes() {
        let text = analysis_table("A", &[Row::new("L", "OK", "d")], &Style::PLAIN)
            + &verdict("go", Verdict::Ok, &Style::PLAIN);
        assert!(!text.contains('\u{1b}'), "{text:?}");
        let coloured = analysis_table("A", &[Row::new("L", "OK", "d")], &Style::COLOUR);
        assert!(coloured.contains('\u{1b}'));
    }

    /// TEST8834: an age reads in the largest unit that fits.
    #[test]
    fn test8834_age_uses_the_largest_unit_that_fits() {
        assert_eq!(age(Some(100), 100), "0s ago");
        assert_eq!(age(Some(41), 100), "59s ago");
        assert_eq!(age(Some(40), 100), "1m ago");
        assert_eq!(age(Some(0), 3_599), "59m ago");
        assert_eq!(age(Some(0), 3_600), "1h ago");
        assert_eq!(age(Some(0), 86_399), "23h ago");
        assert_eq!(age(Some(0), 86_400), "1d ago");
        assert_eq!(age(None, 100), "unknown");
        // A timestamp in the future is not a negative age: the clock moved, and
        // "0s ago" is the honest reading of a file that is not old.
        assert_eq!(age(Some(200), 100), "0s ago");
    }
}