vpac / src / find.v
476 lines · 447 sloc · 14.29 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1module main
2
3import alpm
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 alpm 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. reading needs none of that,
107// and keeps the lean handle of the read-only modes
108fn find_handle(mut ui TransUI, refresh bool) !&alpm.Handle {
109 handle := if refresh {
110 init_handle(ui)!
111 } else {
112 alpm.initialize(root_path, db_path) or { return err }
113 }
114 handle.option_set_dbext('.files') or {
115 handle.release() or { went_on('release the alpm handle', err) }
116 return err
117 }
118 return handle
119}
120
121// FileCache is one file db loaded: the db, for its name, and its package cache
122struct FileCache {
123 db &alpm.DB
124 cache &alpm.List
125}
126
127// find_caches loads the file db package caches the named repos ask for, with
128// a name in the error, because a missing .files file is the one thing a first
129// run trips over. an empty filter loads them all
130fn find_caches(dbs []&alpm.DB, filter []string) ![]FileCache {
131 mut out := []FileCache{}
132 for db in dbs {
133 if filter.len > 0 && db.get_name() !in filter {
134 continue
135 }
136 // a db with no packages is an empty one, not a broken one
137 cache := pkgcache_of(db.get_handle(), db) or {
138 return error('the file database of ${db.get_name()} is missing or broken (${err.msg()}): refresh it with vpac f -y')
139 }
140 out << FileCache{
141 db: db
142 cache: cache
143 }
144 }
145 return out
146}
147
148// OwnerRef is one claim in the inverted file index: the repo whose file db
149// listed the package, and the package by its place in the pkgs list the
150// index walks (the list of packages itself is kept beside the index, so no
151// pointer-bearing struct has to live in the map's cells)
152struct OwnerRef {
153 repo string
154 pkg_i int
155}
156
157// owner_index is the inverted file index of the caches: every file and
158// directory the file dbs hold, naming the packages that carry them. each
159// query path would otherwise walk every package and its C-side filelist
160// once, which is what makes an owner search over a full file db crawl
161// (alpm_filelist_contains is a scan per path). the keys carry no trailing
162// slash — a directory entry and a file land under the same key — and the
163// entries are ordered as the dbs and their packages come, the same order
164// the walk reports them in
165fn owner_index(caches []FileCache) OwnerIndex {
166 mut index := OwnerIndex{}
167 for fc in caches {
168 for pkg in fc.cache.pkgs() {
169 pkg_i := index.pkgs.len
170 index.pkgs << pkg
171 for name in pkg.get_files().names() {
172 key := name.trim_right('/')
173 if key == '' {
174 continue
175 }
176 index.refs[key] << OwnerRef{
177 repo: fc.db.get_name()
178 pkg_i: pkg_i
179 }
180 }
181 }
182 }
183 return index
184}
185
186// OwnerIndex is owner_index's answer, one value: a multi-path search takes it
187// as it is built, where two variables filled after the fact would each be a
188// copy of an index as large as every filelist of the dbs
189struct OwnerIndex {
190mut:
191 refs map[string][]OwnerRef
192 pkgs []&alpm.Package
193}
194
195// owner_matches answers whether a file db entry provides the path. directories
196// in a filelist carry a trailing slash, so the query, given without its own,
197// is tried both ways
198fn owner_matches(pkg &alpm.Package, rel string) bool {
199 return pkg.get_files().contains(rel) != none
200 || pkg.get_files().contains(rel + '/') != none
201}
202
203// OwnerHit is one path's matches, kept so the results print only after the
204// spinner stops. files are the paths that matched in each package: the path
205// asked for, or every file an expression or a bare file name found — listed
206// is set for those two, whose answer is the files and not only the packages
207struct OwnerHit {
208 path string
209 listed bool
210mut:
211 repos []string
212 pkgs []&alpm.Package
213 files [][]string
214}
215
216// machine_line is pacman's --machinereadable line: repo, package, version
217// and path, parted by NUL bytes
218fn machine_line(repo string, pkg &alpm.Package, file string) string {
219 return [repo, pkg.get_name(), pkg.get_version(), file].join('\0')
220}
221
222// find_owner answers which repo package provides a path, pacman's -Fo. the
223// paths are relative to root, with or without the leading slash, and every
224// path given is searched
225fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! {
226 // -x: every expression compiles before anything is searched, and a bad
227 // one stops the run once all of them are named, as in pacman
228 mut patterns := []FilePattern{}
229 defer {
230 for p in patterns {
231 C.regfree(p.re)
232 }
233 }
234 if config.regex {
235 mut bad := 0
236 for target in config.query {
237 patterns << file_pattern(target) or {
238 target_error(err.msg())
239 bad++
240 continue
241 }
242 }
243 if bad > 0 {
244 return
245 }
246 }
247 mut s := ui.spinner(text: 'searching file databases')
248 // quiet pipes its results: no spinner to glue a finished line onto them
249 spun := !config.quiet && !config.machinereadable
250 if spun {
251 s.start()
252 }
253 defer { stop_spinner(mut s) }
254
255 caches := find_caches(dbs, filter)!
256 // many paths or one: building the index costs about one walk of every
257 // filelist, so a single-path search keeps its own walk, and a multi-path
258 // one pays once and does every later path by lookup. an expression is
259 // no key to look up: it walks
260 index := if config.query.len > 1 && !config.regex {
261 owner_index(caches)
262 } else {
263 OwnerIndex{}
264 }
265 mut hits := []OwnerHit{}
266 for qi, path in config.query {
267 // a target with no slash is a file name, looked for in every
268 // directory, as pacman's files_search does without -x too
269 by_name := !path.contains('/')
270 mut hit := OwnerHit{
271 path: path
272 listed: config.regex || by_name
273 }
274 // the keys of the index and the entries of a filelist are matched
275 // without the query's trailing slash, the same in both branches below
276 rel := find_rel(path).trim_right('/')
277 if hit.listed {
278 for fc in caches {
279 for pkg in fc.cache.pkgs() {
280 names := pkg.get_files().names()
281 matched := if config.regex {
282 names.filter(patterns[qi].matches(it))
283 } else {
284 // a directory entry ends in its slash and has no
285 // file name; an entry with no slash has no directory
286 names.filter(it.contains('/') && it.all_after_last('/') == path)
287 }
288 if matched.len > 0 {
289 hit.repos << fc.db.get_name()
290 hit.pkgs << pkg
291 hit.files << matched
292 }
293 }
294 }
295 hits << hit
296 continue
297 }
298 if rel == '' {
299 // reported with the misses, once the spinner is gone
300 hits << hit
301 continue
302 }
303 if config.query.len > 1 {
304 // alpm's own lookup matches the file and every directory on
305 // the way to it, which is what pacman's -Fo does; the index
306 // answers in the same order the walk would
307 for ref in index.refs[rel] {
308 hit.repos << ref.repo
309 hit.pkgs << index.pkgs[ref.pkg_i]
310 hit.files << [rel]
311 }
312 } else {
313 for fc in caches {
314 for pkg in fc.cache.pkgs() {
315 // alpm's own lookup matches the file and every directory
316 // on the way to it, which is what pacman's -Fo does
317 if owner_matches(pkg, rel) {
318 hit.repos << fc.db.get_name()
319 hit.pkgs << pkg
320 hit.files << [rel]
321 }
322 }
323 }
324 }
325 // a miss is kept too: it is reported in its place among the results
326 hits << hit
327 }
328 if spun {
329 end_frame(mut ui, mut s)
330 }
331
332 for hit in hits {
333 if hit.pkgs.len == 0 {
334 if hit.path.trim_left('/') == '' && !hit.listed {
335 target_error('a file path is needed, not "${hit.path}"')
336 } else {
337 target_error('no package provides ${hit.path}')
338 }
339 } else if ipc_on() {
340 mut listing := Listing{
341 fields: ['source', 'name', 'version', 'description']
342 }
343 for i, pkg in hit.pkgs {
344 listing.add_pkg(pkg, hit.repos[i])
345 }
346 emit(ProvidesEvent{
347 path: hit.path
348 fields: listing.fields
349 entries: listing.entries
350 files: if hit.listed { hit.files } else { [][]string{} }
351 })
352 } else if config.machinereadable {
353 // one line a matched path, for a program to split
354 for i, pkg in hit.pkgs {
355 for file in hit.files[i] {
356 println(machine_line(hit.repos[i], pkg, file))
357 }
358 }
359 } else if config.quiet {
360 for i, pkg in hit.pkgs {
361 // pacman's -Fq prints repo/pkg, which is what tells packages
362 // that share a name apart
363 println('${hit.repos[i]}/${pkg.get_name()}')
364 }
365 } else if hit.listed {
366 // an expression or a file name finds many files: each is listed
367 // with its package
368 if config.query.len > 1 {
369 println(heading(hit.path))
370 }
371 mut rows := []Row{}
372 for i, pkg in hit.pkgs {
373 for file in hit.files[i] {
374 rows << row(file, source_style(hit.repos[i]), name_style(pkg.get_name()),
375 version_style(pkg.get_version()))
376 }
377 }
378 println(table_text(rows, '', ' '))
379 } else {
380 if config.query.len > 1 {
381 println(heading(hit.path))
382 }
383 mut listing := Listing{
384 fields: ['source', 'name', 'version', 'description']
385 }
386 for i, pkg in hit.pkgs {
387 listing.add_pkg(pkg, hit.repos[i])
388 }
389 listing.print()
390 }
391 }
392}
393
394// find_list lists the files of a sync package from the file dbs, pacman's -Fl
395fn find_list(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! {
396 mut s := ui.spinner(text: 'searching file databases')
397 // quiet pipes its results: no spinner to glue a finished line onto them
398 plain := config.quiet || config.machinereadable
399 spun := !plain
400 if spun {
401 s.start()
402 }
403 defer { stop_spinner(mut s) }
404
405 caches := find_caches(dbs, filter)!
406 mut lines := []string{}
407 mut rows := []Row{}
408 mut missing := []string{}
409 for target in config.query {
410 // a target may name its repo, repo/package, as pacman's -Fl takes it
411 want_repo, name := if target.contains('/') {
412 target.all_before('/'), target.all_after('/')
413 } else {
414 '', target
415 }
416 if name == '' {
417 missing << target
418 continue
419 }
420 // the package the caches hold, or the miss it is: pkg keeps the nil
421 // answer as none instead of a sentinel &alpm.Package
422 mut pkg := ?&alpm.Package(none)
423 mut repo := ''
424 for fc in caches {
425 if want_repo != '' && fc.db.get_name() != want_repo {
426 continue
427 }
428 if p := fc.cache.pkg_find(name) {
429 pkg = ?&alpm.Package(p)
430 repo = fc.db.get_name()
431 break
432 }
433 }
434 if p := pkg {
435 // the miss is counted, the hit is listed; under ipc it leaves as
436 // soon as it is collected, like find_owner's answers do
437 if ipc_on() {
438 emit(FilesEvent{
439 package: p.get_name()
440 repo: repo
441 paths: p.get_files().names()
442 })
443 continue
444 }
445 for file in p.get_files().names() {
446 // quiet is pacman's -Flq: the file paths alone, with no package
447 // name, so a file two packages hold is listed twice; the form's
448 // help says 'repo/pkg for paths, file paths for -l'
449 if config.machinereadable {
450 lines << machine_line(repo, p, file)
451 } else if config.quiet {
452 lines << file
453 } else {
454 // pacman's dump_file_list: the package, then the path
455 rows << row(name_style(p.get_name()), file)
456 }
457 }
458 } else {
459 // no cache holds it: the miss is named once the listing is out
460 missing << target
461 }
462 }
463 if spun {
464 end_frame(mut ui, mut s)
465 }
466 if plain && lines.len > 0 {
467 println(lines.join('\n'))
468 } else if !plain && rows.len > 0 {
469 println(table_text(rows, ' ', ' '))
470 }
471 // the misses follow the listing: written while the spinner ran, they
472 // would be drawn over
473 for name in missing {
474 target_error('"${name}" is not in the file databases: refresh them with vpac f -y')
475 }
476}
477