diff --git a/src/import.rs b/src/commands/import.rs similarity index 54% rename from src/import.rs rename to src/commands/import.rs index 7cb741f..95cb06e 100644 --- a/src/import.rs +++ b/src/commands/import.rs @@ -2,14 +2,41 @@ use std::io::{self, BufRead}; use log::{error, info}; -use crate::db::{Entry, SqliteClipboardDb, detect_mime}; +use crate::db::{ + ClipboardDb, + Entry, + SqliteClipboardDb, + StashError, + detect_mime, +}; pub trait ImportCommand { - fn import_tsv(&self, input: impl io::Read); + /// Import clipboard entries from TSV format. + /// + /// # Arguments + /// + /// * `input` - A readable stream containing TSV lines, each of the form + /// `\t`. + /// * `max_items` - The maximum number of clipboard entries to keep after + /// import. If set to `u64::MAX`, no trimming occurs. + /// + /// # Returns + /// + /// * `Ok(())` if all entries are imported and trimming succeeds. + /// * `Err(StashError)` if any error occurs during import or trimming. + fn import_tsv( + &self, + input: impl io::Read, + max_items: u64, + ) -> Result<(), StashError>; } impl ImportCommand for SqliteClipboardDb { - fn import_tsv(&self, input: impl io::Read) { + fn import_tsv( + &self, + input: impl io::Read, + max_items: u64, + ) -> Result<(), StashError> { let reader = io::BufReader::new(input); let mut imported = 0; for line in reader.lines().map_while(Result::ok) { @@ -41,5 +68,10 @@ impl ImportCommand for SqliteClipboardDb { } } info!("Imported {imported} records from TSV into SQLite database."); + + // Trim database to max_items after import + self.trim_db(max_items)?; + info!("Trimmed clipboard database to max_items = {max_items}"); + Ok(()) } } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 34294bc..67e9950 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,5 +1,6 @@ pub mod decode; pub mod delete; +pub mod import; pub mod list; pub mod query; pub mod store; diff --git a/src/main.rs b/src/main.rs index eefb248..ceebedf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,19 +11,16 @@ use inquire::Confirm; mod commands; mod db; -mod import; -use crate::{ - commands::{ - decode::DecodeCommand, - delete::DeleteCommand, - list::ListCommand, - query::QueryCommand, - store::StoreCommand, - watch::WatchCommand, - wipe::WipeCommand, - }, +use crate::commands::{ + decode::DecodeCommand, + delete::DeleteCommand, import::ImportCommand, + list::ListCommand, + query::QueryCommand, + store::StoreCommand, + watch::WatchCommand, + wipe::WipeCommand, }; #[derive(Parser)] @@ -299,7 +296,9 @@ fn main() { let format = r#type.as_deref().unwrap_or("tsv"); match format { "tsv" => { - if let Err(e) = db.import_tsv(io::stdin(), cli.max_items) { + if let Err(e) = + ImportCommand::import_tsv(&db, io::stdin(), cli.max_items) + { log::error!("Failed to import TSV: {e}"); } },