vpac / src / suggest.v
72 lines · 64 sloc · 2.16 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1@[has_globals]
2module main
3
4import nspkg
5import strings
6
7// suggest_thold is how close a name must be to be suggested. it is the fuzzy
8// search measure, a little stricter, since the user is asked about the answer
9// (options #:suggest) sets it
10__global suggest_thold = 0.85
11
12// closest_name is the name nearest to query, when it is near enough: a score
13// at the threshold counts, and ties fall to the name scanned first, which is
14// the order the names came in, the config's db order among them
15fn closest_name(query string, names []string) ?string {
16 q := query.to_lower()
17 mut best := ''
18 mut best_score := 0.0
19 for name in names {
20 score := strings.jaro_winkler_similarity(q, name.to_lower())
21 if score > best_score {
22 best = name
23 best_score = score
24 }
25 }
26 if best_score >= suggest_thold {
27 return best
28 }
29 return none
30}
31
32// did_you_mean handles a query that matched no package. it asks about the
33// nearest name, and returns it when the user says yes. otherwise, and when no
34// name is near, it is the unknown package error. the question goes through
35// the ui, which pauses a live display first
36fn did_you_mean(mut ui TransUI, query string, names []string) !string {
37 name := closest_name(query, names) or {
38 return error('unknown package: "${query}"')
39 }
40 if ui.noyes('did you mean ${name_style(name)}?') {
41 return name
42 }
43 return error('unknown package: "${query}"')
44}
45
46fn pkg_names(pkgs []&nspkg.Package) []string {
47 return pkgs.map(it.get_name())
48}
49
50// sync_names lists the names of the packages in the sync dbs
51fn sync_names(dbs []&nspkg.DB) []string {
52 mut names := []string{}
53 for db in dbs {
54 mut pkgcache := db.get_pkgcache() or { continue }
55 names << pkg_names(pkgcache.pkgs())
56 }
57 return names
58}
59
60// all_names lists the names of the installed packages and of the sync dbs
61fn all_names(handle &nspkg.Handle, dbs []&nspkg.DB) []string {
62 mut names := local_names(handle)
63 names << sync_names(dbs)
64 return names
65}
66
67// local_names lists the names of the installed packages
68fn local_names(handle &nspkg.Handle) []string {
69 localdb := handle.get_localdb() or { return []string{} }
70 mut pkgcache := localdb.get_pkgcache() or { return []string{} }
71 return pkg_names(pkgcache.pkgs())
72}
73