about summary refs log tree commit diff
path: root/scripts/nix-collect-garbage.in
blob: fc67f1d55d1bcf10b6f0ecafd8f22b3450c9dae2 (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
66
#! @perl@ -w

use strict;
use IPC::Open2;

my $linkdir = "@localstatedir@/nix/profiles";
my $storedir = "@storedir@";

my %alive;

my $keepsuccessors = 1;
my $invert = 0;

foreach my $arg (@ARGV) {
    if ($arg eq "--no-successors") { $keepsuccessors = 0; }
    elsif ($arg eq "--invert") { $invert = 1; }
    else { die "unknown argument `$arg'" };
}

opendir(DIR, $linkdir) or die "cannot open directory $linkdir: $!";
my @links = readdir DIR or die "cannot read directory $linkdir: $!";
closedir DIR;

my @roots;
foreach my $link (@links) {
    $link = $linkdir . "/" . $link;
    next if (!($link =~ /.gcroot$/));
    open ROOT, "<$link" or die "cannot open $link: $!";
    while (<ROOT>) {
        chomp;
        foreach my $root (split ' ') {
            die "bad root `$root' in file `$link'" unless $root =~ /^\S+$/;
            push @roots, $root;
        }
    }
    close ROOT;
}

my $extraarg = "";
if ($keepsuccessors) { $extraarg = "--include-successors"; };
my $pid = open2(\*READ, \*WRITE, "@bindir@/nix-store --query --requisites $extraarg @roots") 
    or die "determining live paths";
close WRITE;
while (<READ>) {
	chomp;
	$alive{$_} = 1;
	if ($invert) { print "$_\n"; };
}
close READ;

waitpid $pid, 0;
$? == 0 or die "determining live paths";

exit 0 if ($invert);

opendir(DIR, $storedir) or die "cannot open directory $storedir: $!";
my @names = readdir DIR;
closedir DIR;

foreach my $name (@names) {
    next if ($name eq "." || $name eq "..");
    $name = "$storedir/$name";
    if (!$alive{$name}) {
        print "$name\n";
    }
}