tauri_typegen/build/
mod.rs

1pub mod dependency_resolver;
2pub mod output_manager;
3pub mod project_scanner;
4
5use crate::analysis::CommandAnalyzer;
6use crate::generators::generator::BindingsGenerator;
7use crate::interface::config::{ConfigError, GenerateConfig};
8use crate::interface::output::{Logger, ProgressReporter};
9use std::path::Path;
10
11pub use dependency_resolver::*;
12pub use output_manager::*;
13pub use project_scanner::*;
14
15/// Build-time code generation orchestrator
16pub struct BuildSystem {
17    logger: Logger,
18}
19
20impl BuildSystem {
21    pub fn new(verbose: bool, debug: bool) -> Self {
22        Self {
23            logger: Logger::new(verbose, debug),
24        }
25    }
26
27    /// Generate TypeScript bindings at build time
28    pub fn generate_at_build_time() -> Result<(), Box<dyn std::error::Error>> {
29        let build_system = Self::new(false, false);
30        build_system.run_generation()
31    }
32
33    /// Run the complete generation process
34    pub fn run_generation(&self) -> Result<(), Box<dyn std::error::Error>> {
35        let mut reporter = ProgressReporter::new(self.logger.clone(), 5);
36
37        reporter.start_step("Detecting Tauri project");
38        let project_scanner = ProjectScanner::new();
39        let project_info = match project_scanner.detect_project()? {
40            Some(info) => {
41                reporter.complete_step(Some(&format!(
42                    "Found project at {}",
43                    info.root_path.display()
44                )));
45                info
46            }
47            None => {
48                reporter.complete_step(Some("No Tauri project detected, skipping generation"));
49                return Ok(());
50            }
51        };
52
53        reporter.start_step("Loading configuration");
54        let config = self.load_configuration(&project_info)?;
55        reporter.complete_step(Some(&format!(
56            "Using {} validation with output to {}",
57            config.validation_library, config.output_path
58        )));
59
60        reporter.start_step("Setting up build dependencies");
61        self.setup_build_dependencies(&config)?;
62        reporter.complete_step(None);
63
64        reporter.start_step("Analyzing and generating bindings");
65        let generated_files = self.generate_bindings(&config)?;
66        reporter.complete_step(Some(&format!("Generated {} files", generated_files.len())));
67
68        reporter.start_step("Managing output");
69        let mut output_manager = OutputManager::new(&config.output_path);
70        output_manager.finalize_generation(&generated_files)?;
71        reporter.complete_step(None);
72
73        reporter.finish(&format!(
74            "Successfully generated TypeScript bindings for {} commands",
75            generated_files.len()
76        ));
77
78        Ok(())
79    }
80
81    fn load_configuration(
82        &self,
83        project_info: &ProjectInfo,
84    ) -> Result<GenerateConfig, ConfigError> {
85        // Try to load from tauri.conf.json first
86        if let Some(tauri_config_path) = &project_info.tauri_config_path {
87            if tauri_config_path.exists() {
88                match GenerateConfig::from_tauri_config(tauri_config_path) {
89                    Ok(config) => {
90                        self.logger
91                            .debug("Loaded configuration from tauri.conf.json");
92                        return Ok(config);
93                    }
94                    Err(e) => {
95                        self.logger.warning(&format!(
96                            "Failed to load config from tauri.conf.json: {}. Using defaults.",
97                            e
98                        ));
99                    }
100                }
101            }
102        }
103
104        // Try standalone config file
105        let standalone_config = project_info.root_path.join("typegen.json");
106        if standalone_config.exists() {
107            match GenerateConfig::from_file(&standalone_config) {
108                Ok(config) => {
109                    self.logger.debug("Loaded configuration from typegen.json");
110                    return Ok(config);
111                }
112                Err(e) => {
113                    self.logger.warning(&format!(
114                        "Failed to load config from typegen.json: {}. Using defaults.",
115                        e
116                    ));
117                }
118            }
119        }
120
121        // Use defaults
122        self.logger.debug("Using default configuration");
123        Ok(GenerateConfig::default())
124    }
125
126    fn setup_build_dependencies(
127        &self,
128        config: &GenerateConfig,
129    ) -> Result<(), Box<dyn std::error::Error>> {
130        // Set up cargo rerun directives
131        println!("cargo:rerun-if-changed={}", config.project_path);
132
133        // Watch for changes in configuration files
134        if Path::new("tauri.conf.json").exists() {
135            println!("cargo:rerun-if-changed=tauri.conf.json");
136        }
137        if Path::new("typegen.json").exists() {
138            println!("cargo:rerun-if-changed=typegen.json");
139        }
140
141        // Watch output directory for cleanup detection
142        if Path::new(&config.output_path).exists() {
143            println!("cargo:rerun-if-changed={}", config.output_path);
144        }
145
146        Ok(())
147    }
148
149    fn generate_bindings(
150        &self,
151        config: &GenerateConfig,
152    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
153        let mut analyzer = CommandAnalyzer::new();
154        let commands = analyzer.analyze_project(&config.project_path)?;
155
156        if commands.is_empty() {
157            self.logger
158                .info("No Tauri commands found. Skipping generation.");
159            return Ok(vec![]);
160        }
161
162        let validation = match config.validation_library.as_str() {
163            "zod" | "none" => Some(config.validation_library.clone()),
164            _ => return Err("Invalid validation library. Use 'zod' or 'none'".into()),
165        };
166
167        let mut generator = BindingsGenerator::new(validation);
168        let generated_files = generator.generate_models(
169            &commands,
170            analyzer.get_discovered_structs(),
171            &config.output_path,
172            &analyzer,
173        )?;
174
175        // Generate dependency visualization if requested
176        if config.should_visualize_deps() {
177            self.generate_dependency_visualization(&analyzer, &commands, &config.output_path)?;
178        }
179
180        Ok(generated_files)
181    }
182
183    fn generate_dependency_visualization(
184        &self,
185        analyzer: &CommandAnalyzer,
186        commands: &[crate::models::CommandInfo],
187        output_path: &str,
188    ) -> Result<(), Box<dyn std::error::Error>> {
189        use std::fs;
190
191        self.logger.debug("Generating dependency visualization");
192
193        let text_viz = analyzer.visualize_dependencies(commands);
194        let viz_file_path = Path::new(output_path).join("dependency-graph.txt");
195        fs::write(&viz_file_path, text_viz)?;
196
197        let dot_viz = analyzer.generate_dot_graph(commands);
198        let dot_file_path = Path::new(output_path).join("dependency-graph.dot");
199        fs::write(&dot_file_path, dot_viz)?;
200
201        self.logger.verbose(&format!(
202            "Generated dependency graphs: {} and {}",
203            viz_file_path.display(),
204            dot_file_path.display()
205        ));
206
207        Ok(())
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use tempfile::TempDir;
215
216    #[test]
217    fn test_build_system_creation() {
218        let build_system = BuildSystem::new(true, false);
219        assert!(build_system
220            .logger
221            .should_log(crate::interface::output::LogLevel::Verbose));
222    }
223
224    #[test]
225    fn test_load_default_configuration() {
226        let temp_dir = TempDir::new().unwrap();
227        let project_info = ProjectInfo {
228            root_path: temp_dir.path().to_path_buf(),
229            src_tauri_path: temp_dir.path().join("src-tauri"),
230            tauri_config_path: None,
231        };
232
233        let build_system = BuildSystem::new(false, false);
234        let config = build_system.load_configuration(&project_info).unwrap();
235
236        assert_eq!(config.validation_library, "zod");
237        assert_eq!(config.project_path, "./src-tauri");
238    }
239}