1use crate::error::{AppError, AppResult, ErrorKind};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum Locale {
44 En,
46 PtBr,
48}
49
50impl Locale {
51 pub fn as_bcp47(self) -> &'static str {
53 match self {
54 Self::En => "en",
55 Self::PtBr => "pt-BR",
56 }
57 }
58
59 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 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 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 #[cfg(test)]
110 pub fn resolve_ignores_product_env_for_tests() -> AppResult<Self> {
111 Self::resolve(None)
113 }
114
115 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 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 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 pub fn error_prefix(self) -> &'static str {
164 match self {
165 Self::En => "error",
166 Self::PtBr => "erro",
167 }
168 }
169
170 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 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
192fn 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
204fn translate_error_pt_br(technical_en: &str) -> String {
208 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 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 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}