Skip to main content

bynk_driver/
progress.rs

1//! #3100: per-context build progress, printed to stderr.
2//!
3//! The pipeline reports each context through a [`ProgressSink`]
4//! ([`crate::project::CompileOptions::progress`]); this is the one printer the
5//! verbs that build share, so `build`, `dev` and `deploy` read the same.
6//!
7//! The lines appear only when stderr is a terminal and `--quiet` is not given,
8//! so a script or CI log that captures the output sees exactly what it did
9//! before.
10
11use std::io::IsTerminal;
12use std::sync::Arc;
13use std::sync::atomic::{AtomicBool, Ordering};
14
15use crate::project::{ProgressEvent, ProgressSink};
16
17static QUIET: AtomicBool = AtomicBool::new(false);
18
19/// `--quiet`: turn the per-context lines off for this process.
20pub fn set_quiet(quiet: bool) {
21    QUIET.store(quiet, Ordering::Relaxed);
22}
23
24/// The printer for this process, or `None` when nothing should print: stderr
25/// is not a terminal, or `--quiet` was given.
26pub fn terminal_sink() -> Option<ProgressSink> {
27    printer_if(std::io::stderr().is_terminal() && !QUIET.load(Ordering::Relaxed))
28}
29
30fn printer_if(on: bool) -> Option<ProgressSink> {
31    let colour = crate::colour::stderr();
32    on.then(|| {
33        Arc::new(move |event: &ProgressEvent| eprintln!("{}", coloured_line(event, colour)))
34            as ProgressSink
35    })
36}
37
38/// [`line`], with the verb green and bold when `colour` is on, as `cargo` has it.
39fn coloured_line(event: &ProgressEvent, colour: bool) -> String {
40    use crate::colour::{Style, paint};
41    let (verb, name) = match event {
42        ProgressEvent::Started(name) => ("Compiling", name),
43        ProgressEvent::Finished(name) => ("Finished", name),
44    };
45    let verb = format!("{verb:>10}");
46    let verb = paint(colour, Style::Green, &paint(colour, Style::Bold, &verb));
47    format!("{verb} {name}")
48}
49
50/// One event's line: a right-aligned verb, then the context, as `cargo` does.
51pub fn line(event: &ProgressEvent) -> String {
52    coloured_line(event, false)
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn lines_align_their_verbs() {
61        assert_eq!(
62            line(&ProgressEvent::Started("shop".into())),
63            " Compiling shop"
64        );
65        assert_eq!(
66            line(&ProgressEvent::Finished("shop".into())),
67            "  Finished shop"
68        );
69    }
70
71    #[test]
72    fn off_means_no_sink() {
73        assert!(printer_if(false).is_none());
74        assert!(printer_if(true).is_some());
75    }
76}