Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/Zai-Kun/rustyclip
Browse files Browse the repository at this point in the history
  • Loading branch information
Zai-Kun committed Nov 25, 2024
2 parents c75138f + bba0839 commit 1d03f0f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 23 deletions.
14 changes: 8 additions & 6 deletions src/args_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,23 @@ pub struct ListCommand {}
pub struct StoreCommand {}

#[derive(FromArgs, Debug)]
/// Get a clipboard item by query
/// Get a clipboard item by entry
#[argh(subcommand, name = "get")]
pub struct GetCommand {
#[argh(positional)]
/// it must start with an int (index to the item) sperated by ':' or just an int
pub query: Option<String>,
/// the entry must be either an integer index (starting from 1) or an integer index followed by a colon `:`
/// and a descriptive text (e.g., `1` or `1: some descriptive text`).
pub entry: Option<String>,
}

#[derive(FromArgs, Debug)]
/// Remove a clipboard item by query
/// Remove a clipboard item by entry
#[argh(subcommand, name = "remove")]
pub struct RemoveCommand {
#[argh(positional)]
/// it must start with an int (index to the item) sperated by ':' or just an int
pub query: Option<String>,
/// the entry must be either an integer index (starting from 1) or an integer index followed by a colon `:`
/// and a descriptive text (e.g., `1` or `1: some descriptive text`).
pub entry: Option<String>,
}

#[derive(FromArgs, Debug)]
Expand Down
19 changes: 17 additions & 2 deletions src/data_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ impl DataManager {
pub fn add_item(&mut self, data: &[u8]) -> Result<(), Box<dyn Error>> {
let key = xxh3_64(data).to_string();

if self.manifest_data.iter().any(|item| item.file_name == key) {
if let Some(index) = self
.manifest_data
.iter()
.position(|item| item.file_name == key)
{
self.put_item_on_top(index)?;
return Ok(());
}

Expand Down Expand Up @@ -89,6 +94,16 @@ impl DataManager {
self.manifest_data.clear();
self.write_manifest()
}

pub fn put_item_on_top(&mut self, p: usize) -> Result<(), io::Error> {
if p >= self.manifest_data.len() {
return Ok(());
}
let i = self.manifest_data.remove(p);
self.manifest_data.insert(0, i);
self.write_manifest()?;
Ok(())
}
}

fn load_manifest(data_path: &Path) -> Result<Vec<ClipboardItem>, io::Error> {
Expand All @@ -106,7 +121,7 @@ fn generate_preview_and_mime_type(data: &[u8]) -> Result<(String, String), Box<d
if let Ok(preview) = str::from_utf8(data) {
let preview = preview.trim();
return Ok((
preview[..(PREVIEW_LENGTH+1).min(preview.len())].to_string(),
preview[..(PREVIEW_LENGTH + 1).min(preview.len())].to_string(),
"text/plain".to_string(),
));
}
Expand Down
36 changes: 21 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ fn run_app() -> Result<(), Box<dyn Error>> {
Commands::List(_) => list_items(&data_manager),
Commands::Store(_) => store_item(&mut data_manager),
Commands::Clear(_) => clear_database(&mut data_manager),
Commands::Remove(remove_cmd) => remove_item(&mut data_manager, remove_cmd.query),
Commands::Get(get_cmd) => get_item(&data_manager, get_cmd.query),
Commands::Remove(remove_cmd) => remove_item(&mut data_manager, remove_cmd.entry),
Commands::Get(get_cmd) => get_item(&mut data_manager, get_cmd.entry),
}
}

/// List all items in the database.
fn list_items(data_manager: &DataManager) -> Result<(), Box<dyn Error>> {
for (index, item) in data_manager.manifest_data.iter().enumerate() {
println!("{index}: {}", item.preview.replace("\n", "").trim());
println!("{}: {}", index+1, item.preview.replace("\n", "").trim());
}
Ok(())
}
Expand All @@ -67,37 +67,37 @@ fn clear_database(data_manager: &mut DataManager) -> Result<(), Box<dyn Error>>
Ok(())
}

/// Remove an item based on a query.
/// Remove an item based on a entry.
fn remove_item(
data_manager: &mut DataManager,
query: Option<String>,
entry: Option<String>,
) -> Result<(), Box<dyn Error>> {
let query_string = query.unwrap_or_else(|| {
let query_string = entry.unwrap_or_else(|| {
match String::from_utf8(read_stdin_as_bytes().unwrap_or_default()) {
Ok(value) => value,
Err(_) => String::new(), // Default to an empty string on error
}
});
if query_string.is_empty() {
return Ok(()); // No query, no action
return Ok(()); // No entry, no action
}

let parsed_index = parse_query(&query_string)?;
data_manager.remove_item(parsed_index)?;
Ok(())
}

/// Retrieve an item based on a query.
fn get_item(data_manager: &DataManager, query: Option<String>) -> Result<(), Box<dyn Error>> {
let query_string = query.unwrap_or_else(|| {
/// Retrieve an item based on a entry.
fn get_item(data_manager: &mut DataManager, entry: Option<String>) -> Result<(), Box<dyn Error>> {
let query_string = entry.unwrap_or_else(|| {
match String::from_utf8(read_stdin_as_bytes().unwrap_or_default()) {
Ok(value) => value,
Err(_) => String::new(), // Default to an empty string on error
}
});

if query_string.is_empty() {
return Ok(()); // No query, no action
return Ok(()); // No entry, no action
}

let parsed_index = parse_query(&query_string)?;
Expand All @@ -112,13 +112,19 @@ fn get_item(data_manager: &DataManager, query: Option<String>) -> Result<(), Box
item.mime_type
);

data_manager.put_item_on_top(parsed_index)?;
Ok(())
}

/// Parse the query string and extract an index.
fn parse_query(query: &str) -> Result<usize, Box<dyn Error>> {
let index_str = query.split(':').next().unwrap_or(query).trim();
Ok(index_str.parse::<usize>()?)
/// Parse the entry string and extract an index.
fn parse_query(entry: &str) -> Result<usize, Box<dyn Error>> {
let index_str = entry.split(':').next().unwrap_or(entry).trim();
let index_parsed = index_str.parse::<usize>()?;
if index_parsed == 0 {
return Err("Invalid position".into())
}

return Ok(index_parsed-1)
}

/// Read data from standard input as bytes.
Expand Down

0 comments on commit 1d03f0f

Please sign in to comment.