~llndqvst/notmuch-mvrs

ref: c9d0f1aff772878fe2ad5f312aa0bc0f2f752079 notmuch-mvrs/src/lib.rs -rw-r--r-- 2.2 KiB
c9d0f1afLukas Lindqvist Fix formating 6 months ago
                                                                                
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
pub mod config;
pub mod mover_config;
pub mod movers;
pub mod notmuch_db_loader;

// use dirs::data_local_dir;
use config::{ConfigShim, MoverOption};
use mover_config::MoverConfig;
use movers::mbsync::Mbsync;
use movers::mover::Mover;
use std::path::PathBuf;

static CONFIG_DIR: &'static str = "notmuch-mvrs/config.toml";
static DEFAULT_MOVER: &'static str = "mbsync";

pub fn init() {
    let p = dirs::config_dir().unwrap().join(PathBuf::from(CONFIG_DIR));
    let c = load_config(p).unwrap();
    if c.dry_run {
        dry_run()
    } else {
        run();
    }
}

fn load_config(location: PathBuf) -> Result<ConfigShim, String> {
    Ok(ConfigShim::new(location))
}

fn run_movers<T>(db: &notmuch::Database, movers: Vec<MoverOption>)
where
    T: Mover<PathBuf>,
{
    for m in movers {
        let p = PathBuf::from(m.target_dir);
        let mut t: MoverConfig<T> = MoverConfig::new(db, m.query.as_str(), p);
        match t.execute() {
            Err(e) => println!("{}", e),
            Ok(k) => println!("Moved: {} items", k),
        }
    }
}

pub fn run() {
    let p = dirs::config_dir().unwrap().join(PathBuf::from(CONFIG_DIR));
    let t = load_config(p).unwrap();
    match t.mover.as_str() {
        "mbsync" => {
            run_movers::<Mbsync>(&t.db, t.mover_options);
        }
        s => eprintln!("Not a recognized mover: {}", s),
    }
    println!("Reloading database with notmuch new");
    match notmuch::AtomicOperation::new(&t.db) {
        Ok(_) => (),
        Err(e) => eprintln!("{}", e),
    };
}

fn dry_run_movers<T>(db: notmuch::Database, movers: Vec<MoverOption>)
where
    T: Mover<PathBuf>,
{
    for m in movers {
        let p = PathBuf::from(m.target_dir);
        let mut t: MoverConfig<T> = MoverConfig::new(&db, m.query.as_str(), p);
        match t.dry_execute() {
            Err(e) => eprintln!("{}", e),
            Ok(k) => println!("Processed {} items", k),
        }
    }
}

pub fn dry_run() {
    let p = dirs::config_dir().unwrap().join(PathBuf::from(CONFIG_DIR));
    let t = load_config(p).unwrap();
    match t.mover.as_str() {
        "mbsync" => {
            dry_run_movers::<Mbsync>(t.db, t.mover_options);
        }
        s => eprintln!("Not a recognized mover: {}", s),
    }
}