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
use indicatif::ProgressDrawTarget;
use snowchains_core::{color_spec, web::StatusCodeColor};
use std::{
    fmt,
    io::{self, BufRead, Write},
};
use strum::{EnumString, EnumVariantNames};
use termcolor::{BufferedStandardStream, Color, NoColor, WriteColor};

pub struct Shell {
    input: ShellIn,
    output: ShellOut,
    needs_clear: bool,
}

impl Shell {
    pub fn new() -> Self {
        Self {
            input: ShellIn::stdin(),
            output: ShellOut::stream(),
            needs_clear: false,
        }
    }

    pub fn from_read_write(rdr: Box<dyn BufRead>, wtr: Box<dyn Write>) -> Self {
        Self {
            input: ShellIn::Reader(rdr),
            output: ShellOut::Write(NoColor::new(wtr)),
            needs_clear: false,
        }
    }

    pub(crate) fn progress_draw_target(&self) -> ProgressDrawTarget {
        if self.output.stderr_tty() {
            ProgressDrawTarget::stderr()
        } else {
            ProgressDrawTarget::hidden()
        }
    }

    pub(crate) fn out(&mut self) -> &mut dyn Write {
        self.output.stdout()
    }

    pub fn err(&mut self) -> &mut dyn WriteColor {
        self.output.stderr()
    }

    pub(crate) fn set_color_choice(&mut self, color: ColorChoice) {
        self.output.set_color_choice(color);
    }

    pub(crate) fn warn(&mut self, message: impl fmt::Display) -> io::Result<()> {
        if self.needs_clear {
            self.err_erase_line();
        }

        let stderr = self.err();

        stderr.set_color(color_spec!(Bold, Fg(Color::Yellow)))?;
        write!(stderr, "warning:")?;
        stderr.reset()?;

        writeln!(stderr, " {}", message)?;

        stderr.flush()
    }

    pub(crate) fn status(
        &mut self,
        status: impl fmt::Display,
        message: impl fmt::Display,
    ) -> io::Result<()> {
        self.status_with_color(status, message, Color::Green)
    }

    pub(crate) fn status_with_color(
        &mut self,
        status: impl fmt::Display,
        message: impl fmt::Display,
        color: Color,
    ) -> io::Result<()> {
        if self.needs_clear {
            self.err_erase_line();
        }
        self.output.message_stderr(status, message, color)
    }

    fn err_erase_line(&mut self) {
        if let ShellOut::Stream {
            stderr,
            stderr_tty: true,
            ..
        } = &mut self.output
        {
            err_erase_line(stderr);
            self.needs_clear = false;
        }

        #[cfg(unix)]
        fn err_erase_line(mut stderr: impl Write) {
            let _ = stderr.write_all(b"\x1B[K");
        }

        #[cfg(windows)]
        fn err_erase_line(mut stderr: impl Write) {
            if let Some((width, _)) = term_size::dimensions_stderr() {
                let _ = write!(stderr, "{}\r", " ".repeat(width));
            }
        }
    }

    pub(crate) fn read_reply(&mut self, prompt: &str) -> io::Result<String> {
        if self.needs_clear {
            self.err_erase_line();
        }

        let stderr = self.err();

        write!(stderr, "{}", prompt)?;
        stderr.flush()?;
        self.input.read_reply()
    }

    pub(crate) fn read_password(&mut self, prompt: &str) -> io::Result<String> {
        if self.needs_clear {
            self.err_erase_line();
        }

        let stderr = self.err();

        write!(stderr, "{}", prompt)?;
        stderr.flush()?;
        self.input.read_password()
    }
}

impl Default for Shell {
    fn default() -> Self {
        Self::new()
    }
}

impl snowchains_core::web::Shell for Shell {
    fn progress_draw_target(&self) -> ProgressDrawTarget {
        self.progress_draw_target()
    }

    fn print_ansi(&mut self, message: &[u8]) -> io::Result<()> {
        fwdansi::write_ansi(self.err(), message)
    }

    fn warn<T: fmt::Display>(&mut self, message: T) -> io::Result<()> {
        self.warn(message)
    }

