mirror of
https://github.com/openharmony/third_party_rust_codespan.git
synced 2026-07-20 19:53:16 -04:00
feat: Color the error severity
This commit is contained in:
@@ -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();
|
||||
}
|
||||
@@ -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,5 +1,5 @@
|
||||
extern crate codespan;
|
||||
extern crate termcolor;
|
||||
pub extern crate termcolor;
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt;
|
||||
|
||||
Reference in New Issue
Block a user