summary refs log tree commit diff
path: root/scripts/nix-collect-garbage.in
blob: 55e0ba7a6fab48666c46d9783efad9ab49ff97e6 (plain) (blame)
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
#! @perl@ -w @perlFlags@

use strict;
use Nix::Config;

my $profilesDir = "@localstatedir@/nix/profiles";


# Process the command line arguments.
my @args = ();
my $arg;

my $removeOld = 0;
my $gen;
my $dryRun = 0;

while ($arg = shift) {
    if ($arg eq "--delete-old" || $arg eq "-d") {
        $removeOld = 1;
        $gen = "old";
    } elsif ($arg eq "--delete-older-than") {
        $removeOld = 1;
        $gen = shift;
    } elsif ($arg eq "--dry-run") {
        $dryRun = 1;
    } elsif ($arg eq "--help") {
        exec "man nix-collect-garbage" or die;
    } else {
        push @args, $arg;
    }
}


# If `-d' was specified, remove all old generations of all profiles.
# Of course, this makes rollbacks to before this point in time
# impossible.

sub removeOldGenerations;
sub removeOldGenerations {
    my $dir = shift;

    my $dh;
    opendir $dh, $dir or die;

    foreach my $name (sort (readdir $dh)) {
        next if $name eq "." || $name eq "..";
        $name = $dir . "/" . $name;
        if (-l $name && (readlink($name) =~ /link/)) {
            print STDERR "removing old generations of profile $name\n";

            system("$Nix::Config::binDir/nix-env", "-p", $name, "--delete-generations", $gen, $dryRun ? "--dry-run" : ());
        }
        elsif (! -l $name && -d $name) {
            removeOldGenerations $name;
        }
    }

    closedir $dh or die;
}

removeOldGenerations $profilesDir if $removeOld;


# Run the actual garbage collector.
exec "$Nix::Config::binDir/nix-store", "--gc", @args unless $dryRun;