From 2f59e8b68a435d3f3925d7e5448bff22958c3de4 Mon Sep 17 00:00:00 2001 From: Martin von Zweigbergk Date: Sat, 19 Mar 2022 10:00:13 -0700 Subject: [PATCH] cli: respect `$NO_COLOR` environment variable --- CHANGELOG.md | 3 +++ src/ui.rs | 25 ++++++++++++++++--------- tests/test_global_opts.rs | 13 +++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 291c6c440..677c8807f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 config file. That will then be read instead of your regular config file. This is mostly intended for testing and scripts. +* The [standard `$NO_COLOR` environment variable](https://no-color.org/) is now + respected. + ## [0.3.3] - 2022-03-16 No changes, only trying to get the automated build to work. diff --git a/src/ui.rs b/src/ui.rs index b4f620a91..6cf102df7 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -46,6 +46,21 @@ fn new_formatter<'output>( } } +fn use_color(settings: &UserSettings) -> bool { + if std::env::var("NO_COLOR").is_ok() { + return false; + } + let color_setting = settings + .config() + .get_string("ui.color") + .unwrap_or_else(|_| "auto".to_string()); + match color_setting.as_str() { + "always" => true, + "never" => false, + _ => atty::is(Stream::Stdout), + } +} + impl<'stdout> Ui<'stdout> { pub fn new( cwd: PathBuf, @@ -65,15 +80,7 @@ impl<'stdout> Ui<'stdout> { pub fn for_terminal(settings: UserSettings) -> Ui<'static> { let cwd = std::env::current_dir().unwrap(); let stdout: Box = Box::new(io::stdout()); - let color_setting = settings - .config() - .get_string("ui.color") - .unwrap_or_else(|_| "auto".to_string()); - let color = match color_setting.as_str() { - "always" => true, - "never" => false, - _ => atty::is(Stream::Stdout), - }; + let color = use_color(&settings); Ui::new(cwd, stdout, color, settings) } diff --git a/tests/test_global_opts.rs b/tests/test_global_opts.rs index 6ef2a0133..b39bf9d84 100644 --- a/tests/test_global_opts.rs +++ b/tests/test_global_opts.rs @@ -85,6 +85,8 @@ fn test_repo_arg_with_git_clone() { #[test] fn test_color_config() { let test_env = TestEnvironment::default(); + + // Test that color is used if it's requested in the config file let mut config_file = std::fs::File::options() .append(true) .open(test_env.config_path()) @@ -110,4 +112,15 @@ color="always""#, @ 230dd059e1b059aefc0da06a2e5a7dbf22362f22 o 0000000000000000000000000000000000000000 "###); + + // Test that NO_COLOR overrides the request for color in the config file + let assert = test_env + .jj_cmd(&repo_path, &["log", "-T", "commit_id"]) + .env("NO_COLOR", "") + .assert() + .success(); + insta::assert_snapshot!(get_stdout_string(&assert), @r###" + @ 230dd059e1b059aefc0da06a2e5a7dbf22362f22 + o 0000000000000000000000000000000000000000 + "###); }