use clap::Parser;
use std::sync::{Arc, Mutex};
use knot::{
cli_tools,
config::{Config, OutputFormat},
db::{
graph::{ConnectExt, GraphDb},
vector::VectorConnectExt,
},
models::{Cli, Commands, RepoScope},
pipeline::embed::Embedder,
utils,
};
async fn run_callers(
command: Commands,
cfg: &Config,
graph_db: &Arc<GraphDb>,
) -> anyhow::Result<()> {
let Commands::Callers {
entity_name,
repo,
max_targets,
kinds,
include_tests,
output,
} = command
else {
return Ok(());
};
let target_repo = build_repo_scope(repo.as_deref(), &cfg.repo_name);
let json_result = cli_tools::run_find_callers(
&entity_name,
&target_repo,
graph_db,
max_targets,
kinds.as_deref(),
)
.await?;
let formatted = utils::format_callers_output_with(
&entity_name,
json_result,
output,
cli_tools::CallersFormat { include_tests },
);
utils::print_with_pager(&formatted);
Ok(())
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
utils::init_logging_for_cli()?;
let cli = Cli::parse();
let cfg = Config::load_knot_cli().expect("Failed to load configuration");
utils::inject_custom_ca_certs(&cfg.custom_ca_certs);
if cli.command == Commands::EmbedModel {
return print_embed_model(&cfg);
}
let vector_db = Arc::new(
knot::db::vector::VectorDb::connect(&cfg.qdrant_url, &cfg.qdrant_collection, cfg.embed_dim)
.await?,
);
let graph_db =
Arc::new(GraphDb::connect(&cfg.neo4j_uri, &cfg.neo4j_user, &cfg.neo4j_password).await?);
knot::startup_guard::verify_startup(&cfg).await?;
let embedder = Arc::new(Mutex::new(Embedder::init(
knot::pipeline::state::fastembed_cache_dir(&cfg.repo_path),
)?));
match cli.command {
Commands::Search {
query,
max_results,
repo,
kinds,
path,
detail,
include_tests,
output,
} => {
report_search_clamp(max_results);
let target_repo = build_repo_scope(repo.as_deref(), &cfg.repo_name);
let json_result = cli_tools::run_search_hybrid_context(
&query,
max_results,
&target_repo,
cli_tools::SearchFilters {
kinds: kinds.as_deref(),
path: path.as_deref(),
},
&cli_tools::SearchContext {
vector_db: &vector_db,
graph_db: &graph_db,
embedder: &embedder,
},
)
.await?;
let search_format = cli_tools::formatters::SearchFormat {
detail: cli_tools::formatters::Detail::parse(&detail).unwrap_or_default(),
include_tests,
};
let formatted = utils::format_output(json_result, output, search_format);
utils::print_with_pager(&formatted);
}
command @ Commands::Callers { .. } => run_callers(command, &cfg, &graph_db).await?,
Commands::Explore {
file_path,
repo,
include_markup,
output,
} => {
let target_repo = build_repo_scope(repo.as_deref(), &cfg.repo_name);
let (fp, json_result) =
cli_tools::run_explore_file(&file_path, &target_repo, &graph_db).await?;
let formatted = utils::format_explore_output(&fp, json_result, output, include_markup);
utils::print_with_pager(&formatted);
}
command
@ (Commands::Files { .. } | Commands::Endpoints { .. } | Commands::Repos { .. }) => {
run_listing_command(command, &cfg, &graph_db).await?;
}
Commands::Deps {
repo_name,
depth,
reverse,
output,
} => {
run_deps_command(&repo_name, depth, reverse, output, &graph_db).await?;
}
Commands::EmbedModel => unreachable!("handled before database connections"),
}
Ok(())
}
fn print_embed_model(cfg: &Config) -> anyhow::Result<()> {
use std::str::FromStr as _;
let choice = knot::pipeline::embed::EmbedModelChoice::from_str(&cfg.embed_model)
.map_err(|e| anyhow::anyhow!("{e}"))?;
println!(
"{} {} {}",
cfg.embed_model,
choice.dim,
choice.default_collection("knot_entities")
);
Ok(())
}
async fn run_listing_command(
command: Commands,
cfg: &Config,
graph_db: &Arc<GraphDb>,
) -> anyhow::Result<()> {
let formatted = match command {
Commands::Files { path, repo, output } => {
let target_repo = build_repo_scope(repo.as_deref(), &cfg.repo_name);
let json_result =
cli_tools::run_list_files(path.as_deref(), &target_repo, graph_db).await?;
cli_tools::format_files_output(&json_result, output)
}
Commands::Endpoints {
method,
path,
repo,
output,
} => {
let target_repo = build_repo_scope(repo.as_deref(), &cfg.repo_name);
let json_result = cli_tools::run_list_endpoints(
method.as_deref(),
path.as_deref(),
&target_repo,
graph_db,
)
.await?;
cli_tools::format_endpoints_output(&json_result, output)
}
Commands::Repos { filter, output } => {
let json_result = cli_tools::run_list_repos(filter.as_deref(), graph_db).await?;
cli_tools::format_repos_output(&json_result, output)
}
_ => unreachable!("only listing commands are routed here"),
};
utils::print_with_pager(&formatted);
Ok(())
}
async fn run_deps_command(
repo_name: &str,
depth: u32,
reverse: bool,
output: OutputFormat,
graph_db: &Arc<GraphDb>,
) -> anyhow::Result<()> {
report_depth_clamp(depth, reverse);
let json_result = cli_tools::run_deps(repo_name, depth, reverse, graph_db).await?;
match output {
OutputFormat::Json => {
println!(
"{}",
serde_json::to_string_pretty(&json_result).unwrap_or_default()
);
}
OutputFormat::Table | OutputFormat::Markdown => {
let diagnostics = if json_result.as_array().is_some_and(|a| a.is_empty()) {
Some(cli_tools::collect_deps_diagnostics(repo_name, reverse, graph_db).await?)
} else {
None
};
let formatted = cli_tools::format_deps_output_with_diagnostics(
repo_name,
reverse,
&json_result,
diagnostics.as_ref(),
);
utils::print_with_pager(&formatted);
}
}
Ok(())
}
fn build_repo_scope(repo: Option<&str>, default: &str) -> RepoScope {
repo.map(RepoScope::parse)
.unwrap_or_else(|| RepoScope::One(default.to_string()))
}
fn report_search_clamp(max_results: usize) {
let resolved = cli_tools::resolve_max_results(max_results);
if let Some(notice) = resolved.notice() {
eprintln!("{}", notice.trim_end());
}
}
fn report_depth_clamp(depth: u32, reverse: bool) {
let resolved = cli_tools::resolve_max_depth(depth);
if resolved != depth {
let word = if depth == 0 { "floored" } else { "clamped" };
eprintln!(
"Note: --depth was {word} from {depth} to {resolved} (bound applies to {} traversal).",
if reverse { "reverse" } else { "forward" }
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repo_flag_builds_scope_list() {
let scope = build_repo_scope(Some("a,b"), "default-repo");
assert_eq!(
scope,
RepoScope::Many(vec!["a".to_string(), "b".to_string()])
);
}
#[test]
fn repo_flag_builds_scope_all() {
let scope = build_repo_scope(Some("all"), "default-repo");
assert_eq!(scope, RepoScope::All);
}
#[test]
fn repo_flag_absent_uses_config_default() {
let scope = build_repo_scope(None, "default-repo");
assert_eq!(scope, RepoScope::One("default-repo".to_string()));
}
}