Skip to content

Feature csv import #2669

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/atuin-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ futures = "0.3"
crypto_secretbox = "0.1.1"
generic-array = { version = "0.14", features = ["serde"] }
serde_with = "3.8.1"
csv = "1.1"

# encryption
rusty_paseto = { version = "0.7.0", default-features = false }
Expand All @@ -78,3 +79,4 @@ strum = { version = "0.26.2", features = ["strum_macros"] }
tokio = { version = "1", features = ["full"] }
pretty_assertions = { workspace = true }
testing_logger = "0.1.1"
tempfile ="3.3"
105 changes: 105 additions & 0 deletions crates/atuin-client/src/import/csv_history.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;

use async_trait::async_trait;
use csv::Reader;
use eyre::{Result, eyre};
use time::OffsetDateTime;

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

const HISTORY_FILE: &str = "history.csv"; // Global constant for history file

#[derive(Debug)]
pub struct CsvHistoryImporter;

fn default_histpath() -> Result<PathBuf> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default_histpath approach made sense for classic shell history import where there is usually an expected location for data, but I think in this case it isn't needed

Instead, we should make it so that the import csv subcommand takes a mandatory argument of the file to import

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's not a facility i'm seeing in any of the other importers to specify the location of a file as part of the command line parsing - am i missing it somewhere?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

trying to dig more on this (excuse my rust n00bness) - it looks like it would be either a modification to the main Importer class, which means everything would get an option, but only one of them would support it, or i create a single "one off" function to basically mimic async fn import but takes a path.

are there better options i'm not seeing?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ellie - any suggestions on the above comment?

let histpath = PathBuf::from(HISTORY_FILE);
if histpath.exists() {
Ok(histpath)
} else {
Err(eyre!(
"Could not find history file. Please create 'history.csv' in the current directory."
))
}
}

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

async fn new() -> Result<Self> {
let _ = default_histpath()?; // Ensure the file exists
Ok(Self)
}

async fn entries(&mut self) -> Result<usize> {
let file = File::open(default_histpath()?)?;
let reader = BufReader::new(file);
Ok(reader.lines().count() - 1) // Exclude header row
}

async fn load(self, h: &mut impl Loader) -> Result<()> {
let file = File::open(default_histpath()?)?;
let mut reader = Reader::from_reader(file);

for result in reader.records() {
let record = result?;
if let (Some(timestamp), Some(duration), Some(command)) =
(record.get(0), record.get(1), record.get(2))
{
let timestamp = timestamp
.parse::<i64>()
.ok()
.and_then(|t| OffsetDateTime::from_unix_timestamp(t).ok())
.unwrap_or_else(OffsetDateTime::now_utc);
let duration = duration.parse::<i64>().map_or(-1, |t| t * 1_000_000_000);

let imported = History::import()
.timestamp(timestamp)
.command(command.trim().to_string())
.duration(duration);

h.push(imported.build().into()).await?;
}
}
Ok(())
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::import::tests::TestLoader;
use itertools::assert_equal;
use std::fs;
use std::io::Write;
use tempfile::NamedTempFile;

#[tokio::test]
async fn test_parse_file() {
let mut file = NamedTempFile::new().unwrap();
writeln!(file, "timestamp,duration,command").unwrap();
writeln!(file, "1613322469,10,cargo install atuin").unwrap();
writeln!(file, "1613322470,5,ls -la").unwrap();
writeln!(file, "1613322471,3,git status").unwrap();

let path = file.path().to_path_buf();
fs::copy(&path, HISTORY_FILE).unwrap();

let mut importer = CsvHistoryImporter::new().await.unwrap();
assert_eq!(importer.entries().await.unwrap(), 3);

let mut loader = TestLoader::default();
importer.load(&mut loader).await.unwrap();

assert_equal(
loader.buf.iter().map(|h| h.command.as_str()),
["cargo install atuin", "ls -la", "git status"],
);

fs::remove_file(HISTORY_FILE).unwrap();
}
}
1 change: 1 addition & 0 deletions crates/atuin-client/src/import/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use memchr::Memchr;
use crate::history::History;

pub mod bash;
pub mod csv_history;
pub mod fish;
pub mod nu;
pub mod nu_histdb;
Expand Down
8 changes: 6 additions & 2 deletions crates/atuin/src/command/client/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ use atuin_client::{
database::Database,
history::History,
import::{
Importer, Loader, bash::Bash, fish::Fish, nu::Nu, nu_histdb::NuHistDb, replxx::Replxx,
resh::Resh, xonsh::Xonsh, xonsh_sqlite::XonshSqlite, zsh::Zsh, zsh_histdb::ZshHistDb,
Importer, Loader, bash::Bash, csv_history::CsvHistoryImporter, fish::Fish, nu::Nu,
nu_histdb::NuHistDb, replxx::Replxx, resh::Resh, xonsh::Xonsh, xonsh_sqlite::XonshSqlite,
zsh::Zsh, zsh_histdb::ZshHistDb,
},
};

Expand All @@ -26,6 +27,8 @@ pub enum Cmd {
ZshHistDb,
/// Import history from the bash history file
Bash,
/// Import history from user csv history file
CsvHistoryImporter,
/// Import history from the replxx history file
Replxx,
/// Import history from the resh history file
Expand Down Expand Up @@ -111,6 +114,7 @@ impl Cmd {
Self::Zsh => import::<Zsh, DB>(db).await,
Self::ZshHistDb => import::<ZshHistDb, DB>(db).await,
Self::Bash => import::<Bash, DB>(db).await,
Self::CsvHistoryImporter => import::<CsvHistoryImporter, DB>(db).await,
Self::Replxx => import::<Replxx, DB>(db).await,
Self::Resh => import::<Resh, DB>(db).await,
Self::Fish => import::<Fish, DB>(db).await,
Expand Down
Loading