aboutsummaryrefslogtreecommitdiffstats
path: root/atuin-client/src/import/nu.rs
blob: 0f1076048961bd156048152191588e0f9cfac03f (plain) (blame)
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
// import old shell history!
// automatically hoover up all that we can find

use std::{fs::File, io::Read, path::PathBuf};

use async_trait::async_trait;
use directories::BaseDirs;
use eyre::{eyre, Result};

use super::{unix_byte_lines, Importer, Loader};
use crate::history::History;

#[derive(Debug)]
pub struct Nu {
    bytes: Vec<u8>,
}

fn get_histpath() -> Result<PathBuf> {
    let base = BaseDirs::new().ok_or_else(|| eyre!("could not determine data directory"))?;
    let config_dir = base.config_dir().join("nushell");

    let histpath = config_dir.join("history.txt");
    if histpath.exists() {
        Ok(histpath)
    } else {
        Err(eyre!("Could not find history file."))
    }
}

#[async_trait]
impl Importer for Nu {
    const NAME: &'static str = "nu";

    async fn new() -> Result<Self> {
        let mut bytes = Vec::new();
        let path = get_histpath()?;
        let mut f = File::open(path)?;
        f.read_to_end(&mut bytes)?;
        Ok(Self { bytes })
    }

    async fn entries(&mut self) -> Result<usize> {
        Ok(super::count_lines(&self.bytes))
    }

    async fn load(self, h: &mut impl Loader) -> Result<()> {
        let now = chrono::Utc::now();

        let mut counter = 0;
        for b in unix_byte_lines(&self.bytes) {
            let s = match std::str::from_utf8(b) {
                Ok(s) => s,
                Err(_) => continue, // we can skip past things like invalid utf8
            };

            let cmd: String = s.replace("<\\n>", "\n");

            let offset = chrono::Duration::nanoseconds(counter);
            counter += 1;

            h.push(History::new(
                now - offset, // preserve ordering
                cmd,
                String::from("unknown"),
                -1,
                -1,
                None,
                None,
                None,
            ))
            .await?;
        }

        Ok(())
    }
}