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#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum Verbosity {
13 Verbose,
14 Normal,
15 Quiet,
16}
17
18pub struct Shell {
21 err: ShellOut,
24 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
44enum ShellOut {
46 Write(Box<dyn Write>),
48 Stream {
50 stream: StandardStream,
51 tty: bool,
52 color_choice: ColorChoice,
53 },
54}
55
56#[derive(Debug, PartialEq, Clone, Copy)]
58pub enum ColorChoice {
59 Always,
61 Never,
63 CargoAuto,
65}
66
67impl Shell {
68 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 pub fn from_write(out: Box<dyn Write>) -> Shell {
83 Shell {
84 err: ShellOut::Write(out),
85 verbosity: Verbosity::Verbose,
86 }
87 }
88
89 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 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 pub fn is_err_tty(&self) -> bool {
114 match self.err {
115 ShellOut::Stream { tty, .. } => tty,
116 _ => false,
117 }
118 }
119
120 pub fn err(&mut self) -> &mut dyn Write {
122 self.err.as_write()
123 }
124
125 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 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 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 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 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 pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
186 self.print(&"error:", Some(&message), Red, false)
187 }
188
189 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 pub fn set_verbosity(&mut self, verbosity: Verbosity) {
199 self.verbosity = verbosity;
200 }
201
202 pub fn verbosity(&self) -> Verbosity {
204 self.verbosity
205 }
206
207 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 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 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 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 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 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 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 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 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 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}