From 4bc74f7e9006fc7f182c9dc6ea309ea83c5bb4f9 Mon Sep 17 00:00:00 2001 From: sigoden Date: Tue, 8 Oct 2024 12:38:31 +0800 Subject: refactor: NO_COLOR, highlight and render_error (#915) - If NO_COLOR is enabled, AIChat will not output any ANSI color codes. - `config.highlight` will only affect rendering markdown - improve rendering error --- src/utils/mod.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src/utils') diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 81ae0ff..0bd1d41 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -31,6 +31,7 @@ use unicode_segmentation::UnicodeSegmentation; lazy_static::lazy_static! { pub static ref CODE_BLOCK_RE: Regex = Regex::new(r"(?ms)```\w*(.*)```").unwrap(); pub static ref IS_STDOUT_TERMINAL: bool = std::io::stdout().is_terminal(); + pub static ref NO_COLOR: bool = env::var("NO_COLOR").ok().and_then(|v| parse_bool(&v)).unwrap_or_default() || !*IS_STDOUT_TERMINAL; } pub fn now() -> String { @@ -46,6 +47,14 @@ pub fn normalize_env_name(value: &str) -> String { value.replace('-', "_").to_ascii_uppercase() } +pub fn parse_bool(value: &str) -> Option { + match value { + "1" | "true" => Some(true), + "0" | "false" => Some(false), + _ => None, + } +} + pub fn estimate_token_length(text: &str) -> usize { let words: Vec<&str> = text.unicode_words().collect(); let mut output: f32 = 0.0; @@ -127,9 +136,11 @@ pub fn fuzzy_match(text: &str, pattern: &str) -> bool { pub fn pretty_error(err: &anyhow::Error) -> String { let mut output = vec![]; - output.push(err.to_string()); - output.push("Caused by:".to_string()); + output.push(format!("Error: {err}")); for (i, cause) in err.chain().skip(1).enumerate() { + if i == 0 { + output.push("Caused by:".to_string()); + } output.push(format!(" {i}: {cause}")); } output.push(String::new()); @@ -145,6 +156,9 @@ pub fn warning_text(input: &str) -> String { } pub fn color_text(input: &str, color: nu_ansi_term::Color) -> String { + if *NO_COLOR { + return input.to_string(); + } nu_ansi_term::Style::new() .fg(color) .paint(input) @@ -152,6 +166,9 @@ pub fn color_text(input: &str, color: nu_ansi_term::Color) -> String { } pub fn dimmed_text(input: &str) -> String { + if *NO_COLOR { + return input.to_string(); + } nu_ansi_term::Style::new().dimmed().paint(input).to_string() } -- cgit v1.2.3