Skip to content

Commit 797bf59

Browse files
authored
Detect if terminal supports ANSI (#103)
Fixes #94
1 parent e315342 commit 797bf59

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

src/compose/error.rs

+29-9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use codespan_reporting::{
44
diagnostic::{Diagnostic, Label},
55
files::SimpleFile,
66
term,
7+
term::termcolor::WriteColor,
78
};
89
use thiserror::Error;
910
use tracing::trace;
@@ -180,11 +181,6 @@ impl ComposerError {
180181

181182
let files = SimpleFile::new(path, source.as_str());
182183
let config = term::Config::default();
183-
#[cfg(any(test, target_arch = "wasm32"))]
184-
let mut writer = term::termcolor::NoColor::new(Vec::new());
185-
#[cfg(not(any(test, target_arch = "wasm32")))]
186-
let mut writer = term::termcolor::Ansi::new(Vec::new());
187-
188184
let (labels, notes) = match &self.inner {
189185
ComposerErrorInner::DecorationInSource(range) => {
190186
(vec![Label::primary((), range.clone())], vec![])
@@ -277,11 +273,35 @@ impl ComposerError {
277273
.with_labels(labels)
278274
.with_notes(notes);
279275

280-
term::emit(&mut writer, &config, &files, &diagnostic).expect("cannot write error");
276+
let mut msg = Vec::with_capacity(256);
277+
278+
let mut color_writer;
279+
let mut no_color_writer;
280+
let writer: &mut dyn WriteColor = if supports_color() {
281+
color_writer = term::termcolor::Ansi::new(&mut msg);
282+
&mut color_writer
283+
} else {
284+
no_color_writer = term::termcolor::NoColor::new(&mut msg);
285+
&mut no_color_writer
286+
};
287+
288+
term::emit(writer, &config, &files, &diagnostic).expect("cannot write error");
281289

282-
let msg = writer.into_inner();
283-
let msg = String::from_utf8_lossy(&msg);
290+
String::from_utf8_lossy(&msg).into_owned()
291+
}
292+
}
293+
294+
#[cfg(any(test, target_arch = "wasm32"))]
295+
fn supports_color() -> bool {
296+
false
297+
}
284298

285-
msg.to_string()
299+
// termcolor doesn't expose this logic when using custom buffers
300+
#[cfg(not(any(test, target_arch = "wasm32")))]
301+
fn supports_color() -> bool {
302+
match std::env::var_os("TERM") {
303+
None if cfg!(unix) => false,
304+
Some(term) if term == "dumb" => false,
305+
_ => std::env::var_os("NO_COLOR").is_none(),
286306
}
287307
}

0 commit comments

Comments
 (0)