paccache: add vim modeline
[pacman-ng.git] / contrib / paccache.in
blobeae547dc9d01ba9b3f405c808ecd1941779e7284
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 seen=$name seenarch=$arch
158 printf '%s (%s):\n' "$name" "$arch"
160 printf ' %s\n' "$pkg"
161 elif (( verbose >= 2 )); then
162 printf "$PWD/%s$delim" "$pkg"
163 else
164 printf "%s$delim" "$pkg"
166 done < <(printf '%s\n' "$@" | pacsort)
168 printf -v output 'finished dry run: %d candidates' "$filecount"
171 printf '\n' >&2
172 msg "$output (diskspace saved: %s)" "$(size_to_human "$totalsaved")"
175 usage() {
176 cat <<EOF
177 usage: ${0##*/} <operation> [options] [targets...]
179 ${0##*/} is a flexible pacman cache cleaning utility, which has numerous
180 options to help control how much, and what, is deleted from any directory
181 containing pacman package tarballs.
183 Operations:
184 -d perform a dry run, only finding candidate packages.
185 -m <movedir> move candidate packages to 'movedir'.
186 -r remove candidate packages.
188 Options:
189 -a <arch> scan for 'arch' (default: all architectures).
190 -c <cachedir> scan 'cachedir' for packages (default: @localstatedir@/cache/pacman/pkg).
191 -f apply force to mv(1) and rm(1) operations.
192 -h display this help message.
193 -i <pkgs> ignore 'pkgs', which is a comma separated. Alternatively,
194 specify '-' to read package names from stdin, newline delimited.
195 -k <num> keep 'num' of each package in 'cachedir' (default: 3).
196 -u target uninstalled packages.
197 -v increase verbosity. specify up to 3 times.
198 -z use null delimiters for candidate names (only with -v and -vv)
203 if (( ! UID )); then
204 error "Do not run this script as root. You will be prompted for privilege escalation."
205 exit 42
208 while getopts ':a:c:dfhi:k:m:rsuvz' opt; do
209 case $opt in
210 a) scanarch=$OPTARG ;;
211 c) cachedir=$OPTARG ;;
212 d) dryrun=1 ;;
213 f) cmdopts=(-f) ;;
214 h) usage
215 exit 0 ;;
216 i) if [[ $OPTARG = '-' ]]; then
217 [[ ! -t 0 ]] && IFS=$'\n' read -r -d '' -a ign
218 else
219 IFS=',' read -r -a ign <<< "$OPTARG"
221 blacklist+=("${ign[@]}")
222 unset i ign ;;
223 k) keep=$OPTARG
224 if [[ -z $keep || -n ${keep//[0-9]/} ]]; then
225 die 'argument to option -k must be a non-negative integer'
226 else
227 keep=$(( 10#$keep ))
228 fi ;;
229 m) move=1 movedir=$OPTARG ;;
230 r) delete=1 ;;
231 u) IFS=$'\n' read -r -d '' -a ign < <(pacman -Qq)
232 blacklist+=("${ign[@]}")
233 unset ign ;;
234 v) (( ++verbose )) ;;
235 z) delim='\0' ;;
236 :) die "option '--%s' requires an argument" "$OPTARG" ;;
237 ?) die "invalid option -- '%s'" "$OPTARG" ;;
238 esac
239 done
240 shift $(( OPTIND - 1 ))
242 # remaining args are a whitelist
243 whitelist=("$@")
245 # sanity checks
246 case $(( dryrun+delete+move )) in
247 0) die "no operation specified (use -h for help)" ;;
248 [^1]) die "only one operation may be used at a time" ;;
249 esac
251 [[ -d $cachedir ]] ||
252 die "cachedir \`%s' does not exist or is not a directory" "$cachedir"
254 [[ $movedir && ! -d $movedir ]] &&
255 die "move-to directory \`%s' does not exist or is not a directory" "$movedir"
257 if (( move || delete )); then
258 # make it an absolute path since we're about to chdir
259 [[ ${movedir:0:1} != '/' ]] && movedir=$PWD/$movedir
260 [[ ! -w $cachedir || ( $movedir && ! -w $movedir ) ]] && needsroot=1
263 # unlikely that this will fail, but better make sure
264 cd "$cachedir" || die "failed to chdir to \`%s'" "$cachedir"
266 # note that these results are returned in an arbitrary order from awk, but
267 # they'll be resorted (in summarize) iff we have a verbosity level set.
268 IFS=$'\n' read -r -d '' -a candidates < \
269 <(printf '%s\n' *.pkg.tar?(.+([^.])) | pacsort |
270 pkgfilter "$keep" "$scanarch" \
271 "${#whitelist[*]}" "${whitelist[@]}" \
272 "${#blacklist[*]}" "${blacklist[@]}")
274 if (( ! ${#candidates[*]} )); then
275 msg 'no candidate packages found for pruning'
276 exit 1
279 # grab this prior to signature scavenging
280 pkgcount=${#candidates[*]}
282 # copy the list, merging in any found sigs
283 for cand in "${candidates[@]}"; do
284 candtemp+=("$cand")
285 [[ -f $cand.sig ]] && candtemp+=("$cand.sig")
286 done
287 candidates=("${candtemp[@]}")
288 unset candtemp
290 # do this before we destroy anything
291 totalsaved=$(@SIZECMD@ "${candidates[@]}" | awk '{ sum += $1 } END { print sum }')
293 # crush. kill. destroy.
294 (( verbose )) && cmdopts+=(-v)
295 if (( delete )); then
296 runcmd rm "${cmdopts[@]}" "${candidates[@]}"
297 elif (( move )); then
298 runcmd mv "${cmdopts[@]}" "${candidates[@]}" "$movedir"
301 summarize "$pkgcount" "${candidates[@]}"
303 # vim: set ts=2 sw=2 noet: