From 39e1fea36f8c8338e1b670d9a1093c7965f87778 Mon Sep 17 00:00:00 2001 From: kjuulh Date: Sun, 15 Sep 2024 22:36:39 +0200 Subject: [PATCH] chore: refactor fuzzy match into own function --- crates/gitnow/src/commands/root.rs | 53 +++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/crates/gitnow/src/commands/root.rs b/crates/gitnow/src/commands/root.rs index 584c845..c7968bc 100644 --- a/crates/gitnow/src/commands/root.rs +++ b/crates/gitnow/src/commands/root.rs @@ -1,5 +1,11 @@ +use std::collections::BTreeMap; + use crate::{ - app::App, cache::CacheApp, fuzzy_matcher::FuzzyMatcherApp, projects_list::ProjectsListApp, + app::App, + cache::CacheApp, + fuzzy_matcher::{FuzzyMatcher, FuzzyMatcherApp}, + git_provider::Repository, + projects_list::ProjectsListApp, }; #[derive(Debug, Clone)] @@ -31,16 +37,11 @@ impl RootCommand { None => todo!(), }; - let haystack = repositories - .iter() - .map(|r| r.to_rel_path().display().to_string()) - .collect::>(); - - let haystack = haystack.as_str_vec(); - - let res = self.app.fuzzy_matcher().match_pattern(&needle, &haystack); - - let res = res.iter().take(10).rev().collect::>(); + let matched_repos = self + .app + .fuzzy_matcher() + .match_repositories(&needle, &repositories); + let res = matched_repos.iter().take(10).rev().collect::>(); for repo in res { tracing::debug!("repo: {:?}", repo); @@ -61,3 +62,33 @@ impl StringExt for Vec { self.iter().map(|r| r.as_ref()).collect() } } + +impl StringExt for Vec<&String> { + fn as_str_vec(&self) -> Vec<&str> { + self.iter().map(|r| r.as_ref()).collect() + } +} + +trait RepositoryMatcher { + fn match_repositories(&self, pattern: &str, repositories: &[Repository]) -> Vec; +} + +impl RepositoryMatcher for FuzzyMatcher { + fn match_repositories(&self, pattern: &str, repositories: &[Repository]) -> Vec { + let haystack = repositories + .iter() + .map(|r| (r.to_rel_path().display().to_string(), r)) + .collect::>(); + let haystack_keys = haystack.keys().collect::>(); + let haystack_keys = haystack_keys.as_str_vec(); + + let res = self.match_pattern(pattern, &haystack_keys); + + let matched_repos = res + .into_iter() + .filter_map(|repo_key| haystack.get(repo_key).map(|r| (*r).to_owned())) + .collect::>(); + + matched_repos + } +}