about summary refs log tree commit diff
path: root/scripts/nix-collect-garbage.in
blob: c92737f25c13dd07aa10b2f99e8afb76051b3504 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#! @perl@ -w

use strict;
use IPC::Open2;

my $rootsDir = "@localstatedir@/nix/gcroots";
my $storeDir = "@storedir@";

my %alive;

my $gcOper = "--delete";
my $extraArgs = "";

my @roots = ();


# Parse the command line.
for (my $i = 0; $i < scalar @ARGV; $i++) {
    my $arg = $ARGV[$i];
    if ($arg eq "--delete" || $arg eq "--print-live" || $arg eq "--print-dead") {
        $gcOper = $arg;
    }
    elsif ($arg =~ /^-v+$/) {
        $extraArgs = "$extraArgs $arg";
    }
    else { die "unknown argument `$arg'" };
}


# Recursively finds all symlinks to the store in the given directory.
sub findRoots;
sub findRoots {
    my $followSymlinks = shift;
    my $dir = shift;

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

    foreach my $name (@names) {
        next if $name eq "." || $name eq "..";
        my $path = $dir . "/" . $name;

        if (-l $path) {
            my $target = readlink $path
                or die "cannot read symlink `$path': $!";
            
            if (substr($target, 0, length $storeDir) eq $storeDir) {
                # We're only interested in the store-level part.
                $target = substr($target, length $storeDir);
                $target = "$storeDir/$target";
                push @roots, $target;
            }

            elsif ($followSymlinks && -d $path) {
                findRoots 0, $path;
            }
        }
        
        elsif (-d $path) {
            findRoots $followSymlinks, $path;
        }
    }
    
}


# Find GC roots, starting at $rootsDir.
findRoots 1, $rootsDir;


# Run the collector with the roots we found.
my $pid = open2(">&1", \*WRITE, "@bindir@/nix-store --gc $gcOper $extraArgs")
    or die "cannot run `nix-store --gc'";

foreach my $root (@roots) {
    print WRITE "$root\n";
}

close WRITE;

waitpid $pid, 0;
$? == 0 or die "`nix-store --gc' failed";