| 1 | // cache lookup and partial size accounting follow pacman util.c and sync.c. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | pub struct CachedFile { |
| 8 | pub: |
| 9 | found bool |
| 10 | path string |
| 11 | size i64 |
| 12 | } |
| 13 | |
| 14 | pub fn (mut handle Handle) find_cached_file(filename string) !CachedFile { |
| 15 | handle.check()! |
| 16 | return handle.cached_file(filename) |
| 17 | } |
| 18 | |
| 19 | fn (mut handle Handle) cached_file(filename string) !CachedFile { |
| 20 | for directory in handle.opts.lists[.cache_dirs] { |
| 21 | path := directory + filename |
| 22 | info := os.stat(path) or { |
| 23 | if err.code() != int(C.ENOENT) { |
| 24 | handle.diagnostics << 'could not stat ${path}: ${err.msg()}' |
| 25 | handle.log(.warning, "could not open '${path}'\n: ${err.msg()}") |
| 26 | } |
| 27 | continue |
| 28 | } |
| 29 | if info.mode & 0o170000 == 0o100000 { |
| 30 | handle.log(.debug, 'found cached pkg: ${path}\n') |
| 31 | return CachedFile{ found: true, path: path, size: i64(info.size) } |
| 32 | } |
| 33 | handle.diagnostics << 'cached package is not a regular file: ${path}' |
| 34 | handle.log(.warning, "cached pkg '${path}' is not a regular file: mode=${info.mode}\n") |
| 35 | } |
| 36 | return CachedFile{} |
| 37 | } |
| 38 | |
| 39 | fn (mut handle Handle) compute_download_size(mut pkg Package) ! { |
| 40 | if pkg.origin != .sync_db { |
| 41 | pkg.download_bytes = 0 |
| 42 | pkg.download_size_loaded = true |
| 43 | return |
| 44 | } |
| 45 | if pkg.filename == '' && !pkg.has_filename { |
| 46 | return handle.fail(.pkg_invalid_name, pkg.name) |
| 47 | } |
| 48 | cached := handle.cached_file(pkg.filename)! |
| 49 | if cached.found { |
| 50 | pkg.download_bytes = 0 |
| 51 | } else { |
| 52 | partial := handle.cached_file(pkg.filename + '.part')! |
| 53 | if partial.found { |
| 54 | // sync.c stats again after lookup; callbacks can change the partial file. |
| 55 | pkg.download_bytes = 0 |
| 56 | if info := os.stat(partial.path) { |
| 57 | handle.log(.debug, 'using (package - .part) size\n') |
| 58 | pkg.download_bytes = if pkg.size > i64(info.size) { |
| 59 | pkg.size - i64(info.size) |
| 60 | } else { |
| 61 | 0 |
| 62 | } |
| 63 | } |
| 64 | } else { |
| 65 | pkg.download_bytes = pkg.size |
| 66 | } |
| 67 | } |
| 68 | handle.log(.debug, 'setting download size ${pkg.download_bytes} for pkg ${pkg.name}\n') |
| 69 | pkg.download_size_loaded = true |
| 70 | } |
| 71 | |
| 72 | pub fn (mut handle Handle) package_download_size(mut pkg Package) !i64 { |
| 73 | handle.require_live()! |
| 74 | if !pkg.download_size_loaded { handle.compute_download_size(mut pkg)! } |
| 75 | return pkg.download_bytes |
| 76 | } |
| 77 | |