file_integrity/
json.rs

1use std::fs::File;
2use std::io::Write;
3use serde_json;
4use crate::data::FileList;
5use my_logger::log;
6
7/// Write a `FileList` struct to a JSON file.
8///
9/// This function serializes a given `FileList` struct into a JSON-formatted string,
10/// and writes it to the specified output file. The JSON is formatted with indentation
11/// for readability.
12///
13/// If the serialization fails or if there are issues with file I/O, appropriate error
14/// messages are logged.
15///
16/// # Arguments
17///
18/// * `hash_set` - The `FileList` struct to be serialized and written to the JSON file.
19///
20/// # Examples
21///
22/// ```
23/// use file_integrity::{write_json_file, FileList};
24///
25/// let file_list = FileList {
26///     date: "2023-08-10".to_string(),
27///     files: vec![/* FileInfo entries */],
28/// };
29/// let file_name = "output.json" ;
30/// write_json_file(&file_list, &file_name);
31/// ```
32///
33/// # Errors
34///
35/// This function can return an error if serialization to JSON fails or if there are issues
36/// with file I/O operations.
37
38pub fn write_json_file(hash_set: &FileList, output_file_name: &str) {
39    log!("STATUS: Writing json: Please wait...");
40    let json_output = match serde_json::to_string_pretty(&hash_set) {
41        Ok(output) => output,
42        Err(err) => {
43            log!("ERROR: Failed to serialize to JSON: {}", err);
44            return;
45        }
46    };
47
48    let output_file = output_file_name;
49    match File::create(output_file) {
50        Ok(mut file) => {
51            if let Err(err) = file.write_all(json_output.as_bytes()) {
52                log!("ERROR: Failed to write JSON to file: {}", err);
53            } else {
54                log!("STATUS: Writing json: Success !");
55            }
56        }
57        Err(err) => {
58            log!("ERROR: Failed to create output file: {}", err);
59        }
60    }
61}