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    /// Generate shell completions for bash, zsh, fish, or PowerShell.
85    #[command(alias = "completion")]
86    Completions {
87        /// Shell to generate completions for.
88        shell: clap_complete::Shell,
89    },
90}
91
92/// Operations available under the `keys` subcommand.
93#[derive(Debug, Subcommand)]
94pub enum OperacaoKeys {
95    /// Add an API key to XDG storage.
96    Add {
97        /// API key to add (e.g. `ctx7sk-abc123…`).
98        key: String,
99    },
100    /// List all stored keys (masked).
101    List,
102    /// Remove a key by 1-based index (use `keys list` to see indices).
103    Remove {
104        /// Index of the key to remove (starting at 1).
105        index: usize,
106    },
107    /// Remove all stored keys.
108    Clear {
109        /// Confirm removal without an interactive prompt.
110        #[arg(long)]
111        yes: bool,
112    },
113    /// Print the XDG config file path.
114    Path,
115    /// Import keys from a `.env` file (reads `CONTEXT7_API=` entries).
116    Import {
117        /// Path to the `.env` file to import.
118        file: std::path::PathBuf,
119    },
120    /// Export all keys to stdout (one per line, unmasked).
121    Export,
122}
123
124// ─── HELPERS INTERNOS ────────────────────────────────────────────────────────
125
126/// Exibe dica se o erro for `BibliotecaNaoEncontrada`.
127fn verificar_e_exibir_dica_nao_encontrada<T>(resultado: &anyhow::Result<T>) {
128    if let Err(ref e) = resultado {
129        if let Some(ErroContext7::BibliotecaNaoEncontrada { .. }) = e.downcast_ref::<ErroContext7>()
130        {
131            exibir_dica_biblioteca_nao_encontrada();
132        }
133    }
134}
135
136// ─── DISPATCHERS ─────────────────────────────────────────────────────────────
137
138/// Dispatches `keys` subcommand operations — no HTTP client or API keys needed.
139pub fn executar_keys(operacao: OperacaoKeys, json: bool) -> Result<()> {
140    match operacao {
141        OperacaoKeys::Add { key } => cmd_keys_add(&key),
142        OperacaoKeys::List => cmd_keys_list(json),
143        OperacaoKeys::Remove { index } => cmd_keys_remove(index),
144        OperacaoKeys::Clear { yes } => cmd_keys_clear(yes),
145        OperacaoKeys::Path => cmd_keys_path(),
146        OperacaoKeys::Import { file } => cmd_keys_import(&file),
147        OperacaoKeys::Export => cmd_keys_export(),
148    }
149}
150
151/// Dispatches the `library` subcommand — searches libraries via the API.
152pub async fn executar_library(name: String, query: Option<String>, json: bool) -> Result<()> {
153    info!("Buscando biblioteca: {}", name);
154
155    let chaves = carregar_chaves_api()?;
156    let cliente = criar_cliente_http()?;
157
158    info!(
159        "Iniciando context7 com {} chaves de API disponíveis",
160        chaves.len()
161    );
162
163    // API requires the query parameter; fall back to the library name itself
164    let query_contexto = query.as_deref().unwrap_or(&name).to_string();
165
166    let cliente_arc = std::sync::Arc::new(cliente);
167    let name_clone = name.clone();
168    let query_clone = query_contexto.clone();
169    let resultado = executar_com_retry(&chaves, move |chave| {
170        let c = std::sync::Arc::clone(&cliente_arc);
171        let n = name_clone.clone();
172        let q = query_clone.clone();
173        async move { buscar_biblioteca(&c, &chave, &n, &q).await }
174    })
175    .await;
176
177    // Show hint before propagating BibliotecaNaoEncontrada
178    verificar_e_exibir_dica_nao_encontrada(&resultado);
179
180    let resultado =
181        resultado.with_context(|| format!("{} '{}'", t(Mensagem::FalhaBuscarBiblioteca), name))?;
182
183    if json {
184        exibir_json_resultados(
185            &serde_json::to_string_pretty(&resultado.results)
186                .with_context(|| t(Mensagem::FalhaSerializarJson))?,
187        );
188    } else {
189        exibir_bibliotecas_formatado(&resultado.results);
190    }
191    Ok(())
192}
193
194/// Dispatches the `docs` subcommand — fetches library documentation via the API.
195pub async fn executar_docs(
196    library_id: String,
197    query: Option<String>,
198    text: bool,
199    json: bool,
200) -> Result<()> {
201    info!("Buscando documentação para: {}", library_id);
202
203    let chaves = carregar_chaves_api()?;
204    let cliente = criar_cliente_http()?;
205
206    info!(
207        "Iniciando context7 com {} chaves de API disponíveis",
208        chaves.len()
209    );
210
211    let cliente_arc = std::sync::Arc::new(cliente);
212    let id_clone = library_id.clone();
213    let query_clone = query.clone();
214
215    if text {
216        // Plain-text mode: use txt endpoint, print raw markdown
217        let texto = executar_com_retry(&chaves, move |chave| {
218            let c = std::sync::Arc::clone(&cliente_arc);
219            let id = id_clone.clone();
220            let q = query_clone.clone();
221            async move { buscar_documentacao_texto(&c, &chave, &id, q.as_deref()).await }
222        })
223        .await;
224
225        // Show hint before propagating BibliotecaNaoEncontrada
226        verificar_e_exibir_dica_nao_encontrada(&texto);
227
228        let texto = texto.with_context(|| {
229            format!("{} '{}'", t(Mensagem::FalhaBuscarDocumentacao), library_id)
230        })?;
231
232        exibir_texto_plano(&texto);
233        return Ok(());
234    }
235
236    // JSON or formatted mode: use json endpoint
237    let resultado = executar_com_retry(&chaves, move |chave| {
238        let c = std::sync::Arc::clone(&cliente_arc);
239        let id = id_clone.clone();
240        let q = query_clone.clone();
241        async move { buscar_documentacao(&c, &chave, &id, q.as_deref()).await }
242    })
243    .await;
244
245    // Show hint before propagating BibliotecaNaoEncontrada
246    verificar_e_exibir_dica_nao_encontrada(&resultado);
247
248    let resultado = resultado
249        .with_context(|| format!("{} '{}'", t(Mensagem::FalhaBuscarDocumentacao), library_id))?;
250
251    if json {
252        exibir_json_resultados(
253            &serde_json::to_string_pretty(&resultado)
254                .with_context(|| t(Mensagem::FalhaSerializarDocs))?,
255        );
256    } else {
257        exibir_documentacao_formatada(&resultado);
258    }
259    Ok(())
260}