tinsel 0.5.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and more.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! What shape output takes (drawn for people, JSON lines for programs, or only what matters),
//! and where it goes.

use std::fmt::Write as _;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicU8, Ordering};

/// What shape tinsel's output takes. Set it from a `--json` or `--quiet` flag with
/// [`set_output`], or with `TINSEL_OUTPUT=json|quiet`.
///
/// ```
/// tinsel::set_output(tinsel::Output::Json);
/// tinsel::success("deployed");    // {"event":"message","level":"success","text":"deployed"}
/// # tinsel::set_output(tinsel::Output::Pretty);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Output {
    /// For people: colour and animation on a terminal, plain `[ok] Build (1.2s)` lines elsewhere.
    #[default]
    Pretty,
    /// For programs: one JSON object per line on stdout (or the [`Target`]), for every message, step, report and
    /// block. Each has an `"event"` field saying what it is. Prompts still ask on the terminal.
    Json,
    /// Only what needs attention: warnings, errors, failed steps and anything printed
    /// explicitly (tables, trees and other blocks). Progress, spinners and success messages
    /// stay silent.
    Quiet,
}

// 0 = not decided yet; otherwise 1 + the Output's position
static OUTPUT: AtomicU8 = AtomicU8::new(0);

/// The output shape in use. Decided once from `TINSEL_OUTPUT`, unless [`set_output`] has chosen one.
pub fn output() -> Output {
    #[cfg(test)]
    if let Some(out) = TEST_OUTPUT.get() {
        return out;
    }
    match OUTPUT.load(Ordering::Relaxed) {
        1 => Output::Pretty,
        2 => Output::Json,
        3 => Output::Quiet,
        _ => {
            let out = parse_output(std::env::var("TINSEL_OUTPUT").ok().as_deref());
            set_output(out);
            out
        }
    }
}

pub(crate) fn parse_output(env: Option<&str>) -> Output {
    match env {
        Some("json") => Output::Json,
        Some("quiet") => Output::Quiet,
        _ => Output::Pretty,
    }
}

#[cfg(test)]
thread_local! {
    static TEST_OUTPUT: std::cell::Cell<Option<Output>> = const { std::cell::Cell::new(None) };
    static TEST_TARGET: std::cell::Cell<Option<Target>> = const { std::cell::Cell::new(None) };
}

