@@ -4,6 +4,7 @@ use codespan_reporting::{
4
4
diagnostic:: { Diagnostic , Label } ,
5
5
files:: SimpleFile ,
6
6
term,
7
+ term:: termcolor:: WriteColor ,
7
8
} ;
8
9
use thiserror:: Error ;
9
10
use tracing:: trace;
@@ -180,11 +181,6 @@ impl ComposerError {
180
181
181
182
let files = SimpleFile :: new ( path, source. as_str ( ) ) ;
182
183
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
-
188
184
let ( labels, notes) = match & self . inner {
189
185
ComposerErrorInner :: DecorationInSource ( range) => {
190
186
( vec ! [ Label :: primary( ( ) , range. clone( ) ) ] , vec ! [ ] )
@@ -277,11 +273,35 @@ impl ComposerError {
277
273
. with_labels ( labels)
278
274
. with_notes ( notes) ;
279
275
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" ) ;
281
289
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
+ }
284
298
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 ( ) ,
286
306
}
287
307
}
0 commit comments