From 8ba6277cce65747da5f4e4fdbaf313405066245f Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" Date: Sun, 20 Dec 2020 19:54:38 -0500 Subject: [PATCH] use 'atty' to detect when colors can be used --- Cargo.lock | 1 + cli/Cargo.toml | 1 + cli/src/invocation/mod.rs | 11 ++++++++++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index b8549ae21..7b3aeae18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2264,6 +2264,7 @@ name = "taskchampion-cli" version = "0.2.0" dependencies = [ "assert_cmd", + "atty", "config", "dirs 3.0.1", "env_logger", diff --git a/cli/Cargo.toml b/cli/Cargo.toml index a243a5d44..9daeb1653 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -13,6 +13,7 @@ nom = "*" prettytable-rs = "^0.8.0" textwrap = "0.12.1" termcolor = "1.1.2" +atty = "0.2.14" [dependencies.config] default-features = false diff --git a/cli/src/invocation/mod.rs b/cli/src/invocation/mod.rs index ec04b3ac1..18d8000b6 100644 --- a/cli/src/invocation/mod.rs +++ b/cli/src/invocation/mod.rs @@ -18,7 +18,7 @@ pub(crate) fn invoke(command: Command, settings: Config) -> Fallible<()> { log::debug!("command: {:?}", command); log::debug!("settings: {:?}", settings); - let mut w = StandardStream::stdout(ColorChoice::Auto); + let mut w = get_writer()?; // This function examines the command and breaks out the necessary bits to call one of the // `execute` functions in a submodule of `cmd`. @@ -110,3 +110,12 @@ fn get_server(settings: &Config) -> Fallible> { client_id, })?) } + +/// Get a WriteColor implementation based on whether the output is a tty. +fn get_writer() -> Fallible { + Ok(StandardStream::stdout(if atty::is(atty::Stream::Stdout) { + ColorChoice::Auto + } else { + ColorChoice::Never + })) +}