2025-01-16 13:26:07 +01:00

54 lines
1.7 KiB
Rust

use std::path::Path;
use std::fs::File;
use std::io::{ErrorKind, Read};
use std::process::exit;
use std::collections::HashMap;
pub fn get_json(path: &Path) -> HashMap<String, String> {
let mut data = HashMap::new();
let json_data = read_file(path);
let parsed_data = json::parse(json_data.as_str()).unwrap_or_else(|e| {
eprintln!("[ERROR] Invalid JSON: {e}");
exit(1);
});
let ha_url = parsed_data["ha_url"].clone();
let access_token = parsed_data["access_token"].clone();
let light_entity_id = parsed_data["light_entity_id"].clone();
if ha_url.is_null() || access_token.is_null() || light_entity_id.is_null() {
eprintln!("[ERROR] JSON data is NULL");
exit(1);
}
data.insert("ha_url".to_string(), json::stringify(ha_url));
data.insert("access_token".to_string(), json::stringify(access_token));
data.insert("light_entity_id".to_string(), json::stringify(light_entity_id));
data
}
fn read_file(path: &Path) -> String {
let read_result = File::open(path);
let mut result = String::new();
match read_result {
Ok(mut t) => {
// file exists
println!("[INFO] JSON file located, reading ...");
match t.read_to_string(&mut result) {
// handling the reading
Ok(_r) => result,
Err(e) => panic!("[ERROR] While reading the file: {e}"),
}
},
Err(err) => match err.kind() {
ErrorKind::NotFound => {
eprintln!("[ERROR] The file '{}' does not exist", path.display());
exit(1);
},
_ => panic!("[ERROR] Unexpected error, closing ..."),
}
}
}