globetrotter 0.0.13

Polyglot, type-safe internationalization
Documentation
//! Concurrent diagnostic rendering backed by a shared source-file registry.

use codespan_reporting::{diagnostic::Diagnostic, files, term};
use std::path::Path;
use std::sync::{Arc, LazyLock};
use tokio::sync::{Mutex, RwLock};

/// Renders diagnostics and tracks the source files their labels refer to.
///
/// Clones share the source registry and serialized stderr writer, so files may
/// be registered and diagnostics emitted safely from concurrent tasks.
#[derive(Clone)]
pub struct Printer {
    writer: Arc<Mutex<term::StylesWriter<'static, term::termcolor::StandardStream>>>,
    diagnostic_config: term::Config,
    files: Arc<RwLock<files::SimpleFiles<String, String>>>,
}

impl Default for Printer {
    fn default() -> Self {
        Self::new(term::termcolor::ColorChoice::Auto)
    }
}

static DEFAULT_STYLES: LazyLock<term::Styles> = LazyLock::new(term::Styles::default);

impl Printer {
    /// Creates a printer that writes to stderr using the given color choice.
    #[must_use]
    pub fn new(color_choice: term::termcolor::ColorChoice) -> Self {
        let writer = term::termcolor::StandardStream::stderr(color_choice);
        let writer = term::StylesWriter::new(writer, &DEFAULT_STYLES);
        let diagnostic_config = term::Config::default();
        Self {
            writer: Arc::new(Mutex::new(writer)),
            diagnostic_config,
            files: Arc::new(RwLock::new(files::SimpleFiles::new())),
        }
    }

    /// Registers a source file and returns the id its diagnostic labels use.
    ///
    /// `name` is the path diagnostics display for the file, so callers pass
    /// the form they want shown, such as a path relative to the project.
    pub async fn add_source_file(&self, name: impl AsRef<Path>, source: String) -> usize {
        let mut files = self.files.write().await;
        files.add(name.as_ref().to_string_lossy().into_owned(), source)
    }

    /// Renders a diagnostic to an ANSI-colored string for printing above a
    /// progress bar (where the normal streaming writer cannot be used directly).
    ///
    /// # Errors
    ///
    /// Returns an error if the diagnostic cannot be formatted.
    pub async fn render(&self, diagnostic: &Diagnostic<usize>) -> Result<String, files::Error> {
        let mut buffer = term::termcolor::Buffer::ansi();
        {
            let mut styled = term::StylesWriter::new(&mut buffer, &DEFAULT_STYLES);
            term::emit_to_write_style(
                &mut styled,
                &self.diagnostic_config,
                &*self.files.read().await,
                diagnostic,
            )?;
        }
        Ok(String::from_utf8_lossy(buffer.as_slice()).into_owned())
    }

    /// Emit a single diagnostic to the configured writer.
    ///
    /// # Errors
    ///
    /// Returns an error if writing the formatted diagnostic to the underlying
    /// output stream fails.
    pub async fn emit(&self, diagnostic: &Diagnostic<usize>) -> Result<(), files::Error> {
        let mut writer = self.writer.lock().await;

        term::emit_to_write_style(
            &mut *writer,
            &self.diagnostic_config,
            &*self.files.read().await,
            diagnostic,
        )
    }
}