aboutsummaryrefslogtreecommitdiff
path: root/src/tool.rs
blob: c431c09d208ead60e27fdf27c2867c2c0f07d1ef (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
use crate::state::{Config, T_IMPRESSIONS_RAW, T_IMPRESSIONS_WEIGHTED};
use anyhow::{anyhow, bail, Result};
use redb::{Database, ReadableTable};

pub fn tool_main(config: Config, action: &str, args: Vec<String>) -> Result<()> {
    match action {
        "move_host" => {
            let oldhost = args.get(0).ok_or(anyhow!("2nd arg is old host"))?;
            let newhost = args.get(1).ok_or(anyhow!("3rd arg is new host"))?;
            move_host(config, oldhost, newhost)?;
        }
        _ => bail!("unknown action"),
    }
    Ok(())
}

pub fn move_host(config: Config, oldhost: &str, newhost: &str) -> Result<()> {
    let db = Database::open(config.database_path)?;

    let txn = db.begin_write()?;
    {
        let mut t_impressions = txn.open_table(T_IMPRESSIONS_RAW)?;
        let mut t_weighted = txn.open_table(T_IMPRESSIONS_WEIGHTED)?;

        let old_imp = t_impressions
            .remove(oldhost)?
            .map(|g| g.value())
            .unwrap_or_default();
        let old_wei = t_weighted
            .remove(oldhost)?
            .map(|g| g.value())
            .unwrap_or_default();

        let new_imp = t_impressions
            .get(newhost)?
            .map(|g| g.value())
            .unwrap_or_default();
        let new_wei = t_weighted
            .get(newhost)?
            .map(|g| g.value())
            .unwrap_or_default();

        println!("impressions old={old_imp} new={new_imp}");
        println!("weighted old={old_wei} new={new_wei}");
        t_impressions.insert(newhost, old_imp + new_imp)?;
        t_weighted.insert(newhost, old_wei + new_wei)?;
    }
    txn.commit()?;

    Ok(())
}