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
use anyhow::Result;
use console::Term;
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use std::{borrow::Cow, io::Write, time::Duration};

pub trait Renderer {
    fn writer<T>(&mut self, func: impl FnOnce(&mut dyn Write) -> Result<T>) -> Result<T>;

    fn are_spinners_visible(&self) -> bool;

    fn spinner<T>(
        &mut self,
        description: impl Into<Cow<'static, str>>,
        func: impl FnOnce() -> Result<T>,
    ) -> Result<T>;
}

pub struct TerminalRenderer(Term);

impl TerminalRenderer {
    pub fn stdout() -> Self {
        Self(Term::buffered_stdout())
    }
}

impl Renderer for TerminalRenderer {
    fn writer<T>(&mut self, func: impl FnOnce(&mut dyn Write) -> Result<T>) -> Result<T> {
        let ret = func(&mut self.0)?;
        self.0.flush()?;
        Ok(ret)
    }

    fn are_spinners_visible(&self) -> bool {
        self.0.is_term()
    }

    fn spinner<T>(
        &mut self,
        description: impl Into<Cow<'static, str>>,
        func: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let spinner =
            ProgressBar::with_draw_target(None, ProgressDrawTarget::term(self.0.clone(), 10));
        spinner.set_style(
            ProgressStyle::default_spinner()
                .tick_strings(&[" ..", ". .", ".. ", "..."])
                .template("{msg}{spinner} {elapsed}")
                .unwrap(),
        );
        spinner.set_message(description);
        spinner.enable_steady_tick(Duration::from_millis(150));

        let ret = func();
        spinner.finish();

        // The finish call merely redraws the progress bar in its final state. The line needs to be
        // explicitly terminated.
        add_newline_if_spinners_are_visible(self)?;

        ret
    }
}

/// Adds a newline to separate output from spinners, but that's only necessary if spinners are even
/// being displayed.
pub fn add_newline_if_spinners_are_visible(renderer: &mut impl Renderer) -> Result<()> {
    if renderer.are_spinners_visible() {
        renderer.writer(|w| {
            writeln!(w)?;
            Ok(())
        })?;
    }

    Ok(())
}

#[cfg(test)]
pub mod test_terminal {
    use anyhow::Context;

    use crate::renderer::{Renderer, TerminalRenderer};

    #[test]
    fn writer() {
        let mut renderer = TerminalRenderer::stdout();
        renderer
            .writer(|w| write!(w, "").context("write in test"))
            .unwrap();
    }

    #[test]
    fn are_spinners_visible() {
        TerminalRenderer::stdout().are_spinners_visible();
    }

    #[test]
    fn spinner() {
        let mut renderer = TerminalRenderer::stdout();
        let mut func_called = false;
        renderer
            .spinner("Spinning", || {
                func_called = true;
                Ok(())
            })
            .unwrap();
        assert!(func_called);
    }
}

#[cfg(test)]
pub mod test {
    use std::io::Write;
    use std::{borrow::Cow, io};

    use anyhow::{Context, Result};

    use super::{add_newline_if_spinners_are_visible, Renderer};

    pub struct MemoryRenderer(Vec<u8>);

    impl MemoryRenderer {
        pub fn new() -> Self {
            Self(Vec::new())
        }

        pub fn as_str(&self) -> &str {
            std::str::from_utf8(self.0.as_slice()).expect("tests should have utf8 output")
        }
    }

    impl Renderer for MemoryRenderer {
        fn writer<T>(&mut self, func: impl FnOnce(&mut dyn Write) -> Result<T>) -> Result<T> {
            func(&mut self.0)
        }

        fn are_spinners_visible(&self) -> bool {
            true
        }

        fn spinner<T>(
            &mut self,
            description: impl Into<Cow<'static, str>>,
            func: impl FnOnce() -> Result<T>,
        ) -> Result<T> {
            writeln!(self.0, "{}...", description.into())?;
            func()
        }
    }

    pub struct NoRenderer;

    impl Renderer for NoRenderer {
        fn writer<T>(&mut self, func: impl FnOnce(&mut dyn Write) -> Result<T>) -> Result<T> {
            func(&mut io::sink())
        }

        fn are_spinners_visible(&self) -> bool {
            false
        }

        fn spinner<T>(
            &mut self,
            _description: impl Into<Cow<'static, str>>,
            func: impl FnOnce() -> Result<T>,
        ) -> Result<T> {
            func()
        }
    }

    #[test]
    fn writer() {
        let mut renderer = MemoryRenderer::new();
        renderer
            .writer(|w| writeln!(w, "foo").context("write in test"))
            .unwrap();
        assert_eq!(renderer.as_str(), "foo\n");
    }

    #[test]
    fn spinner() {
        let mut renderer = MemoryRenderer::new();
        let mut func_called = false;
        renderer
            .spinner("Spinning", || {
                func_called = true;
                Ok(())
            })
            .unwrap();

        assert_eq!(renderer.as_str(), "Spinning...\n");
        assert!(func_called);
    }

    #[test]
    fn add_newline() {
        let mut renderer = MemoryRenderer::new();
        add_newline_if_spinners_are_visible(&mut renderer).unwrap();
        assert_eq!(renderer.as_str(), "\n");
    }
}