How to automatically clear Pikaur's cache

I’ve been using Arch Linux (btw) on my laptop for a while now and I’ve always used an AUR helper to automate finding, installing and updating AUR packages.

I started with packer and then moved on to yaourt when packers development stopped. This also happened to yaourt so I started looking for another.

The yay utility gets a lot of recommendations but it comes with a ~130MB Go dependency which put me off. So I kept looking.

That’s when I found pikaur. And it’s awesome!

The only issue I noticed a few days ago is that pikaur retains multiple copies of the AUR packages that it builds at /home/$USER/.cache/pikaur/pkg. The AUR packages that I install tend to be larger e.g. Chrome, Atom, etc, so this directory was growing to be quite large.

So I decided to do something about it.

The Arch package manager, pacman has the ability to run commands via hook files, at different points during installation. This means that we can create hook that will run any time a package is installed, either from the standard repos or from the AUR, that will remove old versions of packages in pikaurs cache directory.

All you need to do is to create a new hook file at /etc/pacman.d/hooks/clean_pikaur_cache.hook:

sudo nano /etc/pacman.d/hooks/clean_pikaur_cache.hook

And put the following contents into it:

Operation = Upgrade
Operation = Install
Operation = Remove
Type = Package
Target = *

Description = Cleaning pikaur cache...
When = PostTransaction
Exec = /usr/bin/paccache -rk1 -c /home/<USER>/.cache/pikaur/pkg

Replace <USER> in the above with the username of the user that runs pikaur and you’re done.

The command that the hook runs is paccache -rk1 -c <PATH>:

The -k1 option means that only an install file of the currently running version of the package it kept. If you want to keep the current one and one version older set this to -k2. This allows you to roll back if you need to. I’ve never had the need and my space is pretty tight so I only keep one.