|
| 1 | +use std::fs; |
| 2 | +use std::path::Path; |
| 3 | + |
| 4 | +use anyhow::{Context, Result}; |
| 5 | +use tracing::info; |
| 6 | + |
| 7 | +use crate::config::load_config_for_graph; |
| 8 | +use crate::files::ensure_output_dir; |
| 9 | +use crate::graph::Format; |
| 10 | +use crate::optimization::OptimizationMode; |
| 11 | +use crate::transforms::yaml_loader::build_graph_and_executor_from_yaml; |
| 12 | + |
| 13 | +/// Run graph-based execution targeting a single output format. |
| 14 | +/// |
| 15 | +/// The transform graph is resolved automatically from the `transforms` YAML |
| 16 | +/// file referenced in `config_path`. The shortest path (according to |
| 17 | +/// `optimization`) from the detected source format to `target` is found, |
| 18 | +/// and every intermediate and final format is produced. |
| 19 | +/// |
| 20 | +/// # Errors |
| 21 | +/// |
| 22 | +/// Returns an error when: |
| 23 | +/// * the config file cannot be read or parsed, |
| 24 | +/// * no `transforms` key is present in the config, |
| 25 | +/// * `target` is not a recognised format, |
| 26 | +/// * `target` is not reachable from the source format, |
| 27 | +/// * any transform in the execution plan fails. |
| 28 | +pub fn run_target( |
| 29 | + config_path: &str, |
| 30 | + target: &str, |
| 31 | + dry_run: bool, |
| 32 | + optimization: Option<OptimizationMode>, |
| 33 | +) -> Result<()> { |
| 34 | + let target_format = target |
| 35 | + .parse::<Format>() |
| 36 | + .with_context(|| format!("'{}' is not a valid target format", target))?; |
| 37 | + |
| 38 | + run_impl(config_path, Some(vec![target_format]), dry_run, optimization) |
| 39 | +} |
| 40 | + |
| 41 | +/// Run graph-based execution targeting all formats reachable from the source. |
| 42 | +/// |
| 43 | +/// The transform graph is resolved automatically from the `transforms` YAML |
| 44 | +/// file referenced in `config_path`. Every format reachable from the source |
| 45 | +/// format is produced in dependency order. |
| 46 | +/// |
| 47 | +/// # Errors |
| 48 | +/// |
| 49 | +/// Returns an error when: |
| 50 | +/// * the config file cannot be read or parsed, |
| 51 | +/// * no `transforms` key is present in the config, |
| 52 | +/// * no output formats are reachable from the source format, |
| 53 | +/// * any transform in the execution plan fails. |
| 54 | +pub fn run_all( |
| 55 | + config_path: &str, |
| 56 | + dry_run: bool, |
| 57 | + optimization: Option<OptimizationMode>, |
| 58 | +) -> Result<()> { |
| 59 | + run_impl(config_path, None, dry_run, optimization) |
| 60 | +} |
| 61 | + |
| 62 | +/// Shared implementation for `run_target` and `run_all`. |
| 63 | +/// |
| 64 | +/// `explicit_targets` is `Some(vec)` for `--target` mode and `None` for |
| 65 | +/// `--all` mode (targets are discovered dynamically from the graph). |
| 66 | +fn run_impl( |
| 67 | + config_path: &str, |
| 68 | + explicit_targets: Option<Vec<Format>>, |
| 69 | + dry_run: bool, |
| 70 | + optimization: Option<OptimizationMode>, |
| 71 | +) -> Result<()> { |
| 72 | + if dry_run { |
| 73 | + info!("Dry-run mode enabled — no files will be created and no commands will be executed"); |
| 74 | + } |
| 75 | + info!("Running graph-based build pipeline"); |
| 76 | + |
| 77 | + let config = load_config_for_graph(config_path)?; |
| 78 | + info!("Loaded config successfully"); |
| 79 | + |
| 80 | + let transforms_path = config.transforms.as_deref().ok_or_else(|| { |
| 81 | + anyhow::anyhow!( |
| 82 | + "Graph-based execution requires a 'transforms' key in the config file \ |
| 83 | + pointing to a YAML transform configuration" |
| 84 | + ) |
| 85 | + })?; |
| 86 | + |
| 87 | + let (graph, executor) = build_graph_and_executor_from_yaml(transforms_path)?; |
| 88 | + info!("Loaded transform graph from '{}'", transforms_path); |
| 89 | + |
| 90 | + let opt_mode = optimization.unwrap_or(config.optimization); |
| 91 | + info!(optimization = %opt_mode, "Using optimization mode"); |
| 92 | + |
| 93 | + // Derive the source format from the config's input field. |
| 94 | + let source_format: Format = config |
| 95 | + .input_format() |
| 96 | + .to_string() |
| 97 | + .parse() |
| 98 | + .with_context(|| { |
| 99 | + format!( |
| 100 | + "Could not map input format '{}' to a known graph format", |
| 101 | + config.input_format() |
| 102 | + ) |
| 103 | + })?; |
| 104 | + |
| 105 | + // Determine which formats to build. |
| 106 | + let targets: Vec<Format> = match explicit_targets { |
| 107 | + Some(t) => t, |
| 108 | + None => { |
| 109 | + // --all: discover every format reachable from the source. |
| 110 | + let reachable = graph.reachable_from(source_format); |
| 111 | + if reachable.is_empty() { |
| 112 | + anyhow::bail!( |
| 113 | + "No output formats are reachable from '{}' in the transform graph", |
| 114 | + source_format |
| 115 | + ); |
| 116 | + } |
| 117 | + info!( |
| 118 | + "Discovered {} reachable output format(s): {}", |
| 119 | + reachable.len(), |
| 120 | + reachable |
| 121 | + .iter() |
| 122 | + .map(|f| f.to_string()) |
| 123 | + .collect::<Vec<_>>() |
| 124 | + .join(", ") |
| 125 | + ); |
| 126 | + reachable |
| 127 | + } |
| 128 | + }; |
| 129 | + |
| 130 | + // Build the minimal DAG that covers all targets. |
| 131 | + let dag = graph |
| 132 | + .build_multi_target_dag_with_mode(source_format, &targets, opt_mode) |
| 133 | + .ok_or_else(|| { |
| 134 | + anyhow::anyhow!( |
| 135 | + "Could not build an execution plan: one or more target formats \ |
| 136 | + are not reachable from '{}' in the transform graph", |
| 137 | + source_format |
| 138 | + ) |
| 139 | + })?; |
| 140 | + |
| 141 | + let input_stem = Path::new(&config.input) |
| 142 | + .file_stem() |
| 143 | + .and_then(|s| s.to_str()) |
| 144 | + .unwrap_or("document"); |
| 145 | + |
| 146 | + let output_dir = if dry_run { |
| 147 | + let path = std::path::PathBuf::from(&config.output_dir); |
| 148 | + info!( |
| 149 | + "[DRY RUN] Would create output directory: {}", |
| 150 | + path.display() |
| 151 | + ); |
| 152 | + for target in &targets { |
| 153 | + let output_path = path.join(format!("{}.{}", input_stem, target)); |
| 154 | + info!("[DRY RUN] Would write '{}' output to: {}", target, output_path.display()); |
| 155 | + } |
| 156 | + return Ok(()); |
| 157 | + } else { |
| 158 | + ensure_output_dir(&config.output_dir)? |
| 159 | + }; |
| 160 | + |
| 161 | + // Read and execute. |
| 162 | + let content = fs::read_to_string(&config.input) |
| 163 | + .with_context(|| format!("Failed to read input file: {}", config.input))?; |
| 164 | + |
| 165 | + info!("Executing graph-based pipeline"); |
| 166 | + let results = executor |
| 167 | + .execute(&dag, source_format, content) |
| 168 | + .context("Graph execution failed")?; |
| 169 | + |
| 170 | + // Write each produced format to disk (skip the source format). |
| 171 | + for (format, output_content) in &results { |
| 172 | + if *format == source_format { |
| 173 | + continue; |
| 174 | + } |
| 175 | + let output_path = output_dir.join(format!("{}.{}", input_stem, format)); |
| 176 | + fs::write(&output_path, output_content) |
| 177 | + .with_context(|| format!("Failed to write output to '{}'", output_path.display()))?; |
| 178 | + info!("✔ Output written to: {}", output_path.display()); |
| 179 | + } |
| 180 | + |
| 181 | + Ok(()) |
| 182 | +} |
0 commit comments