puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
//! Errors told the way rustc tells them (Fase 37.3): what is wrong, where (the argument, with `^^^`
//! under the bad part), an `ayuda:` with the fix when there is one and a `nota:` with what is valid.
//!
//! A diagnostic renders to the `String` every error of the CLI already is, so it travels through
//! each `Result<_, String>` unchanged; `main` paints it, on a terminal.
use std::fmt;
use std::ops::Range;

pub struct Diagnostic {
    message: String,
    snippet: Option<(String, Range<usize>)>,
    help: Option<String>,
    notes: Vec<String>,
}

impl Diagnostic {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            snippet: None,
            help: None,
            notes: vec![],
        }
    }

    /// `source` under the message, with `^` under the bytes of `part`; an empty `part` at its end
    /// points just past it (what is missing goes there).
    pub fn at(mut self, source: &str, part: Range<usize>) -> Self {
        self.snippet = Some((source.to_string(), part));
        self
    }

    pub fn help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    pub fn maybe_help(mut self, help: Option<String>) -> Self {
        self.help = help.or(self.help);
        self
    }

    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some((source, part)) = &self.snippet {
            let pad = source[..part.start].chars().count();
            let width = source[part.clone()].chars().count().max(1);
            write!(
                f,
                "\n  --> {source}\n      {}{}",
                " ".repeat(pad),
                "^".repeat(width)
            )?;
        }
        let labelled = self
            .help
            .iter()
            .map(|h| ("ayuda", h))
            .chain(self.notes.iter().map(|n| ("nota", n)));
        for (label, text) in labelled {
            // A long note goes on under its first line, as rustc's do.
            let indent = format!("\n{}", " ".repeat(label.len() + 6));
            write!(f, "\n  = {label}: {}", text.replace('\n', &indent))?;
        }
        Ok(())
    }
}

impl From<Diagnostic> for String {
    fn from(d: Diagnostic) -> Self {
        d.to_string()
    }
}

/// The candidate closest to `typed`, if it is close enough to be what was meant. Damerau, not the
/// Jaro of clap's suggestions: Jaro looks at no neighbour in a word of three letters, and `i46` is
/// `i64` with two swapped.
pub fn similar<'a>(typed: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
    candidates
        .into_iter()
        .map(|c| (strsim::normalized_damerau_levenshtein(typed, c), c))
        .filter(|(score, _)| *score >= 0.6)
        .max_by(|a, b| a.0.total_cmp(&b.0))
        .map(|(_, c)| c)
}

/// `¿querías decir …?`, if there is a similar one.
pub fn did_you_mean<'a>(
    typed: &str,
    candidates: impl IntoIterator<Item = &'a str>,
) -> Option<String> {
    similar(typed, candidates).map(|s| format!("¿querías decir `{s}`?"))
}

/// Whether stderr takes colours: a terminal, and no `NO_COLOR` (https://no-color.org).
pub fn use_color() -> bool {
    use std::io::IsTerminal;
    std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
}

const RED: &str = "\x1b[1;31m";
const YELLOW: &str = "\x1b[1;33m";
const BLUE: &str = "\x1b[1;34m";
const BOLD: &str = "\x1b[1m";
const RESET: &str = "\x1b[0m";

/// `<label>: <text>` (`error`, `aviso`), coloured as rustc colours it when `color`.
pub fn paint(label: &str, text: &str, color: bool) -> String {
    let text = format!("{label}: {text}");
    if !color {
        return text;
    }
    text.lines()
        .map(|line| {
            for (head, colour) in [("error: ", RED), ("aviso: ", YELLOW)] {
                if let Some(rest) = line.strip_prefix(head) {
                    return format!("{colour}{}{RESET}{BOLD} {rest}{RESET}", head.trim_end());
                }
            }
            if let Some(rest) = line.strip_prefix("  --> ") {
                return format!("  {BLUE}-->{RESET} {rest}");
            }
            if line.trim_start().starts_with('^') && line.trim().chars().all(|c| c == '^') {
                return format!("{RED}{line}{RESET}");
            }
            for head in ["ayuda:", "nota:"] {
                if let Some(rest) = line.strip_prefix(&format!("  = {head}")) {
                    return format!("  {BLUE}={RESET} {BOLD}{head}{RESET}{rest}");
                }
            }
            line.to_string()
        })
        .collect::<Vec<_>>()
        .join("\n")
}