ctl_input/messages.rs
1//! The wording of every problem, in one place, and the process default that
2//! replaces it.
3
4use std::sync::{PoisonError, RwLock};
5
6use super::format::{Fault, Raise};
7#[cfg(feature = "yaml")]
8use super::limits::REPO_FILE;
9
10/// The words of every [`Fault`], so a CLI can write them in another language
11/// or another voice.
12///
13/// A fault's variant and span stay the same whatever words it gets. The trait
14/// words a fault and nothing else: the line, the column and the field come
15/// from where the fault is.
16///
17/// ```
18/// # #[cfg(any(feature = "yaml", feature = "toml"))]
19/// # {
20/// use ctl_input::format::Fault;
21/// use ctl_input::{EnglishMessages, Messages};
22///
23/// let fault = Fault::MissingField { field: "port" };
24/// assert_eq!(EnglishMessages.message(&fault), "missing field `port`");
25/// # }
26/// ```
27pub trait Messages: Sync {
28 /// The words for `fault`.
29 fn message(&self, fault: &Fault) -> String;
30}
31
32/// The English wording, which names no parser option.
33#[derive(Clone, Copy, Debug, Default)]
34pub struct EnglishMessages;
35
36impl Messages for EnglishMessages {
37 fn message(&self, fault: &Fault) -> String {
38 match fault {
39 Fault::Syntax { detail } | Fault::InvalidValue { detail } => detail.clone(),
40 Fault::DuplicateKey { key } => format!("duplicate key `{key}`"),
41 Fault::MergeKey => "merge key `<<` is not allowed".to_owned(),
42 Fault::ExpectedKind { expected, found } => {
43 format!("expected {expected}, found {found}")
44 }
45 Fault::UnknownField { field, expected } => {
46 format!("unknown field `{field}`{}", choices(expected, "fields"))
47 }
48 Fault::UnknownVariant { variant, expected } => {
49 format!(
50 "unknown variant `{variant}`{}",
51 choices(expected, "variants")
52 )
53 }
54 Fault::MissingField { field } => format!("missing field `{field}`"),
55 Fault::Limit { name, value, raise } => exceeds(name, value, *raise),
56 Fault::TooLarge {
57 bytes,
58 limit,
59 raise,
60 } => format!(
61 "is {bytes} bytes, which {}",
62 exceeds("max_reader_input_bytes", &limit.to_string(), *raise)
63 ),
64 }
65 }
66}
67
68/// That a text went past the limit `name` of the value `value`, and where a
69/// person raises it.
70fn exceeds(name: &str, value: &str, raise: Raise) -> String {
71 match raise {
72 #[cfg(feature = "yaml")]
73 Raise::InRepository => {
74 format!("exceeds {name} ({value}); raise limits.{name} in {REPO_FILE}")
75 }
76 #[cfg(feature = "yaml")]
77 Raise::InProcess => format!(
78 "exceeds {name} ({value}); raise {name} in the tool's process default, which reads {REPO_FILE}"
79 ),
80 #[cfg(not(feature = "yaml"))]
81 Raise::InTool => format!("exceeds {name} ({value}); the tool sets this limit"),
82 }
83}
84
85/// `text` with each control character escaped as Rust's `escape_debug` does,
86/// so a name or a value a text wrote cannot move a terminal that prints the
87/// problem.
88pub(crate) fn printable(text: &str) -> String {
89 let mut shown = String::with_capacity(text.len());
90 for character in text.chars() {
91 if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
92 shown.extend(character.escape_debug());
93 } else {
94 shown.push(character);
95 }
96 }
97 shown
98}
99
100/// What follows an unknown name: the names that exist, or that there are none.
101fn choices(expected: &[&str], plural: &str) -> String {
102 if expected.is_empty() {
103 return format!(", there are no {plural}");
104 }
105 let names: Vec<String> = expected.iter().map(|name| format!("`{name}`")).collect();
106 format!(", expected one of {}", names.join(", "))
107}
108
109static PROCESS: RwLock<Option<&'static dyn Messages>> = RwLock::new(None);
110
111/// Set the wording the process uses for a [`Refusal`](crate::format::Refusal)'s
112/// text and for every problem an [`Input`](crate::Input) reports. Without a
113/// call, the process uses [`EnglishMessages`].
114///
115/// The wording changes the text and never the fault or where it is. The
116/// wording is global to the process, so this doc-test, which runs in a
117/// process of its own, is the one place that sets it.
118///
119/// ```
120/// # #[cfg(feature = "yaml")]
121/// # {
122/// use ctl_input::format::{Fault, Refusal};
123/// use ctl_input::{EnglishMessages, Input, Limits, Messages, set_messages};
124/// use serde::de::IgnoredAny;
125///
126/// struct Shout;
127///
128/// impl Messages for Shout {
129/// fn message(&self, fault: &Fault) -> String {
130/// EnglishMessages.message(fault).to_uppercase()
131/// }
132/// }
133///
134/// static SHOUT: Shout = Shout;
135///
136/// let refusal = Refusal::new(Fault::MissingField { field: "port" }, Some(3..7), None);
137/// assert_eq!(refusal.to_string(), "missing field `port`");
138/// set_messages(&SHOUT);
139/// assert_eq!(refusal.to_string(), "MISSING FIELD `PORT`");
140/// assert_eq!(refusal.fault(), &Fault::MissingField { field: "port" });
141/// assert_eq!(refusal.span(), Some(3..7));
142///
143/// let limits = Limits {
144/// max_reader_input_bytes: Some(2),
145/// ..Limits::NONE
146/// };
147/// let error = Input::new("a.yaml", "a: 1\n")
148/// .limits(limits)
149/// .parse::<IgnoredAny>()
150/// .unwrap_err();
151/// assert_eq!(
152/// error.to_string(),
153/// "a.yaml: IS 5 BYTES, WHICH EXCEEDS MAX_READER_INPUT_BYTES (2); \
154/// RAISE LIMITS.MAX_READER_INPUT_BYTES IN .CTL/INPUT.YAML"
155/// );
156/// # }
157/// ```
158pub fn set_messages(messages: &'static dyn Messages) {
159 *PROCESS.write().unwrap_or_else(PoisonError::into_inner) = Some(messages);
160}
161
162/// The wording the process uses: what [`set_messages`] installed, or English.
163pub(crate) fn messages() -> &'static dyn Messages {
164 PROCESS
165 .read()
166 .unwrap_or_else(PoisonError::into_inner)
167 .unwrap_or(&EnglishMessages)
168}