Skip to main content

context7_cli/
output.rs

1/// Terminal output formatting.
2///
3/// This is the **only** module allowed to call `println!` or `eprintln!`.
4/// All coloured formatting via the `colored` crate is centralised here.
5/// All user-facing strings are resolved via [`crate::i18n::t`].
6use colored::Colorize;
7
8use crate::api::{DocumentationSnippet, LibrarySearchResult, RespostaDocumentacao};
9use crate::i18n::{idioma_atual, t, Idioma, Mensagem};
10use crate::storage::ChaveArmazenada;
11
12// ─── BIBLIOTECA ───────────────────────────────────────────────────────────────
13
14/// Prints the list of libraries returned by the search endpoint.
15///
16/// Displays index, title bold with trust score inline, library ID (dimmed),
17/// and optional description (italic).
18pub fn exibir_bibliotecas_formatado(resultados: &[LibrarySearchResult]) {
19    if resultados.is_empty() {
20        println!("{}", t(Mensagem::NenhumaBibliotecaEncontrada).yellow());
21        return;
22    }
23
24    println!("{}", t(Mensagem::BibliotecasEncontradas).green().bold());
25    println!("{}", "─".repeat(60).dimmed());
26
27    for (i, lib) in resultados.iter().enumerate() {
28        let numero = format!("{}.", i + 1);
29
30        // Title bold with trust score inline
31        let titulo = if let Some(score) = lib.trust_score {
32            format!(
33                "{} {} ({} {:.1}/10)",
34                numero.cyan(),
35                lib.title.bold(),
36                t(Mensagem::ConfiancaScore),
37                score
38            )
39        } else {
40            format!("{} {}", numero.cyan(), lib.title.bold())
41        };
42        println!("{}", titulo);
43
44        // ID secondary (dimmed)
45        println!("   {}", lib.id.dimmed());
46
47        if let Some(desc) = &lib.description {
48            println!("   {}", desc.italic());
49        }
50
51        println!();
52    }
53}
54
55/// Prints a user-friendly hint when the requested library was not found.
56///
57/// Called from dispatchers in `cli.rs` before propagating the error,
58/// so the user sees the hint on stderr before the error message.
59pub fn exibir_dica_biblioteca_nao_encontrada() {
60    eprintln!("{}", t(Mensagem::BibliotecaNaoEncontradaApi).yellow());
61}
62
63// ─── DOCUMENTAÇÃO ─────────────────────────────────────────────────────────────
64
65/// Prints structured documentation from the docs endpoint.
66///
67/// Iterates over `snippets`. Shows a "no documentation found" message if empty.
68pub fn exibir_documentacao_formatada(doc: &RespostaDocumentacao) {
69    let snippets = match &doc.snippets {
70        Some(s) if !s.is_empty() => s,
71        _ => {
72            println!("{}", t(Mensagem::NenhumaDocumentacaoEncontrada).yellow());
73            return;
74        }
75    };
76
77    println!("{}", t(Mensagem::TituloDocumentacao).green().bold());
78    println!("{}", "─".repeat(60).dimmed());
79
80    for snippet in snippets {
81        exibir_snippet(snippet);
82    }
83}
84
85/// Prints a single documentation snippet with formatted fields.
86///
87/// Display order: page_title → code_title → code_description → code_list blocks → code_id (source)
88fn exibir_snippet(snippet: &DocumentationSnippet) {
89    if let Some(titulo_pagina) = &snippet.page_title {
90        println!("{}", format!("## {}", titulo_pagina).green().bold());
91    }
92
93    if let Some(titulo_codigo) = &snippet.code_title {
94        println!("{}", format!("▸ {}", titulo_codigo).cyan());
95    }
96
97    if let Some(descricao) = &snippet.code_description {
98        println!("  {}", descricao.dimmed().italic());
99    }
100
101    if let Some(blocos) = &snippet.code_list {
102        for bloco in blocos {
103            println!("```{}", bloco.language);
104            println!("{}", bloco.code);
105            println!("```");
106        }
107    }
108
109    if let Some(source) = &snippet.code_id {
110        println!("{}", source.blue().bold().dimmed());
111    }
112
113    println!();
114}
115
116// ─── CHAVES ───────────────────────────────────────────────────────────────────
117
118/// Prints all stored keys with 1-based indices and masked values.
119pub fn exibir_chaves_mascaradas(chaves: &[ChaveArmazenada], mascarar: impl Fn(&str) -> String) {
120    println!(
121        "{}",
122        format!("{} {}", chaves.len(), t(Mensagem::ContadorChaves))
123            .green()
124            .bold()
125    );
126    println!("{}", "─".repeat(60).dimmed());
127
128    let rotulo_adicionada = match idioma_atual() {
129        Idioma::English => "added:",
130        Idioma::Portugues => "adicionada:",
131    };
132
133    for (i, chave) in chaves.iter().enumerate() {
134        println!(
135            "  {}  {}  {}",
136            format!("[{}]", i + 1).cyan(),
137            mascarar(&chave.value).bold(),
138            format!("({} {})", rotulo_adicionada, chave.added_at).dimmed()
139        );
140    }
141}
142
143/// Prints the "no keys stored" hint message.
144pub fn exibir_nenhuma_chave() {
145    println!("{}", t(Mensagem::NenhumaChaveArmazenada).yellow());
146    println!("{}", t(Mensagem::UsarKeysAdd).cyan());
147}
148
149/// Prints the "no keys to remove" message.
150pub fn exibir_nenhuma_chave_para_remover() {
151    println!("{}", t(Mensagem::NenhumaChaveParaRemover).yellow());
152}
153
154/// Prints an invalid index error.
155pub fn exibir_indice_invalido(_indice: usize, total: usize) {
156    println!(
157        "{}",
158        format!("{} {}.", t(Mensagem::IndiceInvalido), total).red()
159    );
160}
161
162/// Prints the success message for `keys add`.
163pub fn exibir_chave_adicionada(caminho: &std::path::Path) {
164    println!(
165        "{} {}",
166        t(Mensagem::ChaveAdicionada),
167        caminho.display().to_string().green()
168    );
169}
170
171/// Prints the success message for `keys remove`.
172pub fn exibir_chave_removida(chave_mascarada: &str) {
173    println!(
174        "{} {}",
175        chave_mascarada.bold(),
176        t(Mensagem::ChaveRemovidaSucesso)
177    );
178}
179
180/// Prints the cancellation message for `keys clear`.
181pub fn exibir_operacao_cancelada() {
182    println!("{}", t(Mensagem::OperacaoCancelada).yellow());
183}
184
185/// Prints the success message for `keys clear`.
186pub fn exibir_chaves_removidas() {
187    println!("{}", t(Mensagem::TodasChavesRemovidas).green());
188}
189
190/// Prints an "XDG not supported" error for `keys path`.
191pub fn exibir_xdg_nao_suportado() {
192    println!("{}", t(Mensagem::SistemaXdgNaoSuportado).red());
193}
194
195/// Prints the success message for `keys import`.
196pub fn exibir_importacao_concluida(importadas: usize, total: usize) {
197    println!(
198        "{}",
199        format!(
200            "{}/{} {}",
201            importadas,
202            total,
203            t(Mensagem::ChavesImportadasSucesso)
204        )
205        .green()
206    );
207}