diff options
| author | sigoden <sigoden@gmail.com> | 2024-10-08 12:38:31 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-10-08 12:38:31 +0800 |
| commit | 4bc74f7e9006fc7f182c9dc6ea309ea83c5bb4f9 (patch) | |
| tree | 1ed8ef0b37879ea543fe1ba2060757e4079c90ce /src/utils/mod.rs | |
| parent | c211d1e43a02266226fb8d04856e703a4e6a625d (diff) | |
| download | aichat-4bc74f7e9006fc7f182c9dc6ea309ea83c5bb4f9.tar.gz | |
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
Diffstat (limited to 'src/utils/mod.rs')
| -rw-r--r-- | src/utils/mod.rs | 21 |
1 files changed, 19 insertions, 2 deletions
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<bool> { + 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() } |
