vpac / src / find.v
482 lines · 453 sloc · 14.47 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1module main
2
3import nspkg
4
5#include <regex.h>
6
7@[typedef]
8struct C.regex_t {}
9
10fn C.regcomp(preg &C.regex_t, pattern &char, cflags int) int
11
12fn C.regexec(preg &C.regex_t, text &char, nmatch uint, pmatch voidptr, eflags int) int
13
14fn C.regfree(preg &C.regex_t)
15
16// FilePattern is one -x target, compiled as pacman's files_search compiles
17// it: a posix extended expression, case ignored. a target with a slash is
18// matched against whole paths, one without against file names alone
19struct FilePattern {
20 re &C.regex_t
21 whole bool
22}
23
24// find_rel is a target as the filelists spell paths, with no leading slash.
25// as in pacman's files_search the slashes go while more than one byte is
26// left, so a target of slashes alone stays '/' instead of becoming the empty
27// expression that matches everything
28fn find_rel(target string) string {
29 mut rel := target
30 for rel.len > 1 && rel[0] == `/` {
31 rel = rel[1..]
32 }
33 return rel
34}
35
36fn file_pattern(target string) !FilePattern {
37 whole := target.contains('/')
38 text := if whole { find_rel(target) } else { target }
39 re := &C.regex_t{}
40 if C.regcomp(re, &char(text.str), C.REG_EXTENDED | C.REG_NOSUB | C.REG_ICASE | C.REG_NEWLINE) != 0 {
41 return error("invalid regular expression '${target}'")
42 }
43 return FilePattern{
44 re: re
45 whole: whole
46 }
47}
48
49// matches is whether a filelist entry answers the pattern. a file name is
50// what follows the last slash: a directory has none, and is no match
51fn (p FilePattern) matches(file string) bool {
52 text := if p.whole { file } else { file.all_after_last('/') }
53 if text == '' || (!p.whole && !file.contains('/')) {
54 return false
55 }
56 return C.regexec(p.re, &char(text.str), 0, unsafe { nil }, 0) == 0
57}
58
59// find is pacman's -F: the sync file databases, one .files file per repo.
60// a path asks which repo package provides it, -l lists the files of a sync
61// package, and -y refreshes the file dbs. the file dbs are the sync dbs read
62// with a .files extension, so they live in their own handle. -r narrows the
63// repos searched, while -y still refreshes all of them
64fn find(config ConfigFind) ! {
65 need_query(config.query, 'a file path, or a package name with -l')!
66
67 mut ui := new_trans_ui(noconfirm: config.noconfirm)
68 mut handle := find_handle(mut ui, config.refresh)!
69 defer { handle.release() or { went_on('release the nspkg handle', err) } }
70 defer { ui.stop() }
71
72 dbs := init_repos(mut handle)!
73 mut filter := []string{}
74 if config.repos != '' {
75 filter = config.repos.split(',').map(it.trim_space()).filter(it != '')
76 known := dbs.map(it.get_name())
77 for name in filter {
78 if name !in known {
79 return error('not a sync repo: ${name} (these are: ${known.join(', ')})')
80 }
81 }
82 }
83
84 if config.refresh {
85 check_ask_db_lock(mut ui)
86 mut s := ui.spinner(text: 'refreshing file databases')
87 s.start()
88 defer { stop_spinner(mut s) }
89 // "up to date" is libalpm saying nothing needed fetching: success
90 handle.db_update(handle.get_syncdbs()!, false) or {
91 return error('could not refresh the file databases: ${err.msg()}')
92 }
93 stop_spinner(mut s)
94 }
95
96 if config.list {
97 find_list(mut ui, dbs, filter, config)!
98 return
99 }
100 find_owner(mut ui, dbs, filter, config)!
101}
102
103// find_handle opens the handle the file dbs are read through, with their
104// .files extension. a refresh downloads, as root: it takes the full handle,
105// so the download runs as the sandbox user with the configured keyring,
106// timeout and progress, as pacman -Fy's does. a cached file database
107// still needs the configured keyring to verify its signature
108fn find_handle(mut ui TransUI, refresh bool) !&nspkg.Handle {
109 handle := if refresh {
110 init_handle(ui)!
111 } else {
112 nspkg.initialize(root_path, db_path) or { return err }
113 }
114 if !refresh && cfg_gpgdir != '' {
115 handle.option_set_gpgdir(cfg_gpgdir) or {
116 handle.release() or { went_on('release the nspkg handle', err) }
117 return err
118 }
119 }
120 handle.option_set_dbext('.files') or {
121 handle.release() or { went_on('release the nspkg handle', err) }
122 return err
123 }
124 return handle
125}
126
127// FileCache is one file db loaded: the db, for its name, and its package cache
128struct FileCache {
129 db &nspkg.DB
130 cache &nspkg.List
131}
132
133// find_caches loads the file db package caches the named repos ask for, with
134// a name in the error, because a missing .files file is the one thing a first
135// run trips over. an empty filter loads them all
136fn find_caches(dbs []&nspkg.DB, filter []string) ![]FileCache {
137 mut out := []FileCache{}
138 for db in dbs {
139 if filter.len > 0 && db.get_name() !in filter {
140 continue
141 }
142 // a db with no packages is an empty one, not a broken one
143 cache := pkgcache_of(db.get_handle(), db) or {
144 return error('the file database of ${db.get_name()} is missing or broken (${err.msg()}): refresh it with vpac f -y')
145 }
146 out << FileCache{
147 db: db
148 cache: cache
149 }
150 }
151 return out
152}
153
154// OwnerRef is one claim in the inverted file index: the repo whose file db
155// listed the package, and the package by its place in the pkgs list the
156// index walks (the list of packages itself is kept beside the index, so no
157// pointer-bearing struct has to live in the map's cells)
158struct OwnerRef {
159 repo string
160 pkg_i int
161}
162
163// owner_index is the inverted file index of the caches: every file and
164// directory the file dbs hold, naming the packages that carry them. each
165// query path would otherwise walk every package and its C-side filelist
166// once, which is what makes an owner search over a full file db crawl
167// (alpm_filelist_contains is a scan per path). the keys carry no trailing
168// slash — a directory entry and a file land under the same key — and the
169// entries are ordered as the dbs and their packages come, the same order
170// the walk reports them in
171fn owner_index(caches []FileCache) OwnerIndex {
172 mut index := OwnerIndex{}
173 for fc in caches {
174 for pkg in fc.cache.pkgs() {
175 pkg_i := index.pkgs.len
176 index.pkgs << pkg
177 for name in pkg.get_files().names() {
178 key := name.trim_right('/')
179 if key == '' {
180 continue
181 }
182 index.refs[key] << OwnerRef{
183 repo: fc.db.get_name()
184 pkg_i: pkg_i
185 }
186 }
187 }
188 }
189 return index
190}
191
192// OwnerIndex is owner_index's answer, one value: a multi-path search takes it
193// as it is built, where two variables filled after the fact would each be a
194// copy of an index as large as every filelist of the dbs
195struct OwnerIndex {
196mut:
197 refs map[string][]OwnerRef
198 pkgs []&nspkg.Package
199}
200
201// owner_matches answers whether a file db entry provides the path. directories
202// in a filelist carry a trailing slash, so the query, given without its own,
203// is tried both ways
204fn owner_matches(pkg &nspkg.Package, rel string) bool {
205 return pkg.get_files().contains(rel) != none
206 || pkg.get_files().contains(rel + '/') != none
207}
208
209// OwnerHit is one path's matches, kept so the results print only after the
210// spinner stops. files are the paths that matched in each package: the path
211// asked for, or every file an expression or a bare file name found — listed
212// is set for those two, whose answer is the files and not only the packages
213struct OwnerHit {
214 path string
215 listed bool
216mut:
217 repos []string
218 pkgs []&nspkg.Package
219 files [][]string
220}
221
222// machine_line is pacman's --machinereadable line: repo, package, version
223// and path, parted by NUL bytes
224fn machine_line(repo string, pkg &nspkg.Package, file string) string {
225 return [repo, pkg.get_name(), pkg.get_version(), file].join('\0')
226}
227
228// find_owner answers which repo package provides a path, pacman's -Fo. the
229// paths are relative to root, with or without the leading slash, and every
230// path given is searched
231fn find_owner(mut ui TransUI, dbs []&nspkg.DB, filter []string, config ConfigFind) ! {
232 // -x: every expression compiles before anything is searched, and a bad
233 // one stops the run once all of them are named, as in pacman
234 mut patterns := []FilePattern{}
235 defer {
236 for p in patterns {
237 C.regfree(p.re)
238 }
239 }
240 if config.regex {
241 mut bad := 0
242 for target in config.query {
243 patterns << file_pattern(target) or {
244 target_error(err.msg())
245 bad++
246 continue
247 }
248 }
249 if bad > 0 {
250 return
251 }
252 }
253 mut s := ui.spinner(text: 'searching file databases')
254 // quiet pipes its results: no spinner to glue a finished line onto them
255 spun := !config.quiet && !config.machinereadable
256 if spun {
257 s.start()
258 }
259 defer { stop_spinner(mut s) }
260
261 caches := find_caches(dbs, filter)!
262 // many paths or one: building the index costs about one walk of every
263 // filelist, so a single-path search keeps its own walk, and a multi-path
264 // one pays once and does every later path by lookup. an expression is
265 // no key to look up: it walks
266 index := if config.query.len > 1 && !config.regex {
267 owner_index(caches)
268 } else {
269 OwnerIndex{}
270 }
271 mut hits := []OwnerHit{}
272 for qi, path in config.query {
273 // a target with no slash is a file name, looked for in every
274 // directory, as pacman's files_search does without -x too
275 by_name := !path.contains('/')
276 mut hit := OwnerHit{
277 path: path
278 listed: config.regex || by_name
279 }
280 // the keys of the index and the entries of a filelist are matched
281 // without the query's trailing slash, the same in both branches below
282 rel := find_rel(path).trim_right('/')
283 if hit.listed {
284 for fc in caches {
285 for pkg in fc.cache.pkgs() {
286 names := pkg.get_files().names()
287 matched := if config.regex {
288 names.filter(patterns[qi].matches(it))
289 } else {
290 // a directory entry ends in its slash and has no
291 // file name; an entry with no slash has no directory
292 names.filter(it.contains('/') && it.all_after_last('/') == path)
293 }
294 if matched.len > 0 {
295 hit.repos << fc.db.get_name()
296 hit.pkgs << pkg
297 hit.files << matched
298 }
299 }
300 }
301 hits << hit
302 continue
303 }
304 if rel == '' {
305 // reported with the misses, once the spinner is gone
306 hits << hit
307 continue
308 }
309 if config.query.len > 1 {
310 // nspkg's own lookup matches the file and every directory on
311 // the way to it, which is what pacman's -Fo does; the index
312 // answers in the same order the walk would
313 for ref in index.refs[rel] {
314 hit.repos << ref.repo
315 hit.pkgs << index.pkgs[ref.pkg_i]
316 hit.files << [rel]
317 }
318 } else {
319 for fc in caches {
320 for pkg in fc.cache.pkgs() {
321 // nspkg's own lookup matches the file and every directory
322 // on the way to it, which is what pacman's -Fo does
323 if owner_matches(pkg, rel) {
324 hit.repos << fc.db.get_name()
325 hit.pkgs << pkg
326 hit.files << [rel]
327 }
328 }
329 }
330 }
331 // a miss is kept too: it is reported in its place among the results
332 hits << hit
333 }
334 if spun {
335 end_frame(mut ui, mut s)
336 }
337
338 for hit in hits {
339 if hit.pkgs.len == 0 {
340 if hit.path.trim_left('/') == '' && !hit.listed {
341 target_error('a file path is needed, not "${hit.path}"')
342 } else {
343 target_error('no package provides ${hit.path}')
344 }
345 } else if ipc_on() {
346 mut listing := Listing{
347 fields: ['source', 'name', 'version', 'description']
348 }
349 for i, pkg in hit.pkgs {
350 listing.add_pkg(pkg, hit.repos[i])
351 }
352 emit(ProvidesEvent{
353 path: hit.path
354 fields: listing.fields
355 entries: listing.entries
356 files: if hit.listed { hit.files } else { [][]string{} }
357 })
358 } else if config.machinereadable {
359 // one line a matched path, for a program to split
360 for i, pkg in hit.pkgs {
361 for file in hit.files[i] {
362 println(machine_line(hit.repos[i], pkg, file))
363 }
364 }
365 } else if config.quiet {
366 for i, pkg in hit.pkgs {
367 // pacman's -Fq prints repo/pkg, which is what tells packages
368 // that share a name apart
369 println('${hit.repos[i]}/${pkg.get_name()}')
370 }
371 } else if hit.listed {
372 // an expression or a file name finds many files: each is listed
373 // with its package
374 if config.query.len > 1 {
375 println(heading(hit.path))
376 }
377 mut rows := []Row{}
378 for i, pkg in hit.pkgs {
379 for file in hit.files[i] {
380 rows << row(file, source_style(hit.repos[i]), name_style(pkg.get_name()),
381 version_style(pkg.get_version()))
382 }
383 }
384 println(table_text(rows, '', ' '))
385 } else {
386 if config.query.len > 1 {
387 println(heading(hit.path))
388 }
389 mut listing := Listing{
390 fields: ['source', 'name', 'version', 'description']
391 }
392 for i, pkg in hit.pkgs {
393 listing.add_pkg(pkg, hit.repos[i])
394 }
395 listing.print()
396 }
397 }
398}
399
400// find_list lists the files of a sync package from the file dbs, pacman's -Fl
401fn find_list(mut ui TransUI, dbs []&nspkg.DB, filter []string, config ConfigFind) ! {
402 mut s := ui.spinner(text: 'searching file databases')
403 // quiet pipes its results: no spinner to glue a finished line onto them
404 plain := config.quiet || config.machinereadable
405 spun := !plain
406 if spun {
407 s.start()
408 }
409 defer { stop_spinner(mut s) }
410
411 caches := find_caches(dbs, filter)!
412 mut lines := []string{}
413 mut rows := []Row{}
414 mut missing := []string{}
415 for target in config.query {
416 // a target may name its repo, repo/package, as pacman's -Fl takes it
417 want_repo, name := if target.contains('/') {
418 target.all_before('/'), target.all_after('/')
419 } else {
420 '', target
421 }
422 if name == '' {
423 missing << target
424 continue
425 }
426 // the package the caches hold, or the miss it is: pkg keeps the nil
427 // answer as none instead of a sentinel &nspkg.Package
428 mut pkg := ?&nspkg.Package(none)
429 mut repo := ''
430 for fc in caches {
431 if want_repo != '' && fc.db.get_name() != want_repo {
432 continue
433 }
434 if p := fc.cache.pkg_find(name) {
435 pkg = ?&nspkg.Package(p)
436 repo = fc.db.get_name()
437 break
438 }
439 }
440 if p := pkg {
441 // the miss is counted, the hit is listed; under ipc it leaves as
442 // soon as it is collected, like find_owner's answers do
443 if ipc_on() {
444 emit(FilesEvent{
445 package: p.get_name()
446 repo: repo
447 paths: p.get_files().names()
448 })
449 continue
450 }
451 for file in p.get_files().names() {
452 // quiet is pacman's -Flq: the file paths alone, with no package
453 // name, so a file two packages hold is listed twice; the form's
454 // help says 'repo/pkg for paths, file paths for -l'
455 if config.machinereadable {
456 lines << machine_line(repo, p, file)
457 } else if config.quiet {
458 lines << file
459 } else {
460 // pacman's dump_file_list: the package, then the path
461 rows << row(name_style(p.get_name()), file)
462 }
463 }
464 } else {
465 // no cache holds it: the miss is named once the listing is out
466 missing << target
467 }
468 }
469 if spun {
470 end_frame(mut ui, mut s)
471 }
472 if plain && lines.len > 0 {
473 println(lines.join('\n'))
474 } else if !plain && rows.len > 0 {
475 println(table_text(rows, ' ', ' '))
476 }
477 // the misses follow the listing: written while the spinner ran, they
478 // would be drawn over
479 for name in missing {
480 target_error('"${name}" is not in the file databases: refresh them with vpac f -y')
481 }
482}
483