@[has_globals] module main import nspkg import strings // suggest_thold is how close a name must be to be suggested. it is the fuzzy // search measure, a little stricter, since the user is asked about the answer // (options #:suggest) sets it __global suggest_thold = 0.85 // closest_name is the name nearest to query, when it is near enough: a score // at the threshold counts, and ties fall to the name scanned first, which is // the order the names came in, the config's db order among them fn closest_name(query string, names []string) ?string { q := query.to_lower() mut best := '' mut best_score := 0.0 for name in names { score := strings.jaro_winkler_similarity(q, name.to_lower()) if score > best_score { best = name best_score = score } } if best_score >= suggest_thold { return best } return none } // did_you_mean handles a query that matched no package. it asks about the // nearest name, and returns it when the user says yes. otherwise, and when no // name is near, it is the unknown package error. the question goes through // the ui, which pauses a live display first fn did_you_mean(mut ui TransUI, query string, names []string) !string { name := closest_name(query, names) or { return error('unknown package: "${query}"') } if ui.noyes('did you mean ${name_style(name)}?') { return name } return error('unknown package: "${query}"') } fn pkg_names(pkgs []&nspkg.Package) []string { return pkgs.map(it.get_name()) } // sync_names lists the names of the packages in the sync dbs fn sync_names(dbs []&nspkg.DB) []string { mut names := []string{} for db in dbs { mut pkgcache := db.get_pkgcache() or { continue } names << pkg_names(pkgcache.pkgs()) } return names } // all_names lists the names of the installed packages and of the sync dbs fn all_names(handle &nspkg.Handle, dbs []&nspkg.DB) []string { mut names := local_names(handle) names << sync_names(dbs) return names } // local_names lists the names of the installed packages fn local_names(handle &nspkg.Handle) []string { localdb := handle.get_localdb() or { return []string{} } mut pkgcache := localdb.get_pkgcache() or { return []string{} } return pkg_names(pkgcache.pkgs()) }