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

Add --color setting to CLI. #721

Merged
merged 7 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ rayon = "1.8.0"
[dev-dependencies]
assert_cmd = "2.0"
similar-asserts = { version = "1.5.0", features = ["serde"] }
predicates = "3.1.0"

# In dev and test profiles, compile all dependencies with optimizations enabled,
# but still checking debug assertions and overflows.
Expand Down
6 changes: 6 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ impl GlobalConfig {
&mut self.stderr
}

pub fn set_color_choice(mut self, choice: ColorChoice) -> Self {
self.stdout = StandardStream::stdout(choice);
self.stderr = StandardStream::stderr(choice);
self
}

/// Print a message with a colored title in the style of Cargo shell messages.
pub fn shell_print(
&mut self,
Expand Down
23 changes: 23 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub struct Check {
current: Rustdoc,
baseline: Rustdoc,
log_level: Option<log::Level>,
color_choice: Option<termcolor::ColorChoice>,
release_type: Option<ReleaseType>,
current_feature_config: rustdoc_gen::FeatureConfig,
baseline_feature_config: rustdoc_gen::FeatureConfig,
Expand Down Expand Up @@ -247,6 +248,7 @@ impl Check {
current,
baseline: Rustdoc::from_registry_latest_crate_version(),
log_level: Default::default(),
color_choice: None,
release_type: None,
current_feature_config: rustdoc_gen::FeatureConfig::default_for_current(),
baseline_feature_config: rustdoc_gen::FeatureConfig::default_for_baseline(),
Expand Down Expand Up @@ -283,6 +285,21 @@ impl Check {
self.log_level.as_ref()
}

/// Set the termcolor [color choice](termcolor::ColorChoice).
/// If `None`, the use of colors will be determined automatically by
/// the `CARGO_TERM_COLOR` env var and tty type of output.
pub fn with_color_choice(&mut self, choice: Option<termcolor::ColorChoice>) -> &mut Self {
self.color_choice = choice;
self
}

/// Get the current color choice. If `None`, the use of colors is determined
/// by the `CARGO_TERM_COLOR` env var and whether the output is a tty
#[inline]
pub fn color_choice(&self) -> Option<&termcolor::ColorChoice> {
self.color_choice.as_ref()
}

pub fn with_release_type(&mut self, release_type: ReleaseType) -> &mut Self {
self.release_type = Some(release_type);
self
Expand Down Expand Up @@ -386,6 +403,12 @@ impl Check {

pub fn check_release(&self) -> anyhow::Result<Report> {
let mut config = GlobalConfig::new().set_level(self.log_level);
// we don't want to set auto if the choice is not set because it would overwrite
// the value if the CARGO_TERM_COLOR env var read in GlobalConfig::new() if it is set
if let Some(choice) = self.color_choice {
config = config.set_color_choice(choice);
}

let rustdoc_cmd = RustdocCommand::new().deps(false).silence(config.is_info());

// If both the current and baseline rustdoc are given explicitly as a file path,
Expand Down
16 changes: 16 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ fn main() {
exit_on_error(true, || {
let mut config =
GlobalConfig::new().set_level(args.check_release.verbosity.log_level());

// we don't want to set auto if the choice is not set because it would overwrite
// the value if the CARGO_TERM_COLOR env var read in GlobalConfig::new() if it is set
if let Some(choice) = args.check_release.color_choice {
config = config.set_color_choice(choice);
}

let queries = SemverQuery::all_queries();
let mut rows = vec![["id", "type", "description"], ["==", "====", "==========="]];
for query in queries.values() {
Expand Down Expand Up @@ -282,6 +289,14 @@ struct CheckRelease {

#[command(flatten)]
verbosity: clap_verbosity_flag::Verbosity<clap_verbosity_flag::InfoLevel>,

/// Whether to print colors to the terminal:
/// always, alwaysansi (always use only ANSI color codes),
/// auto (based on whether output is a tty), and never
///
/// Default is auto (use colors if output is a TTY, otherwise don't use colors)
#[arg(value_enum, long = "color")]
color_choice: Option<termcolor::ColorChoice>,
}

impl From<CheckRelease> for cargo_semver_checks::Check {
Expand Down Expand Up @@ -344,6 +359,7 @@ impl From<CheckRelease> for cargo_semver_checks::Check {
}

check.with_log_level(value.verbosity.log_level());
check.with_color_choice(value.color_choice);

if let Some(release_type) = value.release_type {
check.with_release_type(release_type);
Expand Down
99 changes: 99 additions & 0 deletions tests/color_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//! Tests the --color flag and CARGO_TERM_COLOR env var, and their interactions
//!
//! The --color flag should take precedence over the environment variable
use assert_cmd::Command;
use predicates::boolean::PredicateBooleanExt;

/// helper function to run `check-release` on a given directory in `test_crates/` with the given color arg/env var
/// - `color_arg` is the argument to `--color=<choice>`, if set
/// - `color_env_var` sets the `CARGO_TERM_COLOR=choice`, if set
///
/// Panics with a failed assertion if there are colors (i.e., ANSI color codes) in the output and `assert_colors` is false, or vice versa
fn run_on_crate_diff(
test_crate_name: &'static str,
color_arg: Option<&'static str>,
color_env_var: Option<&'static str>,
assert_colors: bool,
) {
let mut cmd = Command::cargo_bin("cargo-semver-checks").unwrap();

cmd.current_dir(format!("test_crates/{}", test_crate_name))
.args([
"semver-checks",
"check-release",
"--manifest-path=new/Cargo.toml",
"--baseline-root=old/",
]);

if let Some(color_arg) = color_arg {
cmd.arg("--color").arg(color_arg);
}

if let Some(color_env) = color_env_var {
cmd.env("CARGO_TERM_COLOR", color_env);
} else {
cmd.env_remove("CARGO_TERM_COLOR");
}

let pred = predicates::str::contains("\u{1b}[");

let assert = cmd.assert();

if assert_colors {
assert.stderr(pred);
} else {
assert.stderr(pred.not());
}
}

/// test for colors when using the --color=always flag
#[test]
fn always_flag() {
// test on a crate diff returning no errors
run_on_crate_diff("template", Some("always"), None, true);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", Some("always"), None, true);
}

/// test for no colors when using the --color=never flag
#[test]
fn never_flag() {
// test on a crate diff returning no errors
run_on_crate_diff("template", Some("never"), None, false);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", Some("never"), None, false);
}

/// test for colors when using the CARGO_TERM_COLOR=always env var
#[test]
fn always_var() {
// test on a crate diff returning no errors
run_on_crate_diff("template", None, Some("always"), true);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", None, Some("always"), true);
}

/// test for colors when using the CARGO_TERM_COLOR=never env var
#[test]
fn never_var() {
// test on a crate diff returning no errors
run_on_crate_diff("template", None, Some("never"), false);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", None, Some("never"), false);
}

/// test for the behavior of the --color flag overriding the `CARGO_TERM_COLOR` env var when they conflict
#[test]
fn cli_flag_overrides_env_var() {
// test when --color=always and CARGO_TERM_COLOR=never
// test on a crate diff returning no errors
run_on_crate_diff("template", Some("always"), Some("never"), true);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", Some("always"), Some("never"), true);

// test when --color=never and CARGO_TERM_COLOR=always
// test on a crate diff returning no errors
run_on_crate_diff("template", Some("never"), Some("always"), false);
// test on a crate diff that will return errors
run_on_crate_diff("enum_missing", Some("never"), Some("always"), false);
}
Loading