weather_cli/
user_setup.rs

1use anyhow::{anyhow, Context, Result};
2
3use crate::{constants::API_JSON_NAME, make_json_file_name, types::user_settings::UserSetting};
4
5/// Sets up an API key.
6pub fn setup_api(api_key_input: String) -> Result<()> {
7    use std::{fs::File, io::Write};
8
9    use regex::Regex;
10
11    use crate::{get_executable_directory, types::user_settings::ApiSetting};
12
13    let executable_dir = get_executable_directory()?;
14    let regex = Regex::new(r"^[a-zA-Z0-9]+$")?;
15
16    if api_key_input.len() != 32 || !regex.is_match(&api_key_input) {
17        return Err(anyhow!("Please enter a valid key!"));
18    } else {
19        let new_api_setting = ApiSetting { key: api_key_input };
20
21        let api_json_string = serde_json::to_string(&new_api_setting)?;
22        File::create(format!(
23            "{}/{}",
24            executable_dir,
25            make_json_file_name(API_JSON_NAME)
26        ))?
27        .write_all(api_json_string.as_bytes())?;
28
29        println!("Successfully updated your key data!");
30    }
31
32    Ok(())
33}
34
35/// Update user setting.
36pub fn update_user_settings(setting_args: &UserSetting) -> Result<()> {
37    use std::{fs::File, io::Write};
38
39    use crate::{
40        constants::USER_SETTING_JSON_NAME,
41        types::user_settings::City,
42        {get_executable_directory, read_json_file},
43    };
44
45    let mut json_data = read_json_file::<UserSetting>(USER_SETTING_JSON_NAME)?; // ERROR
46
47    // 1. City
48    {
49        let mut using_city: Option<City> = None;
50        if let Some(args_city) = &setting_args.city {
51            using_city = Some(City {
52                name: String::from(&args_city.name),
53                lat: args_city.lat,
54                lon: args_city.lon,
55                country: String::from(&args_city.country),
56            });
57        }
58        json_data.city = using_city;
59    }
60
61    // 2. Unit
62    json_data.units.clone_from(&setting_args.units);
63
64    let json_string = serde_json::to_string(&json_data)?;
65
66    // Generate a new setting file.
67    let executable_dir = get_executable_directory()?;
68    File::create(format!(
69        "{}/{}",
70        executable_dir,
71        make_json_file_name(USER_SETTING_JSON_NAME)
72    ))?
73    .write_all(json_string.as_bytes())
74    .context(format!(
75        "Failed to write a JSON file: {}",
76        USER_SETTING_JSON_NAME
77    ))?;
78
79    Ok(())
80}