From f6f41e76aa9337851b72832156c6127e9fe56e22 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Mon, 14 Jan 2019 09:05:12 +0100 Subject: [PATCH] Use --color=always/auto/never instead of --no-color --- Cargo.lock | 1 + Cargo.toml | 1 + src/main.rs | 25 ++++++++++++++++++------- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 462cf70..4a063fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,6 +41,7 @@ name = "hexyl" version = "0.3.1" dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/Cargo.toml b/Cargo.toml index e73ec91..5105636 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ version = "0.3.1" [dependencies] ansi_term = "0.11" +atty = "0.2" [dependencies.clap] version = "2" diff --git a/src/main.rs b/src/main.rs index 3106008..aa3233f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ #[macro_use] extern crate clap; extern crate ansi_term; +extern crate atty; use std::fs::File; use std::io::{self, prelude::*, StdoutLock}; @@ -10,6 +11,8 @@ use clap::{App, AppSettings, Arg}; use ansi_term::Colour; use ansi_term::Colour::Fixed; +use atty::Stream; + const BUFFER_SIZE: usize = 256; const COLOR_NULL: Colour = Fixed(242); // grey @@ -138,7 +141,7 @@ impl<'a> Printer<'a> { fn print_byte(&mut self, b: u8) -> io::Result<()> { if self.idx % 16 == 1 { let style = COLOR_OFFSET.normal(); - let byte_index = format!("{:08x}", self.idx -1); + let byte_index = format!("{:08x}", self.idx - 1); let formatted_string = if self.show_color { format!("{}", style.paint(byte_index)) } else { @@ -226,13 +229,17 @@ fn run() -> Result<(), Box<::std::error::Error>> { .long("length") .takes_value(true) .value_name("N") - .help("read only N bytes from the input"), + .help("Read only N bytes from the input"), ) .arg( - Arg::with_name("no-color") - .long("no-color") - .takes_value(false) - .help("Don't output ANSI color characters") + Arg::with_name("color") + .long("color") + .takes_value(true) + .value_name("when") + .possible_values(&["always", "auto", "never"]) + .default_value("always") + .help("When to use colors. The auto-mode only displays colors if the output \ + goes to an interactive terminal"), ); let matches = app.get_matches_safe()?; @@ -251,7 +258,11 @@ fn run() -> Result<(), Box<::std::error::Error>> { reader = Box::new(reader.take(length)); } - let show_color = !matches.is_present("no-color"); + let show_color = match matches.value_of("color") { + Some("never") => false, + Some("auto") => atty::is(Stream::Stdout), + _ => true, + }; let stdout = io::stdout(); let mut printer = Printer::new(stdout.lock(), show_color);