Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to configure colors using an environment variable #4136

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Allow to configure colors using an environment variable
This commit add support for configuring colors used by cargo through a
environment variable (CARGO_COLORS). The used syntax for the environment
variable is similar to that one used by gcc (GCC_COLORS).

Example:
CARGO_COLORS="status=01;2:warn=01;3:error=01;1:default:01;231:blocked=01;4"
  • Loading branch information
weiznich committed Jun 7, 2017
commit 53b2c42080b55d632a8de378cac5f42623382da4
158 changes: 144 additions & 14 deletions src/cargo/core/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fmt;
use std::io::prelude::*;
use std::io;

use term::color::{Color, BLACK, RED, GREEN, YELLOW};
use term::color::{Color, BLACK, RED, GREEN, YELLOW, CYAN};
use term::{self, Terminal, TerminfoTerminal, color, Attr};

use self::AdequateTerminal::{NoColor, Colored};
Expand All @@ -18,6 +18,130 @@ pub enum Verbosity {
Quiet
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
color: Color,
attr: Option<Attr>,
}

impl Default for Style {
fn default() -> Self {
Style {
color: BLACK,
attr: None,
}
}
}

impl Style {
fn from_str(config: &str, mut color: Color, mut attr: Option<Attr>) -> Self {
let parts = config.split(";").collect::<Vec<_>>();
if let Some(p) = parts.get(0) {
if let Ok(p) = p.parse() {
match p {
0 if attr == Some(Attr::Bold) => {
attr = None;
}
1 => {
attr = Some(Attr::Bold);
}
3 => {
attr = Some(Attr::Italic(true));
}
4 => {
attr = Some(Attr::Underline(true));
}
5 | 6 => {
attr = Some(Attr::Blink)
}
i if i >= 30 && i <= 39 => {
color = i
}
_ => {
// ignore everything else
}
}
}
}
if let Some(p) = parts.get(1) {
if let Ok(p) = p.parse() {
color = p;
}
}
Style {
color: color,
attr: attr,
}
}

fn apply(&self, shell: &mut Shell) -> CargoResult<()> {
if self.color != BLACK { shell.fg(self.color)?; }
if let Some(attr) = self.attr {
if shell.supports_attr(attr) {
shell.attr(attr)?;
}
}
Ok(())
}
}

#[derive(Clone, Copy, PartialEq)]
pub struct Styles {
pub status: Style,
pub warning: Style,
pub error: Style,
pub default: Style,
pub blocked: Style,
}


impl Default for Styles {
fn default() -> Self {
Styles {
status: Style {
color: GREEN,
attr: Some(Attr::Bold),
},
warning: Style {
color: YELLOW,
attr: Some(Attr::Bold),
},
error: Style {
color: RED,
attr: Some(Attr::Bold),
},
default: Style::default(),
blocked: Style {
color: CYAN,
attr: Some(Attr::Bold),
}
}
}
}

impl Styles {
fn from_env() -> Styles {
use std::env::var;
let mut ret = Styles::default();
if let Ok(config) = var("CARGO_COLORS") {
for p in config.split(":") {
if p.starts_with("status=") {
ret.status = Style::from_str(&p[7..], ret.status.color, ret.status.attr);
} else if p.starts_with("warning=") {
ret.warning = Style::from_str(&p[8..], ret.warning.color, ret.warning.attr);
} else if p.starts_with("error=") {
ret.error = Style::from_str(&p[6..], ret.error.color, ret.error.attr);
} else if p.starts_with("default=") {
ret.default = Style::from_str(&p[8..], ret.default.color, ret.default.attr);
} else if p.starts_with("blocked=") {
ret.blocked = Style::from_str(&p[8..], ret.blocked.color, ret.blocked.attr);
}
}
}
ret
}
}

