From 2885f7ab2c4fe8a804c1be9952aaf7807ce04e5a Mon Sep 17 00:00:00 2001 From: Fahmi Akbar Wildana <f.a.wildana@gmail.com> Date: Wed, 11 Sep 2019 10:38:04 +0700 Subject: [PATCH] Disable clap color on blind terminal --- Cargo.lock | 1 + Cargo.toml | 2 ++ src/main.rs | 15 +++++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91bce9a..fa3ae85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -260,6 +260,7 @@ version = "0.5.0" dependencies = [ "assert_cmd 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)", "assert_fs 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)", + "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "colored 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "predicates 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index 4e03e81..39fc2ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,8 @@ name = "mask" path = "src/lib.rs" [dependencies] +# see https://rust-lang-nursery.github.io/cli-wg/in-depth/machine-communication.html?highlight=atty#whos-reading-this +atty = "0.2" # https://github.com/softprops/atty colored = "1.8.0" # https://github.com/mackwic/colored pulldown-cmark = { version = "0.5", default-features = false } # https://github.com/raphlinus/pulldown-cmark diff --git a/src/main.rs b/src/main.rs index 206ff46..a2b0207 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use std::env; use std::path::Path; +use atty::{self, Stream}; use clap::{ crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, ArgMatches, SubCommand, @@ -14,7 +15,11 @@ fn main() { let cli_app = App::new(crate_name!()) .setting(AppSettings::VersionlessSubcommands) .setting(AppSettings::SubcommandRequired) - .setting(AppSettings::ColoredHelp) + .setting(if atty::is(Stream::Stdout) { + AppSettings::ColoredHelp + } else { + AppSettings::ColorNever // in case it run on terminal without color support + }) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) @@ -90,7 +95,13 @@ fn build_subcommands<'a, 'b>( subcommands: &'a Vec<Command>, ) -> App<'a, 'b> { for c in subcommands { - let mut subcmd = SubCommand::with_name(&c.name).about(c.desc.as_ref()).setting(AppSettings::ColoredHelp); + let mut subcmd = SubCommand::with_name(&c.name) + .about(c.desc.as_ref()) + .setting(if atty::is(Stream::Stdout) { + AppSettings::ColoredHelp + } else { + AppSettings::ColorNever // in case it run on terminal without color support + }); if !c.subcommands.is_empty() { subcmd = build_subcommands(subcmd, &c.subcommands); // If this parent command has no script source, require a subcommand.