1use std::fmt;
2use std::io::prelude::*;
3use std::io::IsTerminal;
4
5use annotate_snippets::{Message, Renderer};
6use anstream::AutoStream;
7use anstyle::Style;
8
9use crate::util::errors::CargoResult;
10use crate::util::hostname;
11use crate::util::style::*;
12
13pub struct Shell {
16 output: ShellOut,
19 verbosity: Verbosity,
21 needs_clear: bool,
24 hostname: Option<String>,
25}
26
27impl fmt::Debug for Shell {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 match self.output {
30 ShellOut::Write(_) => f
31 .debug_struct("Shell")
32 .field("verbosity", &self.verbosity)
33 .finish(),
34 ShellOut::Stream { color_choice, .. } => f
35 .debug_struct("Shell")
36 .field("verbosity", &self.verbosity)
37 .field("color_choice", &color_choice)
38 .finish(),
39 }
40 }
41}
42
43impl Shell {
44 pub fn new() -> Shell {
47 let auto_clr = ColorChoice::CargoAuto;
48 let stdout_choice = auto_clr.to_anstream_color_choice();
49 let stderr_choice = auto_clr.to_anstream_color_choice();
50 Shell {
51 output: ShellOut::Stream {
52 stdout: AutoStream::new(std::io::stdout(), stdout_choice),
53 stderr: AutoStream::new(std::io::stderr(), stderr_choice),
54 color_choice: auto_clr,
55 hyperlinks: supports_hyperlinks(),
56 stderr_tty: std::io::stderr().is_terminal(),
57 stdout_unicode: supports_unicode(&std::io::stdout()),
58 stderr_unicode: supports_unicode(&std::io::stderr()),
59 stderr_term_integration: supports_term_integration(&std::io::stderr()),
60 },
61 verbosity: Verbosity::Verbose,
62 needs_clear: false,
63 hostname: None,
64 }
65 }
66
67 pub fn from_write(out: Box<dyn Write>) -> Shell {
69 Shell {
70 output: ShellOut::Write(AutoStream::never(out)), verbosity: Verbosity::Verbose,
72 needs_clear: false,
73 hostname: None,
74 }
75 }
76
77 fn print(
80 &mut self,
81 status: &dyn fmt::Display,
82 message: Option<&dyn fmt::Display>,
83 color: &Style,
84 justified: bool,
85 ) -> CargoResult<()> {
86 match self.verbosity {
87 Verbosity::Quiet => Ok(()),
88 _ => {
89 if self.needs_clear {
90 self.err_erase_line();
91 }
92 self.output
93 .message_stderr(status, message, color, justified)
94 }
95 }
96 }
97
98 pub fn set_needs_clear(&mut self, needs_clear: bool) {
100 self.needs_clear = needs_clear;
101 }
102
103 pub fn is_cleared(&self) -> bool {
105 !self.needs_clear
106 }
107
108 pub fn err_width(&self) -> TtyWidth {
110 match self.output {
111 ShellOut::Stream {
112 stderr_tty: true, ..
113 } => imp::stderr_width(),
114 _ => TtyWidth::NoTty,
115 }
116 }
117
118 pub fn is_err_tty(&self) -> bool {
120 match self.output {
121 ShellOut::Stream { stderr_tty, .. } => stderr_tty,
122 _ => false,
123 }
124 }
125
126 pub fn is_err_term_integration_available(&self) -> bool {
127 if let ShellOut::Stream {
128 stderr_term_integration,
129 ..
130 } = self.output
131 {
132 stderr_term_integration
133 } else {
134 false
135 }
136 }
137
138 pub fn out(&mut self) -> &mut dyn Write {
140 if self.needs_clear {
141 self.err_erase_line();
142 }
143 self.output.stdout()
144 }
145
146 pub fn err(&mut self) -> &mut dyn Write {
148 if self.needs_clear {
149 self.err_erase_line();
150 }
151 self.output.stderr()
152 }
153
154 pub fn err_erase_line(&mut self) {
156 if self.err_supports_color() {
157 imp::err_erase_line(self);
158 self.needs_clear = false;
159 }
160 }
161
162 pub fn status<T, U>(&mut self, status: T, message: U) -> CargoResult<()>
164 where
165 T: fmt::Display,
166 U: fmt::Display,
167 {
168 self.print(&status, Some(&message), &HEADER, true)
169 }
170
171 pub fn status_header<T>(&mut self, status: T) -> CargoResult<()>
172 where
173 T: fmt::Display,
174 {
175 self.print(&status, None, &NOTE, true)
176 }
177
178 pub fn status_with_color<T, U>(
180 &mut self,
181 status: T,
182 message: U,
183 color: &Style,
184 ) -> CargoResult<()>
185 where
186 T: fmt::Display,
187 U: fmt::Display,
188 {
189 self.print(&status, Some(&message), color, true)
190 }
191
192 pub fn verbose<F>(&mut self, mut callback: F) -> CargoResult<()>
194 where
195 F: FnMut(&mut Shell) -> CargoResult<()>,
196 {
197 match self.verbosity {
198 Verbosity::Verbose => callback(self),
199 _ => Ok(()),
200 }
201 }
202
203 pub fn concise<F>(&mut self, mut callback: F) -> CargoResult<()>
205 where
206 F: FnMut(&mut Shell) -> CargoResult<()>,
207 {
208 match self.verbosity {
209 Verbosity::Verbose => Ok(()),
210 _ => callback(self),
211 }
212 }
213
214 pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
216 if self.needs_clear {
217 self.err_erase_line();
218 }
219 self.output
220 .message_stderr(&"error", Some(&message), &ERROR, false)
221 }
222
223 pub fn warn<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
225 match self.verbosity {
226 Verbosity::Quiet => Ok(()),
227 _ => self.print(&"warning", Some(&message), &WARN, false),
228 }
229 }
230
231 pub fn note<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
233 self.print(&"note", Some(&message), &NOTE, false)
234 }
235
236 pub fn set_verbosity(&mut self, verbosity: Verbosity) {
238 self.verbosity = verbosity;
239 }
240
241 pub fn verbosity(&self) -> Verbosity {
243 self.verbosity
244 }
245
246 pub fn set_color_choice(&mut self, color: Option<&str>) -> CargoResult<()> {
248 if let ShellOut::Stream {
249 stdout,
250 stderr,
251 color_choice,
252 ..
253 } = &mut self.output
254 {
255 let cfg = color
256 .map(|c| c.parse())
257 .transpose()?
258 .unwrap_or(ColorChoice::CargoAuto);
259 *color_choice = cfg;
260 let stdout_choice = cfg.to_anstream_color_choice();
261 let stderr_choice = cfg.to_anstream_color_choice();
262 *stdout = AutoStream::new(std::io::stdout(), stdout_choice);
263 *stderr = AutoStream::new(std::io::stderr(), stderr_choice);
264 }
265 Ok(())
266 }
267
268 pub fn set_unicode(&mut self, yes: bool) -> CargoResult<()> {
269 if let ShellOut::Stream {
270 stdout_unicode,
271 stderr_unicode,
272 ..
273 } = &mut self.output
274 {
275 *stdout_unicode = yes;
276 *stderr_unicode = yes;
277 }
278 Ok(())
279 }
280
281 pub fn set_hyperlinks(&mut self, yes: bool) -> CargoResult<()> {
282 if let ShellOut::Stream { hyperlinks, .. } = &mut self.output {
283 *hyperlinks = yes;
284 }
285 Ok(())
286 }
287
288 pub fn out_unicode(&self) -> bool {
289 match &self.output {
290 ShellOut::Write(_) => true,
291 ShellOut::Stream { stdout_unicode, .. } => *stdout_unicode,
292 }
293 }
294
295 pub fn err_unicode(&self) -> bool {
296 match &self.output {
297 ShellOut::Write(_) => true,
298 ShellOut::Stream { stderr_unicode, .. } => *stderr_unicode,
299 }
300 }
301
302 pub fn color_choice(&self) -> ColorChoice {
307 match self.output {
308 ShellOut::Stream { color_choice, .. } => color_choice,
309 ShellOut::Write(_) => ColorChoice::Never,
310 }
311 }
312
313 pub fn err_supports_color(&self) -> bool {
315 match &self.output {
316 ShellOut::Write(_) => false,
317 ShellOut::Stream { stderr, .. } => supports_color(stderr.current_choice()),
318 }
319 }
320
321 pub fn out_supports_color(&self) -> bool {
322 match &self.output {
323 ShellOut::Write(_) => false,
324 ShellOut::Stream { stdout, .. } => supports_color(stdout.current_choice()),
325 }
326 }
327
328 pub fn out_hyperlink<D: fmt::Display>(&self, url: D) -> Hyperlink<D> {
329 let supports_hyperlinks = match &self.output {
330 ShellOut::Write(_) => false,
331 ShellOut::Stream {
332 stdout, hyperlinks, ..
333 } => stdout.current_choice() == anstream::ColorChoice::AlwaysAnsi && *hyperlinks,
334 };
335 Hyperlink {
336 url: supports_hyperlinks.then_some(url),
337 }
338 }
339
340 pub fn err_hyperlink<D: fmt::Display>(&self, url: D) -> Hyperlink<D> {
341 let supports_hyperlinks = match &self.output {
342 ShellOut::Write(_) => false,
343 ShellOut::Stream {
344 stderr, hyperlinks, ..
345 } => stderr.current_choice() == anstream::ColorChoice::AlwaysAnsi && *hyperlinks,
346 };
347 if supports_hyperlinks {
348 Hyperlink { url: Some(url) }
349 } else {
350 Hyperlink { url: None }
351 }
352 }
353
354 pub fn out_file_hyperlink(&mut self, path: &std::path::Path) -> Hyperlink<url::Url> {
355 let url = self.file_hyperlink(path);
356 url.map(|u| self.out_hyperlink(u)).unwrap_or_default()
357 }
358
359 pub fn err_file_hyperlink(&mut self, path: &std::path::Path) -> Hyperlink<url::Url> {
360 let url = self.file_hyperlink(path);
361 url.map(|u| self.err_hyperlink(u)).unwrap_or_default()
362 }
363
364 fn file_hyperlink(&mut self, path: &std::path::Path) -> Option<url::Url> {
365 let mut url = url::Url::from_file_path(path).ok()?;
366 let hostname = if cfg!(windows) {
369 None
371 } else {
372 if let Some(hostname) = self.hostname.as_deref() {
373 Some(hostname)
374 } else {
375 self.hostname = hostname().ok().and_then(|h| h.into_string().ok());
376 self.hostname.as_deref()
377 }
378 };
379 let _ = url.set_host(hostname);
380 Some(url)
381 }
382
383 pub fn print_ansi_stderr(&mut self, message: &[u8]) -> CargoResult<()> {
385 if self.needs_clear {
386 self.err_erase_line();
387 }
388 self.err().write_all(message)?;
389 Ok(())
390 }
391
392 pub fn print_ansi_stdout(&mut self, message: &[u8]) -> CargoResult<()> {
394 if self.needs_clear {
395 self.err_erase_line();
396 }
397 self.out().write_all(message)?;
398 Ok(())
399 }
400
401 pub fn print_json<T: serde::ser::Serialize>(&mut self, obj: &T) -> CargoResult<()> {
402 let encoded = serde_json::to_string(&obj)?;
404 drop(writeln!(self.out(), "{}", encoded));
406 Ok(())
407 }
408
409 pub fn print_message(&mut self, message: Message<'_>) -> std::io::Result<()> {
411 let term_width = self
412 .err_width()
413 .diagnostic_terminal_width()
414 .unwrap_or(annotate_snippets::renderer::DEFAULT_TERM_WIDTH);
415 writeln!(
416 self.err(),
417 "{}",
418 Renderer::styled().term_width(term_width).render(message)
419 )
420 }
421}
422
423impl Default for Shell {
424 fn default() -> Self {
425 Self::new()
426 }
427}
428
429enum ShellOut {
431 Write(AutoStream<Box<dyn Write>>),
433 Stream {
435 stdout: AutoStream<std::io::Stdout>,
436 stderr: AutoStream<std::io::Stderr>,
437 stderr_tty: bool,
438 color_choice: ColorChoice,
439 hyperlinks: bool,
440 stdout_unicode: bool,
441 stderr_unicode: bool,
442 stderr_term_integration: bool,
443 },
444}
445
446impl ShellOut {
447 fn message_stderr(
451 &mut self,
452 status: &dyn fmt::Display,
453 message: Option<&dyn fmt::Display>,
454 style: &Style,
455 justified: bool,
456 ) -> CargoResult<()> {
457 let bold = anstyle::Style::new() | anstyle::Effects::BOLD;
458
459 let mut buffer = Vec::new();
460 if justified {
461 write!(&mut buffer, "{style}{status:>12}{style:#}")?;
462 } else {
463 write!(&mut buffer, "{style}{status}{style:#}{bold}:{bold:#}")?;
464 }
465 match message {
466 Some(message) => writeln!(buffer, " {message}")?,
467 None => write!(buffer, " ")?,
468 }
469 self.stderr().write_all(&buffer)?;
470 Ok(())
471 }
472
473 fn stdout(&mut self) -> &mut dyn Write {
475 match self {
476 ShellOut::Stream { stdout, .. } => stdout,
477 ShellOut::Write(w) => w,
478 }
479 }
480
481 fn stderr(&mut self) -> &mut dyn Write {
483 match self {
484 ShellOut::Stream { stderr, .. } => stderr,
485 ShellOut::Write(w) => w,
486 }
487 }
488}
489
490pub enum TtyWidth {
491 NoTty,
492 Known(usize),
493 Guess(usize),
494}
495
496impl TtyWidth {
497 pub fn diagnostic_terminal_width(&self) -> Option<usize> {
500 #[allow(clippy::disallowed_methods)]
502 if let Ok(width) = std::env::var("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS") {
503 return Some(width.parse().unwrap());
504 }
505 match *self {
506 TtyWidth::NoTty | TtyWidth::Guess(_) => None,
507 TtyWidth::Known(width) => Some(width),
508 }
509 }
510
511 pub fn progress_max_width(&self) -> Option<usize> {
513 match *self {
514 TtyWidth::NoTty => None,
515 TtyWidth::Known(width) | TtyWidth::Guess(width) => Some(width),
516 }
517 }
518}
519
520#[derive(Debug, Clone, Copy, PartialEq)]
522pub enum Verbosity {
523 Verbose,
524 Normal,
525 Quiet,
526}
527
528#[derive(Debug, PartialEq, Clone, Copy)]
530pub enum ColorChoice {
531 Always,
533 Never,
535 CargoAuto,
537}
538
539impl ColorChoice {
540 fn to_anstream_color_choice(self) -> anstream::ColorChoice {
542 match self {
543 ColorChoice::Always => anstream::ColorChoice::Always,
544 ColorChoice::Never => anstream::ColorChoice::Never,
545 ColorChoice::CargoAuto => anstream::ColorChoice::Auto,
546 }
547 }
548}
549
550impl std::str::FromStr for ColorChoice {
551 type Err = anyhow::Error;
552 fn from_str(color: &str) -> Result<Self, Self::Err> {
553 let cfg = match color {
554 "always" => ColorChoice::Always,
555 "never" => ColorChoice::Never,
556
557 "auto" => ColorChoice::CargoAuto,
558
559 arg => anyhow::bail!(
560 "argument for --color must be auto, always, or \
561 never, but found `{}`",
562 arg
563 ),
564 };
565 Ok(cfg)
566 }
567}
568
569fn supports_color(choice: anstream::ColorChoice) -> bool {
570 match choice {
571 anstream::ColorChoice::Always
572 | anstream::ColorChoice::AlwaysAnsi
573 | anstream::ColorChoice::Auto => true,
574 anstream::ColorChoice::Never => false,
575 }
576}
577
578fn supports_unicode(stream: &dyn IsTerminal) -> bool {
579 !stream.is_terminal() || supports_unicode::supports_unicode()
580}
581
582fn supports_hyperlinks() -> bool {
583 #[allow(clippy::disallowed_methods)] if std::env::var_os("TERM_PROGRAM").as_deref() == Some(std::ffi::OsStr::new("iTerm.app")) {
585 return false;
587 }
588
589 supports_hyperlinks::supports_hyperlinks()
590}
591
592#[allow(clippy::disallowed_methods)] fn supports_term_integration(stream: &dyn IsTerminal) -> bool {
595 let windows_terminal = std::env::var("WT_SESSION").is_ok();
596 let conemu = std::env::var("ConEmuANSI").ok() == Some("ON".into());
597 let wezterm = std::env::var("TERM_PROGRAM").ok() == Some("WezTerm".into());
598
599 (windows_terminal || conemu || wezterm) && stream.is_terminal()
600}
601
602pub struct Hyperlink<D: fmt::Display> {
603 url: Option<D>,
604}
605
606impl<D: fmt::Display> Default for Hyperlink<D> {
607 fn default() -> Self {
608 Self { url: None }
609 }
610}
611
612impl<D: fmt::Display> fmt::Display for Hyperlink<D> {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 let Some(url) = self.url.as_ref() else {
615 return Ok(());
616 };
617 if f.alternate() {
618 write!(f, "\x1B]8;;\x1B\\")
619 } else {
620 write!(f, "\x1B]8;;{url}\x1B\\")
621 }
622 }
623}
624
625#[cfg(unix)]
626mod imp {
627 use super::{Shell, TtyWidth};
628 use std::mem;
629
630 pub fn stderr_width() -> TtyWidth {
631 unsafe {
632 let mut winsize: libc::winsize = mem::zeroed();
633 if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ.into(), &mut winsize) < 0 {
636 return TtyWidth::NoTty;
637 }
638 if winsize.ws_col > 0 {
639 TtyWidth::Known(winsize.ws_col as usize)
640 } else {
641 TtyWidth::NoTty
642 }
643 }
644 }
645
646 pub fn err_erase_line(shell: &mut Shell) {
647 let _ = shell.output.stderr().write_all(b"\x1B[K");
651 }
652}
653
654#[cfg(windows)]
655mod imp {
656 use std::{cmp, mem, ptr};
657
658 use windows_sys::core::PCSTR;
659 use windows_sys::Win32::Foundation::CloseHandle;
660 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
661 use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE};
662 use windows_sys::Win32::Storage::FileSystem::{
663 CreateFileA, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
664 };
665 use windows_sys::Win32::System::Console::{
666 GetConsoleScreenBufferInfo, GetStdHandle, CONSOLE_SCREEN_BUFFER_INFO, STD_ERROR_HANDLE,
667 };
668
669 pub(super) use super::{default_err_erase_line as err_erase_line, TtyWidth};
670
671 pub fn stderr_width() -> TtyWidth {
672 unsafe {
673 let stdout = GetStdHandle(STD_ERROR_HANDLE);
674 let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
675 if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
676 return TtyWidth::Known((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
677 }
678
679 let h = CreateFileA(
683 "CONOUT$\0".as_ptr() as PCSTR,
684 GENERIC_READ | GENERIC_WRITE,
685 FILE_SHARE_READ | FILE_SHARE_WRITE,
686 ptr::null_mut(),
687 OPEN_EXISTING,
688 0,
689 std::ptr::null_mut(),
690 );
691 if h == INVALID_HANDLE_VALUE {
692 return TtyWidth::NoTty;
693 }
694
695 let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
696 let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
697 CloseHandle(h);
698 if rc != 0 {
699 let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
700 return TtyWidth::Guess(cmp::min(60, width));
709 }
710
711 TtyWidth::NoTty
712 }
713 }
714}
715
716#[cfg(windows)]
717fn default_err_erase_line(shell: &mut Shell) {
718 match imp::stderr_width() {
719 TtyWidth::Known(max_width) | TtyWidth::Guess(max_width) => {
720 let blank = " ".repeat(max_width);
721 drop(write!(shell.output.stderr(), "{}\r", blank));
722 }
723 _ => (),
724 }
725}