Skip to main content

devops_armory/toml_parser/
parser.rs

1use std::fs;
2use std::process::exit;
3
4use toml;
5
6use super::models::Root;
7
8/// Parse TOML based on Root struct. 
9/// File Path location set in parameters
10pub fn toml_parser(file_path: String) -> Result <Root, std::io::Error> {
11
12    let filename = file_path.to_string();
13
14    // Read the contents of the file using a `match` block 
15    // to return the `data: Ok(c)` as a `String` 
16    // or handle any `errors: Err(_)`.
17    let contents = match fs::read_to_string(&filename) {
18        // If successful return the files text as `contents`.
19        // `c` is a local variable.
20        Ok(c) => c,
21        // Handle the `error` case.
22        Err(e) => {
23            // Write `msg` to `stderr`.
24            eprintln!("Could not read file: {}: {}", filename, e);
25            // Exit the program with exit code `1`.
26            exit(1);
27        }
28    };
29
30    //println!("{}", contents);
31
32    // Use a match block to return the 
33    // file contents as a Root struct: Ok(d)
34    // or handle any errors: Err(e).
35    let data: Root = match toml::from_str(&contents) {
36        // If successful, return data as Root struct.
37        // d is a local variable.
38        Ok(d) => d,
39        // Handle the `error` case.
40        Err(e) => {
41            // Write error to stderr.
42            eprintln!("Unable to load data from {}", e);
43            // Exit the program with exit code 1.
44            exit(1);
45        }
46    };
47
48    Ok(data)
49
50}
51