Skip to content
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

Add fuzzy-match search #2

Merged
merged 3 commits into from
Dec 19, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org

root = true

[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4

[*.yml]
indent_size = 2
31 changes: 30 additions & 1 deletion Cargo.lock

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

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ edition = "2018"
clap = "2.33.3"
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8"
webbrowser = "0.5.5"
webbrowser = "0.5.5"
fuzzy-matcher = "0.3.7"
ansi_term = "0.12.1"
56 changes: 54 additions & 2 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::fs::File;
use std::io::Write;
use std::path::Path;

use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use serde::{Deserialize, Serialize};

type Result<T> = std::result::Result<T, Box<dyn error::Error>>;
Expand Down Expand Up @@ -56,11 +58,61 @@ impl Config {
.collect()
}

pub(crate) fn urls_from_context(&self, context: String) -> Vec<String> {
pub(crate) fn urls_from_context(&self, context: Vec<String>) -> Vec<String> {
let matcher = SkimMatcherV2::default();
self.elements
.iter()
.filter(|element| element.context == context)
.filter(|element| {
let matching_terms_count =
Config::matching_term_count(&matcher, &context, &element);
matching_terms_count == context.capacity()
})
.flat_map(|element| element.urls.clone())
.collect()
}

pub(crate) fn nearest_context(&self, context: Vec<String>) -> Option<String> {
self.contexts_sorted_by_matching_accuracy(context)
.first()
.cloned()
}

fn contexts_sorted_by_matching_accuracy(&self, context: Vec<String>) -> Vec<String> {
let matcher = SkimMatcherV2::default();
let mut partially_matching_elements: Vec<&Element> = self
.elements
.iter()
.filter(|element| {
let matching_terms_count =
Config::matching_term_count(&matcher, &context, &element);
matching_terms_count != context.capacity() && matching_terms_count != 0
})
.collect();

partially_matching_elements.sort_by(|first, second| {
let first_count = Config::matching_term_count(&matcher, &context, &first);
let second_count = Config::matching_term_count(&matcher, &context, &second);
first_count.cmp(&second_count)
});

partially_matching_elements
.iter()
.map(|element| element.context.clone())
.collect()
}

fn matching_term_count(
matcher: &SkimMatcherV2,
context: &[String],
element: &Element,
) -> usize {
context
.iter()
.filter(|term| {
matcher
.fuzzy_match(element.context.as_str(), term.as_str())
.is_some()
})
.count()
}
}
64 changes: 48 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,27 @@ mod cfg;
#[macro_use]
extern crate clap;

use ansi_term::Colour::{Green, Red};
use ansi_term::Style;
use cfg::Config;
use clap::{App, Arg};
use std::path::Path;

// ⚠️ is two chars, so need an extra space after it to have the correct "⚠️" output
// ⚠️ is composed of two chars, so need an extra space after it to have the correct "⚠️" output
static CAUTION: &str = "⚠️ ";
static SEARCH: &str = "🔎";
static WRITE: &str = "📝";
static SAD: &str = "😢";

fn main() {
let matches = App::new("wints")
.about("What I Need To See - a fuzzy term-based url opener")
.version(crate_version!())
.author(crate_authors!())
let cli_name = Style::new().bold().paint("wints");
let display_name = Style::new().bold().paint("What I Need To See");
let about = Green.bold().blink().paint("a fuzzy term-based url opener");
let version = Green.bold().paint(crate_version!());

let matches = App::new(cli_name.to_string())
.about(format!("{} - {}", display_name, about).as_str())
.version(version.to_string().as_str())
.arg(
Arg::with_name("terms")
.help("Terms to search for")
Expand All @@ -28,24 +35,43 @@ fn main() {
let config = load_configuration();

match matches.values_of_lossy("terms") {
Some(terms) => open_urls_based_on_terms(terms.join(" "), config),
Some(terms) => open_urls_based_on_terms(terms, config),
None => terms_are_mandatory(config),
}
}

fn terms_are_mandatory(config: Config) {
println!(" {} No terms passed, can't search anything.", CAUTION);
if let Some(possible_terms) = config.list_of_contexts().first() {
println!(" {} Try with '{}'", SEARCH, possible_terms)
println!(
" {} Try with {}.",
SEARCH,
Green.bold().paint(possible_terms)
)
}
}

fn open_urls_based_on_terms(terms_search: String, config: Config) {
println!(" {} Search for '{}'", SEARCH, terms_search);
for url in config.urls_from_context(terms_search).iter() {
fn open_urls_based_on_terms(terms_search: Vec<String>, config: Config) {
println!(
" {} Searching for {}.",
SEARCH,
Green.bold().paint(terms_search.join(" "))
);
let urls = config.urls_from_context(terms_search.clone());
if urls.is_empty() {
match config.nearest_context(terms_search) {
Some(nearest_context) => println!(
" {} Missed, try with terms like in '{}'.",
SAD,
Green.bold().paint(nearest_context)
),
None => println!(" {} Nothing found, try with another term.", SAD),
}
}
for url in urls.iter() {
match webbrowser::open(url) {
Ok(_) => println!("open {}", url),
Err(err) => eprintln!("can't open {}: {}", url, err),
Err(why) => eprintln!("can't open {}: {}", url, Red.paint(why.to_string())),
}
}
}
Expand All @@ -57,8 +83,9 @@ fn load_configuration() -> Config {

match Config::read_file(config_filename) {
Err(why) => panic!(
"can't load configuration file '{}': {}",
config_filename, why
"can't load configuration file {}: {}",
Green.bold().paint(config_filename),
Red.paint(why.to_string())
),
Ok(config) => config,
}
Expand All @@ -70,10 +97,15 @@ fn ensure_configuration_file_exists(config_filename: &str) {
println!(" {} Can't find any '{}' file.", CAUTION, config_filename);

match Config::write_default_file(config_filename) {
Err(why) => panic!("couldn't create '{}': {}", config_filename, why),
Err(why) => panic!(
"couldn't create {}: {}",
Green.bold().paint(config_filename),
Red.paint(why.to_string())
),
Ok(_) => println!(
" {} So an empty '{}' file has been created.",
WRITE, config_filename
" {} So an empty {} file has been created.",
WRITE,
Green.bold().paint(config_filename)
),
};
}
Expand Down