1
Fork 0

Simplfy color availability check

This commit is contained in:
Guillaume Gomez 2020-11-11 16:44:02 +01:00
parent 704001b929
commit 32d64edcf9
6 changed files with 41 additions and 45 deletions

View file

@ -4301,7 +4301,6 @@ dependencies = [
"serde_json", "serde_json",
"smallvec 1.4.2", "smallvec 1.4.2",
"tempfile", "tempfile",
"termcolor",
] ]
[[package]] [[package]]

View file

@ -200,6 +200,11 @@ pub trait Emitter {
true true
} }
/// Checks if we can use colors in the current output stream.
fn supports_color(&self) -> bool {
false
}
fn source_map(&self) -> Option<&Lrc<SourceMap>>; fn source_map(&self) -> Option<&Lrc<SourceMap>>;
/// Formats the substitutions of the primary_span /// Formats the substitutions of the primary_span
@ -504,6 +509,10 @@ impl Emitter for EmitterWriter {
fn should_show_explain(&self) -> bool { fn should_show_explain(&self) -> bool {
!self.short_message !self.short_message
} }
fn supports_color(&self) -> bool {
self.dst.supports_color()
}
} }
/// An emitter that does nothing when emitting a diagnostic. /// An emitter that does nothing when emitting a diagnostic.
@ -2057,6 +2066,14 @@ impl Destination {
Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)), Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
} }
} }
fn supports_color(&self) -> bool {
match *self {
Self::Terminal(ref stream) => stream.supports_color(),
Self::Buffered(ref buffer) => buffer.buffer().supports_color(),
Self::Raw(_, supports_color) => supports_color,
}
}
} }
impl<'a> WritableDst<'a> { impl<'a> WritableDst<'a> {

View file

@ -20,6 +20,3 @@ regex = "1"
[dev-dependencies] [dev-dependencies]
expect-test = "1.0" expect-test = "1.0"
[target.'cfg(windows)'.dependencies]
termcolor = "1.0"

View file

@ -249,7 +249,8 @@ fn run_test(
outdir: DirState, outdir: DirState,
path: PathBuf, path: PathBuf,
) -> Result<(), TestFailure> { ) -> Result<(), TestFailure> {
let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition); let (test, line_offset, supports_color) =
make_test(test, Some(cratename), as_test_harness, opts, edition);
let output_file = outdir.path().join("rust_out"); let output_file = outdir.path().join("rust_out");
@ -294,38 +295,19 @@ fn run_test(
path.to_str().expect("target path must be valid unicode").to_string() path.to_str().expect("target path must be valid unicode").to_string()
} }
}); });
match options.error_format { if let ErrorOutputType::HumanReadable(kind) = options.error_format {
ErrorOutputType::HumanReadable(kind) => { let (_, color_config) = kind.unzip();
let (_, color_config) = kind.unzip(); match color_config {
match color_config { ColorConfig::Never => {
ColorConfig::Never => { compiler.arg("--color").arg("never");
compiler.arg("--color").arg("never"); }
} ColorConfig::Always => {
ColorConfig::Always => { compiler.arg("--color").arg("always");
compiler.arg("--color").arg("always"); }
} ColorConfig::Auto => {
ColorConfig::Auto => { compiler.arg("--color").arg(if supports_color { "always" } else { "never" });
#[cfg(windows)]
{
// This specific check is because old windows consoles require a connection
// to be able to display colors (and they don't support ANSI), which we
// cannot in here, so in case this is an old windows console, we can't
// display colors.
use crate::termcolor::{ColorChoice, StandardStream, WriteColor};
if StandardStream::stdout(ColorChoice::Auto).is_synchronous() {
compiler.arg("--color").arg("never");
} else {
compiler.arg("--color").arg("always");
}
}
#[cfg(not(windows))]
{
compiler.arg("--color").arg("always");
}
}
} }
} }
_ => {}
} }
compiler.arg("-"); compiler.arg("-");
@ -396,18 +378,19 @@ fn run_test(
} }
/// Transforms a test into code that can be compiled into a Rust binary, and returns the number of /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
/// lines before the test code begins. /// lines before the test code begins as well as if the output stream supports colors or not.
crate fn make_test( crate fn make_test(
s: &str, s: &str,
cratename: Option<&str>, cratename: Option<&str>,
dont_insert_main: bool, dont_insert_main: bool,
opts: &TestOptions, opts: &TestOptions,
edition: Edition, edition: Edition,
) -> (String, usize) { ) -> (String, usize, bool) {
let (crate_attrs, everything_else, crates) = partition_source(s); let (crate_attrs, everything_else, crates) = partition_source(s);
let everything_else = everything_else.trim(); let everything_else = everything_else.trim();
let mut line_offset = 0; let mut line_offset = 0;
let mut prog = String::new(); let mut prog = String::new();
let mut supports_color = false;
if opts.attrs.is_empty() && !opts.display_warnings { if opts.attrs.is_empty() && !opts.display_warnings {
// If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
@ -433,7 +416,7 @@ crate fn make_test(
// crate already is included. // crate already is included.
let result = rustc_driver::catch_fatal_errors(|| { let result = rustc_driver::catch_fatal_errors(|| {
rustc_span::with_session_globals(edition, || { rustc_span::with_session_globals(edition, || {
use rustc_errors::emitter::EmitterWriter; use rustc_errors::emitter::{Emitter, EmitterWriter};
use rustc_errors::Handler; use rustc_errors::Handler;
use rustc_parse::maybe_new_parser_from_source_str; use rustc_parse::maybe_new_parser_from_source_str;
use rustc_session::parse::ParseSess; use rustc_session::parse::ParseSess;
@ -447,6 +430,9 @@ crate fn make_test(
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let emitter = let emitter =
EmitterWriter::new(box io::sink(), None, false, false, false, None, false); EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
supports_color = emitter.supports_color();
// FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
let handler = Handler::with_emitter(false, None, box emitter); let handler = Handler::with_emitter(false, None, box emitter);
let sess = ParseSess::with_span_handler(handler, sm); let sess = ParseSess::with_span_handler(handler, sm);
@ -516,7 +502,7 @@ crate fn make_test(
Err(ErrorReported) => { Err(ErrorReported) => {
// If the parser panicked due to a fatal error, pass the test code through unchanged. // If the parser panicked due to a fatal error, pass the test code through unchanged.
// The error will be reported during compilation. // The error will be reported during compilation.
return (s.to_owned(), 0); return (s.to_owned(), 0, false);
} }
}; };
@ -566,7 +552,7 @@ crate fn make_test(
debug!("final doctest:\n{}", prog); debug!("final doctest:\n{}", prog);
(prog, line_offset) (prog, line_offset, supports_color)
} }
// FIXME(aburka): use a real parser to deal with multiline attributes // FIXME(aburka): use a real parser to deal with multiline attributes

View file

@ -243,7 +243,8 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
.collect::<Vec<Cow<'_, str>>>() .collect::<Vec<Cow<'_, str>>>()
.join("\n"); .join("\n");
let krate = krate.as_ref().map(|s| &**s); let krate = krate.as_ref().map(|s| &**s);
let (test, _) = doctest::make_test(&test, krate, false, &Default::default(), edition); let (test, _, _) =
doctest::make_test(&test, krate, false, &Default::default(), edition);
let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" }; let channel = if test.contains("#![feature(") { "&amp;version=nightly" } else { "" };
let edition_string = format!("&amp;edition={}", edition); let edition_string = format!("&amp;edition={}", edition);

View file

@ -54,10 +54,6 @@ extern crate rustc_target;
extern crate rustc_trait_selection; extern crate rustc_trait_selection;
extern crate rustc_typeck; extern crate rustc_typeck;
extern crate test as testing; extern crate test as testing;
#[macro_use]
extern crate tracing;
#[cfg(windows)]
extern crate termcolor;
use std::default::Default; use std::default::Default;
use std::env; use std::env;