Skip to main content

docsrs_cli/
i18n.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//! # Out of scope (OOS) for this one-shot CLI
23//!
24//! Full Rules Rust i18n stacks are **not** product requirements here:
25//!
26//! - `fluent` / `fluent-langneg` / `i18n-embed` resource bundles
27//! - `unic-langid` (two fixed locales; lightweight normalize is enough)
28//! - Top-20 languages, Cargo `i18n-*` features, RTL/CJK/ICU calendars
29//! - Global `OnceLock` (locale is threaded as a value for testability)
30//! - Admin reload of language, Weblate/Crowdin pipelines
31//! - Windows console UTF-8 code-page bootstrap (no Windows-only deps)
32//! - Translating clap `--help` / about strings
33//!
34//! Keep this module the single place for human stderr copy.
35
36use crate::error::{AppError, AppResult, ErrorKind};
37
38/// Resolved UI locale for stderr prose.
39///
40/// Not `#[non_exhaustive]`: only `en` and `pt-BR` ship in the MVP binary and
41/// exhaustive matches in this crate are intentional.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum Locale {
44    /// English human messages.
45    En,
46    /// Brazilian Portuguese human messages.
47    PtBr,
48}
49
50impl Locale {
51    /// Stable BCP 47 tag for diagnostics (`en` or `pt-BR`).
52    pub fn as_bcp47(self) -> &'static str {
53        match self {
54            Self::En => "en",
55            Self::PtBr => "pt-BR",
56        }
57    }
58
59    /// Resolve locale with fail-closed explicit tags and soft system fallback.
60    ///
61    /// Precedence: `explicit` (CLI/config) → system locale → `en`.
62    /// Explicit tags that are not `en` / `pt-BR` (and `en-*` variants)
63    /// return `InvalidInput` (exit 65). Unknown system locales soft-fallback to English.
64    /// Product never reads locale from environment variables.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`ErrorKind::InvalidInput`] when an explicit tag is unsupported.
69    pub fn resolve(explicit: Option<&str>) -> AppResult<Self> {
70        if let Some(tag) = explicit {
71            return Self::parse_supported(tag);
72        }
73        Ok(Self::from_system())
74    }
75
76    /// Parse an explicit lang tag. Fail-closed.
77    ///
78    /// Accepted after normalization:
79    /// - `en`, `en-US`, `en_GB`, `en.UTF-8`, …
80    /// - `pt-BR`, `pt_BR`, `pt-br`, `pt_BR.UTF-8` (region **must** be BR)
81    ///
82    /// Rejected: bare `pt`, `pt-PT`, `fr`, empty, unknown tags.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`ErrorKind::InvalidInput`] when `tag` is empty or unsupported.
87    pub fn parse_supported(tag: &str) -> AppResult<Self> {
88        let t = normalize_lang_tag(tag);
89        if t.is_empty() {
90            return Err(AppError::new(
91                ErrorKind::InvalidInput,
92                "unsupported lang ''; expected en or pt-BR",
93            ));
94        }
95        if t == "en" || t.starts_with("en-") {
96            return Ok(Self::En);
97        }
98        // Explicit path requires region BR — bare `pt` / `pt-PT` are not MVP locales.
99        if t == "pt-br" {
100            return Ok(Self::PtBr);
101        }
102        Err(AppError::new(
103            ErrorKind::InvalidInput,
104            format!("unsupported lang '{tag}'; expected en or pt-BR"),
105        ))
106    }
107
108    /// Policy test helper: env must never win over system when no explicit tag.
109    #[cfg(test)]
110    pub fn resolve_ignores_product_env_for_tests() -> AppResult<Self> {
111        // Call the public resolver with no explicit tag — same path as product.
112        Self::resolve(None)
113    }
114
115    /// Soft-detect from OS locale (unknown tags → English).
116    ///
117    /// Called after tracing init in the binary path. Logs when the OS returns
118    /// no locale so detection failure is visible under `-v` / `RUST_LOG`.
119    pub fn from_system() -> Self {
120        match sys_locale::get_locale() {
121            Some(sys) => {
122                let loc = Self::soft_from_tag(&sys);
123                tracing::debug!(
124                    target: "docsrs_cli::i18n",
125                    system_locale = %sys,
126                    resolved = %loc.as_bcp47(),
127                    "locale resolved from system"
128                );
129                loc
130            }
131            None => {
132                tracing::debug!(
133                    target: "docsrs_cli::i18n",
134                    "sys-locale returned None; defaulting to en"
135                );
136                Self::En
137            }
138        }
139    }
140
141    /// Soft map a system/BCP47-ish tag (never errors).
142    ///
143    /// Any primary language `pt` (including `pt`, `pt-PT`, `pt_BR.UTF-8`) maps
144    /// to [`Locale::PtBr`] for the MVP bilingual bundle.
145    pub fn soft_from_tag(tag: &str) -> Self {
146        let t = normalize_lang_tag(tag);
147        if t == "pt" || t.starts_with("pt-") {
148            Self::PtBr
149        } else {
150            Self::En
151        }
152    }
153
154    /// Progress line after the 2s threshold.
155    pub fn progress_fetching(self, target: &str) -> String {
156        match self {
157            Self::En => format!("fetching {target}..."),
158            Self::PtBr => format!("buscando {target}..."),
159        }
160    }
161
162    /// Prefix for human stderr errors.
163    pub fn error_prefix(self) -> &'static str {
164        match self {
165            Self::En => "error",
166            Self::PtBr => "erro",
167        }
168    }
169
170    /// Human-readable stderr line for a technical English message.
171    pub fn format_error(self, technical_en: &str) -> String {
172        match self {
173            Self::En => format!("{}: {technical_en}", self.error_prefix()),
174            Self::PtBr => {
175                let human = translate_error_pt_br(technical_en);
176                format!("{}: {human}", self.error_prefix())
177            }
178        }
179    }
180
181    /// Doctor summary line.
182    pub fn doctor_ok(self, ok: bool) -> String {
183        match (self, ok) {
184            (Self::En, true) => "doctor: ok".into(),
185            (Self::En, false) => "doctor: failed".into(),
186            (Self::PtBr, true) => "doctor: ok".into(),
187            (Self::PtBr, false) => "doctor: falhou".into(),
188        }
189    }
190}
191
192/// Normalize a locale tag for comparison (BCP47-ish, no full unic-langid).
193///
194/// - trim whitespace
195/// - drop encoding / modifier suffixes (`.UTF-8`, `@euro`)
196/// - `_` → `-`
197/// - lowercase
198fn normalize_lang_tag(tag: &str) -> String {
199    let trimmed = tag.trim();
200    let base = trimmed.split(['.', '@']).next().unwrap_or(trimmed).trim();
201    base.replace('_', "-").to_ascii_lowercase()
202}
203
204/// Best-effort human translation for common English error messages (stderr only).
205///
206/// Technical JSON envelopes always keep the English `message` field.
207fn translate_error_pt_br(technical_en: &str) -> String {
208    // Prefer exact / prefix matches for product messages.
209    if technical_en.starts_with("unsupported lang") {
210        return technical_en
211            .replace("unsupported lang", "idioma não suportado")
212            .replace("expected en or pt-BR", "esperado en ou pt-BR");
213    }
214    if technical_en.starts_with("crate name is empty") {
215        return "nome da crate está vazio".into();
216    }
217    if technical_en.starts_with("crate name exceeds") {
218        return technical_en.replace("crate name exceeds", "nome da crate excede");
219    }
220    if technical_en.starts_with("invalid crate name") {
221        return technical_en.replace("invalid crate name", "nome de crate inválido");
222    }
223    if technical_en.starts_with("search query is empty") {
224        return "consulta de busca está vazia".into();
225    }
226    if technical_en.starts_with("query exceeds") {
227        return technical_en.replace("query exceeds", "consulta excede");
228    }
229    if technical_en.starts_with("item path is empty") {
230        return "caminho do item está vazio".into();
231    }
232    if technical_en.starts_with("item path exceeds") {
233        return technical_en.replace("item path exceeds", "caminho do item excede");
234    }
235    if technical_en.starts_with("item path missing item name") {
236        return "caminho do item sem nome do item".into();
237    }
238    if technical_en.starts_with("invalid item path segment") {
239        return technical_en.replace(
240            "invalid item path segment",
241            "segmento de caminho de item inválido",
242        );
243    }
244    if technical_en.starts_with("item path segment contains whitespace") {
245        return technical_en.replace(
246            "item path segment contains whitespace",
247            "segmento de caminho de item contém espaço em branco",
248        );
249    }
250    if technical_en.starts_with("version exceeds") {
251        return technical_en.replace("version exceeds", "versão excede");
252    }
253    if technical_en.starts_with("invalid version") {
254        return technical_en.replace("invalid version", "versão inválida");
255    }
256    if technical_en.starts_with("unknown item type") {
257        return technical_en.replace("unknown item type", "tipo de item desconhecido");
258    }
259    if technical_en.contains("not found") || technical_en.contains("Not Found") {
260        return technical_en
261            .replace("not found", "não encontrado")
262            .replace("Not Found", "Não encontrado")
263            .replace("resource not found", "recurso não encontrado");
264    }
265    if technical_en.starts_with("rate limited") {
266        return technical_en.replace("rate limited by remote", "limitado por taxa no remoto");
267    }
268    if technical_en.starts_with("wall-clock timeout") {
269        return technical_en.replace("wall-clock timeout after", "tempo esgotado após");
270    }
271    if technical_en.starts_with("response body exceeds max_body_bytes") {
272        return technical_en.replace(
273            "response body exceeds max_body_bytes",
274            "corpo da resposta excede max_body_bytes",
275        );
276    }
277    if technical_en.starts_with("timeout must be >=") {
278        return technical_en
279            .replace(
280                "timeout must be >= 1 second (got 0)",
281                "timeout deve ser >= 1 segundo (recebido 0)",
282            )
283            .replace("timeout must be >=", "timeout deve ser >=");
284    }
285    if technical_en.starts_with("connect_timeout must be >=") {
286        return technical_en.replace(
287            "connect_timeout must be >= 1 second (got 0)",
288            "connect_timeout deve ser >= 1 segundo (recebido 0)",
289        );
290    }
291    if technical_en.starts_with("interrupted by SIGINT") {
292        return "interrompido por SIGINT".into();
293    }
294    if technical_en.starts_with("terminated by SIGTERM") {
295        return "encerrado por SIGTERM".into();
296    }
297    if technical_en.starts_with("broken pipe") {
298        return "pipe quebrado ao escrever em stdout".into();
299    }
300    if technical_en.starts_with("host not allowlisted") {
301        return technical_en.replace("host not allowlisted", "host fora da allowlist");
302    }
303    if technical_en.starts_with("redirect host not allowlisted") {
304        return technical_en.replace(
305            "redirect host not allowlisted",
306            "host de redirecionamento fora da allowlist",
307        );
308    }
309    if technical_en.starts_with("cannot combine --json") {
310        return "não é possível combinar --json com --format text ou --format markdown".into();
311    }
312    if technical_en.starts_with("unknown schema command") {
313        return technical_en.replace("unknown schema command", "comando de schema desconhecido");
314    }
315    if technical_en.starts_with("bad request from remote") {
316        return technical_en.replace("bad request from remote", "requisição inválida do remoto");
317    }
318    if technical_en.starts_with("remote unavailable") {
319        return technical_en.replace("remote unavailable", "remoto indisponível");
320    }
321    if technical_en.starts_with("unexpected HTTP status") {
322        return technical_en.replace("unexpected HTTP status", "status HTTP inesperado");
323    }
324    if technical_en.starts_with("response body exceeds") {
325        return technical_en.replace("response body exceeds", "corpo da resposta excede");
326    }
327    if technical_en.starts_with("response body is not valid UTF-8") {
328        return "corpo da resposta não é UTF-8 válido".into();
329    }
330    // Fallback: keep English body with localized prefix only.
331    technical_en.to_string()
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn normalize_strips_encoding_and_underscore() {
340        assert_eq!(normalize_lang_tag("pt_BR.UTF-8"), "pt-br");
341        assert_eq!(normalize_lang_tag("en-US"), "en-us");
342        assert_eq!(normalize_lang_tag("  PT-br@euro  "), "pt-br");
343    }
344
345    #[test]
346    fn parse_supported_en_pt_br() {
347        assert_eq!(Locale::parse_supported("pt-BR").unwrap(), Locale::PtBr);
348        assert_eq!(Locale::parse_supported("pt_BR").unwrap(), Locale::PtBr);
349        assert_eq!(
350            Locale::parse_supported("pt_BR.UTF-8").unwrap(),
351            Locale::PtBr
352        );
353        assert_eq!(Locale::parse_supported("en-US").unwrap(), Locale::En);
354        assert_eq!(Locale::parse_supported("en").unwrap(), Locale::En);
355        assert_eq!(Locale::parse_supported("en.UTF-8").unwrap(), Locale::En);
356    }
357
358    #[test]
359    fn parse_supported_fail_closed() {
360        // Bare `pt` and other regions are not explicit MVP tags.
361        assert!(Locale::parse_supported("pt").is_err());
362        assert!(Locale::parse_supported("pt-PT").is_err());
363        assert!(Locale::parse_supported("fr").is_err());
364        assert!(Locale::parse_supported("xx").is_err());
365        assert!(Locale::parse_supported("").is_err());
366        assert!(Locale::parse_supported("  ").is_err());
367        let err = Locale::parse_supported("de").unwrap_err();
368        assert_eq!(err.kind(), ErrorKind::InvalidInput);
369        assert!(err.message().contains("unsupported lang"));
370    }
371
372    #[test]
373    fn soft_system_maps_any_portuguese() {
374        assert_eq!(Locale::soft_from_tag("de-DE"), Locale::En);
375        assert_eq!(Locale::soft_from_tag("pt-BR"), Locale::PtBr);
376        assert_eq!(Locale::soft_from_tag("pt"), Locale::PtBr);
377        assert_eq!(Locale::soft_from_tag("pt-PT"), Locale::PtBr);
378        assert_eq!(Locale::soft_from_tag("pt_BR.UTF-8"), Locale::PtBr);
379        assert_eq!(Locale::soft_from_tag("C"), Locale::En);
380        assert_eq!(Locale::soft_from_tag("C.UTF-8"), Locale::En);
381    }
382
383    #[test]
384    fn as_bcp47_stable() {
385        assert_eq!(Locale::En.as_bcp47(), "en");
386        assert_eq!(Locale::PtBr.as_bcp47(), "pt-BR");
387    }
388
389    #[test]
390    fn progress_localized() {
391        assert!(Locale::En.progress_fetching("x").contains("fetching"));
392        assert!(Locale::PtBr.progress_fetching("x").contains("buscando"));
393    }
394
395    #[test]
396    fn error_and_doctor_lines() {
397        assert!(Locale::En.format_error("boom").starts_with("error:"));
398        assert!(Locale::PtBr.format_error("boom").starts_with("erro:"));
399        let pt = Locale::PtBr.format_error("crate name is empty");
400        assert!(pt.contains("nome da crate está vazio"), "{pt}");
401        let pt2 = Locale::PtBr.format_error("interrupted by SIGINT");
402        assert!(pt2.contains("interrompido por SIGINT"), "{pt2}");
403        let pt3 = Locale::PtBr.format_error("invalid version 'v1'");
404        assert!(pt3.contains("versão inválida"), "{pt3}");
405        assert_eq!(Locale::En.doctor_ok(true), "doctor: ok");
406        assert_eq!(Locale::PtBr.doctor_ok(false), "doctor: falhou");
407        assert_eq!(Locale::resolve(Some("pt-BR")).unwrap(), Locale::PtBr);
408        assert_eq!(Locale::resolve(Some("en")).unwrap(), Locale::En);
409        assert!(Locale::resolve(Some("ja")).is_err());
410        assert!(Locale::resolve(Some("pt")).is_err());
411    }
412}