strv: introduce strv_find_closest()

Follow-up for 1e1ac5d53b.
This commit is contained in:
Yu Watanabe
2024-09-21 05:06:12 +09:00
parent 427848ffd0
commit ffdf497860
4 changed files with 66 additions and 10 deletions
+36 -1
View File
@@ -66,7 +66,28 @@ char* strv_find_startswith(char * const *l, const char *name) {
return NULL;
}
char* strv_find_closest_by_levenshtein(char * const *l, const char *name) {
static char* strv_find_closest_prefix(char * const *l, const char *name) {
size_t best_distance = SIZE_MAX;
char *best = NULL;
assert(name);
STRV_FOREACH(s, l) {
char *e = startswith(*s, name);
if (!e)
continue;
size_t n = strlen(e);
if (n < best_distance) {
best_distance = n;
best = *s;
}
}
return best;
}
static char* strv_find_closest_by_levenshtein(char * const *l, const char *name) {
ssize_t best_distance = SSIZE_MAX;
char *best = NULL;
@@ -93,6 +114,20 @@ char* strv_find_closest_by_levenshtein(char * const *l, const char *name) {
return best;
}
char* strv_find_closest(char * const *l, const char *name) {
assert(name);
/* Be more helpful to the user, and give a hint what the user might have wanted to type. We search
* with two mechanisms: a simple prefix match and – if that didn't yield results –, a Levenshtein
* word distance based match. */
char *found = strv_find_closest_prefix(l, name);
if (found)
return found;
return strv_find_closest_by_levenshtein(l, name);
}
char* strv_find_first_field(char * const *needles, char * const *haystack) {
STRV_FOREACH(k, needles) {
char *value = strv_env_pairs_get((char **)haystack, *k);
+1 -1
View File
@@ -17,7 +17,7 @@ char* strv_find(char * const *l, const char *name) _pure_;
char* strv_find_case(char * const *l, const char *name) _pure_;
char* strv_find_prefix(char * const *l, const char *name) _pure_;
char* strv_find_startswith(char * const *l, const char *name) _pure_;
char* strv_find_closest_by_levenshtein(char * const *l, const char *name) _pure_;
char* strv_find_closest(char * const *l, const char *name) _pure_;
/* Given two vectors, the first a list of keys and the second a list of key-value pairs, returns the value
* of the first key from the first vector that is found in the second vector. */
char* strv_find_first_field(char * const *needles, char * const *haystack) _pure_;