pactree: Add "--config" option
[pacman-ng.git] / contrib / paccache.in
blob4e185c27012637ae2068956d58cc0a3ab4b0deb3
1 #!/bin/bash
3 # pacache - flexible pacman cache cleaning
5 # Copyright (C) 2011 Dave Reisner <dreisner@archlinux.org>
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 shopt -s extglob
23 declare -a candidates=() cmdopts=() whitelist=() blacklist=()
24 declare -i delete=0 dryrun=0 filecount=0 move=0 needsroot=0 totalsaved=0 verbose=0
25 declare cachedir=@localstatedir@/cache/pacman/pkg delim=$'\n' keep=3 movedir= scanarch=
27 msg() {
28 local mesg=$1; shift
29 printf "==> $mesg\n" "$@"
30 } >&2
32 error() {
33 local mesg=$1; shift
34 printf "==> ERROR: $mesg\n" "$@"
35 } >&2
37 die() {
38 error "$@"
39 exit 1
42 # reads a list of files on stdin and prints out deletion candidates
43 pkgfilter() {
44 # there's whitelist and blacklist parameters passed to this
45 # script after the block of awk.
47 awk -v keep="$1" -v scanarch="$2" '
48 function parse_filename(filename, parts, count, i, pkgname, arch) {
50 count = split(filename, parts, "-")
52 i = 1
53 pkgname = parts[i++]
54 while (i <= count - 3) {
55 pkgname = pkgname "-" parts[i++]
58 arch = substr(parts[count], 1, index(parts[count], ".") - 1)
60 # filter on whitelist or blacklist
61 if (wlen && !whitelist[pkgname]) return
62 if (blen && blacklist[pkgname]) return
64 if ("" == packages[pkgname,arch]) {
65 packages[pkgname,arch] = filename
66 } else {
67 packages[pkgname,arch] = packages[pkgname,arch] SUBSEP filename
71 BEGIN {
72 # create whitelist
73 wlen = ARGV[1]; delete ARGV[1]
74 for (i = 2; i < 2 + wlen; i++) {
75 whitelist[ARGV[i]] = 1
76 delete ARGV[i]
79 # create blacklist
80 blen = ARGV[i]; delete ARGV[i]
81 while (i++ < ARGC) {
82 blacklist[ARGV[i]] = 1
83 delete ARGV[i]
86 # read package filenames
87 while (getline < "/dev/stdin") {
88 parse_filename($0)
91 for (pkglist in packages) {
92 # idx[1,2] = idx[pkgname,arch]
93 split(pkglist, idx, SUBSEP)
95 # enforce architecture match if specified
96 if (!scanarch || scanarch == idx[2]) {
97 count = split(packages[idx[1], idx[2]], pkgs, SUBSEP)
98 for(i = 1; i <= count - keep; i++) {
99 print pkgs[i]
103 }' "${@:3}"
106 size_to_human() {
107 awk -v size="$1" '
108 BEGIN {
109 suffix[1] = "B"
110 suffix[2] = "KiB"
111 suffix[3] = "MiB"
112 suffix[4] = "GiB"
113 suffix[5] = "TiB"
114 count = 1
116 while (size > 1024) {
117 size /= 1024
118 count++
121 sizestr = sprintf("%.2f", size)
122 sub(/\.?0+$/, "", sizestr)
123 printf("%s %s", sizestr, suffix[count])
127 runcmd() {
128 if (( needsroot )); then
129 msg "Privilege escalation required"
130 if sudo -v &>/dev/null && sudo -l &>/dev/null; then
131 sudo "$@"
132 else
133 printf '%s ' 'root'
134 su -c "$(printf '%q ' "$@")"
136 else
137 "$@"
141 summarize() {
142 local -i filecount=$1; shift
143 local seenarch= seen= arch= name=
144 local -r pkg_re='(.+)-[^-]+-[0-9]+-([^.]+)\.pkg.*'
146 if (( delete )); then
147 printf -v output 'finished: %d packages removed' "$filecount"
148 elif (( move )); then
149 printf -v output "finished: %d packages moved to \`%s'" "$filecount" "$movedir"
150 elif (( dryrun )); then
151 if (( verbose )); then
152 msg "Candidate packages:"
153 while read -r pkg; do
154 if (( verbose >= 3 )); then
155 [[ $pkg =~ $pkg_re ]] && name=${BASH_REMATCH[1]} arch=${BASH_REMATCH[2]}
156 if [[ -z $seen || $seenarch != "$arch" || $seen != "$name" ]]; then
157 printf '%s (%s):\n' "$name" "$arch"
159 printf ' %s\n' "$pkg"
160 elif (( verbose >= 2 )); then
161 printf "$PWD/%s$delim" "$pkg"
162 else
163 printf "%s$delim" "$pkg"
165 done < <(printf '%s\n' "$@" | pacsort)
167 printf -v output 'finished dry run: %d candidates' "$filecount"
170 printf '\n' >&2
171 msg "$output (diskspace saved: %s)" "$(size_to_human "$totalsaved")"
174 usage() {
175 cat <<EOF
176 usage: ${0##*/} <operation> [options] [targets...]
178 ${0##*/} is a flexible pacman cache cleaning utility, which has numerous
179 options to help control how much, and what, is deleted from any directory
180 containing pacman package tarballs.
182 Operations:
183 -d perform a dry run, only finding candidate packages.
184 -m <movedir> move candidate packages to 'movedir'.
185 -r remove candidate packages.
187 Options:
188 -a <arch> scan for 'arch' (default: all architectures).
189 -c <cachedir> scan 'cachedir' for packages (default: @localstatedir@/cache/pacman/pkg).
190 -f apply force to mv(1) and rm(1) operations.
191 -h display this help message.
192 -i <pkgs> ignore 'pkgs', which is a comma separated. Alternatively,
193 specify '-' to read package names from stdin, newline delimited.
194 -k <num> keep 'num' of each package in 'cachedir' (default: 3).
195 -u target uninstalled packages.
196 -v increase verbosity. specify up to 3 times.
197 -z use null delimiters for candidate names (only with -v and -vv)
202 if (( ! UID )); then
203 error "Do not run this script as root. You will be prompted for privilege escalation."
204 exit 42
207 while getopts ':a:c:dfhi:k:m:rsuvz' opt; do
208 case $opt in
209 a) scanarch=$OPTARG ;;
210 c) cachedir=$OPTARG ;;
211 d) dryrun=1 ;;
212 f) cmdopts=(-f) ;;
213 h) usage
214 exit 0 ;;
215 i) if [[ $OPTARG = '-' ]]; then
216 [[ ! -t 0 ]] && IFS=$'\n' read -r -d '' -a ign
217 else
218 IFS=',' read -r -a ign <<< "$OPTARG"
220 blacklist+=("${ign[@]}")
221 unset i ign ;;
222 k) keep=$OPTARG
223 if [[ -z $keep || -n ${keep//[0-9]/} ]]; then
224 die 'argument to option -k must be a non-negative integer'
225 else
226 keep=$(( 10#$keep ))
227 fi ;;
228 m) move=1 movedir=$OPTARG ;;
229 r) delete=1 ;;
230 u) IFS=$'\n' read -r -d '' -a ign < <(pacman -Qq)
231 blacklist+=("${ign[@]}")
232 unset ign ;;
233 v) (( ++verbose )) ;;
234 z) delim='\0' ;;
235 :) die "option '--%s' requires an argument" "$OPTARG" ;;
236 ?) die "invalid option -- '%s'" "$OPTARG" ;;
237 esac
238 done
239 shift $(( OPTIND - 1 ))
241 # remaining args are a whitelist
242 whitelist=("$@")
244 # sanity checks
245 case $(( dryrun+delete+move )) in
246 0) die "no operation specified (use -h for help)" ;;
247 [^1]) die "only one operation may be used at a time" ;;
248 esac
250 [[ -d $cachedir ]] ||
251 die "cachedir \`%s' does not exist or is not a directory" "$cachedir"
253 [[ $movedir && ! -d $movedir ]] &&
254 die "move-to directory \`%s' does not exist or is not a directory" "$movedir"
256 if (( move || delete )); then
257 # make it an absolute path since we're about to chdir
258 [[ ${movedir:0:1} != '/' ]] && movedir=$PWD/$movedir
259 [[ ! -w $cachedir || ( $movedir && ! -w $movedir ) ]] && needsroot=1
262 # unlikely that this will fail, but better make sure
263 cd "$cachedir" || die "failed to chdir to \`%s'" "$cachedir"
265 # note that these results are returned in an arbitrary order from awk, but
266 # they'll be resorted (in summarize) iff we have a verbosity level set.
267 IFS=$'\n' read -r -d '' -a candidates < \
268 <(printf '%s\n' *.pkg.tar?(.+([^.])) | pacsort |
269 pkgfilter "$keep" "$scanarch" \
270 "${#whitelist[*]}" "${whitelist[@]}" \
271 "${#blacklist[*]}" "${blacklist[@]}")
273 if (( ! ${#candidates[*]} )); then
274 msg 'no candidate packages found for pruning'
275 exit 1
278 # grab this prior to signature scavenging
279 pkgcount=${#candidates[*]}
281 # copy the list, merging in any found sigs
282 for cand in "${candidates[@]}"; do
283 candtemp+=("$cand")
284 [[ -f $cand.sig ]] && candtemp+=("$cand.sig")
285 done
286 candidates=("${candtemp[@]}")
287 unset candtemp
289 # do this before we destroy anything
290 totalsaved=$(@SIZECMD@ "${candidates[@]}" | awk '{ sum += $1 } END { print sum }')
292 # crush. kill. destroy.
293 (( verbose )) && cmdopts+=(-v)
294 if (( delete )); then
295 runcmd rm "${cmdopts[@]}" "${candidates[@]}"
296 elif (( move )); then
297 runcmd mv "${cmdopts[@]}" "${candidates[@]}" "$movedir"
300 summarize "$pkgcount" "${candidates[@]}"