use anyhow::{Context, Result, bail};
use sqry_core::graph::CodeGraph;
use sqry_core::graph::unified::build::{BuildConfig, build_unified_graph_with_progress};
use sqry_core::graph::unified::persistence::{GraphStorage, load_from_path};
use sqry_core::progress::{SharedReporter, no_op_reporter};
use sqry_plugin_registry::create_plugin_manager;
use std::path::Path;
#[derive(Debug, Clone, Default)]
pub struct GraphLoadConfig {
pub include_hidden: bool,
pub follow_symlinks: bool,
pub max_depth: Option<usize>,
pub force_build: bool,
}
pub fn load_unified_graph(root: &Path, config: &GraphLoadConfig) -> Result<CodeGraph> {
load_unified_graph_with_progress(root, config, no_op_reporter())
}
pub fn load_unified_graph_with_progress(
root: &Path,
config: &GraphLoadConfig,
progress: SharedReporter,
) -> Result<CodeGraph> {
if !root.exists() {
bail!("Path {} does not exist", root.display());
}
let plugins = create_plugin_manager();
if config.force_build {
log::info!("Force build enabled, skipping snapshot load");
} else {
let storage = GraphStorage::new(root);
if storage.exists() {
log::info!(
"Loading unified graph from snapshot: {}",
storage.snapshot_path().display()
);
match load_from_path(storage.snapshot_path(), Some(&plugins)) {
Ok(mut graph) => {
log::info!("Loaded graph from snapshot");
if let Ok(manifest) = storage.load_manifest()
&& !manifest.confidence.is_empty()
{
log::debug!(
"Restoring confidence metadata for {} languages",
manifest.confidence.len()
);
graph.set_confidence(manifest.confidence);
}
return Ok(graph);
}
Err(e) => {
bail!(
"Index at {} is corrupted or incomplete ({}). Run `sqry index --force` to rebuild.",
root.display(),
e
);
}
}
}
}
log::info!(
"Building unified graph from source files in {}",
root.display()
);
let build_config = BuildConfig {
include_hidden: config.include_hidden,
follow_links: config.follow_symlinks,
max_depth: config.max_depth,
num_threads: None,
..BuildConfig::default()
};
let graph = build_unified_graph_with_progress(root, &plugins, &build_config, progress)
.context("Failed to build unified graph")?;
log::info!("Built unified graph with {} nodes", graph.node_count());
Ok(graph)
}