devops_armory/toml_parser/
parser.rs

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