use std::fmt;
use std::io::prelude::*;
use std::io::IsTerminal;
use anstream::AutoStream;
use anstyle::Style;
use crate::util::errors::CargoResult;
use crate::util::style::*;
pub enum TtyWidth {
NoTty,
Known(usize),
Guess(usize),
}
impl TtyWidth {
pub fn diagnostic_terminal_width(&self) -> Option<usize> {
#[allow(clippy::disallowed_methods)]
if let Ok(width) = std::env::var("__CARGO_TEST_TTY_WIDTH_DO_NOT_USE_THIS") {
return Some(width.parse().unwrap());
}
match *self {
TtyWidth::NoTty | TtyWidth::Guess(_) => None,
TtyWidth::Known(width) => Some(width),
}
}
pub fn progress_max_width(&self) -> Option<usize> {
match *self {
TtyWidth::NoTty => None,
TtyWidth::Known(width) | TtyWidth::Guess(width) => Some(width),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Verbosity {
Verbose,
Normal,
Quiet,
}
pub struct Shell {
output: ShellOut,
verbosity: Verbosity,
needs_clear: bool,
}
impl fmt::Debug for Shell {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.output {
ShellOut::Write(_) => f
.debug_struct("Shell")
.field("verbosity", &self.verbosity)
.finish(),
ShellOut::Stream { color_choice, .. } => f
.debug_struct("Shell")
.field("verbosity", &self.verbosity)
.field("color_choice", &color_choice)
.finish(),
}
}
}
enum ShellOut {
Write(AutoStream<Box<dyn Write>>),
Stream {
stdout: AutoStream<std::io::Stdout>,
stderr: AutoStream<std::io::Stderr>,
stderr_tty: bool,
color_choice: ColorChoice,
},
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ColorChoice {
Always,
Never,
CargoAuto,
}
impl Shell {
pub fn new() -> Shell {
let auto_clr = ColorChoice::CargoAuto;
let stdout_choice = auto_clr.to_anstream_color_choice();
let stderr_choice = auto_clr.to_anstream_color_choice();
Shell {
output: ShellOut::Stream {
stdout: AutoStream::new(std::io::stdout(), stdout_choice),
stderr: AutoStream::new(std::io::stderr(), stderr_choice),
color_choice: auto_clr,
stderr_tty: std::io::stderr().is_terminal(),
},
verbosity: Verbosity::Verbose,
needs_clear: false,
}
}
pub fn from_write(out: Box<dyn Write>) -> Shell {
Shell {
output: ShellOut::Write(AutoStream::never(out)), verbosity: Verbosity::Verbose,
needs_clear: false,
}
}
fn print(
&mut self,
status: &dyn fmt::Display,
message: Option<&dyn fmt::Display>,
color: &Style,
justified: bool,
) -> CargoResult<()> {
match self.verbosity {
Verbosity::Quiet => Ok(()),
_ => {
if self.needs_clear {
self.err_erase_line();
}
self.output
.message_stderr(status, message, color, justified)
}
}
}
pub fn set_needs_clear(&mut self, needs_clear: bool) {
self.needs_clear = needs_clear;
}
pub fn is_cleared(&self) -> bool {
!self.needs_clear
}
pub fn err_width(&self) -> TtyWidth {
match self.output {
ShellOut::Stream {
stderr_tty: true, ..
} => imp::stderr_width(),
_ => TtyWidth::NoTty,
}
}
pub fn is_err_tty(&self) -> bool {
match self.output {
ShellOut::Stream { stderr_tty, .. } => stderr_tty,
_ => false,
}
}
pub fn out(&mut self) -> &mut dyn Write {
if self.needs_clear {
self.err_erase_line();
}
self.output.stdout()
}
pub fn err(&mut self) -> &mut dyn Write {
if self.needs_clear {
self.err_erase_line();
}
self.output.stderr()
}
pub fn err_erase_line(&mut self) {
if self.err_supports_color() {
imp::err_erase_line(self);
self.needs_clear = false;
}
}
pub fn status<T, U>(&mut self, status: T, message: U) -> CargoResult<()>
where
T: fmt::Display,
U: fmt::Display,
{
self.print(&status, Some(&message), &HEADER, true)
}
pub fn status_header<T>(&mut self, status: T) -> CargoResult<()>
where
T: fmt::Display,
{
self.print(&status, None, &NOTE, true)
}
pub fn status_with_color<T, U>(
&mut self,
status: T,
message: U,
color: &Style,
) -> CargoResult<()>
where
T: fmt::Display,
U: fmt::Display,
{
self.print(&status, Some(&message), color, true)
}
pub fn verbose<F>(&mut self, mut callback: F) -> CargoResult<()>
where
F: FnMut(&mut Shell) -> CargoResult<()>,
{
match self.verbosity {
Verbosity::Verbose => callback(self),
_ => Ok(()),
}
}
pub fn concise<F>(&mut self, mut callback: F) -> CargoResult<()>
where
F: FnMut(&mut Shell) -> CargoResult<()>,
{
match self.verbosity {
Verbosity::Verbose => Ok(()),
_ => callback(self),
}
}
pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
if self.needs_clear {
self.err_erase_line();
}
self.output
.message_stderr(&"error", Some(&message), &ERROR, false)
}
pub fn warn<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
match self.verbosity {
Verbosity::Quiet => Ok(()),
_ => self.print(&"warning", Some(&message), &WARN, false),
}
}
pub fn note<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
self.print(&"note", Some(&message), &NOTE, false)
}
pub fn set_verbosity(&mut self, verbosity: Verbosity) {
self.verbosity = verbosity;
}
pub fn verbosity(&self) -> Verbosity {
self.verbosity
}
pub fn set_color_choice(&mut self, color: Option<&str>) -> CargoResult<()> {
if let ShellOut::Stream {
ref mut stdout,
ref mut stderr,
ref mut color_choice,
..
} = self.output
{
let cfg = match color {
Some("always") => ColorChoice::Always,
Some("never") => ColorChoice::Never,
Some("auto") | None => ColorChoice::CargoAuto,
Some(arg) => anyhow::bail!(
"argument for --color must be auto, always, or \
never, but found `{}`",
arg
),
};
*color_choice = cfg;
let stdout_choice = cfg.to_anstream_color_choice();
let stderr_choice = cfg.to_anstream_color_choice();
*stdout = AutoStream::new(std::io::stdout(), stdout_choice);
*stderr = AutoStream::new(std::io::stderr(), stderr_choice);
}
Ok(())
}
pub fn color_choice(&self) -> ColorChoice {
match self.output {
ShellOut::Stream { color_choice, .. } => color_choice,
ShellOut::Write(_) => ColorChoice::Never,
}
}
pub fn err_supports_color(&self) -> bool {
match &self.output {
ShellOut::Write(_) => false,
ShellOut::Stream { stderr, .. } => supports_color(stderr.current_choice()),
}
}
pub fn out_supports_color(&self) -> bool {
match &self.output {
ShellOut::Write(_) => false,
ShellOut::Stream { stdout, .. } => supports_color(stdout.current_choice()),
}
}
pub fn write_stdout(&mut self, fragment: impl fmt::Display, color: &Style) -> CargoResult<()> {
self.output.write_stdout(fragment, color)
}
pub fn write_stderr(&mut self, fragment: impl fmt::Display, color: &Style) -> CargoResult<()> {
self.output.write_stderr(fragment, color)
}
pub fn print_ansi_stderr(&mut self, message: &[u8]) -> CargoResult<()> {
if self.needs_clear {
self.err_erase_line();
}
self.err().write_all(message)?;
Ok(())
}
pub fn print_ansi_stdout(&mut self, message: &[u8]) -> CargoResult<()> {
if self.needs_clear {
self.err_erase_line();
}
self.out().write_all(message)?;
Ok(())
}
pub fn print_json<T: serde::ser::Serialize>(&mut self, obj: &T) -> CargoResult<()> {
let encoded = serde_json::to_string(&obj)?;
drop(writeln!(self.out(), "{}", encoded));
Ok(())
}
}
impl Default for Shell {
fn default() -> Self {
Self::new()
}
}
impl ShellOut {
fn message_stderr(
&mut self,
status: &dyn fmt::Display,
message: Option<&dyn fmt::Display>,
style: &Style,
justified: bool,
) -> CargoResult<()> {
let style = style.render();
let bold = (anstyle::Style::new() | anstyle::Effects::BOLD).render();
let reset = anstyle::Reset.render();
let mut buffer = Vec::new();
if justified {
write!(&mut buffer, "{style}{status:>12}{reset}")?;
} else {
write!(&mut buffer, "{style}{status}{reset}{bold}:{reset}")?;
}
match message {
Some(message) => writeln!(buffer, " {message}")?,
None => write!(buffer, " ")?,
}
self.stderr().write_all(&buffer)?;
Ok(())
}
fn write_stdout(&mut self, fragment: impl fmt::Display, style: &Style) -> CargoResult<()> {
let style = style.render();
let reset = anstyle::Reset.render();
let mut buffer = Vec::new();
write!(buffer, "{style}{}{reset}", fragment)?;
self.stdout().write_all(&buffer)?;
Ok(())
}
fn write_stderr(&mut self, fragment: impl fmt::Display, style: &Style) -> CargoResult<()> {
let style = style.render();
let reset = anstyle::Reset.render();
let mut buffer = Vec::new();
write!(buffer, "{style}{}{reset}", fragment)?;
self.stderr().write_all(&buffer)?;
Ok(())
}
fn stdout(&mut self) -> &mut dyn Write {
match *self {
ShellOut::Stream { ref mut stdout, .. } => stdout,
ShellOut::Write(ref mut w) => w,
}
}
fn stderr(&mut self) -> &mut dyn Write {
match *self {
ShellOut::Stream { ref mut stderr, .. } => stderr,
ShellOut::Write(ref mut w) => w,
}
}
}
impl ColorChoice {
fn to_anstream_color_choice(self) -> anstream::ColorChoice {
match self {
ColorChoice::Always => anstream::ColorChoice::Always,
ColorChoice::Never => anstream::ColorChoice::Never,
ColorChoice::CargoAuto => anstream::ColorChoice::Auto,
}
}
}
fn supports_color(choice: anstream::ColorChoice) -> bool {
match choice {
anstream::ColorChoice::Always
| anstream::ColorChoice::AlwaysAnsi
| anstream::ColorChoice::Auto => true,
anstream::ColorChoice::Never => false,
}
}
#[cfg(unix)]
mod imp {
use super::{Shell, TtyWidth};
use std::mem;
pub fn stderr_width() -> TtyWidth {
unsafe {
let mut winsize: libc::winsize = mem::zeroed();
if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ.into(), &mut winsize) < 0 {
return TtyWidth::NoTty;
}
if winsize.ws_col > 0 {
TtyWidth::Known(winsize.ws_col as usize)
} else {
TtyWidth::NoTty
}
}
}
pub fn err_erase_line(shell: &mut Shell) {
let _ = shell.output.stderr().write_all(b"\x1B[K");
}
}
#[cfg(windows)]
mod imp {
use std::{cmp, mem, ptr};
use windows_sys::core::PCSTR;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileA, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows_sys::Win32::System::Console::{
GetConsoleScreenBufferInfo, GetStdHandle, CONSOLE_SCREEN_BUFFER_INFO, STD_ERROR_HANDLE,
};
pub(super) use super::{default_err_erase_line as err_erase_line, TtyWidth};
pub fn stderr_width() -> TtyWidth {
unsafe {
let stdout = GetStdHandle(STD_ERROR_HANDLE);
let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
return TtyWidth::Known((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
}
let h = CreateFileA(
"CONOUT$\0".as_ptr() as PCSTR,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null_mut(),
OPEN_EXISTING,
0,
0,
);
if h == INVALID_HANDLE_VALUE {
return TtyWidth::NoTty;
}
let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
CloseHandle(h);
if rc != 0 {
let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
return TtyWidth::Guess(cmp::min(60, width));
}
TtyWidth::NoTty
}
}
}
#[cfg(windows)]
fn default_err_erase_line(shell: &mut Shell) {
match imp::stderr_width() {
TtyWidth::Known(max_width) | TtyWidth::Guess(max_width) => {
let blank = " ".repeat(max_width);
drop(write!(shell.output.stderr(), "{}\r", blank));
}
_ => (),
}
}