1use crate::error::{AppError, AppResult, ErrorKind};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum Locale {
45 En,
47 PtBr,
49}
50
51impl Locale {
52 pub fn as_bcp47(self) -> &'static str {
54 match self {
55 Self::En => "en",
56 Self::PtBr => "pt-BR",
57 }
58 }
59
60 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 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 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 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 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 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 pub fn error_prefix(self) -> &'static str {
163 match self {
164 Self::En => "error",
165 Self::PtBr => "erro",
166 }
167 }
168
169 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 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
191fn normalize_lang_tag(tag: &str) -> String {
198 let trimmed = tag.trim();
199 let base = trimmed
200 .split(['.', '@'])
201 .next()
202 .unwrap_or(trimmed)
203 .trim();
204 base.replace('_', "-").to_ascii_lowercase()
205}
206
207fn translate_error_pt_br(technical_en: &str) -> String {
211 if technical_en.starts_with("unsupported lang") {
213 return technical_en
214 .replace("unsupported lang", "idioma não suportado")
215 .replace("expected en or pt-BR", "esperado en ou pt-BR");
216 }
217 if technical_en.starts_with("crate name is empty") {
218 return "nome da crate está vazio".into();
219 }
220 if technical_en.starts_with("crate name exceeds") {
221 return technical_en.replace("crate name exceeds", "nome da crate excede");
222 }
223 if technical_en.starts_with("invalid crate name") {
224 return technical_en.replace("invalid crate name", "nome de crate inválido");
225 }
226 if technical_en.starts_with("search query is empty") {
227 return "consulta de busca está vazia".into();
228 }
229 if technical_en.starts_with("query exceeds") {
230 return technical_en.replace("query exceeds", "consulta excede");
231 }
232 if technical_en.starts_with("item path is empty") {
233 return "caminho do item está vazio".into();
234 }
235 if technical_en.starts_with("item path exceeds") {
236 return technical_en.replace("item path exceeds", "caminho do item excede");
237 }
238 if technical_en.starts_with("item path missing item name") {
239 return "caminho do item sem nome do item".into();
240 }
241 if technical_en.starts_with("invalid item path segment") {
242 return technical_en.replace("invalid item path segment", "segmento de caminho de item inválido");
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("interrupted by SIGINT") {
272 return "interrompido por SIGINT".into();
273 }
274 if technical_en.starts_with("terminated by SIGTERM") {
275 return "encerrado por SIGTERM".into();
276 }
277 if technical_en.starts_with("broken pipe") {
278 return "pipe quebrado ao escrever em stdout".into();
279 }
280 if technical_en.starts_with("host not allowlisted") {
281 return technical_en.replace("host not allowlisted", "host fora da allowlist");
282 }
283 if technical_en.starts_with("redirect host not allowlisted") {
284 return technical_en.replace(
285 "redirect host not allowlisted",
286 "host de redirecionamento fora da allowlist",
287 );
288 }
289 if technical_en.starts_with("cannot combine --json") {
290 return "não é possível combinar --json com --format text ou --format markdown".into();
291 }
292 if technical_en.starts_with("unknown schema command") {
293 return technical_en.replace("unknown schema command", "comando de schema desconhecido");
294 }
295 if technical_en.starts_with("bad request from remote") {
296 return technical_en.replace("bad request from remote", "requisição inválida do remoto");
297 }
298 if technical_en.starts_with("remote unavailable") {
299 return technical_en.replace("remote unavailable", "remoto indisponível");
300 }
301 if technical_en.starts_with("unexpected HTTP status") {
302 return technical_en.replace("unexpected HTTP status", "status HTTP inesperado");
303 }
304 if technical_en.starts_with("response body exceeds") {
305 return technical_en.replace("response body exceeds", "corpo da resposta excede");
306 }
307 if technical_en.starts_with("response body is not valid UTF-8") {
308 return "corpo da resposta não é UTF-8 válido".into();
309 }
310 technical_en.to_string()
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
319 fn normalize_strips_encoding_and_underscore() {
320 assert_eq!(normalize_lang_tag("pt_BR.UTF-8"), "pt-br");
321 assert_eq!(normalize_lang_tag("en-US"), "en-us");
322 assert_eq!(normalize_lang_tag(" PT-br@euro "), "pt-br");
323 }
324
325 #[test]
326 fn parse_supported_en_pt_br() {
327 assert_eq!(Locale::parse_supported("pt-BR").unwrap(), Locale::PtBr);
328 assert_eq!(Locale::parse_supported("pt_BR").unwrap(), Locale::PtBr);
329 assert_eq!(Locale::parse_supported("pt_BR.UTF-8").unwrap(), Locale::PtBr);
330 assert_eq!(Locale::parse_supported("en-US").unwrap(), Locale::En);
331 assert_eq!(Locale::parse_supported("en").unwrap(), Locale::En);
332 assert_eq!(Locale::parse_supported("en.UTF-8").unwrap(), Locale::En);
333 }
334
335 #[test]
336 fn parse_supported_fail_closed() {
337 assert!(Locale::parse_supported("pt").is_err());
339 assert!(Locale::parse_supported("pt-PT").is_err());
340 assert!(Locale::parse_supported("fr").is_err());
341 assert!(Locale::parse_supported("xx").is_err());
342 assert!(Locale::parse_supported("").is_err());
343 assert!(Locale::parse_supported(" ").is_err());
344 let err = Locale::parse_supported("de").unwrap_err();
345 assert_eq!(err.kind(), ErrorKind::InvalidInput);
346 assert!(err.message().contains("unsupported lang"));
347 }
348
349 #[test]
350 fn soft_system_maps_any_portuguese() {
351 assert_eq!(Locale::soft_from_tag("de-DE"), Locale::En);
352 assert_eq!(Locale::soft_from_tag("pt-BR"), Locale::PtBr);
353 assert_eq!(Locale::soft_from_tag("pt"), Locale::PtBr);
354 assert_eq!(Locale::soft_from_tag("pt-PT"), Locale::PtBr);
355 assert_eq!(Locale::soft_from_tag("pt_BR.UTF-8"), Locale::PtBr);
356 assert_eq!(Locale::soft_from_tag("C"), Locale::En);
357 assert_eq!(Locale::soft_from_tag("C.UTF-8"), Locale::En);
358 }
359
360 #[test]
361 fn as_bcp47_stable() {
362 assert_eq!(Locale::En.as_bcp47(), "en");
363 assert_eq!(Locale::PtBr.as_bcp47(), "pt-BR");
364 }
365
366 #[test]
367 fn progress_localized() {
368 assert!(Locale::En.progress_fetching("x").contains("fetching"));
369 assert!(Locale::PtBr.progress_fetching("x").contains("buscando"));
370 }
371
372 #[test]
373 fn error_and_doctor_lines() {
374 assert!(Locale::En.format_error("boom").starts_with("error:"));
375 assert!(Locale::PtBr.format_error("boom").starts_with("erro:"));
376 let pt = Locale::PtBr.format_error("crate name is empty");
377 assert!(pt.contains("nome da crate está vazio"), "{pt}");
378 let pt2 = Locale::PtBr.format_error("interrupted by SIGINT");
379 assert!(pt2.contains("interrompido por SIGINT"), "{pt2}");
380 let pt3 = Locale::PtBr.format_error("invalid version 'v1'");
381 assert!(pt3.contains("versão inválida"), "{pt3}");
382 assert_eq!(Locale::En.doctor_ok(true), "doctor: ok");
383 assert_eq!(Locale::PtBr.doctor_ok(false), "doctor: falhou");
384 assert_eq!(Locale::resolve(Some("pt-BR")).unwrap(), Locale::PtBr);
385 assert_eq!(Locale::resolve(Some("en")).unwrap(), Locale::En);
386 assert!(Locale::resolve(Some("ja")).is_err());
387 assert!(Locale::resolve(Some("pt")).is_err());
388 }
389}