thread_local! {
    /// Whether to act as if the stream drawn on is a terminal, on this thread, whatever it is.
    static TERMINAL: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// Run `f` with an output shape on this thread alone, so a unit test that wants JSON doesn't
/// turn it on for the tests running beside it.
#[cfg(test)]
pub(crate) fn with_output<T>(out: Output, f: impl FnOnce() -> T) -> T {
    let before = TEST_OUTPUT.replace(Some(out));
    let result = f();
    TEST_OUTPUT.set(before);
    result
}

/// Run `f` as if the stream tinsel draws on were a terminal (or not), on this thread alone.
#[cfg(test)]
pub(crate) fn with_terminal<T>(terminal: bool, f: impl FnOnce() -> T) -> T {
    let before = TERMINAL.replace(Some(terminal));
    let result = f();
    TERMINAL.set(before);
    result
}

/// What this thread is acting as, terminal or not, if anything: see [`capture`].
pub(crate) fn pretended_terminal() -> Option<bool> {
    TERMINAL.get()
}

/// What was written while capturing, from any thread. One capture at a time.
static CAPTURED: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
static CAPTURING: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Whether anything's capturing, so writes needn't take the lock to find out.
static CAPTURE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

fn captured() -> std::sync::MutexGuard<'static, Option<String>> {
    CAPTURED.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Keep `s` if something's capturing, and say whether it was kept.
fn kept(s: &str) -> bool {
    if !CAPTURE_ON.load(Ordering::SeqCst) {
        return false;
    }
    match captured().as_mut() {
        Some(buf) => {
            buf.push_str(s);
            true
        }
        None => false,
    }
}

/// What `f` prints through tinsel, instead of printing it: for testing your own program's
/// output, not just tinsel's pieces. Messages, steps, spinners, printed blocks and errors
/// are all caught, stdout and stderr together, in the order they were printed.
///
/// It's printed as it would be into a pipe: no animation, a [`Live`](crate::Live) display
/// as plain `[ok] Build (1.2s)` lines, and no colour, unless `f` runs inside
/// [`with_color_mode`](crate::with_color_mode). [`Output::Json`] and [`Output::Quiet`] still
/// apply, so a `--json` flag can be tested too.
///
/// Prints from every thread are caught, so steps finished on worker threads are too. That
/// also means one capture runs at a time, and anything another test prints through tinsel
/// meanwhile lands in it as well: capture in every test that prints, or look for what you
/// expect rather than comparing the whole thing.
///
/// ```
/// fn deploy() {
///     tinsel::success("deployed");
///     tinsel::Table::new(["app", "size"]).row(["core", "34 MB"]).print();
/// }
///
/// let printed = tinsel::capture(deploy);
/// assert_eq!(printed, "  ●  deployed\n  app     size\n  ┈┈┈┈┈┈┈┈┈┈┈┈\n  core   34 MB\n");
/// ```
pub fn capture(f: impl FnOnce()) -> String {
    let mut f = Some(f);
    capture_while(&mut || f.take().into_iter().for_each(|f| f()))
}

/// [`capture`], for any closure.
fn capture_while(f: &mut dyn FnMut()) -> String {
    let _one = CAPTURING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
    *captured() = Some(String::new());
    CAPTURE_ON.store(true, Ordering::SeqCst);
    // tinsel's own tests ignore TINSEL_OUTPUT and TINSEL_TARGET unless a test chooses
    #[cfg(test)]
    let before = (TEST_OUTPUT.get(), TEST_TARGET.get());
    #[cfg(test)]
    {
        TEST_OUTPUT.set(before.0.or(Some(Output::Pretty)));
        TEST_TARGET.set(before.1.or(Some(Target::Stdout)));
    }
    let terminal = TERMINAL.get();
    TERMINAL.set(terminal.or(Some(false)));
    let result = crate::style::plain_unless_chosen(|| std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)));
    TERMINAL.set(terminal);
    #[cfg(test)]
    {
        TEST_OUTPUT.set(before.0);
        TEST_TARGET.set(before.1);
    }
    CAPTURE_ON.store(false, Ordering::SeqCst);
    let out = captured().take().unwrap_or_default();
    if let Err(panic) = result {
        std::panic::resume_unwind(panic);
    }
    out
}

/// Choose the output shape, for a `--json` or `--quiet` flag.
pub fn set_output(out: Output) {
    let code = match out {
        Output::Pretty => 1,
        Output::Json => 2,
        Output::Quiet => 3,
    };
    OUTPUT.store(code, Ordering::Relaxed);
}

/// Where tinsel draws: stdout (the default) or stderr. Choose stderr when stdout belongs to
/// something else, like the output of a command your tool runs or data piped to another
/// program. Set it with [`set_target`] or `TINSEL_TARGET=stderr`.
///
/// ```
/// tinsel::set_target(tinsel::Target::Stderr);
/// tinsel::success("checked");    // on stderr, coloured if stderr is a terminal
/// # tinsel::set_target(tinsel::Target::Stdout);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Target {
    /// Standard output.
    #[default]
    Stdout,
    /// Standard error.
    Stderr,
}

// 0 = not decided yet, 1 = stdout, 2 = stderr
static TARGET: AtomicU8 = AtomicU8::new(0);

/// Where tinsel draws. Decided once from `TINSEL_TARGET` (`stderr` or `stdout`), unless
/// [`set_target`] has chosen.
pub fn target() -> Target {
    #[cfg(test)]
    if let Some(target) = TEST_TARGET.get() {
        return target;
    }
    match TARGET.load(Ordering::Relaxed) {
        1 => Target::Stdout,
        2 => Target::Stderr,
        _ => {
            let target = parse_target(std::env::var("TINSEL_TARGET").ok().as_deref());
            TARGET.store(target_code(target), Ordering::Relaxed);
            target
        }
    }
}

