use anyhow::Result;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::config::{SphinxConfig, output_config_hash, resolve_extra_inputs};
use crate::file_index::FileIndex;
use crate::graph::{BuildGraph, Product};
use crate::processors::{ProductDiscovery, ProcessorType, SiblingFilter, scan_root_valid, run_command, anchor_display_dir, check_command_output};
pub struct SphinxProcessor {
config: SphinxConfig,
}
impl SphinxProcessor {
pub fn new(config: SphinxConfig) -> Self {
Self { config }
}
fn execute_sphinx(&self, conf_py: &Path) -> Result<()> {
let mut cmd = Command::new(&self.config.sphinx_build);
let anchor_dir = conf_py.parent().unwrap_or(Path::new(""));
if anchor_dir.as_os_str().is_empty() {
cmd.arg(".");
} else {
cmd.arg(anchor_dir);
}
cmd.arg(&self.config.output_dir);
for arg in &self.config.args {
cmd.arg(arg);
}
if let Some(ref dir) = self.config.working_dir {
cmd.current_dir(dir);
}
let output = run_command(&mut cmd)?;
check_command_output(&output, format_args!("sphinx-build in {}", anchor_display_dir(conf_py)))
}
}
impl ProductDiscovery for SphinxProcessor {
fn description(&self) -> &str {
"Build Sphinx documentation"
}
fn processor_type(&self) -> ProcessorType {
ProcessorType::MassGenerator
}
fn auto_detect(&self, file_index: &FileIndex) -> bool {
scan_root_valid(&self.config.scan) && !file_index.scan(&self.config.scan, true).is_empty()
}
fn required_tools(&self) -> Vec<String> {
vec![self.config.sphinx_build.clone(), "python3".to_string()]
}
fn discover(&self, graph: &mut BuildGraph, file_index: &FileIndex) -> Result<()> {
let Some(files) = crate::processors::scan_or_skip(&self.config.scan, file_index) else {
return Ok(());
};
let hash = Some(output_config_hash(&self.config, &[]));
let extra = resolve_extra_inputs(&self.config.extra_inputs)?;
let siblings = SiblingFilter {
extensions: &[".rst", ".py", ".md"],
excludes: &["/.git/", "/out/", "/.rsconstruct/", "/_build/", "/docs/"],
};
for anchor in files {
let anchor_dir = anchor.parent().map(|p| p.to_path_buf()).unwrap_or_default();
let sibling_files = file_index.query(
&anchor_dir, siblings.extensions, siblings.excludes, &[], &[],
);
let inputs = crate::processors::build_anchor_inputs(&anchor, &sibling_files, &extra);
if self.config.cache_output_dir {
let output_dir = PathBuf::from(&self.config.output_dir);
graph.add_product_with_output_dir(inputs, vec![], crate::processors::names::SPHINX, hash.clone(), output_dir)?;
} else {
graph.add_product(inputs, vec![], crate::processors::names::SPHINX, hash.clone())?;
}
}
Ok(())
}
fn execute(&self, product: &Product) -> Result<()> {
self.execute_sphinx(product.primary_input())
}
fn clean(&self, product: &Product, verbose: bool) -> Result<usize> {
crate::processors::clean_output_dir(product, crate::processors::names::SPHINX, verbose)
}
fn config_json(&self) -> Option<String> {
serde_json::to_string(&self.config).ok()
}
}