hbd/cmd/
add.rs

1use crate::{
2    error::HbdResult,
3    files::storage::Storage,
4    utils::{check_exists::check_user_exists, date::DateAndYear},
5};
6
7
8pub fn add(user: &str, birth_date: &str) -> HbdResult<()> {
9    let mut storage_birthdays = Storage::read_from_json()?;
10
11    let formatted_date = DateAndYear::from_date_str(birth_date)?;
12
13    // If the user exists, we can't proceed!
14    if check_user_exists(&storage_birthdays, user) {
15        println!("A person with the name `{user}` already exists.\nUse `rename` to change that person's name, or, add this person with another name.");
16        std::process::exit(1)
17    }
18
19    if let Some(birthdays) = storage_birthdays
20        .birthdays
21        .get_mut(formatted_date.date_u16())
22    {
23        birthdays.push(user.to_owned());
24    } else {
25        storage_birthdays
26            .birthdays
27            .insert(*formatted_date.date_u16(), vec![user.to_owned()]);
28    }
29
30    if let Some(year) = formatted_date.year() {
31        storage_birthdays.ages.insert(user.to_owned(), *year);
32    }
33
34
35    storage_birthdays.write_to_storage()?;
36
37    Ok(())
38}