context7-cli 0.5.0

Search library documentation from your terminal — zero runtime, bilingual (EN/PT), multi-key rotation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/// Terminal output formatting.
///
/// This is the **only** module allowed to call `println!` or `eprintln!`.
/// All coloured formatting via the `colored` crate is centralised here.
/// All user-facing strings are resolved via [`crate::i18n::t`].
use std::io::IsTerminal;

use anyhow::Context;
use chrono::Utc;
use colored::Colorize;
use serde::Serialize;

use crate::api::{DocumentationSnippet, LibrarySearchResult, RespostaDocumentacao};
use crate::i18n::{idioma_atual, t, Idioma, Mensagem};
use crate::storage::ChaveArmazenada;

/// Retorna o simbolo Unicode ou seu fallback ASCII conforme capacidade do terminal.
///
/// Usa ASCII quando stdout nao e TTY interativo (pipe, redirecionamento),
/// quando `NO_COLOR` esta setado, ou quando a variavel `TERM` e `dumb`.
fn simbolo_ou_ascii<'a>(unicode: &'a str, ascii: &'a str) -> &'a str {
    static USAR_ASCII: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let usar_ascii = *USAR_ASCII.get_or_init(|| {
        !std::io::stdout().is_terminal()
            || std::env::var("NO_COLOR").is_ok()
            || std::env::var("TERM").map(|t| t == "dumb").unwrap_or(false)
    });
    if usar_ascii {
        ascii
    } else {
        unicode
    }
}

// ─── NDJSON ──────────────────────────────────────────────────────────────────

/// Envelope NDJSON para saída estruturada consumível por LLMs.
///
/// Cada evento é emitido como uma linha JSON com `type` e `timestamp`.
#[derive(Serialize)]
struct EventoNdjson<'a, T: Serialize> {
    #[serde(rename = "type")]
    tipo: &'a str,
    timestamp: String,
    #[serde(flatten)]
    dados: T,
}

/// Emite um evento NDJSON (uma linha JSON) para stdout.
pub fn emitir_ndjson<T: Serialize>(tipo: &str, dados: &T) {
    let evento = EventoNdjson {
        tipo,
        timestamp: Utc::now().to_rfc3339(),
        dados,
    };
    if let Ok(json) = serde_json::to_string(&evento) {
        println!("{json}");
    }
}

// ─── BIBLIOTECA ───────────────────────────────────────────────────────────────

/// Prints the list of libraries returned by the search endpoint.
///
/// Displays index, title bold with trust score inline, library ID (dimmed),
/// and optional description (italic).
pub fn exibir_bibliotecas_formatado(resultados: &[LibrarySearchResult]) {
    if resultados.is_empty() {
        println!("{}", t(Mensagem::NenhumaBibliotecaEncontrada).yellow());
        return;
    }

    println!("{}", t(Mensagem::BibliotecasEncontradas).green().bold());
    println!("{}", simbolo_ou_ascii("", "-").repeat(60).dimmed());

    for (i, lib) in resultados.iter().enumerate() {
        let numero = format!("{}.", i + 1);

        // Title bold with trust score inline
        let titulo = if let Some(score) = lib.trust_score {
            format!(
                "{} {} ({} {:.1}/10)",
                numero.cyan(),
                lib.title.bold(),
                t(Mensagem::ConfiancaScore),
                score
            )
        } else {
            format!("{} {}", numero.cyan(), lib.title.bold())
        };
        println!("{}", titulo);

        // ID secondary (dimmed)
        println!("   {}", lib.id.dimmed());

        if let Some(desc) = &lib.description {
            println!("   {}", desc.italic());
        }

        println!();
    }
}

/// Prints a user-friendly hint when the requested library was not found.
///
/// Called from dispatchers in `cli.rs` before propagating the error,
/// so the user sees the hint on stderr before the error message.
pub fn exibir_dica_biblioteca_nao_encontrada() {
    eprintln!("{}", t(Mensagem::BibliotecaNaoEncontradaApi).yellow());
}

// ─── DOCUMENTAÇÃO ─────────────────────────────────────────────────────────────

/// Prints structured documentation from the docs endpoint.
///
/// Iterates over `snippets`. Shows a "no documentation found" message if empty.
pub fn exibir_documentacao_formatada(doc: &RespostaDocumentacao) {
    let snippets = match &doc.snippets {
        Some(s) if !s.is_empty() => s,
        _ => {
            println!("{}", t(Mensagem::NenhumaDocumentacaoEncontrada).yellow());
            return;
        }
    };

    println!("{}", t(Mensagem::TituloDocumentacao).green().bold());
    println!("{}", simbolo_ou_ascii("", "-").repeat(60).dimmed());

    for snippet in snippets {
        exibir_snippet(snippet);
    }
}