#[derive(Clone, Copy, PartialEq)]
pub enum ColorConfig {
Auto,
Expand Down Expand Up @@ -54,12 +178,13 @@ pub struct Shell {
pub struct MultiShell {
out: Shell,
err: Shell,
verbosity: Verbosity
verbosity: Verbosity,
pub styles: Styles,
}

impl MultiShell {
pub fn new(out: Shell, err: Shell, verbosity: Verbosity) -> MultiShell {
MultiShell { out: out, err: err, verbosity: verbosity }
MultiShell { out: out, err: err, verbosity: verbosity, styles: Styles::from_env() }
}

// Create a quiet, basic shell from supplied writers.
Expand All @@ -71,6 +196,7 @@ impl MultiShell {
out: out,
err: err,
verbosity: Verbosity::Quiet,
styles: Styles::from_env(),
}
}

Expand All @@ -82,15 +208,15 @@ impl MultiShell {
&mut self.err
}

pub fn say<T: ToString>(&mut self, message: T, color: Color)
pub fn say<T: ToString>(&mut self, message: T, style: Style)
-> CargoResult<()> {
match self.verbosity {
Quiet => Ok(()),
_ => self.out().say(message, color)
_ => self.out().say(message, style)
}
}

pub fn status_with_color<T, U>(&mut self, status: T, message: U, color: Color)
pub fn status_with_color<T, U>(&mut self, status: T, message: U, color: Style)
-> CargoResult<()>
where T: fmt::Display, U: fmt::Display
{
Expand All @@ -103,7 +229,8 @@ impl MultiShell {
pub fn status<T, U>(&mut self, status: T, message: U) -> CargoResult<()>
where T: fmt::Display, U: fmt::Display
{
self.status_with_color(status, message, GREEN)
let color = self.styles.status;
self.status_with_color(status, message, color)
}

pub fn verbose<F>(&mut self, mut callback: F) -> CargoResult<()>
Expand All @@ -125,13 +252,17 @@ impl MultiShell {
}

pub fn error<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
self.err().say_status("error:", message, RED, false)
let color = self.styles.error;
self.err().say_status("error:", message, color, false)
}

pub fn warn<T: fmt::Display>(&mut self, message: T) -> CargoResult<()> {
match self.verbosity {
Quiet => Ok(()),
_ => self.err().say_status("warning:", message, YELLOW, false),
_ => {
let color = self.styles.warning;
self.err().say_status("warning:", message, color, false)
},
}
}

Expand Down Expand Up @@ -224,9 +355,9 @@ impl Shell {
self.config.color_config = color_config;
}

pub fn say<T: ToString>(&mut self, message: T, color: Color) -> CargoResult<()> {
pub fn say<T: ToString>(&mut self, message: T, style: Style) -> CargoResult<()> {
self.reset()?;
if color != BLACK { self.fg(color)?; }
style.apply(self)?;
write!(self, "{}\n", message.to_string())?;
self.reset()?;
self.flush()?;
Expand All @@ -236,14 +367,13 @@ impl Shell {
pub fn say_status<T, U>(&mut self,
status: T,
message: U,
color: Color,
style: Style,
justified: bool)
-> CargoResult<()>
where T: fmt::Display, U: fmt::Display
{
self.reset()?;
if color != BLACK { self.fg(color)?; }
if self.supports_attr(Attr::Bold) { self.attr(Attr::Bold)?; }
style.apply(self)?;
if justified {
write!(self, "{:>12}", status.to_string())?;
} else {
Expand Down
12 changes: 7 additions & 5 deletions src/cargo/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ use docopt::Docopt;

use core::{Shell, MultiShell, ShellConfig, Verbosity, ColorConfig};
use core::shell::Verbosity::{Verbose};
use term::color::{BLACK};

pub use util::{CargoError, CargoErrorKind, CargoResult, CliError, CliResult, Config};

Expand Down Expand Up @@ -190,12 +189,14 @@ pub fn exit_with_error(err: CliError, shell: &mut MultiShell) -> ! {
} else if fatal {
shell.error(&error)
} else {
shell.say(&error, BLACK)
let color = shell.styles.default;
shell.say(&error, color)
};

if !handle_cause(error, shell) || hide {
let color = shell.styles.default;
let _ = shell.err().say("\nTo learn more, run the command again \
with --verbose.".to_string(), BLACK);
with --verbose.".to_string(), color);
}
}

Expand All @@ -212,8 +213,9 @@ pub fn handle_error(err: CargoError, shell: &mut MultiShell) {
fn handle_cause<E, EKind>(cargo_err: E, shell: &mut MultiShell) -> bool
where E: ChainedError<ErrorKind=EKind> + 'static {
fn print(error: String, shell: &mut MultiShell) {
let _ = shell.err().say("\nCaused by:", BLACK);
let _ = shell.err().say(format!(" {}", error), BLACK);
let color = shell.styles.default;
let _ = shell.err().say("\nCaused by:", color);
let _ = shell.err().say(format!(" {}", error), color);
}

//Error inspection in non-verbose mode requires inspecting the
Expand Down
5 changes: 2 additions & 3 deletions src/cargo/ops/cargo_new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ use rustc_serialize::{Decodable, Decoder};

use git2::Config as GitConfig;

use term::color::BLACK;

use core::Workspace;
use ops::is_bad_artifact_name;
use util::{GitRepo, HgRepo, PijulRepo, internal};
Expand Down Expand Up @@ -108,10 +106,11 @@ fn get_name<'a>(path: &'a Path, opts: &'a NewOptions, config: &Config) -> CargoR
} else {
let new_name = strip_rust_affixes(dir_name);
if new_name != dir_name {
let color = config.shell().styles.default;
let message = format!(
"note: package will be named `{}`; use --name to override",
new_name);
config.shell().say(&message, BLACK)?;
config.shell().say(&message, color)?;
}
Ok(new_name)
}
Expand Down
4 changes: 2 additions & 2 deletions src/cargo/ops/cargo_rustc/job_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::sync::mpsc::{channel, Sender, Receiver};

use crossbeam::{self, Scope};
use jobserver::{Acquired, HelperThread};
use term::color::YELLOW;

use core::{PackageId, Target, Profile};
use util::{Config, DependencyQueue, Fresh, Dirty, Freshness};
Expand Down Expand Up @@ -236,9 +235,10 @@ impl<'a> JobQueue<'a> {
if self.active > 0 {
error = Some("build failed".into());
handle_error(e, &mut *cx.config.shell());
let color = cx.config.shell().styles.warning;
cx.config.shell().say(
"Build failed, waiting for other \
jobs to finish...", YELLOW)?;
jobs to finish...", color)?;
}
else {
error = Some(e);
Expand Down
12 changes: 5 additions & 7 deletions src/cargo/ops/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::time::Duration;
use curl::easy::{Easy, SslOpt};
use git2;
use registry::{Registry, NewCrate, NewCrateDependency};
use term::color::BLACK;

use url::percent_encoding::{percent_encode, QUERY_ENCODE_SET};

Expand Down Expand Up @@ -420,6 +419,7 @@ pub fn search(query: &str,
.max()
.unwrap_or(0);

let color = config.shell().styles.default;
for (name, description) in list_items.into_iter() {
let line = match description {
Some(desc) => {
Expand All @@ -429,24 +429,22 @@ pub fn search(query: &str,
}
None => name
};
config.shell().say(line, BLACK)?;
config.shell().say(line, color)?;
}

let search_max_limit = 100;
if total_crates > limit as u32 && limit < search_max_limit {
config.shell().say(
format!("... and {} crates more (use --limit N to see more)",
total_crates - limit as u32),
BLACK)
total_crates - limit as u32), color)
?;
} else if total_crates > limit as u32 && limit >= search_max_limit {
} else if total_crates > limit as u32 && limit >= search_max_limit {
config.shell().say(
format!(
"... and {} crates more (go to http:https://crates.io/search?q={} to see more)",
total_crates - limit as u32,
percent_encode(query.as_bytes(), QUERY_ENCODE_SET)
),
BLACK)
), color)
?;
}

Expand Down
4 changes: 2 additions & 2 deletions src/cargo/util/flock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::io::*;
use std::io;
use std::path::{Path, PathBuf, Display};

use term::color::CYAN;
use fs2::{FileExt, lock_contended_error};
#[allow(unused_imports)]
use libc;
Expand Down Expand Up @@ -290,7 +289,8 @@ fn acquire(config: &Config,
}
}
let msg = format!("waiting for file lock on {}", msg);
config.shell().status_with_color("Blocking", &msg, CYAN)?;
let color = config.shell().styles.blocked;
config.shell().status_with_color("Blocking", &msg, color)?;

return block().chain_err(|| {
format!("failed to lock file: {}", path.display())
Expand Down