/// Send everything tinsel draws to stdout or stderr: [`Live`](crate::Live) displays,
/// [`Region`](crate::Region)s, spinners and [`Progress`](crate::Progress) bars, messages,
/// printed [`Block`](crate::Block)s and JSON events. Whether to draw in colour and animate
/// is then decided by whether that stream is a terminal. Errors and
/// [`Report`](crate::Report)s go to stderr either way, and prompts still ask on the terminal.
///
/// Call it early, before anything is drawn.
///
/// ```
/// tinsel::set_target(tinsel::Target::Stderr);
/// tinsel::spin("Checking", || std::thread::sleep(std::time::Duration::from_millis(10)));
/// # tinsel::set_target(tinsel::Target::Stdout);
/// ```
pub fn set_target(target: Target) {
    let before = TARGET.swap(target_code(target), Ordering::Relaxed);
    if before != target_code(target) {
        crate::style::forget_detected();
    }
}

fn target_code(target: Target) -> u8 {
    match target {
        Target::Stdout => 1,
        Target::Stderr => 2,
    }
}

pub(crate) fn parse_target(env: Option<&str>) -> Target {
    match env.map(str::trim) {
        Some(v) if v.eq_ignore_ascii_case("stderr") => Target::Stderr,
        _ => Target::Stdout,
    }
}

/// Whether the stream `target` names is a terminal, asking only about that one.
fn on_terminal(target: Target, stdout: &dyn Fn() -> bool, stderr: &dyn Fn() -> bool) -> bool {
    match target {
        Target::Stdout => stdout(),
        Target::Stderr => stderr(),
    }
}

/// Whether the stream tinsel draws on is a terminal.
pub(crate) fn is_terminal() -> bool {
    if let Some(terminal) = pretended_terminal() {
        return terminal;
    }
    on_terminal(target(), &|| std::io::stdout().is_terminal(), &|| {
        std::io::stderr().is_terminal()
    })
}

/// The file descriptor tinsel draws on.
pub(crate) fn fd() -> i32 {
    match target() {
        Target::Stdout => 1,
        Target::Stderr => 2,
    }
}

/// [`fd`] as already decided, deciding nothing: safe in a signal handler.
pub(crate) fn fd_now() -> i32 {
    if TARGET.load(Ordering::Relaxed) == 2 { 2 } else { 1 }
}

/// The stream tinsel draws on.
pub(crate) fn writer() -> Box<dyn Write> {
    match target() {
        Target::Stdout => Box::new(std::io::stdout().lock()),
        Target::Stderr => Box::new(std::io::stderr().lock()),
    }
}

/// Write to the stream tinsel draws on, and flush.
pub(crate) fn write(s: &str) {
    if kept(s) {
        return;
    }
    let mut out = writer();
    let _ = out.write_all(s.as_bytes());
    let _ = out.flush();
}

/// Write a line to stderr, for errors, which go there whatever the target.
pub(crate) fn err_line(s: &str) {
    if kept(&format!("{s}\n")) {
        return;
    }
    eprintln!("{s}");
}

/// Write a line to the stream tinsel draws on.
pub(crate) fn line(s: &str) {
    write(&format!("{s}\n"));
}

pub(crate) fn json() -> bool {
    output() == Output::Json
}

pub(crate) fn quiet() -> bool {
    output() == Output::Quiet
}

