Skip to main content

cargo/core/
shell.rs

1use std::fmt;
2use std::io::prelude::*;
3
4use atty;
5use termcolor::Color::{Cyan, Green, Red, Yellow};
6use termcolor::{self, Color, ColorSpec, StandardStream, WriteColor};
7
8use crate::util::errors::CargoResult;
9
10/// The requested verbosity of output
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum Verbosity {
13    Verbose,
14    Normal,
15    Quiet,
16}
17
18/// An abstraction around a `Write`able object that remembers preferences for output verbosity and
19/// color.
20pub struct Shell {
21    /// the `Write`able object, either with or without color support (represented by different enum
22    /// variants)
23    err: ShellOut,
24    /// How verbose messages should be
25    verbosity: Verbosity,
26}
27
28impl fmt::Debug for Shell {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self.err {
31            ShellOut::Write(_) => f
32                .debug_struct("Shell")
33                .field("verbosity", &self.verbosity)
34                .finish(),
35            ShellOut::Stream { color_choice, .. } => f
36                .debug_struct("Shell")
37                .field("verbosity", &self.verbosity)
38                .field("color_choice", &color_choice)
39                .finish(),
40        }
41    }
42}
43
44/// A `Write`able object, either with or without color support
45enum ShellOut {
46    /// A plain write object without color support
47    Write(Box<dyn Write>),
48    /// Color-enabled stdio, with information on whether color should be used
49    Stream {
50        stream: StandardStream,
51        tty: bool,
52        color_choice: ColorChoice,
53    },
54}
55
56/// Whether messages should use color output
57#[derive(Debug, PartialEq, Clone, Copy)]
58pub enum ColorChoice {
59    /// Force color output
60    Always,
61    /// Force disable color output
62    Never,
63    /// Intelligently guess whether to use color output
64    CargoAuto,
65}
66
67impl Shell {
68    /// Create a new shell (color choice and verbosity), defaulting to 'auto' color and verbose
69    /// output.
70    pub fn new() -> Shell {
71        Shell {
72            err: ShellOut::Stream {
73                stream: StandardStream::stderr(ColorChoice::CargoAuto.to_termcolor_color_choice()),
74                color_choice: ColorChoice::CargoAuto,
75                tty: atty::is(atty::Stream::Stderr),
76            },
77            verbosity: Verbosity::Verbose,
78        }
79    }
80
81    /// Create a shell from a plain writable object, with no color, and max verbosity.
82    pub fn from_write(out: Box<dyn Write>) -> Shell {
83        Shell {
84            err: ShellOut::Write(out),
85            verbosity: Verbosity::Verbose,
86        }
87    }
88
89    /// Print a message, where the status will have `color` color, and can be justified. The
90    /// messages follows without color.
91    fn print(
92        &mut self,
93        status: &dyn fmt::Display,
94        message: Option<&dyn fmt::Display>,
95        color: Color,
96        justified: bool,
97    ) -> CargoResult<()> {
98        match self.verbosity {
99            Verbosity::Quiet => Ok(()),
100            _ => self.err.print(status, message, color, justified),
101        }
102    }
103
104    /// Returns the width of the terminal in spaces, if any
105    pub fn err_width(&self) -> Option<usize> {
106        match self.err {
107            ShellOut::Stream { tty: true, .. } => imp::stderr_width(),
108            _ => None,
109        }
110    }
111
112    /// Returns whether stderr is a tty
113    pub fn is_err_tty(&self) -> bool {
114        match self.err {
115            ShellOut::Stream { tty, .. } => tty,
116            _ => false,
117        }
118    }
119
120    /// Get a reference to the underlying writer
121    pub fn err(&mut self) -> &mut dyn Write {
122        self.err.as_write()
123    }
124
125    /// Erase from cursor to end of line.
126    pub fn err_erase_line(&mut self) {
127        if let ShellOut::Stream { tty: true, .. } = self.err {
128            imp::err_erase_line(self);
129        }
130    }
131
132    /// Shortcut to right-align and color green a status message.
133    pub fn status<T, U>(&mut self, status: T, message: U) -> CargoResult<()>
134    where
135        T: fmt::Display,
136        U: fmt::Display,
137    {
138        self.print(&status, Some(&message), Green, true)
139    }
140
141    pub fn status_header<T>(&mut self, status: T) -> CargoResult<()>
142    where
143        T: fmt::Display,
144    {
145        self.print(&status, None, Cyan, true)
146    }
147
148    /// Shortcut to right-align a status message.
149    pub fn status_with_color<T, U>(
150        &mut self,
151        status: T,
152        message: U,
153        color: Color,
154    ) -> CargoResult<()>
155    where
156        T: fmt::Display,
157        U: fmt::Display,
158    {
159        self.print(&status, Some(&message), color, true)
160    }
161
162    /// Run the callback only if we are in verbose mode
163    pub fn verbose<F>(&mut self, mut callback: F) -> CargoResult<()>
164    where
165        F: FnMut(&mut Shell) -> CargoResult<()>,
166    {
167        match self.verbosity {
168            Verbosity::Verbose => callback(self),
169            _ => Ok(()),
170        }
171    }
172
173    /// Run the callback if we are not in verbose mode.
174    pub fn concise<F>(&mut self, mut callback: F) -> CargoResult<()>
175    where
176        F: FnMut(&mut Shell) -> CargoResult<()>,
177    {
178        match self.verbosity {
179            Verbosity::Verbose => Ok(()),
180            _ => callback(self),
181        }
182    }
183
184    /// Print a red 'error' message
185    pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
186        self.print(&"error:", Some(&message), Red, false)
187    }
188
189    /// Print an amber 'warning' message
190    pub fn warn<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
191        match self.verbosity {
192            Verbosity::Quiet => Ok(()),
193            _ => self.print(&"warning:", Some(&message), Yellow, false),
194        }
195    }
196
197    /// Update the verbosity of the shell
198    pub fn set_verbosity(&mut self, verbosity: Verbosity) {
199        self.verbosity = verbosity;
200    }
201
202    /// Get the verbosity of the shell
203    pub fn verbosity(&self) -> Verbosity {
204        self.verbosity
205    }
206
207    /// Update the color choice (always, never, or auto) from a string.
208    pub fn set_color_choice(&mut self, color: Option<&str>) -> CargoResult<()> {
209        if let ShellOut::Stream {
210            ref mut stream,
211            ref mut color_choice,
212            ..
213        } = self.err
214        {
215            let cfg = match color {
216                Some("always") => ColorChoice::Always,
217                Some("never") => ColorChoice::Never,
218
219                Some("auto") | None => ColorChoice::CargoAuto,
220
221                Some(arg) => failure::bail!(
222                    "argument for --color must be auto, always, or \
223                     never, but found `{}`",
224                    arg
225                ),
226            };
227            *color_choice = cfg;
228            *stream = StandardStream::stderr(cfg.to_termcolor_color_choice());
229        }
230        Ok(())
231    }
232
233    /// Get the current color choice
234    ///
235    /// If we are not using a color stream, this will always return Never, even if the color choice
236    /// has been set to something else.
237    pub fn color_choice(&self) -> ColorChoice {
238        match self.err {
239            ShellOut::Stream { color_choice, .. } => color_choice,
240            ShellOut::Write(_) => ColorChoice::Never,
241        }
242    }
243
244    /// Whether the shell supports color.
245    pub fn supports_color(&self) -> bool {
246        match &self.err {
247            ShellOut::Write(_) => false,
248            ShellOut::Stream { stream, .. } => stream.supports_color(),
249        }
250    }
251
252    /// Prints a message and translates ANSI escape code into console colors.
253    pub fn print_ansi(&mut self, message: &[u8]) -> CargoResult<()> {
254        #[cfg(windows)]
255        {
256            if let ShellOut::Stream { stream, .. } = &mut self.err {
257                ::fwdansi::write_ansi(stream, message)?;
258                return Ok(());
259            }
260        }
261        self.err().write_all(message)?;
262        Ok(())
263    }
264}
265
266impl Default for Shell {
267    fn default() -> Self {
268        Self::new()
269    }
270}
271
272impl ShellOut {
273    /// Print out a message with a status. The status comes first and is bold + the given color.
274    /// The status can be justified, in which case the max width that will right align is 12 chars.
275    fn print(
276        &mut self,
277        status: &dyn fmt::Display,
278        message: Option<&dyn fmt::Display>,
279        color: Color,
280        justified: bool,
281    ) -> CargoResult<()> {
282        match *self {
283            ShellOut::Stream { ref mut stream, .. } => {
284                stream.reset()?;
285                stream.set_color(ColorSpec::new().set_bold(true).set_fg(Some(color)))?;
286                if justified {
287                    write!(stream, "{:>12}", status)?;
288                } else {
289                    write!(stream, "{}", status)?;
290                }
291                stream.reset()?;
292                match message {
293                    Some(message) => writeln!(stream, " {}", message)?,
294                    None => write!(stream, " ")?,
295                }
296            }
297            ShellOut::Write(ref mut w) => {
298                if justified {
299                    write!(w, "{:>12}", status)?;
300                } else {
301                    write!(w, "{}", status)?;
302                }
303                match message {
304                    Some(message) => writeln!(w, " {}", message)?,
305                    None => write!(w, " ")?,
306                }
307            }
308        }
309        Ok(())
310    }
311
312    /// Get this object as a `io::Write`.
313    fn as_write(&mut self) -> &mut dyn Write {
314        match *self {
315            ShellOut::Stream { ref mut stream, .. } => stream,
316            ShellOut::Write(ref mut w) => w,
317        }
318    }
319}
320
321impl ColorChoice {
322    /// Convert our color choice to termcolor's version
323    fn to_termcolor_color_choice(self) -> termcolor::ColorChoice {
324        match self {
325            ColorChoice::Always => termcolor::ColorChoice::Always,
326            ColorChoice::Never => termcolor::ColorChoice::Never,
327            ColorChoice::CargoAuto => {
328                if atty::is(atty::Stream::Stderr) {
329                    termcolor::ColorChoice::Auto
330                } else {
331                    termcolor::ColorChoice::Never
332                }
333            }
334        }
335    }
336}
337
338#[cfg(any(target_os = "linux", target_os = "macos"))]
339mod imp {
340    use std::mem;
341
342    use libc;
343
344    use super::Shell;
345
346    pub fn stderr_width() -> Option<usize> {
347        unsafe {
348            let mut winsize: libc::winsize = mem::zeroed();
349            if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ, &mut winsize) < 0 {
350                return None;
351            }
352            if winsize.ws_col > 0 {
353                Some(winsize.ws_col as usize)
354            } else {
355                None
356            }
357        }
358    }
359
360    pub fn err_erase_line(shell: &mut Shell) {
361        // This is the "EL - Erase in Line" sequence. It clears from the cursor
362        // to the end of line.
363        // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
364        let _ = shell.err().write_all(b"\x1B[K");
365    }
366}
367
368#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
369mod imp {
370    pub(super) use super::default_err_erase_line as err_erase_line;
371
372    pub fn stderr_width() -> Option<usize> {
373        None
374    }
375}
376
377#[cfg(windows)]
378mod imp {
379    use std::{cmp, mem, ptr};
380    use winapi::um::fileapi::*;
381    use winapi::um::handleapi::*;
382    use winapi::um::processenv::*;
383    use winapi::um::winbase::*;
384    use winapi::um::wincon::*;
385    use winapi::um::winnt::*;
386
387    pub(super) use super::default_err_erase_line as err_erase_line;
388
389    pub fn stderr_width() -> Option<usize> {
390        unsafe {
391            let stdout = GetStdHandle(STD_ERROR_HANDLE);
392            let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
393            if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
394                return Some((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
395            }
396
397            // On mintty/msys/cygwin based terminals, the above fails with
398            // INVALID_HANDLE_VALUE. Use an alternate method which works
399            // in that case as well.
400            let h = CreateFileA(
401                "CONOUT$\0".as_ptr() as *const CHAR,
402                GENERIC_READ | GENERIC_WRITE,
403                FILE_SHARE_READ | FILE_SHARE_WRITE,
404                ptr::null_mut(),
405                OPEN_EXISTING,
406                0,
407                ptr::null_mut(),
408            );
409            if h == INVALID_HANDLE_VALUE {
410                return None;
411            }
412
413            let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
414            let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
415            CloseHandle(h);
416            if rc != 0 {
417                let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
418                // Unfortunately cygwin/mintty does not set the size of the
419                // backing console to match the actual window size. This
420                // always reports a size of 80 or 120 (not sure what
421                // determines that). Use a conservative max of 60 which should
422                // work in most circumstances. ConEmu does some magic to
423                // resize the console correctly, but there's no reasonable way
424                // to detect which kind of terminal we are running in, or if
425                // GetConsoleScreenBufferInfo returns accurate information.
426                return Some(cmp::min(60, width));
427            }
428            None
429        }
430    }
431}
432
433#[cfg(any(all(unix, not(any(target_os = "linux", target_os = "macos"))), windows,))]
434fn default_err_erase_line(shell: &mut Shell) {
435    if let Some(max_width) = imp::stderr_width() {
436        let blank = " ".repeat(max_width);
437        drop(write!(shell.err(), "{}\r", blank));
438    }
439}