summaryrefslogtreecommitdiff
path: root/clean-pacman
blob: 2bfa225a0be4b92f7018b7432cded9829225313d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash
# Copyright 2012 Nicolás Reynolds <fauno@parabola.nu> Licensed under GPLv3
#
# Smart cleanup of the chroot, restores chroot to its original state but also
# leaves the dependencies already installed that are needed by the current
# package. In other words, it removes everything that's left.
#
# Useful when you're building a lot of packages one after another and they
# share some dependencies.
#
# Logic: tap into `makepkg -sr`, collect required packages and remove the
# leftovers
#
# Use it as the PACMAN var for makepkg: `PACMAN=$0 makepkg`
#
# Notes
# makepkg runs the following flags three times (depends, makedepends, checkdepends)
# -T check deps (collect here)
# -S install missing deps (remove leftovers here)
# -T check if installed correctly (ignore)
# -R remove installed deps (skip)

set -e
set -x

makepid=$(ps --no-header -o pid -C makepkg | head -n1 | tr -d " ")
cleanup_log=/tmp/libretools-cleanup-${makepid}.log
checkdep=/tmp/libretools-dep-check-${makepid}

cmd="$(echo "$@" | grep -o "\-\(T\|S\|R\|Q\)[^ ]*")"
# remove all flags
args="$(echo " $@" | sed "s/ \-[^ ]\+//g")"

case $cmd in

# Collect the packages that are going to be installed, but use a clean database
# to get the full needed list.
# See update-cleansystem
    -T)
    if [ ! -f "${checkdep}" ]; then
# Use sudo because $0 is run as normal user on -T
# TODO -Sy only once
        sudo pacman -b "${BD:-/var/lib/libretools/clean}" -Sy >/dev/null 2>&1
        sudo pacman -b "${BD:-/var/lib/libretools/clean}" \
                    -Sp \
                    --print-format "%n" \
                    ${args[@]} >${cleanup_log} 2>/dev/null
# Deps are collected, so skip next time
        touch "${checkdep}"

# Diff against previously installed packages and remove the unneeded ones
#
# We don't collect during -S because we never get here if depencies are met
# during -T
        cleanup=($(comm -23 \
                        <(pacman -Qq | sort) \
                        <(cat /etc/libretools.d/cleansystem ${cleanup_log} | sort -u)
                ))

        if [ ${#cleanup[@]} -gt 0 ]; then
            sudo pacman -Rn --noconfirm ${cleanup[@]} 1>&2
        fi
# This is the second -T run
    else
# Remove the cleanup log at the end
        rm "${cleanup_log}" "${checkdep}"
    fi
    ;;
# DON'T LET MAKEPKG DO REMOVALS OF ITS OWN
    -R) exit 0;;
esac

# Make makepkg dreams come true
pacman $@