Skip to content

Commit

Permalink
Add '--top' flag to 'inc' subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementNerma committed May 10, 2022
1 parent 9c4ef78 commit 9961491
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
3 changes: 3 additions & 0 deletions src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pub struct Add {
pub struct Inc {
#[clap()]
pub path: String,

#[clap(long, help = "Give the maximum score to this directory")]
pub top: bool,
}

#[derive(Args)]
Expand Down
23 changes: 15 additions & 8 deletions src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ impl Index {
}
}

pub fn add_or_inc(&mut self, path: String, inc_if_exists: bool) -> Result<(), String> {
pub fn add_or_inc(
&mut self,
path: String,
update_score: impl FnOnce(u64) -> u64,
default_value: u64,
) -> Result<(), String> {
if path.is_empty() {
return Err("Please provide a valid path.".to_string());
}
Expand All @@ -33,24 +38,26 @@ impl Index {

match self.scored_entries.entry(path) {
Entry::Occupied(mut entry) => {
if inc_if_exists {
*entry.get_mut() += 1;
}
*entry.get_mut() = update_score(*entry.get());
}
Entry::Vacant(entry) => {
entry.insert(1);
entry.insert(default_value);
}
}

Ok(())
}

pub fn add(&mut self, path: String) -> Result<(), String> {
self.add_or_inc(path, false)
self.add_or_inc(path, |score| score, 1)
}

pub fn inc(&mut self, path: String) -> Result<(), String> {
self.add_or_inc(path, true)
pub fn inc(&mut self, path: String, set_top: bool) -> Result<(), String> {
self.add_or_inc(
path,
|score| score.saturating_add(1),
if set_top { u64::MAX } else { 1 },
)
}

pub fn query_all(&self, query: &str, after: Option<&str>) -> Vec<IndexEntry> {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ fn main() {
.unwrap_or_else(|e| fail(&format!("Failed to add directory: {e}")));
}

Action::Inc(Inc { path }) => {
Action::Inc(Inc { path, top }) => {
index
.inc(path)
.inc(path, top)
.unwrap_or_else(|e| fail(&format!("Failed to increment directory: {e}")));
}

Expand Down

0 comments on commit 9961491

Please sign in to comment.