/// Prints a single documentation snippet with formatted fields.
///
/// Display order: page_title → code_title → code_description → code_list blocks → code_id (source)
fn exibir_snippet(snippet: &DocumentationSnippet) {
    if let Some(titulo_pagina) = &snippet.page_title {
        println!("{}", format!("## {}", titulo_pagina).green().bold());
    }

    if let Some(titulo_codigo) = &snippet.code_title {
        println!(
            "{}",
            format!("{} {}", simbolo_ou_ascii("", ">"), titulo_codigo).cyan()
        );
    }

    if let Some(descricao) = &snippet.code_description {
        println!("  {}", descricao.dimmed().italic());
    }

    if let Some(blocos) = &snippet.code_list {
        for bloco in blocos {
            println!("```{}", bloco.language);
            println!("{}", bloco.code);
            println!("```");
        }
    }

    if let Some(source) = &snippet.code_id {
        println!("{}", source.blue().bold().dimmed());
    }

    println!();
}

// ─── CHAVES ───────────────────────────────────────────────────────────────────

/// Prints all stored keys with 1-based indices and masked values.
pub fn exibir_chaves_mascaradas(chaves: &[ChaveArmazenada], mascarar: impl Fn(&str) -> String) {
    println!(
        "{}",
        format!("{} {}", chaves.len(), t(Mensagem::ContadorChaves))
            .green()
            .bold()
    );
    println!("{}", simbolo_ou_ascii("", "-").repeat(60).dimmed());

    let rotulo_adicionada = match idioma_atual() {
        Idioma::English => "added:",
        Idioma::Portugues => "adicionada:",
    };

    for (i, chave) in chaves.iter().enumerate() {
        println!(
            "  {}  {}  {}",
            format!("[{}]", i + 1).cyan(),
            mascarar(&chave.value).bold(),
            format!(
                "({} {})",
                rotulo_adicionada,
                formatar_added_at_display(&chave.added_at)
            )
            .dimmed()
        );
    }
}

/// Formata uma string RFC3339 para exibição compacta: `YYYY-MM-DD HH:MM:SS`.
///
/// Retorna a string original se o parse falhar (robustez).
pub fn formatar_added_at_display(iso: &str) -> String {
    chrono::DateTime::parse_from_rfc3339(iso)
        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
        .unwrap_or_else(|_| iso.to_string())
}

/// Prints the "no keys stored" hint message.
pub fn exibir_nenhuma_chave() {
    println!("{}", t(Mensagem::NenhumaChaveArmazenada).yellow());
    println!("{}", t(Mensagem::UsarKeysAdd).cyan());
}

/// Prints the "no keys to remove" message.
pub fn exibir_nenhuma_chave_para_remover() {
    println!("{}", t(Mensagem::NenhumaChaveParaRemover).yellow());
}

/// Prints an invalid index error.
pub fn exibir_indice_invalido(_indice: usize, total: usize) {
    println!(
        "{}",
        format!("{} {}.", t(Mensagem::IndiceInvalido), total).red()
    );
}

/// Prints the success message for `keys add`.
pub fn exibir_chave_adicionada(caminho: &std::path::Path) {
    println!(
        "{} {}",
        t(Mensagem::ChaveAdicionada),
        caminho.display().to_string().green()
    );
}

/// Prints the warning message when a key already exists (dedupe).
pub fn exibir_chave_ja_existia() {
    println!("{}", t(Mensagem::ChaveJaExistia).yellow());
}

/// Displays an error when the user tries to add an empty API key.
pub fn exibir_chave_invalida_vazia() {
    eprintln!("{}", t(Mensagem::ChaveVaziaOuInvalida).red());
}

/// Displays a warning when the key does not match the expected `ctx7sk-` format.
pub fn exibir_aviso_formato_chave() {
    eprintln!("{}", t(Mensagem::AvisoFormatoChave).yellow());
}

/// Prints the success message for `keys remove`.
pub fn exibir_chave_removida(chave_mascarada: &str) {
    println!(
        "{} {}",
        chave_mascarada.bold(),
        t(Mensagem::ChaveRemovidaSucesso)
    );
}

/// Prints the cancellation message for `keys clear`.
pub fn exibir_operacao_cancelada() {
    println!("{}", t(Mensagem::OperacaoCancelada).yellow());
}

/// Prints the success message for `keys clear`.
pub fn exibir_chaves_removidas() {
    println!("{}", t(Mensagem::TodasChavesRemovidas).green());
}