/// A value in a JSON event.
pub(crate) enum Val<'a> {
    Str(&'a str),
    Num(f64),
    List(&'a [String]),
}

/// Write one JSON event line to the stream tinsel draws on: `{"event":"…", …fields}`. Text is stripped of styling.
pub(crate) fn emit(event: &str, fields: &[(&str, Val)]) {
    let mut line = format!("{{\"event\":{}", quote(event));
    for (key, val) in fields {
        let _ = write!(line, ",{}:", quote(key));
        match val {
            Val::Str(s) => line += &quote(s),
            Val::Num(n) if n.is_finite() => line += &format!("{}", (n * 1000.0).round() / 1000.0),
            Val::Num(_) => line += "null",
            Val::List(items) => {
                let items: Vec<String> = items.iter().map(|s| quote(s)).collect();
                let _ = write!(line, "[{}]", items.join(","));
            }
        }
    }
    line += "}\n";
    write(&line);
}

/// A JSON string literal, styling removed.
pub(crate) fn quote(s: &str) -> String {
    let mut out = String::from("\"");
    for c in crate::text::strip_ansi(s).chars() {
        match c {
            '"' => out += "\\\"",
            '\\' => out += "\\\\",
            '\n' => out += "\\n",
            '\r' => out += "\\r",
            '\t' => out += "\\t",
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

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

    #[test]
    fn output_comes_from_the_environment() {
        assert_eq!(parse_output(None), Output::Pretty);
        assert_eq!(parse_output(Some("json")), Output::Json);
        assert_eq!(parse_output(Some("quiet")), Output::Quiet);
        assert_eq!(parse_output(Some("loud")), Output::Pretty);
    }

    #[test]
    fn json_events_carry_every_kind_of_value() {
        let items = ["a".to_string(), "b\"c".to_string()];
        let out = capture(|| {
            emit(
                "thing",
                &[
                    ("name", Val::Str("x")),
                    ("secs", Val::Num(1.23456)),
                    ("ratio", Val::Num(f64::NAN)),
                    ("items", Val::List(&items)),
                ],
            )
        });
        assert!(out.contains(r#"{"event":"thing","name":"x","secs":1.235,"ratio":null,"items":["a","b\"c"]}"#));
    }

    #[test]
    fn lines_end_in_a_newline() {
        assert!(capture(|| line("hello")).contains("hello\n"));
    }

    #[test]
    fn writes_go_to_the_stream_when_nothing_captures() {
        let _one = CAPTURING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        write("");
        let _ = is_terminal();
        assert_eq!(fd(), if target() == Target::Stdout { 1 } else { 2 });
        #[cfg(unix)]
        assert_eq!(fd_now(), fd());
    }

    #[test]
    fn a_capture_gives_back_a_panic() {
        let caught = std::panic::catch_unwind(|| capture(|| panic!("inside")));
        assert!(caught.is_err());
        assert!(capture(|| write("after")).contains("after"));
    }

    #[test]
    fn the_shape_and_the_terminal_can_be_pretended() {
        with_output(Output::Quiet, || {
            assert!(quiet() && !json());
            with_output(Output::Json, || assert!(json()));
        });
        with_terminal(true, || assert!(is_terminal()));
        with_terminal(false, || assert!(!is_terminal()));
    }

    #[test]
    fn target_comes_from_the_environment() {
        assert_eq!(parse_target(None), Target::Stdout);
        assert_eq!(parse_target(Some("stderr")), Target::Stderr);
        assert_eq!(parse_target(Some(" STDERR ")), Target::Stderr);
        assert_eq!(parse_target(Some("stdout")), Target::Stdout);
        assert_eq!(parse_target(Some("nonsense")), Target::Stdout);
    }

    #[test]
    fn the_chosen_stream_decides_whether_to_draw() {
        let (yes, no) = (&|| true, &|| false);
        // stdout piped somewhere, stderr on the terminal
        assert!(!on_terminal(Target::Stdout, no, yes));
        assert!(on_terminal(Target::Stderr, no, yes));
        // and the other way round
        assert!(on_terminal(Target::Stdout, yes, no));
        assert!(!on_terminal(Target::Stderr, yes, no));
        // the other stream is never asked about
        let asked = std::cell::Cell::new(0);
        let ask = || {
            asked.set(asked.get() + 1);
            true
        };
        assert!(on_terminal(Target::Stderr, &ask, &ask));
        assert_eq!(asked.get(), 1);
    }

    #[test]
    fn quotes_strings_safely() {
        assert_eq!(quote("a \"b\"\n\\"), r#""a \"b\"\n\\""#);
        assert_eq!(quote("\x1b[31mred\x1b[39m"), "\"red\"");
        assert_eq!(quote("\x01"), "\"\\u0001\"");
        assert_eq!(quote("a\r\tb"), r#""a\r\tb""#);
    }
}