feat: Color the error severity

This commit is contained in:
Markus Westerlind
2018-04-11 22:00:59 +02:00
parent c7a7e043a0
commit ea4f0979a5
3 changed files with 49 additions and 7 deletions
+25
View File
@@ -0,0 +1,25 @@
extern crate codespan;
extern crate codespan_reporting;
use codespan::CodeMap;
use codespan_reporting::termcolor::{ColorChoice, StandardStream};
use codespan_reporting::{emit, Diagnostic, Label, Severity};
fn main() {
let writer = StandardStream::stdout(ColorChoice::Auto);
let mut code_map = CodeMap::new();
let source = r##"
(define test 123)
(+ test "")
"##;
let file_map = code_map.add_filemap("test".into(), source.to_string());
let diagnostic = Diagnostic::new(Severity::Error, "Unexpected type in `+` application")
.with_label(
Label::new_primary(file_map.line_span(2.into()).unwrap())
.with_message("Expected integer but got string"),
);
emit(&mut writer.lock(), &code_map, &diagnostic).unwrap();
}
+23 -6
View File
@@ -1,23 +1,40 @@
use std::io;
use codespan::CodeMap;
use termcolor::{ColorSpec, WriteColor};
use Diagnostic;
pub fn emit(codemap: &CodeMap, diagnostic: &Diagnostic) {
println!("{}: {}", diagnostic.severity, diagnostic.message);
pub fn emit<W>(mut writer: W, codemap: &CodeMap, diagnostic: &Diagnostic) -> io::Result<()>
where
W: WriteColor,
{
writer.set_color(ColorSpec::new().set_fg(Some(diagnostic.severity.color())))?;
write!(writer, "{}", diagnostic.severity)?;
writer.reset()?;
writeln!(writer, ": {}", diagnostic.message)?;
for label in &diagnostic.labels {
match codemap.find_file(label.span.start()) {
None => if let Some(ref message) = label.message {
println!("- {}", message)
writeln!(writer, "- {}", message)?
},
Some(file) => {
let (line, col) = file.location(label.span.start()).expect("location");
print!("- {}:{}:{}", file.name(), line.number(), col.number());
writeln!(
writer,
"- {}:{}:{}",
file.name(),
line.number(),
col.number()
)?;
match label.message {
None => println!(),
Some(ref label) => println!(": {}", label),
None => writeln!(writer)?,
Some(ref label) => writeln!(writer, ": {}", label)?,
}
},
}
}
Ok(())
}
+1 -1
View File
@@ -1,5 +1,5 @@
extern crate codespan;
extern crate termcolor;
pub extern crate termcolor;
use std::cmp::Ordering;
use std::fmt;