Skip to main content

context7_cli/
cli.rs

1/// CLI argument definitions and command dispatchers.
2///
3/// Defines [`Cli`], [`Comando`], and [`OperacaoKeys`] via `clap` derives,
4/// plus the async dispatcher functions that call into [`crate::api`],
5/// [`crate::storage`], and [`crate::output`].
6use anyhow::{Context, Result};
7use clap::{Parser, Subcommand};
8use tracing::info;
9
10use crate::api::{
11    buscar_biblioteca, buscar_documentacao, buscar_documentacao_texto, criar_cliente_http,
12    executar_com_retry,
13};
14use crate::errors::ErroContext7;
15use crate::i18n::{t, Mensagem};
16use crate::output::{
17    exibir_bibliotecas_formatado, exibir_dica_biblioteca_nao_encontrada,
18    exibir_documentacao_formatada, exibir_json_resultados, exibir_texto_plano,
19};
20use crate::storage::{
21    carregar_chaves_api, cmd_keys_add, cmd_keys_clear, cmd_keys_export, cmd_keys_import,
22    cmd_keys_list, cmd_keys_path, cmd_keys_remove,
23};
24
25// ─── STRUCTS CLI ─────────────────────────────────────────────────────────────
26
27/// Top-level CLI entry point parsed by `clap`.
28#[derive(Debug, Parser)]
29#[command(
30    name = "context7",
31    version,
32    about = "CLI client for the Context7 API (bilingual EN/PT)",
33    long_about = None,
34)]
35pub struct Cli {
36    /// UI language: `en` or `pt`. Default: auto-detect from system locale.
37    #[arg(long, global = true, env = "CONTEXT7_LANG")]
38    pub lang: Option<String>,
39
40    /// Output raw JSON instead of formatted text.
41    #[arg(long, global = true)]
42    pub json: bool,
43
44    /// Subcommand to execute.
45    #[command(subcommand)]
46    pub comando: Comando,
47}
48
49/// Top-level subcommands.
50#[derive(Debug, Subcommand)]
51pub enum Comando {
52    /// Search libraries by name.
53    #[command(alias = "lib", alias = "search")]
54    Library {
55        /// Library name to search for.
56        name: String,
57        /// Optional context for relevance ranking (e.g. "effect hooks").
58        query: Option<String>,
59    },
60
61    /// Fetch documentation for a library.
62    #[command(alias = "doc", alias = "context")]
63    Docs {
64        /// Library identifier (e.g. `/rust-lang/rust`).
65        library_id: String,
66
67        /// Topic or search query.
68        #[arg(short = 'q', long)]
69        query: Option<String>,
70
71        /// Output plain text instead of formatted output (incompatible with `--json`).
72        #[arg(long, conflicts_with = "json")]
73        text: bool,
74    },
75
76    /// Manage locally stored API keys.
77    #[command(alias = "key")]
78    Keys {
79        /// Key management operation.
80        #[command(subcommand)]
81        operacao: OperacaoKeys,
82    },
83}
84
85/// Operations available under the `keys` subcommand.
86#[derive(Debug, Subcommand)]
87pub enum OperacaoKeys {
88    /// Add an API key to XDG storage.
89    Add {
90        /// API key to add (e.g. `ctx7sk-abc123…`).
91        key: String,
92    },
93    /// List all stored keys (masked).
94    List,
95    /// Remove a key by 1-based index (use `keys list` to see indices).
96    Remove {
97        /// Index of the key to remove (starting at 1).
98        index: usize,
99    },
100    /// Remove all stored keys.
101    Clear {
102        /// Confirm removal without an interactive prompt.
103        #[arg(long)]
104        yes: bool,
105    },
106    /// Print the XDG config file path.
107    Path,
108    /// Import keys from a `.env` file (reads `CONTEXT7_API=` entries).
109    Import {
110        /// Path to the `.env` file to import.
111        file: std::path::PathBuf,
112    },
113    /// Export all keys to stdout (one per line, unmasked).
114    Export,
115}
116
117// ─── DISPATCHERS ─────────────────────────────────────────────────────────────
118
119/// Dispatches `keys` subcommand operations — no HTTP client or API keys needed.
120pub fn executar_keys(operacao: OperacaoKeys, json: bool) -> Result<()> {
121    match operacao {
122        OperacaoKeys::Add { key } => cmd_keys_add(&key),
123        OperacaoKeys::List => cmd_keys_list(json),
124        OperacaoKeys::Remove { index } => cmd_keys_remove(index),
125        OperacaoKeys::Clear { yes } => cmd_keys_clear(yes),
126        OperacaoKeys::Path => cmd_keys_path(),
127        OperacaoKeys::Import { file } => cmd_keys_import(&file),
128        OperacaoKeys::Export => cmd_keys_export(),
129    }
130}
131
132/// Dispatches the `library` subcommand — searches libraries via the API.
133pub async fn executar_library(name: String, query: Option<String>, json: bool) -> Result<()> {
134    info!("Buscando biblioteca: {}", name);
135
136    let chaves = carregar_chaves_api()?;
137    let cliente = criar_cliente_http()?;
138
139    info!(
140        "Iniciando context7 com {} chaves de API disponíveis",
141        chaves.len()
142    );
143
144    // API requires the query parameter; fall back to the library name itself
145    let query_contexto = query.as_deref().unwrap_or(&name).to_string();
146
147    let cliente_arc = std::sync::Arc::new(cliente);
148    let name_clone = name.clone();
149    let query_clone = query_contexto.clone();
150    let resultado = executar_com_retry(&chaves, move |chave| {
151        let c = std::sync::Arc::clone(&cliente_arc);
152        let n = name_clone.clone();
153        let q = query_clone.clone();
154        async move { buscar_biblioteca(&c, &chave, &n, &q).await }
155    })
156    .await;
157
158    // Show hint before propagating BibliotecaNaoEncontrada
159    if let Err(ref e) = resultado {
160        if let Some(ErroContext7::BibliotecaNaoEncontrada { .. }) = e.downcast_ref::<ErroContext7>()
161        {
162            exibir_dica_biblioteca_nao_encontrada();
163        }
164    }
165
166    let resultado =
167        resultado.with_context(|| format!("{} '{}'", t(Mensagem::FalhaBuscarBiblioteca), name))?;
168
169    if json {
170        exibir_json_resultados(
171            &serde_json::to_string_pretty(&resultado.results)
172                .with_context(|| t(Mensagem::FalhaSerializarJson))?,
173        );
174    } else {
175        exibir_bibliotecas_formatado(&resultado.results);
176    }
177    Ok(())
178}
179
180/// Dispatches the `docs` subcommand — fetches library documentation via the API.
181pub async fn executar_docs(
182    library_id: String,
183    query: Option<String>,
184    text: bool,
185    json: bool,
186) -> Result<()> {
187    info!("Buscando documentação para: {}", library_id);
188
189    let chaves = carregar_chaves_api()?;
190    let cliente = criar_cliente_http()?;
191
192    info!(
193        "Iniciando context7 com {} chaves de API disponíveis",
194        chaves.len()
195    );
196
197    let cliente_arc = std::sync::Arc::new(cliente);
198    let id_clone = library_id.clone();
199    let query_clone = query.clone();
200
201    if text {
202        // Plain-text mode: use txt endpoint, print raw markdown
203        let texto = executar_com_retry(&chaves, move |chave| {
204            let c = std::sync::Arc::clone(&cliente_arc);
205            let id = id_clone.clone();
206            let q = query_clone.clone();
207            async move { buscar_documentacao_texto(&c, &chave, &id, q.as_deref()).await }
208        })
209        .await;
210
211        // Show hint before propagating BibliotecaNaoEncontrada
212        if let Err(ref e) = texto {
213            if let Some(ErroContext7::BibliotecaNaoEncontrada { .. }) =
214                e.downcast_ref::<ErroContext7>()
215            {
216                exibir_dica_biblioteca_nao_encontrada();
217            }
218        }
219
220        let texto = texto.with_context(|| {
221            format!("{} '{}'", t(Mensagem::FalhaBuscarDocumentacao), library_id)
222        })?;
223
224        exibir_texto_plano(&texto);
225        return Ok(());
226    }
227
228    // JSON or formatted mode: use json endpoint
229    let resultado = executar_com_retry(&chaves, move |chave| {
230        let c = std::sync::Arc::clone(&cliente_arc);
231        let id = id_clone.clone();
232        let q = query_clone.clone();
233        async move { buscar_documentacao(&c, &chave, &id, q.as_deref()).await }
234    })
235    .await;
236
237    // Show hint before propagating BibliotecaNaoEncontrada
238    if let Err(ref e) = resultado {
239        if let Some(ErroContext7::BibliotecaNaoEncontrada { .. }) = e.downcast_ref::<ErroContext7>()
240        {
241            exibir_dica_biblioteca_nao_encontrada();
242        }
243    }
244
245    let resultado = resultado
246        .with_context(|| format!("{} '{}'", t(Mensagem::FalhaBuscarDocumentacao), library_id))?;
247
248    if json {
249        exibir_json_resultados(
250            &serde_json::to_string_pretty(&resultado)
251                .with_context(|| t(Mensagem::FalhaSerializarDocs))?,
252        );
253    } else {
254        exibir_documentacao_formatada(&resultado);
255    }
256    Ok(())
257}