/// Prints an "XDG not supported" error for `keys path`.
pub fn exibir_xdg_nao_suportado() {
    println!("{}", t(Mensagem::SistemaXdgNaoSuportado).red());
}

/// Prints an empty JSON array `[]` to stdout.
pub fn exibir_json_array_vazio() {
    println!("[]");
}

/// Prints a raw JSON string to stdout.
pub fn exibir_json_bruto(json: &str) {
    println!("{}", json);
}

/// Prints a file path to stdout.
pub fn exibir_caminho_config(caminho: &std::path::Path) {
    println!("{}", caminho.display());
}

/// Prints a key in `CONTEXT7_API=<value>` format to stdout.
pub fn exibir_chave_exportada(valor: &str) {
    println!("CONTEXT7_API={}", valor);
}

/// Prints raw JSON results to stdout (used by Library and Docs JSON mode).
pub fn exibir_json_resultados(json: &str) {
    println!("{}", json);
}

/// Prints plain text to stdout (used by Docs text mode).
pub fn exibir_texto_plano(texto: &str) {
    println!("{}", texto);
}

/// Asks for interactive confirmation before clearing all keys.
///
/// Returns `true` if the user confirms with `s`/`sim` (PT) or `y`/`yes` (EN).
pub fn confirmar_clear() -> anyhow::Result<bool> {
    use std::io::Write;
    print!("{}", t(Mensagem::ConfirmarRemoverTodas));
    std::io::stdout()
        .flush()
        .context("Falha ao limpar buffer de saída")?;

    let mut entrada = String::new();
    std::io::stdin()
        .read_line(&mut entrada)
        .context("Falha ao ler confirmação do usuário")?;

    Ok(matches!(
        entrada.trim().to_lowercase().as_str(),
        "s" | "sim" | "y" | "yes"
    ))
}

/// Prints the success message for `keys import`.
pub fn exibir_importacao_concluida(importadas: usize, total: usize) {
    println!(
        "{}",
        format!(
            "{}/{} {}",
            importadas,
            total,
            t(Mensagem::ChavesImportadasSucesso)
        )
        .green()
    );
}

#[cfg(test)]
mod testes {
    use super::formatar_added_at_display;

    #[test]
    fn testa_formatar_added_at_rfc3339_com_nanossegundos() {
        let resultado = formatar_added_at_display("2026-04-09T13:34:59.060818734+00:00");
        assert_eq!(resultado, "2026-04-09 13:34:59");
        assert!(
            !resultado.contains('T'),
            "Resultado não deve conter 'T': {resultado}"
        );
        assert!(
            !resultado.contains('.'),
            "Resultado não deve conter nanossegundos: {resultado}"
        );
        assert!(
            !resultado.contains("+00:00"),
            "Resultado não deve conter offset de timezone: {resultado}"
        );
    }

    #[test]
    fn testa_formatar_added_at_rfc3339_sem_nanossegundos() {
        let resultado = formatar_added_at_display("2026-01-01T00:00:00+00:00");
        assert_eq!(resultado, "2026-01-01 00:00:00");
    }

    #[test]
    fn testa_formatar_added_at_rfc3339_offset_nao_utc() {
        // RFC3339 com offset -03:00 (Brasil) — exibe hora local (sem conversão para UTC)
        let resultado = formatar_added_at_display("2026-04-09T10:00:00-03:00");
        // A função preserva a hora local do timestamp, não converte para UTC
        assert_eq!(resultado, "2026-04-09 10:00:00");
        // Deve remover o offset timezone da exibição
        assert!(
            !resultado.contains("-03:00"),
            "Resultado não deve conter offset de timezone: {resultado}"
        );
    }

    #[test]
    fn testa_formatar_added_at_fallback_string_invalida() {
        let resultado = formatar_added_at_display("lixo-nao-e-data");
        assert_eq!(
            resultado, "lixo-nao-e-data",
            "String inválida deve ser retornada sem modificação"
        );
    }

    #[test]
    fn testa_formatar_added_at_string_vazia() {
        let resultado = formatar_added_at_display("");
        assert_eq!(
            resultado, "",
            "String vazia deve ser retornada sem modificação"
        );
    }

    #[test]
    fn testa_formatar_added_at_formato_saida_legivel() {
        let resultado = formatar_added_at_display("2026-04-09T13:34:59.123456789+00:00");
        // Deve ter exatamente o formato YYYY-MM-DD HH:MM:SS (19 chars)
        assert_eq!(
            resultado.len(),
            19,
            "Formato de saída deve ter 19 caracteres, obteve: '{resultado}'"
        );
        assert!(
            resultado.contains(' '),
            "Resultado deve conter espaço separando data e hora: {resultado}"
        );
    }
}