Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(cli): support --no-color flag and NO_COLOR env var (#2738)
Filipe Verri359cf06debc7
diff --git a/Cargo.lock b/Cargo.lockindex 9954f04de..42152ce02 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2723,6 +2723,7 @@ dependencies = ["serde_json","strum","strum_macros",+ "yansi",][[package]]diff --git a/harper-cli/Cargo.toml b/harper-cli/Cargo.tomlindex 64d555a44..3e2d99bcc 100644--- a/harper-cli/Cargo.toml+++ b/harper-cli/Cargo.toml@@ -27,6 +27,7 @@ strum = "0.27.2"strum_macros = "0.27.2"harper-ink = { version = "1.0.0", path = "../harper-ink" }enum_dispatch = "0.3.13"+yansi = "1.0.1"[features]default = []diff --git a/harper-cli/src/lint.rs b/harper-cli/src/lint.rsindex 53f3a0042..c569ce4fd 100644--- a/harper-cli/src/lint.rs+++ b/harper-cli/src/lint.rs@@ -77,6 +77,7 @@ pub struct LintOptions {pub keep_overlapping_lints: bool,pub dialect: Dialect,pub weirpack_inputs: Vec<SingleInput>,+ pub color: bool,}enum ReportStyle {FullAriadneLintReport,@@ -86,6 +87,7 @@ enum ReportStyle {struct InputInfo<'a> {parent_input_id: &'a str,input: &'a AnyInput,+ color: bool,}struct InputJob {@@ -99,8 +101,10 @@ impl InputInfo<'_> {let child = self.input.get_identifier();if self.parent_input_id.is_empty() {child.into_owned()- } else {+ } else if self.color {format!("\x1b[33m{}/\x1b[0m{}", self.parent_input_id, child)+ } else {+ format!("{}/{}", self.parent_input_id, child)}}}@@ -235,6 +239,7 @@ pub fn lint(InputInfo {parent_input_id: parent_input_id.as_str(),input: &input,+ color: lint_options.color,},)};@@ -270,6 +275,7 @@ pub fn lint(all_rules,all_lint_kind_rule_pairs,all_spellos,+ lint_options.color,);process::exit(1);@@ -313,6 +319,7 @@ fn lint_one_input(keep_overlapping_lints,dialect,weirpack_inputs: _,+ color: _,} = lint_options;let mut lint_kinds: HashMap<LintKind, usize> = HashMap::new();@@ -371,6 +378,7 @@ fn lint_one_input(input: InputInfo {parent_input_id: current.parent_input_id,input: current.input,+ color: current.color,},doc,source,@@ -556,7 +564,7 @@ fn single_input_report(.collect();println!("lint kinds:");- print_formatted_items(lk_vec);+ print_formatted_items(lk_vec, input.color);}if !lint_rules.is_empty() {@@ -569,7 +577,7 @@ fn single_input_report(.collect();println!("rules:");- print_formatted_items(r_vec);+ print_formatted_items(r_vec, input.color);}}@@ -611,6 +619,7 @@ fn final_report(all_rules: HashMap<String, usize>,all_lint_kind_rule_pairs: HashMap<(LintKind, String), usize>,all_spellos: HashMap<String, usize>,+ color: bool,) {// The stats summary of all inputs that we only do when there are multiple inputs.if batch_mode {@@ -632,7 +641,7 @@ fn final_report(if !lint_kind_counts.is_empty() {println!("All files lint kinds:");- print_formatted_items(lint_kind_counts);+ print_formatted_items(lint_kind_counts, color);}let mut all_files_rule_name_counts_vec: Vec<_> = all_rules.into_iter().collect();@@ -646,7 +655,7 @@ fn final_report(if !rule_name_counts.is_empty() {println!("All files rule names:");- print_formatted_items(rule_name_counts);+ print_formatted_items(rule_name_counts, color);}}@@ -674,7 +683,7 @@ fn final_report(if !formatted_lint_kind_rule_pairs.is_empty() {// Print them with line wrapping- print_formatted_items(formatted_lint_kind_rule_pairs);+ print_formatted_items(formatted_lint_kind_rule_pairs, color);}if !all_spellos.is_empty() {@@ -714,16 +723,19 @@ fn final_report(1 => (90, 180, 90), // Green_ => (90, 150, 180), // Cyan};- let color = format!("\x1b[38;2;{};{};{}m", r, g, b);-- variants- .into_iter()- .map(move |(spelling, c)| (Some(color.clone()), format!("(“{spelling}”: {c})")))+ let ansi_color = format!("\x1b[38;2;{};{};{}m", r, g, b);++ variants.into_iter().map(move |(spelling, c)| {+ (+ Some(ansi_color.clone()),+ format!("(\u{201c}{spelling}\u{201d}: {c})"),+ )+ })}).collect();println!("All files Spelling::SpellCheck (For dialect: {})", dialect);- print_formatted_items(spelling_vec);+ print_formatted_items(spelling_vec, color);}}@@ -766,7 +778,7 @@ fn rgb_for_lint_kind(olk: Option<&LintKind>) -> (u8, u8, u8) {.unwrap_or((0, 0, 0))}-fn print_formatted_items(items: impl IntoIterator<Item = (Option<String>, String)>) {+fn print_formatted_items(items: impl IntoIterator<Item = (Option<String>, String)>, color: bool) {let mut first_on_line = true;let mut len_so_far = 0;@@ -784,8 +796,12 @@ fn print_formatted_items(items: impl IntoIterator<Item = (Option<String>, Stringbefore = " ";}- let (set, reset): (&str, &str) = if let Some(prefix) = ansi.as_ref() {- (prefix, "\x1b[0m")+ let (set, reset): (&str, &str) = if color {+ if let Some(prefix) = ansi.as_ref() {+ (prefix.as_str(), "\x1b[0m")+ } else {+ ("", "")+ }} else {("", "")};diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rsindex 6d5de2525..723f660b0 100644--- a/harper-cli/src/main.rs+++ b/harper-cli/src/main.rs@@ -42,6 +42,16 @@ use lint::LintOptions;/// A debugging tool for the Harper grammar checker.#[derive(Parser)]#[command(version, about)]+struct Cli {+ /// Disable colored output.+ #[arg(long, global = true)]+ no_color: bool,++ #[command(subcommand)]+ command: Args,+}++#[derive(clap::Subcommand)]enum Args {/// Lint provided documents.Lint {@@ -203,11 +213,17 @@ enum Args {}fn main() -> anyhow::Result<()> {- let args = Args::parse();+ let cli = Cli::parse();++ let color = !cli.no_color && std::env::var("NO_COLOR").is_err();+ if !color {+ yansi::disable();+ }+let markdown_options = MarkdownOptions::default();let curated_dictionary = FstDictionary::curated();- match args {+ match cli.command {Args::Lint {inputs,count,@@ -233,6 +249,7 @@ fn main() -> anyhow::Result<()> {keep_overlapping_lints,dialect,weirpack_inputs: weirpacks,+ color,},user_dict_path,// TODO workspace_dict_path?@@ -915,7 +932,11 @@ fn main() -> anyhow::Result<()> {let span = Span::new(start, end);let txt = doc.get_span_content_str(&span);- print!("\x1b[33m{}\x1b[0m", txt);+ if color {+ print!("\x1b[33m{}\x1b[0m", txt);+ } else {+ print!("{}", txt);+ }last_end = end;}diff --git a/harper-cli/tests/no_color.rs b/harper-cli/tests/no_color.rsnew file mode 100644index 000000000..cc0e85a5e--- /dev/null+++ b/harper-cli/tests/no_color.rs@@ -0,0 +1,57 @@+use std::process::Command;++fn harper_cli() -> Command {+ Command::new(env!("CARGO_BIN_EXE_harper-cli"))+}++/// Input that triggers at least one lint ("an test" → AnA rule).+const BAD_INPUT: &str = "This is an test.";++fn has_ansi(bytes: &[u8]) -> bool {+ bytes.contains(&0x1b)+}++#[test]+fn default_output_contains_ansi() {+ let output = harper_cli()+ .args(["lint", BAD_INPUT])+ .env_remove("NO_COLOR")+ .output()+ .unwrap();++ let combined = [&output.stdout[..], &output.stderr[..]].concat();+ assert!(+ has_ansi(&combined),+ "default output should contain ANSI escape codes"+ );+}++#[test]+fn no_color_flag_strips_ansi() {+ let output = harper_cli()+ .args(["--no-color", "lint", BAD_INPUT])+ .env_remove("NO_COLOR")+ .output()+ .unwrap();++ let combined = [&output.stdout[..], &output.stderr[..]].concat();+ assert!(+ !has_ansi(&combined),+ "--no-color output should not contain ANSI escape codes"+ );+}++#[test]+fn no_color_env_strips_ansi() {+ let output = harper_cli()+ .env("NO_COLOR", "1")+ .args(["lint", BAD_INPUT])+ .output()+ .unwrap();++ let combined = [&output.stdout[..], &output.stderr[..]].concat();+ assert!(+ !has_ansi(&combined),+ "NO_COLOR=1 output should not contain ANSI escape codes"+ );+}