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