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.split(['.', '@']).next().unwrap_or(trimmed).trim();
200 base.replace('_', "-").to_ascii_lowercase()
201}
202
203fn translate_error_pt_br(technical_en: &str) -> String {
207 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 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 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}