cargo_edit/
util.rs

1use std::io::Write;
2
3pub use termcolor::{Color, ColorChoice};
4use termcolor::{ColorSpec, StandardStream, WriteColor};
5
6use crate::{CargoResult, Context};
7
8/// Whether to color logged output
9pub fn colorize_stderr() -> ColorChoice {
10    if concolor_control::get(concolor_control::Stream::Stderr).color() {
11        ColorChoice::Always
12    } else {
13        ColorChoice::Never
14    }
15}
16
17/// Whether to color logged output
18pub fn colorize_stdout() -> ColorChoice {
19    if concolor_control::get(concolor_control::Stream::Stdout).color() {
20        ColorChoice::Always
21    } else {
22        ColorChoice::Never
23    }
24}
25
26/// Print a message with a colored title in the style of Cargo shell messages.
27pub fn shell_print(status: &str, message: &str, color: Color, justified: bool) -> CargoResult<()> {
28    let color_choice = colorize_stderr();
29    let mut output = StandardStream::stderr(color_choice);
30
31    output.set_color(ColorSpec::new().set_fg(Some(color)).set_bold(true))?;
32    if justified {
33        write!(output, "{status:>12}")?;
34    } else {
35        write!(output, "{status}")?;
36        output.set_color(ColorSpec::new().set_bold(true))?;
37        write!(output, ":")?;
38    }
39    output.reset()?;
40
41    writeln!(output, " {message}").with_context(|| "Failed to write message")?;
42
43    Ok(())
44}
45
46/// Print a styled action message.
47pub fn shell_status(action: &str, message: &str) -> CargoResult<()> {
48    shell_print(action, message, Color::Green, true)
49}
50
51/// Print a styled warning message.
52pub fn shell_warn(message: &str) -> CargoResult<()> {
53    shell_print("warning", message, Color::Yellow, false)
54}
55
56/// Print a styled warning message.
57pub fn shell_note(message: &str) -> CargoResult<()> {
58    shell_print("note", message, Color::Cyan, false)
59}
60
61/// Print a part of a line with formatting
62pub fn shell_write_stderr(fragment: impl std::fmt::Display, spec: &ColorSpec) -> CargoResult<()> {
63    let color_choice = colorize_stderr();
64    let mut output = StandardStream::stderr(color_choice);
65
66    output.set_color(spec)?;
67    write!(output, "{fragment}")?;
68    output.reset()?;
69    Ok(())
70}
71
72/// Print a part of a line with formatting
73pub fn shell_write_stdout(fragment: impl std::fmt::Display, spec: &ColorSpec) -> CargoResult<()> {
74    let color_choice = colorize_stdout();
75    let mut output = StandardStream::stdout(color_choice);
76
77    output.set_color(spec)?;
78    write!(output, "{fragment}")?;
79    output.reset()?;
80    Ok(())
81}