| 1 | @[has_globals] |
| 2 | module main |
| 3 | |
| 4 | import alpm |
| 5 | import 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 |
| 15 | fn 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 |
| 36 | fn 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 | |
| 46 | fn pkg_names(pkgs []&alpm.Package) []string { |
| 47 | return pkgs.map(it.get_name()) |
| 48 | } |
| 49 | |
| 50 | // sync_names lists the names of the packages in the sync dbs |
| 51 | fn sync_names(dbs []&alpm.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 |
| 61 | fn all_names(handle &alpm.Handle, dbs []&alpm.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 |
| 68 | fn local_names(handle &alpm.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 | |