diary_cli/
pull.rs

1use soulog::*;
2use std::{path::PathBuf, fs};
3use crate::{archive::Archive, unwrap_opt};
4
5pub fn pull(path: PathBuf, file_name: String, is_moc: bool, uid: String, one_file: bool, mut logger: impl Logger) {
6    let archive = Archive::load(logger.hollow());
7
8    if_err!((logger) {fs::create_dir_all(&path)} else(err) {
9        log!((logger.vital) Pull("While initialising path '{}': {err:?}; ignoring error...", path.to_string_lossy()) as Inconvenience) 
10    });
11    
12    if is_moc {
13        log!((logger) Pull("Pulling moc with uid '{uid}' from archive..."));
14        pull_moc(archive, path, file_name, uid, logger.hollow());
15    } else {
16        log!((logger) Pull("Pulling entry with uid '{uid}' from archive..."));
17        pull_entry(archive, path, file_name, uid, one_file, logger.hollow());
18    }
19
20    log!((logger.vital) Pull("Successfully pulled config file from archive") as Log);
21}
22
23fn pull_entry(archive: Archive, path: PathBuf, file_name: String, uid: String, one_file: bool, mut logger: impl Logger) {
24    let error_msg = format!("Entry of uid '{uid}' not found in archive");
25    let mut entry = unwrap_opt!((archive.get_entry(uid, logger.hollow())) with logger, format: Pull("{error_msg}"));
26    std::mem::drop(error_msg);
27
28    let map = entry.pull(&path, one_file, logger.hollow());
29    let contents = if_err!((logger) [Pull, err => ("While encoding entry toml: {err:?}")] retry toml::to_string_pretty(&map));
30    
31    let path = path.join(file_name);
32    if_err!((logger) [Pull, err => ("While writing toml to path '{}'", path.to_string_lossy())] retry std::fs::write(&path, &contents));
33}
34
35fn pull_moc(archive: Archive, path: PathBuf, file_name: String, uid: String, mut logger: impl Logger) {
36    let error_msg = format!("moc of uid '{uid}' not found in archive");
37    let mut moc = unwrap_opt!((archive.get_moc(uid, logger.hollow())) with logger, format: Pull("{error_msg}"));
38    std::mem::drop(error_msg);
39
40    let map = moc.pull(logger.hollow());
41    let contents = if_err!((logger) [Pull, err => ("While encoding moc toml: {err:?}")] retry toml::to_string_pretty(&map));
42    
43    let path = path.join(file_name);
44    if_err!((logger) [Pull, err => ("While writing toml to path '{}'", path.to_string_lossy())] retry std::fs::write(&path, &contents));
45}