Skip to main content

olai_codegen/
output.rs

1use std::fs;
2use std::path::Path;
3
4use crate::Result;
5use crate::codegen::GeneratedCode;
6
7/// Return the appropriate "do not edit" header for a given file path.
8///
9/// Python uses `#` comments; Rust/TypeScript/JavaScript (and anything else) use `//`.
10fn generated_header(path: &str) -> &'static str {
11    if path.ends_with(".py") || path.ends_with(".pyi") {
12        "# @generated — do not edit by hand.\n"
13    } else {
14        "// @generated — do not edit by hand.\n"
15    }
16}
17
18pub fn write_generated_code(generated_code: &GeneratedCode, output_dir: &Path) -> Result<()> {
19    fs::create_dir_all(output_dir)?;
20
21    for (relative_path, content) in &generated_code.files {
22        let file_path = output_dir.join(relative_path);
23
24        if let Some(parent) = file_path.parent() {
25            fs::create_dir_all(parent)?;
26        }
27
28        let header = generated_header(relative_path);
29        let final_content = if content.starts_with(header) {
30            content.clone()
31        } else {
32            format!("{header}{content}")
33        };
34
35        fs::write(&file_path, final_content)?;
36    }
37
38    tracing::info!("Successfully wrote all generated files");
39    Ok(())
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use std::collections::HashMap;
46    use tempfile::TempDir;
47
48    fn create_test_generated_code() -> GeneratedCode {
49        let mut files = HashMap::new();
50        files.insert(
51            "test_handler.rs".to_string(),
52            "// Test handler content\npub trait TestHandler {}\n".to_string(),
53        );
54        files.insert(
55            "test_routes.rs".to_string(),
56            "// Test routes content\npub fn test_route() {}\n".to_string(),
57        );
58
59        GeneratedCode { files }
60    }
61
62    #[test]
63    fn test_write_generated_code() {
64        let temp_dir = TempDir::new().unwrap();
65        let generated_code = create_test_generated_code();
66
67        let result = write_generated_code(&generated_code, temp_dir.path());
68        assert!(result.is_ok());
69
70        assert!(temp_dir.path().join("test_handler.rs").exists());
71        assert!(temp_dir.path().join("test_routes.rs").exists());
72    }
73}