aboutsummaryrefslogtreecommitdiff
path: root/src/commands/mod.rs
blob: b1c5f510e3e9098585a846125c786dcc87cd82d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std::{
    fs,
    io::{self,Result,Write},
    path::PathBuf,
};

mod sync;

use crate::{Config,Entry};
use crate::arguments::*;

fn save_config(config: &Config, path: &PathBuf) -> Result<()> {
    let toml = toml::to_string(config).unwrap();
    fs::write(path.join("configs.toml"), toml)?;
    Ok(())
}

pub fn modify_command(
    config: &mut Config,
    args: ModifyArgs,
    configs_path: &PathBuf,
) -> Result<()> {

    if config.contains_key(&args.name) { loop {
        let mut input = String::new();

        print!("Entry already exists for {}. Overwrite it? (y/n) ", &args.name);
        let _ = io::stdout().flush();
        io::stdin()
            .read_line(&mut input)
            .expect("Failed to read user input.");

        match input.to_lowercase().trim() {
            "y" => break,
            "n" => return Ok(()),
            _ => {
                println!("Try again :)");
                continue;
            },
        };
    }}

    let entry = Entry { file: args.file, parent: args.dest };    
    config.insert(args.name, entry);
    save_config(&config, configs_path)?;

    Ok(())
}

pub fn remove_command(
    config: &mut Config,
    args: RemoveArgs,
    configs_path: &PathBuf
) -> Result<()> {

    if !config.contains_key(&args.name) {
        panic!("Such an entry does not exist.");
    }
    config.remove(&args.name);
    save_config(&config, configs_path)?;

    Ok(())
}

pub fn list_command(config: &Config) {
    for (key,entry) in config {
        println!(r#""{}" - src: {}, dest: {}"#, key, entry.file.to_str().unwrap(), entry.parent.to_str().unwrap());
    }
}

pub fn sync_command(config: &Config, args: SyncArgs, configs_path: &PathBuf) {
    if args.all {
        sync::sync_all(config, configs_path, args.force);
        return
    }

    for name in &args.names {
        let entry = match config.get(name) {
            Some(e) => e,
            None => {
                eprintln!(r#"Entry "{name}" not found."#);
                continue;
            },
        };

        sync::sync_config(name, entry, configs_path, &args.force);
    }
}