Skip to content
Draft
Show file tree
Hide file tree
Changes from 9 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
8 changes: 4 additions & 4 deletions src/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
path::{Path, PathBuf},
};

use crate::fuzzy::fuzzy_match_score;
use crate::fuzzy::{fuzzy_match_score, Score};

pub fn get_current_directory() -> PathBuf {
env::current_dir().unwrap_or(PathBuf::from("/"))
Expand Down Expand Up @@ -52,19 +52,19 @@ pub fn sub_directories(cwd: &Path, depth: u32) -> Vec<Directory> {
#[derive(Debug)]
pub struct ScoredDirectory {
directory: Directory,
score: i32,
score: Score,
}

impl ScoredDirectory {
pub fn new(directory: Directory, score: i32) -> Self {
pub fn new(directory: Directory, score: Score) -> Self {
Self { directory, score }
}

pub fn directory(&self) -> &Directory {
&self.directory
}

pub fn score(&self) -> i32 {
pub fn score(&self) -> Score {
self.score
}
}
Expand Down
104 changes: 65 additions & 39 deletions src/fuzzy.rs
Original file line number Diff line number Diff line change
@@ -1,53 +1,66 @@
use std::{collections::HashMap, iter};

pub type Score = u16;

const SCORE_PATTERN_FULL_MATCH: Score = 60;
const SCORE_PATTERN_CONTAINED: Score = 10;
const SCORE_CHAR_STARTING: Score = 5;
const SCORE_CHAR_HIT: Score = 1;
const PENALTY_CHAR_MISS: Score = 5;

/// Creates a score of how much the input and the pattern match
///
/// The higher the score the better. There is no max score.
pub fn fuzzy_match_score(input: &str, pattern: &str) -> i32 {
let mut score = 0;
if input
.to_lowercase()
.contains(pattern.to_lowercase().as_str())
{
score += 10;
}
let mut dir_name_mut = input.to_string();
for c in pattern.chars() {
if dir_name_mut.to_lowercase().contains(c.to_ascii_lowercase()) {
score += 1;
// strip the char to avoid multiple matches
dir_name_mut = dir_name_mut.replacen(c, "", 1);
pub fn fuzzy_match_score(input: &str, pattern: &str) -> Score {
let input = input.to_lowercase();
let pattern = pattern.to_lowercase();

let whole_pattern_score = {
if input == pattern {
SCORE_PATTERN_FULL_MATCH
} else if input.contains(&pattern) {
SCORE_PATTERN_CONTAINED
} else {
score -= 5;
0
}
};

let starting_score = SCORE_CHAR_STARTING
* iter::zip(input.chars(), pattern.chars())
.take_while(|(inp, pat)| inp == pat)
.count() as Score;

let (char_occurrence_score, char_miss_penalty) = {
let input = freqmap(&input);
let pattern = freqmap(&pattern);

let hits = pattern
.iter()
.map(|(char, &amt_in_pat)| {
let amt_in_inp = input.get(char).copied().unwrap_or_default();
amt_in_pat.min(amt_in_inp)
})
.sum::<Score>();
let misses = pattern.values().sum::<Score>() - hits;

(SCORE_CHAR_HIT * hits, PENALTY_CHAR_MISS * misses)
};

(whole_pattern_score + starting_score + char_occurrence_score).saturating_sub(char_miss_penalty)
}

// Doesn't technically need to be score as this is some abstract char count but it's convenient
fn freqmap(str: &str) -> HashMap<char, Score> {
let mut map = HashMap::with_capacity(str.len());
for char in str.chars() {
*map.entry(char).or_default() += 1;
}
if input.to_lowercase() == pattern.to_lowercase() {
score += 50;
}
if score < 0 {
score = 0;
}
score
map
}

#[cfg(test)]
mod tests {
use super::fuzzy_match_score as score;

#[test]
#[should_panic]
fn not_yet_implemented() {
// TODO: Should give more points if parts of query match
// beginning parts of input parts
assert!(score("test", "tt") > score("test", "t"));
assert!(score("test-abc", "ta") > score("test-abc", "te"));
assert!(score("test abc", "ta") > score("test abc", "te"));
assert!(score("test_abc", "ta") > score("test_abc", "te"));

assert!(score("test_abc_a", "taa") > score("test_abc_a", "te"));
assert!(score("test_abc_a", "taa") > score("test_abc_a", "tea"));

assert!(score("testAbc", "ta") > score("testAbc", "te"));
}

#[test]
fn test_simple() {
assert_eq!(score("test", "test"), score("test", "test"));
Expand All @@ -63,6 +76,19 @@ mod tests {
assert!(score("helloworld", "hello") > score("helloworld", "hellohello"));
}

#[test]
fn test_starting_with() {
assert!(score("test", "t") > score("test", "tt"));

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

test has two tt, why shouldn't it score higher?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

hm, actually ok, fair
I'll replace it with the length of common starting chars instead

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it already worked like that lol
this is because t is contained in test and tt is not

assert!(score("test-abc", "te") > score("test-abc", "ta"));
assert!(score("test abc", "te") > score("test abc", "ta"));
assert!(score("test_abc", "te") > score("test_abc", "ta"));

assert!(score("test_abc_a", "te") > score("test_abc_a", "taa"));

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

taa should have more value

my thought process behind this was that if you have multiple words you just type the first letter

"test abc abc" taa
"test uo uo" tuu

but now for both te is better.

ig you could argue that

te and ta for "test abc" can give the same value, but not better imo

assert!(score("test_abc_a", "tea") > score("test_abc_a", "taa"));

assert!(score("testAbc", "te") > score("testAbc", "tA"));
}

#[test]
fn test_negative_queries() {
assert!(score("helloworld", "ellovvvv") == 0);
Expand Down
44 changes: 22 additions & 22 deletions src/query_part.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,41 +69,41 @@ impl QueryPart {
vec![dir]
}
QueryPart::Text(text) => {
let mut scored_dirs = scored_directories(
&dirs
.iter()
.flat_map(|dir| sub_directories(dir.location().as_path(), 0))
.collect::<Vec<_>>(),
text.as_str(),
);
let scored_dirs = {
let mut dirs = scored_directories(
&dirs
.iter()
.flat_map(|dir| sub_directories(dir.location(), 0))
.collect::<Vec<_>>(),
text.as_str(),
);
// sort by score, if scores are equal by alphabetical order
dirs.sort_unstable_by(|a, b| {
a.score()
.cmp(&b.score())
.then(a.directory().location().cmp(b.directory().location()))
});
dirs
};

let average_score: f64 = scored_dirs
let average_score = scored_dirs
.iter()
.map(|scored_dir| f64::from(scored_dir.score()))
.sum::<f64>()
/ scored_dirs.len() as f64;

let half_of_highest_score = scored_dirs
.iter()
.last() // since it's sorted by score the last one has the most score
.map(ScoredDirectory::score)
.max()
.unwrap_or(0_i32)
/ 2;

// sort by score, if scores are equal by alphabetical order
scored_dirs.sort_unstable_by(|a, b| {
a.score()
.cmp(&b.score())
.then(a.directory().location().cmp(b.directory().location()))
});
.unwrap_or_default() as f64
/ 2.;

scored_dirs
.iter()
// remove dirs with low score
.filter(|scored_dir| {
f64::from(scored_dir.score()) > 0.0
&& f64::from(scored_dir.score()) >= average_score
&& scored_dir.score() >= half_of_highest_score
let score = scored_dir.score() as f64;
score > 0. && score >= average_score && score >= half_of_highest_score
})
.map(|scored_dir| scored_dir.directory().clone())
.collect()
Expand Down
12 changes: 8 additions & 4 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ fn test_absolute() {
#[test]
fn test_nonexisting() {
let env = TempEnv::new();
assert!(env.resolve_query("test zzzzzzzzz zzzzzzzzz").is_empty());
assert_eq!(

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Just curious, is there any difference here? Or just readability?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

expected empty vec, found this instead assert_eq error message is more informative than expected vec to be empty, it was not

env.resolve_query("test zzzzzzzzz zzzzzzzzz"),
Vec::<PathBuf>::new()
);
}

#[test]
Expand Down Expand Up @@ -183,10 +186,11 @@ fn test_dir_skip() {
let env = TempEnv::new();

assert_eq!(
env.resolve_query("test gamma - u"),
env.resolve_query("test alpha - eps"),
vec!(
env.abs_path("test/gamma/sigm#a/upsilon3"),
env.abs_path("test/gamma/sigma9/t@u0"),
env.abs_path("test/alpha/beta/epsil@on8"),
env.abs_path("test/alpha/betabeta/epsil#on"),
env.abs_path("test/alpha/betabeta/epsil0n"),
)
);
assert_eq!(
Expand Down
Loading