module main import alpm #include @[typedef] struct C.regex_t {} fn C.regcomp(preg &C.regex_t, pattern &char, cflags int) int fn C.regexec(preg &C.regex_t, text &char, nmatch uint, pmatch voidptr, eflags int) int fn C.regfree(preg &C.regex_t) // FilePattern is one -x target, compiled as pacman's files_search compiles // it: a posix extended expression, case ignored. a target with a slash is // matched against whole paths, one without against file names alone struct FilePattern { re &C.regex_t whole bool } // find_rel is a target as the filelists spell paths, with no leading slash. // as in pacman's files_search the slashes go while more than one byte is // left, so a target of slashes alone stays '/' instead of becoming the empty // expression that matches everything fn find_rel(target string) string { mut rel := target for rel.len > 1 && rel[0] == `/` { rel = rel[1..] } return rel } fn file_pattern(target string) !FilePattern { whole := target.contains('/') text := if whole { find_rel(target) } else { target } re := &C.regex_t{} if C.regcomp(re, &char(text.str), C.REG_EXTENDED | C.REG_NOSUB | C.REG_ICASE | C.REG_NEWLINE) != 0 { return error("invalid regular expression '${target}'") } return FilePattern{ re: re whole: whole } } // matches is whether a filelist entry answers the pattern. a file name is // what follows the last slash: a directory has none, and is no match fn (p FilePattern) matches(file string) bool { text := if p.whole { file } else { file.all_after_last('/') } if text == '' || (!p.whole && !file.contains('/')) { return false } return C.regexec(p.re, &char(text.str), 0, unsafe { nil }, 0) == 0 } // find is pacman's -F: the sync file databases, one .files file per repo. // a path asks which repo package provides it, -l lists the files of a sync // package, and -y refreshes the file dbs. the file dbs are the sync dbs read // with a .files extension, so they live in their own handle. -r narrows the // repos searched, while -y still refreshes all of them fn find(config ConfigFind) ! { need_query(config.query, 'a file path, or a package name with -l')! mut ui := new_trans_ui(noconfirm: config.noconfirm) mut handle := find_handle(mut ui, config.refresh)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } dbs := init_repos(mut handle)! mut filter := []string{} if config.repos != '' { filter = config.repos.split(',').map(it.trim_space()).filter(it != '') known := dbs.map(it.get_name()) for name in filter { if name !in known { return error('not a sync repo: ${name} (these are: ${known.join(', ')})') } } } if config.refresh { check_ask_db_lock(mut ui) mut s := ui.spinner(text: 'refreshing file databases') s.start() defer { stop_spinner(mut s) } // "up to date" is libalpm saying nothing needed fetching: success handle.db_update(handle.get_syncdbs()!, false) or { return error('could not refresh the file databases: ${err.msg()}') } stop_spinner(mut s) } if config.list { find_list(mut ui, dbs, filter, config)! return } find_owner(mut ui, dbs, filter, config)! } // find_handle opens the handle the file dbs are read through, with their // .files extension. a refresh downloads, as root: it takes the full handle, // so the download runs as the sandbox user with the configured keyring, // timeout and progress, as pacman -Fy's does. reading needs none of that, // and keeps the lean handle of the read-only modes fn find_handle(mut ui TransUI, refresh bool) !&alpm.Handle { handle := if refresh { init_handle(ui)! } else { alpm.initialize(root_path, db_path) or { return err } } handle.option_set_dbext('.files') or { handle.release() or { went_on('release the alpm handle', err) } return err } return handle } // FileCache is one file db loaded: the db, for its name, and its package cache struct FileCache { db &alpm.DB cache &alpm.List } // find_caches loads the file db package caches the named repos ask for, with // a name in the error, because a missing .files file is the one thing a first // run trips over. an empty filter loads them all fn find_caches(dbs []&alpm.DB, filter []string) ![]FileCache { mut out := []FileCache{} for db in dbs { if filter.len > 0 && db.get_name() !in filter { continue } // a db with no packages is an empty one, not a broken one cache := pkgcache_of(db.get_handle(), db) or { return error('the file database of ${db.get_name()} is missing or broken (${err.msg()}): refresh it with vpac f -y') } out << FileCache{ db: db cache: cache } } return out } // OwnerRef is one claim in the inverted file index: the repo whose file db // listed the package, and the package by its place in the pkgs list the // index walks (the list of packages itself is kept beside the index, so no // pointer-bearing struct has to live in the map's cells) struct OwnerRef { repo string pkg_i int } // owner_index is the inverted file index of the caches: every file and // directory the file dbs hold, naming the packages that carry them. each // query path would otherwise walk every package and its C-side filelist // once, which is what makes an owner search over a full file db crawl // (alpm_filelist_contains is a scan per path). the keys carry no trailing // slash — a directory entry and a file land under the same key — and the // entries are ordered as the dbs and their packages come, the same order // the walk reports them in fn owner_index(caches []FileCache) OwnerIndex { mut index := OwnerIndex{} for fc in caches { for pkg in fc.cache.pkgs() { pkg_i := index.pkgs.len index.pkgs << pkg for name in pkg.get_files().names() { key := name.trim_right('/') if key == '' { continue } index.refs[key] << OwnerRef{ repo: fc.db.get_name() pkg_i: pkg_i } } } } return index } // OwnerIndex is owner_index's answer, one value: a multi-path search takes it // as it is built, where two variables filled after the fact would each be a // copy of an index as large as every filelist of the dbs struct OwnerIndex { mut: refs map[string][]OwnerRef pkgs []&alpm.Package } // owner_matches answers whether a file db entry provides the path. directories // in a filelist carry a trailing slash, so the query, given without its own, // is tried both ways fn owner_matches(pkg &alpm.Package, rel string) bool { return pkg.get_files().contains(rel) != none || pkg.get_files().contains(rel + '/') != none } // OwnerHit is one path's matches, kept so the results print only after the // spinner stops. files are the paths that matched in each package: the path // asked for, or every file an expression or a bare file name found — listed // is set for those two, whose answer is the files and not only the packages struct OwnerHit { path string listed bool mut: repos []string pkgs []&alpm.Package files [][]string } // machine_line is pacman's --machinereadable line: repo, package, version // and path, parted by NUL bytes fn machine_line(repo string, pkg &alpm.Package, file string) string { return [repo, pkg.get_name(), pkg.get_version(), file].join('\0') } // find_owner answers which repo package provides a path, pacman's -Fo. the // paths are relative to root, with or without the leading slash, and every // path given is searched fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! { // -x: every expression compiles before anything is searched, and a bad // one stops the run once all of them are named, as in pacman mut patterns := []FilePattern{} defer { for p in patterns { C.regfree(p.re) } } if config.regex { mut bad := 0 for target in config.query { patterns << file_pattern(target) or { target_error(err.msg()) bad++ continue } } if bad > 0 { return } } mut s := ui.spinner(text: 'searching file databases') // quiet pipes its results: no spinner to glue a finished line onto them spun := !config.quiet && !config.machinereadable if spun { s.start() } defer { stop_spinner(mut s) } caches := find_caches(dbs, filter)! // many paths or one: building the index costs about one walk of every // filelist, so a single-path search keeps its own walk, and a multi-path // one pays once and does every later path by lookup. an expression is // no key to look up: it walks index := if config.query.len > 1 && !config.regex { owner_index(caches) } else { OwnerIndex{} } mut hits := []OwnerHit{} for qi, path in config.query { // a target with no slash is a file name, looked for in every // directory, as pacman's files_search does without -x too by_name := !path.contains('/') mut hit := OwnerHit{ path: path listed: config.regex || by_name } // the keys of the index and the entries of a filelist are matched // without the query's trailing slash, the same in both branches below rel := find_rel(path).trim_right('/') if hit.listed { for fc in caches { for pkg in fc.cache.pkgs() { names := pkg.get_files().names() matched := if config.regex { names.filter(patterns[qi].matches(it)) } else { // a directory entry ends in its slash and has no // file name; an entry with no slash has no directory names.filter(it.contains('/') && it.all_after_last('/') == path) } if matched.len > 0 { hit.repos << fc.db.get_name() hit.pkgs << pkg hit.files << matched } } } hits << hit continue } if rel == '' { // reported with the misses, once the spinner is gone hits << hit continue } if config.query.len > 1 { // alpm's own lookup matches the file and every directory on // the way to it, which is what pacman's -Fo does; the index // answers in the same order the walk would for ref in index.refs[rel] { hit.repos << ref.repo hit.pkgs << index.pkgs[ref.pkg_i] hit.files << [rel] } } else { for fc in caches { for pkg in fc.cache.pkgs() { // alpm's own lookup matches the file and every directory // on the way to it, which is what pacman's -Fo does if owner_matches(pkg, rel) { hit.repos << fc.db.get_name() hit.pkgs << pkg hit.files << [rel] } } } } // a miss is kept too: it is reported in its place among the results hits << hit } if spun { end_frame(mut ui, mut s) } for hit in hits { if hit.pkgs.len == 0 { if hit.path.trim_left('/') == '' && !hit.listed { target_error('a file path is needed, not "${hit.path}"') } else { target_error('no package provides ${hit.path}') } } else if ipc_on() { mut listing := Listing{ fields: ['source', 'name', 'version', 'description'] } for i, pkg in hit.pkgs { listing.add_pkg(pkg, hit.repos[i]) } emit(ProvidesEvent{ path: hit.path fields: listing.fields entries: listing.entries files: if hit.listed { hit.files } else { [][]string{} } }) } else if config.machinereadable { // one line a matched path, for a program to split for i, pkg in hit.pkgs { for file in hit.files[i] { println(machine_line(hit.repos[i], pkg, file)) } } } else if config.quiet { for i, pkg in hit.pkgs { // pacman's -Fq prints repo/pkg, which is what tells packages // that share a name apart println('${hit.repos[i]}/${pkg.get_name()}') } } else if hit.listed { // an expression or a file name finds many files: each is listed // with its package if config.query.len > 1 { println(heading(hit.path)) } mut rows := []Row{} for i, pkg in hit.pkgs { for file in hit.files[i] { rows << row(file, source_style(hit.repos[i]), name_style(pkg.get_name()), version_style(pkg.get_version())) } } println(table_text(rows, '', ' ')) } else { if config.query.len > 1 { println(heading(hit.path)) } mut listing := Listing{ fields: ['source', 'name', 'version', 'description'] } for i, pkg in hit.pkgs { listing.add_pkg(pkg, hit.repos[i]) } listing.print() } } } // find_list lists the files of a sync package from the file dbs, pacman's -Fl fn find_list(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! { mut s := ui.spinner(text: 'searching file databases') // quiet pipes its results: no spinner to glue a finished line onto them plain := config.quiet || config.machinereadable spun := !plain if spun { s.start() } defer { stop_spinner(mut s) } caches := find_caches(dbs, filter)! mut lines := []string{} mut rows := []Row{} mut missing := []string{} for target in config.query { // a target may name its repo, repo/package, as pacman's -Fl takes it want_repo, name := if target.contains('/') { target.all_before('/'), target.all_after('/') } else { '', target } if name == '' { missing << target continue } // the package the caches hold, or the miss it is: pkg keeps the nil // answer as none instead of a sentinel &alpm.Package mut pkg := ?&alpm.Package(none) mut repo := '' for fc in caches { if want_repo != '' && fc.db.get_name() != want_repo { continue } if p := fc.cache.pkg_find(name) { pkg = ?&alpm.Package(p) repo = fc.db.get_name() break } } if p := pkg { // the miss is counted, the hit is listed; under ipc it leaves as // soon as it is collected, like find_owner's answers do if ipc_on() { emit(FilesEvent{ package: p.get_name() repo: repo paths: p.get_files().names() }) continue } for file in p.get_files().names() { // quiet is pacman's -Flq: the file paths alone, with no package // name, so a file two packages hold is listed twice; the form's // help says 'repo/pkg for paths, file paths for -l' if config.machinereadable { lines << machine_line(repo, p, file) } else if config.quiet { lines << file } else { // pacman's dump_file_list: the package, then the path rows << row(name_style(p.get_name()), file) } } } else { // no cache holds it: the miss is named once the listing is out missing << target } } if spun { end_frame(mut ui, mut s) } if plain && lines.len > 0 { println(lines.join('\n')) } else if !plain && rows.len > 0 { println(table_text(rows, ' ', ' ')) } // the misses follow the listing: written while the spinner ran, they // would be drawn over for name in missing { target_error('"${name}" is not in the file databases: refresh them with vpac f -y') } }