Files
imeai-aKode/akode-rs/cli/src/code_graph_cmd.rs

123 lines
4.8 KiB
Rust

//! `akode code-graph`: builds and queries the local code graph of a repository (tree-sitter and
//! git, no model). The same index is used by the `code_graph` tool.
use std::path::PathBuf;
use akode_code_graph::CodeIndex;
use akode_code_graph::anchor::Citation;
use akode_code_graph::anchor::anchors_for_memory;
use akode_core::config::Config;
use clap::Parser;
use clap::Subcommand;
#[derive(Debug, Parser)]
pub struct CodeGraphCommand {
/// Directory inside the repository (default: current directory).
#[arg(long, global = true)]
cwd: Option<PathBuf>,
/// Answer budget in tokens.
#[arg(long, global = true, default_value_t = 1500)]
budget: usize,
#[command(subcommand)]
action: CodeGraphAction,
}
#[derive(Debug, Subcommand)]
enum CodeGraphAction {
/// Update the index (incremental from git) and print what was done.
Index,
/// Delete the index of this repository and build it again.
Rebuild,
/// Symbols whose name matches.
Search { query: String },
/// Where a symbol is defined.
Definition { symbol: String },
/// Who calls (or uses) a symbol.
Callers { symbol: String },
/// What a symbol calls.
Callees { symbol: String },
/// Files linked to a file or symbol.
Related { target: String },
/// Outline of a file or folder.
Map { path: Option<String> },
/// Short map of the repository.
Summary,
/// Anchors for a citation `path[:lines]`, as sent to the memory server (no source code).
Anchors {
citation: String,
#[arg(long)]
quote: Option<String>,
},
}
pub async fn run(cmd: CodeGraphCommand, config: &Config) -> anyhow::Result<()> {
let cwd = match cmd.cwd {
Some(cwd) => cwd,
None => std::env::current_dir()?,
};
let home = config.codex_home.to_path_buf();
let budget = cmd.budget;
let action = cmd.action;
let text = tokio::task::spawn_blocking(move || -> anyhow::Result<String> {
let mut index = CodeIndex::open_for_dir(&home, &cwd).map_err(anyhow::Error::msg)?;
if matches!(action, CodeGraphAction::Rebuild) {
let path = CodeIndex::default_path(&home, index.root());
let root = index.root().to_path_buf();
drop(index);
for suffix in ["", "-wal", "-shm"] {
let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
}
index = CodeIndex::open(&path, &root).map_err(anyhow::Error::msg)?;
}
let report = index.update().map_err(anyhow::Error::msg)?;
let prefix = cwd
.canonicalize()
.ok()
.and_then(|cwd| cwd.strip_prefix(index.root()).ok().map(|p| p.to_string_lossy().to_string()))
.unwrap_or_default();
let answer: Result<String, String> = match action {
CodeGraphAction::Index | CodeGraphAction::Rebuild => Ok(format!(
"{}: mode {}, {} path(s) checked, {} parsed, {} removed in {} ms; index: {} files, {} symbols, {} references ({})",
index.root().display(),
report.mode,
report.checked,
report.parsed,
report.removed,
report.millis,
report.files,
report.symbols,
report.references,
CodeIndex::default_path(&home, index.root()).display()
)),
CodeGraphAction::Search { query } => index.search(&query, None, None, 30, budget),
CodeGraphAction::Definition { symbol } => index.definition(&symbol, 12, budget),
CodeGraphAction::Callers { symbol } => index.callers(&symbol, budget),
CodeGraphAction::Callees { symbol } => index.callees(&symbol, budget),
CodeGraphAction::Related { target } => index.related(&target, &prefix, budget),
CodeGraphAction::Map { path } => index.module_map(path.as_deref().unwrap_or(&prefix), &prefix, budget),
CodeGraphAction::Summary => index.repo_summary(budget),
CodeGraphAction::Anchors { citation, quote } => {
let (path, lines) = match citation.rsplit_once(':') {
Some((path, lines)) if lines.chars().all(|c| c.is_ascii_digit() || c == '-') => {
(path.to_string(), Some(lines.to_string()))
}
_ => (citation.clone(), None),
};
let path = index.normalize_path(&path, &prefix);
let anchors = anchors_for_memory(
index.root(),
&[Citation { path, lines, quote }],
"",
);
Ok(serde_json::to_string_pretty(&anchors).unwrap_or_default())
}
};
answer.map_err(anyhow::Error::msg)
})
.await??;
println!("{text}");
Ok(())
}