Skip to main content

lechange_core/output/
writer.rs

1//! File output writer for writing results to files
2
3use crate::error::Result;
4use std::path::Path;
5
6/// Output file writer
7pub struct OutputWriter;
8
9impl OutputWriter {
10    /// Write a list of values to a text file
11    pub fn write_text(
12        output_dir: &Path,
13        name: &str,
14        values: &[&str],
15        separator: &str,
16    ) -> Result<()> {
17        let path = output_dir.join(format!("{}.txt", name));
18        let content = values.join(separator);
19        std::fs::write(&path, content)?;
20        Ok(())
21    }
22
23    /// Write a JSON array to a file
24    pub fn write_json(output_dir: &Path, name: &str, values: &[&str]) -> Result<()> {
25        let path = output_dir.join(format!("{}.json", name));
26        let content = super::json_format::format_json_array(values);
27        std::fs::write(&path, content)?;
28        Ok(())
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35    use tempfile::TempDir;
36
37    #[test]
38    fn test_write_text() {
39        let dir = TempDir::new().unwrap();
40        OutputWriter::write_text(dir.path(), "files", &["a.rs", "b.rs", "c.rs"], "\n").unwrap();
41        let content = std::fs::read_to_string(dir.path().join("files.txt")).unwrap();
42        assert_eq!(content, "a.rs\nb.rs\nc.rs");
43    }
44
45    #[test]
46    fn test_write_text_custom_separator() {
47        let dir = TempDir::new().unwrap();
48        OutputWriter::write_text(dir.path(), "files", &["a.rs", "b.rs"], ",").unwrap();
49        let content = std::fs::read_to_string(dir.path().join("files.txt")).unwrap();
50        assert_eq!(content, "a.rs,b.rs");
51    }
52
53    #[test]
54    fn test_write_json() {
55        let dir = TempDir::new().unwrap();
56        OutputWriter::write_json(dir.path(), "files", &["a.rs", "b.rs"]).unwrap();
57        let content = std::fs::read_to_string(dir.path().join("files.json")).unwrap();
58        assert_eq!(content, r#"["a.rs","b.rs"]"#);
59    }
60
61    #[test]
62    fn test_write_json_empty() {
63        let dir = TempDir::new().unwrap();
64        OutputWriter::write_json(dir.path(), "files", &[]).unwrap();
65        let content = std::fs::read_to_string(dir.path().join("files.json")).unwrap();
66        assert_eq!(content, "[]");
67    }
68
69    #[test]
70    fn test_write_json_escaping() {
71        let dir = TempDir::new().unwrap();
72        OutputWriter::write_json(dir.path(), "files", &["path\"with\"quotes"]).unwrap();
73        let content = std::fs::read_to_string(dir.path().join("files.json")).unwrap();
74        assert!(content.contains(r#"\""#));
75        // Verify it's valid JSON structure
76        assert!(content.starts_with('['));
77        assert!(content.ends_with(']'));
78    }
79}