diary_cli/
uncommit.rs

1use std::fs;
2use lazy_db::*;
3use soulog::*;
4use crate::{archive::Archive, home_dir, list, sort};
5
6pub fn uncommmit(uid: String, is_moc: bool, mut logger: impl Logger) {
7    let archive = Archive::load(logger.hollow());
8    
9    let path = if is_moc {
10        archive.database().path().join("mocs").join(&uid)
11    } else {
12        archive.database().path().join("entries").join(&uid)
13    };
14    
15    // Check if path exists
16    if !path.is_dir() {
17        println!("{path:?}");
18        if is_moc {
19            log!((logger.error) Remove("moc of uid '{uid}' doesn't exist") as Fatal);
20        } else {
21            log!((logger.error) Remove("entry of uid '{uid}' doesn't exist") as Fatal);
22        } return logger.crash();
23    }
24
25    // Confirm with the user about the action
26    let expected = "mhm, yep, I do wanna remove this entry/moc permanently";
27    log!((logger.vital) Remove("To confirm with removing an entry/moc of uid '{uid}' PERMANENTLY enter the phrase below (without quotes):") as Log);
28    if_err!((logger) [Remove, err => ("Entered phrase incorrect, please retry")] retry {
29        log!((logger.vital) Remove("\"{expected}\"") as Log);
30        let input = logger.ask("Remove", "Enter the phrase");
31        if &input[0..input.len() - 1] != expected { Err(()) }
32        else { Ok(()) }
33    });
34    
35    // Backup archive before modification
36    log!((logger) Remove("Backing up archive before removal, if you want to revert back, run `diary-cli rollback -f`"));
37    let _ = std::fs::remove_file(home_dir().join("backup.ldb")); // Clean up
38    Archive::backup(home_dir().join("backup.ldb"), logger.hollow());
39
40    log!((logger) Remove("Removing entry/moc of uid '{uid}'..."));
41
42    // Remove the entry/moc
43    sort::sort(logger.hollow());
44    if_err!((logger) [Remove, err => ("While removing entry/moc from archive: {err:?}")] retry fs::remove_dir_all(&path));
45
46    // Update order lists
47    if is_moc { return; }
48
49    let sorted_container = if_err!((logger) [Remove, err => ("While loading sorted list: {err:?}")] retry search_database!((archive.database()) /order/sorted));
50    let sorted: Box<[String]> = sort::read_sorted(&archive, logger.hollow()).into_vec().into_iter().filter(|x| *x != uid).collect();
51
52    list::write(&sorted, |f, x| LazyData::new_string(f, x), &sorted_container, logger.hollow());
53
54    // Update itver
55    log!((logger) Commit("Updating archive itver..."));
56    if_err!((logger) [Commit, err => ("While update archive itver: {err:?}")] retry write_database!((archive.database()) itver = new_u16(archive.itver + 1)));
57
58    log!((logger.vital) Remove("Successfully removed entry/moc of uid '{uid}'") as Log)
59}