docsrs_cli/i18n/mod.rs
1//! Human-facing messages for stderr prose (`en` / `pt-BR`).
2//!
3//! # Product contract (agent-first)
4//!
5//! - **Stdout** (JSON envelopes, markdown data): always English technical content.
6//! Agents parse `error.message` as stable English; never localize JSON fields.
7//! - **Stderr** human path (`--format text|markdown`, progress, doctor prose):
8//! localized via [`Locale`] after resolution at process start.
9//! - **Technical logs** (`tracing`): English only.
10//!
11//! # Resolution precedence
12//!
13//! 1. Explicit CLI `--lang` / config `lang` (fail-closed)
14//! 2. OS locale via [`sys_locale::get_locale`] (soft-fallback)
15//! 3. Default `en`
16//!
17//! Explicit tags accept only `en` / `en-*` and exact `pt-BR` (after BCP47-ish
18//! normalization). Bare `pt` and regional Portuguese other than `pt-BR` fail
19//! closed (exit 65). Soft system detection maps any `pt` primary language to
20//! Brazilian Portuguese messages (MVP has no `pt-PT` bundle).
21//!
22//! # What step 2 actually reads
23//!
24//! [`sys_locale::get_locale`] consults the host's locale, which on Unix means
25//! `LC_ALL`, `LC_MESSAGES` and `LANG`. So `LANG=pt_BR.UTF-8` does change stderr
26//! prose when no explicit tag is given — state it plainly rather than claim the
27//! process never touches the environment, because the read is real and merely
28//! delegated to a dependency where the policy gate cannot see it.
29//!
30//! This belongs to the same category as `NO_COLOR` and `TERM` in
31//! [`crate::platform`]: it describes the *user's environment*, the way `isatty`
32//! does, and carries no product configuration. The distinction that matters is
33//! the one this module already enforces — **no product knob** comes from the
34//! environment, and stdout stays English byte for byte whatever `LANG` says.
35//! An explicit `--lang` or the TOML `lang` key always outranks the host.
36//!
37//! # Out of scope (OOS) for this one-shot CLI
38//!
39//! Full Rules Rust i18n stacks are **not** product requirements here:
40//!
41//! - `fluent` / `fluent-langneg` / `i18n-embed` resource bundles
42//! - `unic-langid` (two fixed locales; lightweight normalize is enough)
43//! - Top-20 languages, Cargo `i18n-*` features, RTL/CJK/ICU calendars
44//! - Global `OnceLock` (locale is threaded as a value for testability)
45//! - Admin reload of language, Weblate/Crowdin pipelines
46//! - Windows console UTF-8 code-page bootstrap (no Windows-only deps)
47//! - Translating clap `--help` / about strings
48//!
49//! Keep this module the single place for human stderr copy.
50
51#[cfg(test)]
52mod tests;
53
54use crate::error::{AppError, AppResult, ErrorDetail};
55
56/// Resolved UI locale for stderr prose.
57///
58/// Not `#[non_exhaustive]`: only `en` and `pt-BR` ship in the MVP binary and
59/// exhaustive matches in this crate are intentional.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub enum Locale {
62 /// English human messages.
63 En,
64 /// Brazilian Portuguese human messages.
65 PtBr,
66}
67
68impl Locale {
69 /// Stable BCP 47 tag for diagnostics (`en` or `pt-BR`).
70 pub fn as_bcp47(self) -> &'static str {
71 match self {
72 Self::En => "en",
73 Self::PtBr => "pt-BR",
74 }
75 }
76
77 /// Resolve locale with fail-closed explicit tags and soft system fallback.
78 ///
79 /// Precedence: `explicit` (CLI/config) → system locale → `en`.
80 /// Explicit tags that are not `en` / `pt-BR` (and `en-*` variants)
81 /// return `InvalidInput` (exit 65). Unknown system locales soft-fallback to English.
82 ///
83 /// No product **knob** comes from the environment. The host locale does
84 /// reach step 2 through `sys_locale` (`LC_ALL` / `LC_MESSAGES` / `LANG` on
85 /// Unix); it steers stderr prose only, never a setting, and never stdout.
86 ///
87 /// # Errors
88 ///
89 /// Returns [`crate::error::ErrorKind::InvalidInput`] when an explicit tag is unsupported.
90 pub fn resolve(explicit: Option<&str>) -> AppResult<Self> {
91 if let Some(tag) = explicit {
92 return Self::parse_supported(tag);
93 }
94 Ok(Self::from_system())
95 }
96
97 /// Parse an explicit lang tag. Fail-closed.
98 ///
99 /// Accepted after normalization:
100 /// - `en`, `en-US`, `en_GB`, `en.UTF-8`, …
101 /// - `pt-BR`, `pt_BR`, `pt-br`, `pt_BR.UTF-8` (region **must** be BR)
102 ///
103 /// Rejected: bare `pt`, `pt-PT`, `fr`, empty, unknown tags.
104 ///
105 /// # Errors
106 ///
107 /// Returns [`crate::error::ErrorKind::InvalidInput`] when `tag` is empty or unsupported.
108 pub fn parse_supported(tag: &str) -> AppResult<Self> {
109 let t = normalize_lang_tag(tag);
110 if t.is_empty() {
111 return Err(AppError::of(ErrorDetail::UnsupportedLang {
112 tag: String::new(),
113 }));
114 }
115 if t == "en" || t.starts_with("en-") {
116 return Ok(Self::En);
117 }
118 // Explicit path requires region BR — bare `pt` / `pt-PT` are not MVP locales.
119 if t == "pt-br" {
120 return Ok(Self::PtBr);
121 }
122 Err(AppError::of(ErrorDetail::UnsupportedLang {
123 tag: tag.to_string(),
124 }))
125 }
126
127 /// Policy test helper: env must never win over system when no explicit tag.
128 ///
129 /// # Errors
130 ///
131 /// Propagates [`crate::error::ErrorKind::InvalidInput`] from [`Locale::resolve`]. With no
132 /// explicit tag the resolver takes the soft system path, so this helper
133 /// returns `Ok` in practice; the signature mirrors the product resolver.
134 #[cfg(test)]
135 pub fn resolve_ignores_product_env_for_tests() -> AppResult<Self> {
136 // Call the public resolver with no explicit tag — same path as product.
137 Self::resolve(None)
138 }
139
140 /// Soft-detect from OS locale (unknown tags → English).
141 ///
142 /// Called after tracing init in the binary path. Logs when the OS returns
143 /// no locale so detection failure is visible under `-v`.
144 pub fn from_system() -> Self {
145 match sys_locale::get_locale() {
146 Some(sys) => {
147 let loc = Self::soft_from_tag(&sys);
148 tracing::debug!(
149 target: "docsrs_cli::i18n",
150 system_locale = %sys,
151 resolved = %loc.as_bcp47(),
152 "locale resolved from system"
153 );
154 loc
155 }
156 None => {
157 tracing::debug!(
158 target: "docsrs_cli::i18n",
159 "sys-locale returned None; defaulting to en"
160 );
161 Self::En
162 }
163 }
164 }
165
166 /// Soft map a system/BCP47-ish tag (never errors).
167 ///
168 /// Any primary language `pt` (including `pt`, `pt-PT`, `pt_BR.UTF-8`) maps
169 /// to [`Locale::PtBr`] for the MVP bilingual bundle.
170 pub fn soft_from_tag(tag: &str) -> Self {
171 let t = normalize_lang_tag(tag);
172 if t == "pt" || t.starts_with("pt-") {
173 Self::PtBr
174 } else {
175 Self::En
176 }
177 }
178
179 /// Progress line after the 2s threshold.
180 pub fn progress_fetching(self, target: &str) -> String {
181 match self {
182 Self::En => format!("fetching {target}..."),
183 Self::PtBr => format!("buscando {target}..."),
184 }
185 }
186
187 /// Prefix for human stderr errors.
188 pub fn error_prefix(self) -> &'static str {
189 match self {
190 Self::En => "error",
191 Self::PtBr => "erro",
192 }
193 }
194
195 /// Prefix and render an [`AppError`] for human stderr.
196 ///
197 /// The message comes from the typed catalogue via [`AppError::localized`],
198 /// so pt-BR coverage is enforced by the compiler. This replaced a
199 /// `starts_with` matcher over English prose whose fallback returned English
200 /// unchanged: a new message was untranslatable *and* indistinguishable from
201 /// a translated one.
202 pub fn format_error(self, err: &AppError) -> String {
203 format!("{}: {}", self.error_prefix(), err.localized(self))
204 }
205
206 /// Doctor summary line.
207 pub fn doctor_ok(self, ok: bool) -> String {
208 match (self, ok) {
209 (Self::En, true) => "doctor: ok".into(),
210 (Self::En, false) => "doctor: failed".into(),
211 (Self::PtBr, true) => "doctor: ok".into(),
212 (Self::PtBr, false) => "doctor: falhou".into(),
213 }
214 }
215
216 /// Locale for messages emitted **before** argv is parsed.
217 ///
218 /// The binary entrypoint reports two failures that happen during bootstrap:
219 /// a duplicate rustls `CryptoProvider` and a runtime that will not build.
220 /// Both precede `clap`, so neither [`Locale::resolve`] nor the XDG config is
221 /// available — reading `config.toml` there would put disk I/O ahead of TLS
222 /// setup and invert the bootstrap order fixed by ADR 0007.
223 ///
224 /// So this scans argv directly for `--lang <tag>` / `--lang=<tag>`: no disk,
225 /// no environment variable, one linear pass. It uses
226 /// [`Locale::soft_from_tag`] rather than [`Locale::parse_supported`] on
227 /// purpose — a malformed tag must not turn a bootstrap failure into a second,
228 /// unrelated error. Absent or unknown tags fall back to English, matching
229 /// what the normal path would print before the system locale is consulted.
230 ///
231 /// This is the **only** sanctioned pre-argv message path in the product.
232 pub fn from_argv_for_bootstrap<I, T>(args: I) -> Self
233 where
234 I: IntoIterator<Item = T>,
235 T: AsRef<std::ffi::OsStr>,
236 {
237 const FLAG: &str = "--lang";
238 let mut want_value = false;
239 for arg in args {
240 // Non-UTF-8 argv cannot hold a locale tag; skip without allocating.
241 let Some(a) = arg.as_ref().to_str() else {
242 want_value = false;
243 continue;
244 };
245 if want_value {
246 return Self::soft_from_tag(a);
247 }
248 if let Some(tag) = a.strip_prefix("--lang=") {
249 return Self::soft_from_tag(tag);
250 }
251 if a == FLAG {
252 want_value = true;
253 }
254 }
255 Self::En
256 }
257
258 /// Bootstrap failure: a rustls `CryptoProvider` was already installed.
259 pub fn bootstrap_provider_conflict(self) -> &'static str {
260 match self {
261 Self::En => {
262 "docsrs-cli: rustls CryptoProvider was already installed; refusing dual init"
263 }
264 Self::PtBr => {
265 "docsrs-cli: o CryptoProvider do rustls já estava instalado; recusando init duplo"
266 }
267 }
268 }
269
270 /// Bootstrap failure: the async runtime could not be built.
271 pub fn bootstrap_runtime_failure(self, detail: &str) -> String {
272 match self {
273 Self::En => format!("docsrs-cli: failed to build async runtime: {detail}"),
274 Self::PtBr => format!("docsrs-cli: falha ao construir o runtime assíncrono: {detail}"),
275 }
276 }
277}
278
279/// Normalize a locale tag for comparison (BCP47-ish, no full unic-langid).
280///
281/// - trim whitespace
282/// - drop encoding / modifier suffixes (`.UTF-8`, `@euro`)
283/// - `_` → `-`
284/// - lowercase
285fn normalize_lang_tag(tag: &str) -> String {
286 let trimmed = tag.trim();
287 let base = trimmed.split(['.', '@']).next().unwrap_or(trimmed).trim();
288 base.replace('_', "-").to_ascii_lowercase()
289}