From d3958169290eb6f35a034e84950e38cd98d36b42 Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Fri, 1 Oct 2021 09:00:08 -0500 Subject: [PATCH] remove ansi colors if this is not a tty (#4058) --- Cargo.lock | 2 ++ crates/nu-table/Cargo.toml | 2 ++ crates/nu-table/src/main.rs | 14 ++++++++++++-- crates/nu-table/src/table.rs | 12 +++++++++++- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 11cbbc91b6..226e691222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2900,8 +2900,10 @@ dependencies = [ name = "nu-table" version = "0.37.1" dependencies = [ + "atty", "nu-ansi-term", "regex", + "strip-ansi-escapes", "unicode-width", ] diff --git a/crates/nu-table/Cargo.toml b/crates/nu-table/Cargo.toml index f689eb3e75..4d3409daff 100644 --- a/crates/nu-table/Cargo.toml +++ b/crates/nu-table/Cargo.toml @@ -12,7 +12,9 @@ name = "table" path = "src/main.rs" [dependencies] +atty = "0.2.14" nu-ansi-term = { version = "0.37.1", path="../nu-ansi-term" } regex = "1.4" +strip-ansi-escapes = "0.1.1" unicode-width = "0.1.8" diff --git a/crates/nu-table/src/main.rs b/crates/nu-table/src/main.rs index 638582a1fa..bb464ca069 100644 --- a/crates/nu-table/src/main.rs +++ b/crates/nu-table/src/main.rs @@ -27,8 +27,18 @@ fn main() { let color_hm: HashMap = HashMap::new(); // Capture the table as a string let output_table = draw_table(&table, width, &color_hm); - // Draw the table - println!("{}", output_table) + + if atty::is(atty::Stream::Stdout) { + // Draw the table with ansi colors + println!("{}", output_table) + } else { + // Draw the table without ansi colors + if let Ok(bytes) = strip_ansi_escapes::strip(&output_table) { + println!("{}", String::from_utf8_lossy(&bytes)) + } else { + println!("{}", output_table) + } + } } fn make_table_data() -> (Vec<&'static str>, Vec<&'static str>) { diff --git a/crates/nu-table/src/table.rs b/crates/nu-table/src/table.rs index 817c59ef99..38f826552b 100644 --- a/crates/nu-table/src/table.rs +++ b/crates/nu-table/src/table.rs @@ -918,7 +918,17 @@ impl WrappedTable { output.push_str(&self.print_separator(SeparatorPosition::Bottom, color_hm)); } - output + if atty::is(atty::Stream::Stdout) { + // Draw the table with ansi colors + output + } else { + // Draw the table without ansi colors + if let Ok(bytes) = strip_ansi_escapes::strip(&output) { + String::from_utf8_lossy(&bytes).to_string() + } else { + output + } + } } }