Skip to main content

rspack_error/displayer/
string.rs

1use std::io::Write;
2
3use termcolor::{Buffer, WriteColor};
4
5use super::{Display, renderer::Renderer};
6use crate::diagnostic::Diagnostic;
7
8#[derive(Default, Debug, Clone)]
9pub struct StringDisplayer {
10  colored: bool,
11  sorted: bool,
12}
13
14impl StringDisplayer {
15  pub fn new(colored: bool, sorted: bool) -> Self {
16    Self { colored, sorted }
17  }
18}
19
20impl Display for StringDisplayer {
21  type Output = crate::Result<String>;
22
23  fn emit_batch_diagnostic<'a>(
24    &self,
25    diagnostics: impl Iterator<Item = &'a Diagnostic>,
26  ) -> Self::Output {
27    let renderer = Renderer::new(self.colored);
28    let mut diagnostic_strings = vec![];
29    for d in diagnostics {
30      diagnostic_strings.push(renderer.render(d)?);
31    }
32    if self.sorted {
33      diagnostic_strings.sort_unstable();
34    }
35    if self.colored {
36      let mut writer = Buffer::ansi();
37      for s in diagnostic_strings {
38        writer.write_all(s.as_bytes())?;
39        writer.reset()?;
40      }
41      return Ok(String::from_utf8(writer.into_inner())?);
42    }
43    Ok(diagnostic_strings.join(""))
44  }
45
46  fn emit_diagnostic(&self, diagnostic: &Diagnostic) -> Self::Output {
47    self.emit_batch_diagnostic(std::iter::once(diagnostic))
48  }
49}