    fn on_request(&mut self, req: &reqwest::blocking::Request) -> io::Result<()> {
        if let ShellOut::Stream {
            stderr,
            stderr_tty: true,
            ..
        } = &mut self.output
        {
            stderr.set_color(color_spec!(Bold, Fg(Color::Cyan)))?;
            write!(stderr, "{:>12}", req.method())?;
            stderr.reset()?;
            write!(stderr, " {} ...\r", req.url())?;
            stderr.flush()?;

            self.needs_clear = true;
        }
        Ok(())
    }

    fn on_response(
        &mut self,
        _: &reqwest::blocking::Response,
        _: StatusCodeColor,
    ) -> io::Result<()> {
        if self.needs_clear {
            self.err_erase_line();
        }
        Ok(())
    }
}

enum ShellIn {
    Tty,
    PipedStdin,
    Reader(Box<dyn BufRead>),
}

impl ShellIn {
    fn stdin() -> Self {
        if atty::is(atty::Stream::Stdin) {
            Self::Tty
        } else {
            Self::PipedStdin
        }
    }
}

impl ShellIn {
    fn read_reply(&mut self) -> io::Result<String> {
        match self {
            Self::Tty | Self::PipedStdin => rprompt::read_reply(),
            Self::Reader(r) => rpassword::read_password_with_reader(Some(r)),
        }
    }

    fn read_password(&mut self) -> io::Result<String> {
        match self {
            Self::Tty => rpassword::read_password_from_tty(None),
            Self::PipedStdin => rprompt::read_reply(),
            Self::Reader(r) => rpassword::read_password_with_reader(Some(r)),
        }
    }
}

enum ShellOut {
    Write(NoColor<Box<dyn Write>>),
    Stream {
        stdout: BufferedStandardStream,
        stderr: BufferedStandardStream,
        stderr_tty: bool,
    },
}

impl ShellOut {
    fn stream() -> Self {
        Self::Stream {
            stdout: BufferedStandardStream::stdout(if atty::is(atty::Stream::Stdout) {
                termcolor::ColorChoice::Auto
            } else {
                termcolor::ColorChoice::Never
            }),
            stderr: BufferedStandardStream::stderr(if atty::is(atty::Stream::Stderr) {
                termcolor::ColorChoice::Auto
            } else {
                termcolor::ColorChoice::Never
            }),
            stderr_tty: atty::is(atty::Stream::Stderr),
        }
    }

    fn stdout(&mut self) -> &mut dyn Write {
        match self {
            Self::Write(wtr) => wtr,
            Self::Stream { stdout, .. } => stdout,
        }
    }

    fn stderr(&mut self) -> &mut dyn WriteColor {
        match self {
            Self::Write(wtr) => wtr,
            Self::Stream { stderr, .. } => stderr,
        }
    }

    fn stderr_tty(&self) -> bool {
        match *self {
            Self::Write(_) => false,
            Self::Stream { stderr_tty, .. } => stderr_tty,
        }
    }

    fn set_color_choice(&mut self, color: ColorChoice) {
        if let Self::Stream { stdout, stderr, .. } = self {
            let _ = stdout.flush();
            let _ = stderr.flush();

            *stdout = BufferedStandardStream::stdout(
                color.to_termcolor_color_choice(atty::Stream::Stdout),
            );

            *stderr = BufferedStandardStream::stderr(
                color.to_termcolor_color_choice(atty::Stream::Stderr),
            );
        }
    }

    fn message_stderr(
        &mut self,
        status: impl fmt::Display,
        message: impl fmt::Display,
        color: Color,
    ) -> io::Result<()> {
        let stderr = self.stderr();

        stderr.set_color(color_spec!(Bold, Fg(color)))?;
        write!(stderr, "{:>12}", status)?;
        stderr.reset()?;

        writeln!(stderr, " {}", message)?;
        stderr.flush()
    }
}

#[derive(EnumString, EnumVariantNames, Clone, Copy, Debug)]
#[strum(serialize_all = "kebab-case")]
pub enum ColorChoice {
    Auto,
    Always,
    Never,
}

impl ColorChoice {
    fn to_termcolor_color_choice(self, stream: atty::Stream) -> termcolor::ColorChoice {
        match (self, atty::is(stream)) {
            (Self::Auto, true) => termcolor::ColorChoice::Auto,
            (Self::Always, _) => termcolor::ColorChoice::Always,
            _ => termcolor::ColorChoice::Never,
        }
    }
}