use std::sync::{PoisonError, RwLock};
use super::format::{Fault, Raise};
#[cfg(feature = "yaml")]
use super::limits::REPO_FILE;
pub trait Messages: Sync {
fn message(&self, fault: &Fault) -> String;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct EnglishMessages;
impl Messages for EnglishMessages {
fn message(&self, fault: &Fault) -> String {
match fault {
Fault::Syntax { detail } | Fault::InvalidValue { detail } => detail.clone(),
Fault::DuplicateKey { key } => format!("duplicate key `{key}`"),
Fault::MergeKey => "merge key `<<` is not allowed".to_owned(),
Fault::ExpectedKind { expected, found } => {
format!("expected {expected}, found {found}")
}
Fault::UnknownField { field, expected } => {
format!("unknown field `{field}`{}", choices(expected, "fields"))
}
Fault::UnknownVariant { variant, expected } => {
format!(
"unknown variant `{variant}`{}",
choices(expected, "variants")
)
}
Fault::MissingField { field } => format!("missing field `{field}`"),
Fault::Limit { name, value, raise } => exceeds(name, value, *raise),
Fault::TooLarge {
bytes,
limit,
raise,
} => format!(
"is {bytes} bytes, which {}",
exceeds("max_reader_input_bytes", &limit.to_string(), *raise)
),
}
}
}
fn exceeds(name: &str, value: &str, raise: Raise) -> String {
match raise {
#[cfg(feature = "yaml")]
Raise::InRepository => {
format!("exceeds {name} ({value}); raise limits.{name} in {REPO_FILE}")
}
#[cfg(feature = "yaml")]
Raise::InProcess => format!(
"exceeds {name} ({value}); raise {name} in the tool's process default, which reads {REPO_FILE}"
),
#[cfg(not(feature = "yaml"))]
Raise::InTool => format!("exceeds {name} ({value}); the tool sets this limit"),
}
}
pub(crate) fn printable(text: &str) -> String {
let mut shown = String::with_capacity(text.len());
for character in text.chars() {
if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
shown.extend(character.escape_debug());
} else {
shown.push(character);
}
}
shown
}
fn choices(expected: &[&str], plural: &str) -> String {
if expected.is_empty() {
return format!(", there are no {plural}");
}
let names: Vec<String> = expected.iter().map(|name| format!("`{name}`")).collect();
format!(", expected one of {}", names.join(", "))
}
static PROCESS: RwLock<Option<&'static dyn Messages>> = RwLock::new(None);
pub fn set_messages(messages: &'static dyn Messages) {
*PROCESS.write().unwrap_or_else(PoisonError::into_inner) = Some(messages);
}
pub(crate) fn messages() -> &'static dyn Messages {
PROCESS
.read()
.unwrap_or_else(PoisonError::into_inner)
.unwrap_or(&EnglishMessages)
}