1use std::fmt;
2use std::io::IsTerminal;
3use std::io::prelude::*;
4
5use annotate_snippets::renderer::DecorStyle;
6use annotate_snippets::{Renderer, Report};
7use anstream::AutoStream;
8use anstyle::Style;
9
10use crate::CargoResult;
11use crate::style::*;
12
13pub use anstyle_hyperlink::Hyperlink;
14
15pub struct Shell {
18 output: ShellOut,
21 verbosity: Verbosity,
23 needs_clear: bool,
26}
27
28impl fmt::Debug for Shell {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self.output {
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
44impl Shell {
45 pub fn new() -> Shell {
48 let auto_clr = ColorChoice::CargoAuto;
49 let stdout_choice = auto_clr.to_anstream_color_choice();
50 let stderr_choice = auto_clr.to_anstream_color_choice();
51 let no_graphics = std::env::var_os("NO_GRAPHICS").is_some_and(|v| !v.is_empty());
52 Shell {
53 output: ShellOut::Stream {
54 stdout: AutoStream::new(std::io::stdout(), stdout_choice),
55 stderr: AutoStream::new(std::io::stderr(), stderr_choice),
56 color_choice: auto_clr,
57 graphics: !no_graphics,
58 hyperlinks: supports_hyperlinks(),
59 stderr_tty: std::io::stderr().is_terminal(),
60 stdout_unicode: supports_unicode(&std::io::stdout()),
61 stderr_unicode: supports_unicode(&std::io::stderr()),
62 stderr_term_integration: supports_term_integration(&std::io::stderr()),
63 unstable_flags_rustc_unicode: false,
64 },
65 verbosity: Verbosity::Verbose,
66 needs_clear: false,
67 }
68 }
69
70 pub fn from_write(out: Box<dyn Write + Send + Sync>) -> Shell {
72 Shell {
73 output: ShellOut::Write(AutoStream::never(out)), verbosity: Verbosity::Verbose,
75 needs_clear: false,
76 }
77 }
78
79 fn print(
82 &mut self,
83 status: &dyn fmt::Display,
84 message: Option<&dyn fmt::Display>,
85 color: &Style,
86 justified: bool,
87 ) -> CargoResult<()> {
88 match self.verbosity {
89 Verbosity::Quiet => Ok(()),
90 _ => {
91 if self.needs_clear {
92 self.err_erase_line();
93 }
94 self.output
95 .message_stderr(status, message, color, justified)
96 }
97 }
98 }
99
100 pub fn set_needs_clear(&mut self, needs_clear: bool) {
102 self.needs_clear = needs_clear;
103 }
104
105 pub fn is_cleared(&self) -> bool {
107 !self.needs_clear
108 }
109
110 pub fn err_width(&self) -> TtyWidth {
112 match self.output {
113 ShellOut::Stream {
114 stderr_tty: true, ..
115 } => imp::stderr_width(),
116 _ => TtyWidth::NoTty,
117 }
118 }
119
120 pub fn is_err_tty(&self) -> bool {
122 match self.output {
123 ShellOut::Stream { stderr_tty, .. } => stderr_tty,
124 _ => false,
125 }
126 }
127
128 pub fn is_err_term_integration_available(&self) -> bool {
129 if let ShellOut::Stream {
130 stderr_term_integration,
131 ..
132 } = self.output
133 {
134 stderr_term_integration
135 } else {
136 false
137 }
138 }
139
140 pub fn out(&mut self) -> &mut dyn Write {
142 if self.needs_clear {
143 self.err_erase_line();
144 }
145 self.output.stdout()
146 }
147
148 pub fn err(&mut self) -> &mut dyn Write {
150 if self.needs_clear {
151 self.err_erase_line();
152 }
153 self.output.stderr()
154 }
155
156 pub fn err_erase_line(&mut self) {
158 if self.err_supports_color() {
159 imp::err_erase_line(self);
160 self.needs_clear = false;
161 }
162 }
163
164 pub fn status<T, U>(&mut self, status: T, message: U) -> CargoResult<()>
166 where
167 T: fmt::Display,
168 U: fmt::Display,
169 {
170 self.print(&status, Some(&message), &HEADER, true)
171 }
172
173 pub fn transient_status<T>(&mut self, status: T) -> CargoResult<()>
174 where
175 T: fmt::Display,
176 {
177 self.print(&status, None, &TRANSIENT, true)
178 }
179
180 pub fn status_with_color<T, U>(
182 &mut self,
183 status: T,
184 message: U,
185 color: &Style,
186 ) -> CargoResult<()>
187 where
188 T: fmt::Display,
189 U: fmt::Display,
190 {
191 self.print(&status, Some(&message), color, true)
192 }
193
194 pub fn verbose<F>(&mut self, mut callback: F) -> CargoResult<()>
196 where
197 F: FnMut(&mut Shell) -> CargoResult<()>,
198 {
199 match self.verbosity {
200 Verbosity::Verbose => callback(self),
201 _ => Ok(()),
202 }
203 }
204
205 pub fn concise<F>(&mut self, mut callback: F) -> CargoResult<()>
207 where
208 F: FnMut(&mut Shell) -> CargoResult<()>,
209 {
210 match self.verbosity {
211 Verbosity::Verbose => Ok(()),
212 _ => callback(self),
213 }
214 }
215
216 pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
218 if self.needs_clear {
219 self.err_erase_line();
220 }
221 self.output
222 .message_stderr(&"error", Some(&message), &ERROR, false)
223 }
224
225 pub fn warn<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
227 self.print(&"warning", Some(&message), &WARN, false)
228 }
229
230 pub fn note<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
232 let report = &[annotate_snippets::Group::with_title(
233 annotate_snippets::Level::NOTE.secondary_title(message.to_string()),
234 )];
235 self.print_report(report, false)
236 }
237
238 pub fn set_verbosity(&mut self, verbosity: Verbosity) {
240 self.verbosity = verbosity;
241 }
242
243 pub fn verbosity(&self) -> Verbosity {
245 self.verbosity
246 }
247
248 pub fn set_color_choice(&mut self, color: Option<&str>) -> CargoResult<()> {
250 if let ShellOut::Stream {
251 stdout,
252 stderr,
253 color_choice,
254 ..
255 } = &mut self.output
256 {
257 let cfg = color
258 .map(|c| c.parse())
259 .transpose()?
260 .unwrap_or(ColorChoice::CargoAuto);
261 *color_choice = cfg;
262 let stdout_choice = cfg.to_anstream_color_choice();
263 let stderr_choice = cfg.to_anstream_color_choice();
264 *stdout = AutoStream::new(std::io::stdout(), stdout_choice);
265 *stderr = AutoStream::new(std::io::stderr(), stderr_choice);
266 }
267 Ok(())
268 }
269
270 pub fn set_unicode(&mut self, yes: bool) -> CargoResult<()> {
271 if let ShellOut::Stream {
272 stdout_unicode,
273 stderr_unicode,
274 ..
275 } = &mut self.output
276 {
277 *stdout_unicode = yes;
278 *stderr_unicode = yes;
279 }
280 Ok(())
281 }
282
283 pub fn set_hyperlinks(&mut self, yes: bool) -> CargoResult<()> {
284 if let ShellOut::Stream { hyperlinks, .. } = &mut self.output {
285 *hyperlinks = yes;
286 }
287 Ok(())
288 }
289
290 pub fn out_unicode(&self) -> bool {
291 match &self.output {
292 ShellOut::Write(_) => true,
293 ShellOut::Stream { stdout_unicode, .. } => *stdout_unicode,
294 }
295 }
296
297 pub fn err_unicode(&self) -> bool {
298 match &self.output {
299 ShellOut::Write(_) => true,
300 ShellOut::Stream { stderr_unicode, .. } => *stderr_unicode,
301 }
302 }
303
304 pub fn color_choice(&self) -> ColorChoice {
309 match self.output {
310 ShellOut::Stream { color_choice, .. } => color_choice,
311 ShellOut::Write(_) => ColorChoice::Never,
312 }
313 }
314
315 pub fn err_supports_color(&self) -> bool {
317 match &self.output {
318 ShellOut::Write(_) => false,
319 ShellOut::Stream { stderr, .. } => supports_color(stderr.current_choice()),
320 }
321 }
322
323 pub fn out_supports_color(&self) -> bool {
324 match &self.output {
325 ShellOut::Write(_) => false,
326 ShellOut::Stream { stdout, .. } => supports_color(stdout.current_choice()),
327 }
328 }
329
330 pub fn out_hyperlink<D: fmt::Display>(&self, url: D) -> Hyperlink<D> {
331 let supports_hyperlinks = match &self.output {
332 ShellOut::Write(_) => false,
333 ShellOut::Stream {
334 stdout, hyperlinks, ..
335 } => stdout.current_choice() == anstream::ColorChoice::AlwaysAnsi && *hyperlinks,
336 };
337 if supports_hyperlinks {
338 Hyperlink::with_url(url)
339 } else {
340 Hyperlink::default()
341 }
342 }
343
344 pub fn err_hyperlink<D: fmt::Display>(&self, url: D) -> Hyperlink<D> {
345 let supports_hyperlinks = match &self.output {
346 ShellOut::Write(_) => false,
347 ShellOut::Stream {
348 stderr, hyperlinks, ..
349 } => stderr.current_choice() == anstream::ColorChoice::AlwaysAnsi && *hyperlinks,
350 };
351 if supports_hyperlinks {
352 Hyperlink::with_url(url)
353 } else {
354 Hyperlink::default()
355 }
356 }
357
358 pub fn out_file_hyperlink(&mut self, path: &std::path::Path) -> Hyperlink<String> {
359 let url = anstyle_hyperlink::path_to_url(path);
360 url.map(|u| self.out_hyperlink(u)).unwrap_or_default()
361 }
362
363 pub fn err_file_hyperlink(&mut self, path: &std::path::Path) -> Hyperlink<String> {
364 let url = anstyle_hyperlink::path_to_url(path);
365 url.map(|u| self.err_hyperlink(u)).unwrap_or_default()
366 }
367
368 pub fn progress_supported(&self) -> bool {
370 if self.verbosity == Verbosity::Quiet
374 || std::env::var("TERM").as_deref() == Ok("dumb")
375 || cargo_util::is_ci()
376 {
377 false
378 } else {
379 true
380 }
381 }
382
383 fn unstable_flags_rustc_unicode(&self) -> bool {
384 match &self.output {
385 ShellOut::Write(_) => false,
386 ShellOut::Stream {
387 unstable_flags_rustc_unicode,
388 ..
389 } => *unstable_flags_rustc_unicode,
390 }
391 }
392
393 pub fn set_unstable_flags_rustc_unicode(&mut self, yes: bool) -> CargoResult<()> {
394 if let ShellOut::Stream {
395 unstable_flags_rustc_unicode,
396 ..
397 } = &mut self.output
398 {
399 *unstable_flags_rustc_unicode = yes;
400 }
401 Ok(())
402 }
403
404 pub fn graphics(&self) -> bool {
405 match &self.output {
406 ShellOut::Write(_) => true,
407 ShellOut::Stream { graphics, .. } => *graphics,
408 }
409 }
410
411 pub fn set_graphics(&mut self, yes: bool) -> CargoResult<()> {
412 if let ShellOut::Stream { graphics, .. } = &mut self.output {
413 *graphics = yes;
414 }
415 Ok(())
416 }
417
418 pub fn print_ansi_stderr(&mut self, message: &[u8]) -> CargoResult<()> {
420 if self.needs_clear {
421 self.err_erase_line();
422 }
423 self.err().write_all(message)?;
424 Ok(())
425 }
426
427 pub fn print_ansi_stdout(&mut self, message: &[u8]) -> CargoResult<()> {
429 if self.needs_clear {
430 self.err_erase_line();
431 }
432 self.out().write_all(message)?;
433 Ok(())
434 }
435
436 pub fn print_json<T: serde::ser::Serialize>(&mut self, obj: &T) -> CargoResult<()> {
437 let encoded = serde_json::to_string(obj)?;
439 drop(writeln!(self.out(), "{}", encoded));
441 Ok(())
442 }
443
444 pub fn print_report(&mut self, report: Report<'_>, force: bool) -> CargoResult<()> {
446 if !force && matches!(self.verbosity, Verbosity::Quiet) {
447 return Ok(());
448 }
449
450 if self.needs_clear {
451 self.err_erase_line();
452 }
453 let term_width = self
454 .err_width()
455 .diagnostic_terminal_width()
456 .unwrap_or(annotate_snippets::renderer::DEFAULT_TERM_WIDTH);
457 let decor_style = if self.err_unicode() && self.unstable_flags_rustc_unicode() {
458 DecorStyle::Unicode
459 } else {
460 DecorStyle::Ascii
461 };
462 let rendered = Renderer::styled()
463 .term_width(term_width)
464 .decor_style(decor_style)
465 .no_graphics(!self.graphics())
466 .render(report);
467 self.err().write_all(rendered.as_bytes())?;
468 self.err().write_all(b"\n")?;
469 Ok(())
470 }
471}
472
473impl Default for Shell {
474 fn default() -> Self {
475 Self::new()
476 }
477}
478
479enum ShellOut {
481 Write(AutoStream<Box<dyn Write + Send + Sync>>),
483 Stream {
485 stdout: AutoStream<std::io::Stdout>,
486 stderr: AutoStream<std::io::Stderr>,
487 stderr_tty: bool,
488 color_choice: ColorChoice,
489 graphics: bool,
490 hyperlinks: bool,
491 stdout_unicode: bool,
492 stderr_unicode: bool,
493 stderr_term_integration: bool,
494 unstable_flags_rustc_unicode: bool,
495 },
496}
497
498impl ShellOut {
499 fn message_stderr(
503 &mut self,
504 status: &dyn fmt::Display,
505 message: Option<&dyn fmt::Display>,
506 style: &Style,
507 justified: bool,
508 ) -> CargoResult<()> {
509 let mut buffer = Vec::new();
510 if justified {
511 write!(&mut buffer, "{style}{status:>12}{style:#}")?;
512 } else {
513 write!(&mut buffer, "{style}{status}{style:#}:")?;
514 }
515 match message {
516 Some(message) => writeln!(buffer, " {message}")?,
517 None => write!(buffer, " ")?,
518 }
519 self.stderr().write_all(&buffer)?;
520 Ok(())
521 }
522
523 fn stdout(&mut self) -> &mut dyn Write {
525 match self {
526 ShellOut::Stream { stdout, .. } => stdout,
527 ShellOut::Write(w) => w,
528 }
529 }
530
531 fn stderr(&mut self) -> &mut dyn Write {
533 match self {
534 ShellOut::Stream { stderr, .. } => stderr,
535 ShellOut::Write(w) => w,
536 }
537 }
538}
539
540pub enum TtyWidth {
541 NoTty,
542 Known(usize),
543 Guess(usize),
544}
545
546impl TtyWidth {
547 pub fn diagnostic_terminal_width(&self) -> Option<usize> {
550 #[expect(
551 clippy::disallowed_methods,
552 reason = "testing only, no reason for config support"
553 )]
554 if let Ok(width) = std::env::var("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS") {
555 return Some(width.parse().unwrap());
556 }
557 match *self {
558 TtyWidth::NoTty | TtyWidth::Guess(_) => None,
559 TtyWidth::Known(width) => Some(width),
560 }
561 }
562
563 pub fn progress_max_width(&self) -> Option<usize> {
565 match *self {
566 TtyWidth::NoTty => None,
567 TtyWidth::Known(width) | TtyWidth::Guess(width) => Some(width),
568 }
569 }
570}
571
572#[derive(Debug, Clone, Copy, PartialEq)]
574pub enum Verbosity {
575 Verbose,
576 Normal,
577 Quiet,
578}
579
580#[derive(Debug, PartialEq, Clone, Copy)]
582pub enum ColorChoice {
583 Always,
585 Never,
587 CargoAuto,
589}
590
591impl ColorChoice {
592 fn to_anstream_color_choice(self) -> anstream::ColorChoice {
594 match self {
595 ColorChoice::Always => anstream::ColorChoice::Always,
596 ColorChoice::Never => anstream::ColorChoice::Never,
597 ColorChoice::CargoAuto => anstream::ColorChoice::Auto,
598 }
599 }
600}
601
602impl std::str::FromStr for ColorChoice {
603 type Err = anyhow::Error;
604 fn from_str(color: &str) -> Result<Self, Self::Err> {
605 let cfg = match color {
606 "always" => ColorChoice::Always,
607 "never" => ColorChoice::Never,
608
609 "auto" => ColorChoice::CargoAuto,
610
611 arg => anyhow::bail!(
612 "argument for --color must be auto, always, or \
613 never, but found `{}`",
614 arg
615 ),
616 };
617 Ok(cfg)
618 }
619}
620
621fn supports_color(choice: anstream::ColorChoice) -> bool {
622 match choice {
623 anstream::ColorChoice::Always
624 | anstream::ColorChoice::AlwaysAnsi
625 | anstream::ColorChoice::Auto => true,
626 anstream::ColorChoice::Never => false,
627 }
628}
629
630fn supports_unicode(stream: &dyn IsTerminal) -> bool {
631 !stream.is_terminal() || supports_unicode::supports_unicode()
632}
633
634fn supports_hyperlinks() -> bool {
635 #[expect(
636 clippy::disallowed_methods,
637 reason = "reading the state of the system, not config"
638 )]
639 if std::env::var_os("TERM_PROGRAM").as_deref() == Some(std::ffi::OsStr::new("iTerm.app")) {
640 return false;
642 }
643
644 supports_hyperlinks::supports_hyperlinks()
645}
646
647fn supports_term_integration(stream: &dyn IsTerminal) -> bool {
649 anstyle_progress::supports_term_progress(stream.is_terminal())
650}
651
652#[cfg(unix)]
653mod imp {
654 use super::{Shell, TtyWidth};
655 use std::mem;
656
657 pub fn stderr_width() -> TtyWidth {
658 unsafe {
659 let mut winsize: libc::winsize = mem::zeroed();
660 if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ.into(), &mut winsize) < 0 {
663 return TtyWidth::NoTty;
664 }
665 if winsize.ws_col > 0 {
666 TtyWidth::Known(winsize.ws_col as usize)
667 } else {
668 TtyWidth::NoTty
669 }
670 }
671 }
672
673 pub fn err_erase_line(shell: &mut Shell) {
674 let _ = shell.output.stderr().write_all(b"\x1B[K");
678 }
679}
680
681#[cfg(windows)]
682mod imp {
683 use std::{cmp, mem, ptr};
684
685 use windows_sys::Win32::Foundation::CloseHandle;
686 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
687 use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE};
688 use windows_sys::Win32::Storage::FileSystem::{
689 CreateFileA, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
690 };
691 use windows_sys::Win32::System::Console::{
692 CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle, STD_ERROR_HANDLE,
693 };
694 use windows_sys::core::PCSTR;
695
696 pub(super) use super::{TtyWidth, default_err_erase_line as err_erase_line};
697
698 pub fn stderr_width() -> TtyWidth {
699 unsafe {
700 let stdout = GetStdHandle(STD_ERROR_HANDLE);
701 let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
702 if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
703 return TtyWidth::Known((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
704 }
705
706 let h = CreateFileA(
710 "CONOUT$\0".as_ptr() as PCSTR,
711 GENERIC_READ | GENERIC_WRITE,
712 FILE_SHARE_READ | FILE_SHARE_WRITE,
713 ptr::null_mut(),
714 OPEN_EXISTING,
715 0,
716 std::ptr::null_mut(),
717 );
718 if h == INVALID_HANDLE_VALUE {
719 return TtyWidth::NoTty;
720 }
721
722 let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
723 let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
724 CloseHandle(h);
725 if rc != 0 {
726 let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
727 return TtyWidth::Guess(cmp::min(60, width));
736 }
737
738 TtyWidth::NoTty
739 }
740 }
741}
742
743#[cfg(windows)]
744fn default_err_erase_line(shell: &mut Shell) {
745 match imp::stderr_width() {
746 TtyWidth::Known(max_width) | TtyWidth::Guess(max_width) => {
747 let blank = " ".repeat(max_width);
748 drop(write!(shell.output.stderr(), "{}\r", blank));
749 }
750 _ => (),
751 }
752}