rush_ecs_parser/
utils.rs

1use rush_ecs_core::blueprint::BlueprintString;
2use std::{
3    fs::{read_dir, read_to_string},
4    path::Path,
5};
6
7/// Load Blueprint from file
8///
9/// Loads blueprint from a file directly. Panics when
10/// path is invalid
11///
12/// Returns a [`BlueprintString`] of the entire blueprint
13pub fn file_to_string(path: &Path) -> BlueprintString {
14    // expecting valid path
15    read_to_string(path).expect("invalid path")
16}
17
18/// Load Blueprint from Directory
19///
20/// Loads blueprint from combination of files in
21/// a given directory. Panics when path is invalid.
22///
23/// Returns a [`BlueprintString`] of the entire combined
24/// blueprint separated with an empty line (\n)
25///
26/// Example:
27///
28/// file1_contents
29/// -> Empty line
30/// file2_contents
31///
32pub fn dir_to_string(path: &Path) -> BlueprintString {
33    let list_of_files = read_dir(path).expect("invalid path");
34
35    // holds the entire blueprint string
36    let mut loaded_string = String::default();
37
38    // loop over files in given directory
39    for de in list_of_files {
40        // expecting valid path
41        let dir_entry = de.expect("invalid directory entry");
42        let filepath = dir_entry.path();
43        let content = read_to_string(filepath).expect("invalid path");
44
45        // combine
46        loaded_string += format!("{content}\n").as_str();
47    }
48
49    loaded_string
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_file_to_string() {
58        let path = Path::new("mock/fixtures/utils/file_to_string");
59        let string = file_to_string(path);
60        assert_eq!(string, "abcd\n");
61    }
62
63    #[test]
64    fn test_dir_to_string() {
65        let path = Path::new("mock/fixtures/utils/dir_to_string");
66        let string = dir_to_string(path);
67        assert_eq!(string, "a\n\nb\n\n");
68    }
69}