module main import nspkg import os import v.profiler // one archive file sitting in the cache, with its .sig companion removed // alongside it, like pacman's cleancache does. the failures are collected and // reported after: a clean that could not remove a file does not look // successful, and the meter only moves past the files that went fn cache_purge(mut ui TransUI, files []string) { mut bar := ui.meter(files.len, 'removing cached packages') bar.start() mut failed := []string{} for f in files { os.rm(f) or { failed << f continue } // the sig goes only once its package did. one that was never signed // has no companion to remove, so only a real failure is reported if os.exists(f + '.sig') { os.rm(f + '.sig') or { failed << f + '.sig' } } bar.add(1) } if failed.len > 0 { warn('could not remove ${failed.len} of ${files.len} cached files: ${failed.map(os.base(it)).join(', ')}') } } // is_pkg_archive is whether a file name is a package archive's: compressed // (.pkg.tar.zst and the like) or the plain .pkg.tar makepkg writes with no // compression, as pacman's cache clean takes both; never a signature fn is_pkg_archive(f string) bool { return (f.contains('.pkg.tar.') || f.ends_with('.pkg.tar')) && !f.ends_with('.sig') } fn cached_pkg_files() ![]string { mut out := []string{} for dir in cfg_cachedirs { names := os.ls(dir) or { // one unreadable cache dir does not take the others' cleaning // down with it: the run cleans what it can see, and says so warn('could not list the cache directory ${dir}: ${err.msg()}, cleaning the rest') continue } // package archives only, with their directory prefixed; sigs go with // their package, dbs stay out << names.filter(|f| is_pkg_archive(f)).map(|f| os.join_path(dir, f)) } return out } // sync_db_exts are the files a sync db is kept as, sigs and file dbs too const sync_db_exts = ['.db.sig', '.files.sig', '.db', '.files'] // unused_sync_dbs are the sync db files of repos the config does not name // any more, what pacman's -Sc asks about as 'unused repositories'. pacman // clears everything else out of the sync dir with them; only what is // plainly a db goes here, so the sync stamp and anything unknown stay fn unused_sync_dbs() []string { dir := db_path + 'sync/' if !os.is_dir(dir) { return []string{} } mut names := os.ls(dir) or { warn('could not list the sync databases in ${dir}: ${err.msg()}, none is cleaned') return []string{} } names.sort() known := cfg_repos.filter(it.kind != 'pkgbuild').map(it.name) mut out := []string{} for f in names { for ext in sync_db_exts { if f.len > ext.len && f.ends_with(ext) { if f[..f.len - ext.len] !in known { out << dir + f } break } } } return out } // a cached package archive: pkgname-pkgver-pkgrel-arch.pkg.tar[.*] struct CacheFile { name string version string file string } // installed_file is whether a cached archive is the installed version of its // package. the cache is listed as full paths and the prefixes are // name-version-, so the file name is what they are matched against: its // name and version read out whole, as pacman compares the archive's own, so // a package whose name merely begins with another's name-version- is not // taken for it. a name that does not read as an archive's is matched by its // beginning, the careful way round: it is kept fn installed_file(f string, keep_prefixes []string) bool { if c := parse_cache_file(f) { return '${c.name}-${c.version}-' in keep_prefixes } name := os.base(f) return keep_prefixes.any(|k| name.starts_with(k)) } fn parse_cache_file(f string) ?CacheFile { base := os.base(f).all_before('.pkg.tar') toks := base.split('-') if toks.len < 4 { return none } arch_t := toks.last() rel := toks[toks.len - 2] ver := toks[toks.len - 3] name := toks[..toks.len - 3].join('-') if arch_t == '' || rel == '' || ver == '' || name == '' { return none } return CacheFile{ name: name version: ver + '-' + rel file: f } } // paccache's KeepInstalled+KeepN: keep the newest `keep_n` versions of every // package, plus whatever is currently installed. an installed version is // kept once even though it also counts among the newest, so the answer is a // set and the caller's filtering reads it straight fn paccache_keep(keep_n int, files []string, keep_prefixes []string) map[string]bool { mut groups := map[string][]CacheFile{} mut kept := map[string]bool{} for f in files { // installed versions are always kept, and they still count among the // newest: -k 2 keeps two versions, not the installed one and two more if installed_file(f, keep_prefixes) { kept[f] = true } cf := parse_cache_file(f) or { continue } if cf.name !in groups { groups[cf.name] = []CacheFile{} } groups[cf.name] << cf } for name in groups.keys() { mut gg := groups[name] // newest first, using the same vercmp as pacman gg.sort_with_compare(fn (a &CacheFile, b &CacheFile) int { return nspkg.pkg_vercmp(b.version, a.version) }) for i, cf in gg { if i < keep_n { kept[cf.file] = true } } } return kept } // BuildClean is what vpac c does with the pkgbuild build dirs: of the builds // found under root, the ones it removes and their size struct BuildClean { user string root string mut: found int dirs []string size u64 // partial says the size is a floor: part of a build could not be read, // and what is there is more than was counted partial bool } // build_dirs_to_clean picks the pkgbuild builds vpac c removes. like paru's // and yay's clean, a build stays while its package is installed: its dir is // named after an installed package base (vpac i --pkgbuild), or it holds a // built archive of an installed package (vpac b, split packages). with all, // every build goes. a build is pulled afresh each time, so nothing in a // removed one is ever reused fn build_dirs_to_clean(user string, all bool, bases []string, names []string) !BuildClean { root := pkgbuild_root(user)! mut bc := BuildClean{ user: user root: root } if !os.is_dir(root) { return bc } for entry in os.ls(root)! { dir := os.join_path(root, entry) if os.is_link(dir) || !os.is_dir(dir) { continue } bc.found++ if !all && build_in_use(dir, entry, bases, names) { continue } bc.dirs << dir size, whole := tree_size(dir) bc.size += size if !whole { bc.partial = true } } return bc } // build_in_use is whether a build dir belongs to an installed package fn build_in_use(dir string, entry string, bases []string, names []string) bool { if entry in bases { return true } // fail closed: when the build cannot even be listed, it cannot be proven // unused, and clean never deletes something it is not sure of. clean runs // as root through run_as_user, so an unreadable dir is reported plainly pkgs := archives_in(dir) or { warn("could not list the built packages of '${dir}': ${err.msg()}, keeping the build") return true } for archive in pkgs { cf := parse_cache_file(os.base(archive)) or { continue } if cf.name in names { return true } } return false } // tree_size adds up the files under path, and says whether that is the // whole of it: a directory that cannot be listed is warned about and // counted as nothing, which makes the sum a floor and not the size. the // rest of the tree is still counted. links are not followed: a build tree // may point anywhere fn tree_size(path string) (u64, bool) { if os.is_link(path) { return 0, true } if !os.is_dir(path) { return os.file_size(path), true } names := os.ls(path) or { warn('could not read ${path}: ${err.msg()}, its size is left out') return 0, false } mut total := u64(0) mut whole := true for name in names { size, sub_whole := tree_size(os.join_path(path, name)) total += size whole = whole && sub_whole } return total, whole } // size_text spells a size for a person; one that is a floor says so fn size_text(size u64, partial bool) string { text := profiler.format_bytes(size) return if partial { 'at least ${text}' } else { text } } // clean_event is what a frontend is told before the proceed question. the // build root goes out only when an invoker was known and its builds looked // at; BuildClean{} is the unlooked-at one fn clean_event(to_remove []string, total u64, builds BuildClean, dbs []string, preview bool) CleanEvent { return CleanEvent{ cache_dirs: cfg_cachedirs build_root: if builds.user != '' { ?string(builds.root) } else { none } files: to_remove files_size: total builds: builds.dirs build_size: builds.size build_size_partial: builds.partial dbs: dbs preview: preview } } fn clean(config ConfigClean) ! { mut ui := new_trans_ui(noconfirm: config.noconfirm) mut handle := init_handle(ui)! defer { handle.release() or { went_on('release the nspkg handle', err) } } defer { ui.stop() } mut pkgcache := local_pkgcache(handle)! installed := pkgcache.pkgs() // the package cache: everything with -a or -cc (pacman's -Scc), // otherwise pacman's default KeepInstalled clean method, optionally // paccache style with -k N: keep the newest N versions of every package every := config.all || config.level >= 2 pkg_files := cached_pkg_files()! to_remove := if every { pkg_files } else { mut keep_prefixes := installed.map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-') // pacman's KeepCurrent: a version a sync db still carries stays too if config.keep_current { for db in init_repos(mut handle)! { // a sync db that cannot be read would keep nothing: what it // carries would be cleaned as if no repo had it any more mut cache := pkgcache_of(handle, db)! keep_prefixes << cache.pkgs().map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-') } } to_keep := if config.keep > 0 { // a set of paths, not a list: a cache of thousands of archives is // filtered by map lookup per file, not a scan per file paccache_keep(config.keep, pkg_files, keep_prefixes) } else { mut keep := map[string]bool{} for f in pkg_files.filter(|f| installed_file(f, keep_prefixes)) { keep[f] = true } keep } pkg_files.filter(|f| !to_keep[f]) } mut total := u64(0) for f in to_remove { total += os.file_size(f) } // the pkgbuild builds are the invoker's: root running vpac c itself has // none, since builds never run as root. a root session nobody asked for // says so, instead of quietly leaving every build dir behind it mut builds := BuildClean{} if user := invoker_user() { builds = build_dirs_to_clean(user, config.all, installed.map(it.get_base()), installed.map(it.get_name()))! } else { warn('pkgbuild builds are not cleaned: run vpac as your own user') } // the sync dbs of repos the config dropped go with any clean, as // pacman's -Sc offers dbs := unused_sync_dbs() // a frontend gets what would go as one event; the proceed question follows // it unless this is a --print preview if ipc_on() { emit(clean_event(to_remove, total, builds, dbs, config.print_only)) if config.print_only || (to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0) { return } } // --print lists what would go, a path a line, and removes nothing if config.print_only { for f in to_remove { println(f) } for dir in builds.dirs { println(dir) } for f in dbs { println(f) } return } mut summary := [kv('cache directory', cfg_cachedirs.join(', '))] if pkg_files.len > 0 { if every { summary << kv('remove', 'all ${pkg_files.len} files (${profiler.format_bytes(total)})') } else { summary << kv('keep', 'all locally installed packages') if config.keep_current { summary << row('', 'the versions the sync dbs carry') } if config.keep > 0 { summary << row('', 'the ${config.keep} newest versions of every package') } summary << kv('remove', if to_remove.len == 0 { 'nothing' } else { '${to_remove.len} files (${profiler.format_bytes(total)})' }) } } if builds.found > 0 { summary << kv('build directory', builds.root) if config.all { summary << kv('remove', 'all ${builds.found} builds (${size_text(builds.size, builds.partial)})') } else { summary << kv('keep', 'the builds of installed packages') summary << kv('remove', if builds.dirs.len == 0 { 'nothing' } else { '${builds.dirs.len} builds (${size_text(builds.size, builds.partial)}): ${builds.dirs.map(os.base(it)).join(', ')}' }) } } if dbs.len > 0 { summary << kv('database directory', db_path + 'sync/') summary << kv('remove', '${dbs.len} files of unused repos: ${dbs.map(os.base(it)).join(', ')}') } if !ipc_on() { println(table_text(summary, '', ' ')) } if to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0 { println(if pkg_files.len == 0 && builds.found == 0 { 'cache is empty' } else { 'nothing to remove' }) return } if !ui.proceed('proceed?') { return } if to_remove.len > 0 { cache_purge(mut ui, to_remove) } if dbs.len > 0 { mut failed := []string{} for f in dbs { os.rm(f) or { failed << os.base(f) } } if failed.len > 0 { warn('could not remove ${failed.len} of ${dbs.len} unused sync database files: ${failed.join(', ')}') } } if builds.dirs.len > 0 { // removed as the user who built them, the way the builds clear their // own dirs: root never deletes inside the user's tree mut s := ui.spinner(text: 'removing pkgbuild builds') s.start() defer { stop_spinner(mut s) } mut args := ['rm', '-rf', '--'] args << builds.dirs run_as_user(builds.user, args)! stop_spinner(mut s) } }