summaryrefslogtreecommitdiff
path: root/Build/cdbuild/zap-empty-dirs
blob: b34ca0708c5dc8c378072312f41efa84b459ccc0 (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
#!/usr/bin/perl -s

# Usage: $0 [-debug] [-noaction] dir-name [regexp]

# checks whether only files matching regexp are contained in
#   dir-name and removes the directory if this is the case.
# -debug prints out what it does
# -noaction suppresses the deletion

$debug = 0 unless $debug;
$noaction = 0 unless $noaction;

sub usage {
    print STDERR "Usage: $0 [-debug] [-noaction] dir-name [regexp]\n";
}


if ($#ARGV >= 0) {
    $dir_name = shift;
} else {
    &usage;
    exit 1;
}

if ($#ARGV < 0) {
    $regexp = "^(\\.zipped|\\.cache|\\.cache\\+|00Contents|00Description)\$";
} elsif ($#ARGV == 0) {
    $regexp = shift;
} else {
    &usage;
    exit 1;
}


opendir(DIR,$dir_name) || die "Cannot open directory `$dir_name'. Reason: $!";

@all_files = grep(! /^\.\.?$/,readdir(DIR)); # exclude . and ..

closedir(DIR);

@files = grep(! /$regexp/,@all_files);

if ($#files < 0) {
    print "Empty directory: $dir_name\n";
    &deldir;
}

exit 0;

sub deldir {

#    system "ls -lA $dir_name";
#    return;

    foreach $file (@all_files) {
         $debug && print "unlink($dir_name/$file)\n";
         $noaction ||
           unlink("$dir_name/$file") ||
           die "Could not unlink file `$dir_name/$file'! Reason: $!\n";
    }

    $debug && print "rmdir($dir_name)\n";
    $noaction ||
       rmdir($dir_name) ||
       "Could not rmdir directory `$dir_name'! Reason: $!\n";
}