dupemerge: document --progress option, and expand tabs in rest of usage
[dupemerge] / faster-dupemerge
1 #!/usr/bin/perl -w
2 use strict;
3 use Fcntl qw(:DEFAULT :flock);
4 use File::Compare;
5 use File::Temp;
6
7 # Copyright (C) 2003-2010 Zygo Blaxell <faster-dupemerge@mailtoo.hungrycats.org>
8
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
23 my $input_links = 0;
24 my $input_files = 0;
25 my $input_bogons = 0;
26 my $hash_bytes = 0;
27 my $hash_files = 0;
28 my $hash_errors = 0;
29 my $compare_bytes = 0;
30 my $compare_count = 0;
31 my $compare_errors = 0;
32 my $compare_differences = 0;
33 my $trivially_unique = 0;
34 my $merges_attempted = 0;
35 my $hard_links = 0;
36 my $link_errors = 0;
37 my $link_retries = 0;
38 my $recovered_bytes = 0;
39 my $recovered_files = 0;
40 my $lost_files = 0;
41 my $lost_bytes = 0;
42 my $surprises = 0;
43
44 eval '
45         use Digest::SHA1 qw(sha1 sha1_hex sha1_base64);
46 ';
47
48 if ($@) {
49         warn "Digest::SHA1: $@\nUsing external md5sum program to generate hashes.\nPlease install Digest::SHA1 (libdigest-sha1-perl)";
50
51         eval <<'DIGEST';
52                 sub really_digest {
53                         my ($filename) = (@_);
54                         my $fv = open(MD5SUM, "-|");    
55                         die "fork: $!" unless defined($fv);
56                         if ($fv) {
57                                 my ($sum_line) = <MD5SUM>;
58                                 close(MD5SUM) or die "md5sum: exit status $? (error status $!)";
59                                 die "hash error:  got EOF instead of md5sum output" unless defined($sum_line);
60                                 my ($sum) = $sum_line =~ m/^([a-fA-F0-9]{32})/o;
61                                 die "hash error:  got \Q$sum_line\E instead of md5sum output" unless defined($sum);
62                                 return $sum;
63                         } else {
64                                 sysopen(STDIN, $filename, O_RDONLY|O_NONBLOCK) or die "open: $filename: $!";
65                                 exec('md5sum');
66                                 # Perl guarantees it will die here
67                         }
68                 }
69 DIGEST
70 } else {
71         eval <<'DIGEST';
72                 sub really_digest {
73                         my ($filename) = (@_);
74                         die "'$filename' is not a plain file" if (-l $filename) || ! (-f _);
75                         my $ctx = Digest::SHA1->new;
76                         sysopen(FILE, $filename, O_RDONLY|O_NONBLOCK) or die "open: $filename: $!";
77                         binmode(FILE);          # FIXME:  Necessary?  Probably harmless...
78                         $ctx->addfile(\*FILE);
79                         close(FILE) or die "close: $filename: $!";
80                         return $ctx->b64digest;
81                 }
82 DIGEST
83 }
84         
85 my $collapse_access = 0;
86 my $collapse_timestamp = 0;
87 my $collapse_zero = 0;
88 my $skip_compares = 0;
89 my $skip_hashes = 0;
90 my $progress = 0;
91 my $verbose = 0;
92 my $debug = 0;
93 my $dry_run = 0;
94 my $humane = 0;
95 my @extra_find_opts = ();
96 my @extra_sort_opts = ();
97 my $lock_file;
98 my $lock_rm = 0;
99 my $lock_obtained = 0;
100
101 sub digest {
102         my ($filename) = (@_);
103         if ($skip_hashes) {
104                 return "SKIPPING HASHES";
105         } else {
106                 print STDERR 'H' if $progress;
107                 my $digest = &really_digest($filename);
108                 $hash_bytes += -s $filename;
109                 $hash_files++;
110                 return $digest
111         }
112 }
113
114 my @directories;
115
116 sub usage {
117         my $name = shift(@_);
118         die <<USAGE;
119 Usage: $name [--opts] directory [directory...]
120 Finds duplicate files in the given directories, and replaces all identical
121 copies of a file with hard-links to a single file.
122
123 Several options modify the definition of a "duplicate".  By default, files
124 which have differences in owner uid or gid, permission (mode), or
125 modification time (mtime) are considered different, so that hardlinking
126 files does not also change their attributes.  Additionally, all files of
127 zero size are ignored for performance reasons (there tend to be many
128 of them, and they tend not to release any space when replaced with
129 hard links).
130
131         --access        uid, gid, and mode may be different for identical
132                         files
133
134         --debug         show all steps in duplication discovery process
135                         (implies --verbose)
136
137         --dry-run       do not lock files or make changes to filesystem
138
139         --find          pass next options (up to --) to find command
140
141         --humane        human-readable statistics (e.g. 1 048 576)
142
143         --lock FILE     exit immediately (status 10) if unable to obtain a 
144                         flock(LOCK_EX|LOCK_NB) on FILE
145
146         --lock-rm       remove lock file at exit
147
148         --progress      output single-character progress indicators:
149                         C - compare
150                         H - hash
151                         L - link(2)
152                         R - rename(2)
153                         S, s - lstat(2) (see source for details)
154                         U - unlink(2)
155                         . - all inodes with similar attributes done
156
157         --sort          pass next options (up to --) to sort command
158
159         --timestamps    mtime may be different for identical files
160
161         --skip-compare  skip byte-by-byte file comparisons
162
163         --skip-hash     skip calculation of hash function on files
164
165         --trust         old name for --skip-compare
166                         (trust the hash function)
167
168         --verbose       report files as they are considered
169
170         --zeros         hard-link zero-length files too
171 USAGE
172 }
173
174 while ($#ARGV >= 0) {
175         my $arg = shift(@ARGV);
176         if ($arg eq '--access') {
177                 $collapse_access = 1;
178         } elsif ($arg eq '--timestamps') {
179                 $collapse_timestamp = 1;
180         } elsif ($arg eq '--zeros') {
181                 $collapse_zero = 1;
182         } elsif ($arg eq '--trust' || $arg eq '--skip-compare') {
183                 $skip_compares = 1;
184         } elsif ($arg eq '--skip-hash') {
185                 $skip_hashes = 1;
186         } elsif ($arg eq '--progress') {
187                 $progress = 1;
188         } elsif ($arg eq '--verbose') {
189                 $verbose = 1;
190         } elsif ($arg eq '--lock-rm') {
191                 $lock_rm = 1;
192         } elsif ($arg eq '--lock') {
193                 $lock_file = shift(@ARGV);
194                 unless (defined($lock_file)) {
195                         usage($0);
196                         exit(1);
197                 }
198         } elsif ($arg eq '--debug') {
199                 $debug = $verbose = 1;
200         } elsif ($arg eq '--dry-run') {
201                 $dry_run = 1;
202         } elsif ($arg eq '--humane') {
203                 $humane = 1;
204         } elsif ($arg eq '--find') {
205                 while ($#ARGV >= 0) {
206                         my $extra_arg = shift(@ARGV);
207                         last if $extra_arg eq '--';
208                         push(@extra_find_opts, $extra_arg);
209                 }
210         } elsif ($arg eq '--sort') {
211                 while ($#ARGV >= 0) {
212                         my $extra_arg = shift(@ARGV);
213                         last if $extra_arg eq '--';
214                         push(@extra_sort_opts, $extra_arg);
215                 }
216         } elsif ($arg =~ /^-/o) {
217                 usage($0);
218                 exit(1);
219         } else {
220                 push(@directories, $arg);
221         }
222 }
223
224 if ($skip_hashes && $skip_compares) {
225         die "Cannot skip both hashes and compares.\n";
226 }
227
228 @directories or usage;
229
230 if (defined($lock_file) && !$dry_run) {
231         sysopen(LOCK_FILE, $lock_file, O_CREAT|O_RDONLY, 0666) or die "open: $lock_file: $!";
232         flock(LOCK_FILE, LOCK_EX|LOCK_NB) or die "flock: $lock_file: LOCK_EX|LOCK_NB: $!";
233         print STDERR "Locked '$lock_file' in LOCK_EX mode.\n" if $verbose;
234         $lock_obtained = 1;
235 }
236
237 END {
238         if ($lock_obtained && !$dry_run) {
239                 print STDERR "Removing '$lock_file'.\n" if $verbose;
240                 unlink($lock_file) or warn "unlink: $lock_file: $!";
241         }
242 }
243
244 sub tick_quote {
245         my ($text) = (@_);
246         $text =~ s/'/'\\''/go;
247         return "'$text'";
248 }
249
250 my @find_command = ('find', @directories, @extra_find_opts, '-type', 'f');
251 my $printf_string = '%s ' .
252         ($collapse_access    ? '0 0 0 ' : '%U %G %m ') .
253         ($collapse_timestamp ? '0 '     : '%T@ ') .
254         '%D %i %p\0';
255
256 push(@find_command, '!', '-empty') unless $collapse_zero;
257 push(@find_command, '-printf', $printf_string);
258
259 my @sort_command = ('sort', '-znr', @extra_sort_opts);
260 my @quoted_sort_command = @sort_command;
261 grep(tick_quote($_), @quoted_sort_command);
262 my $quoted_sort_command = "'" . join("' '", @quoted_sort_command) . "'";
263
264 my @quoted_find_command = @find_command;
265 grep(tick_quote($_), @quoted_find_command);
266 my $quoted_find_command = "'" . join("' '", @quoted_find_command) . "'";
267 print STDERR "find command:  $quoted_find_command | $quoted_sort_command\n" if $verbose;
268
269 open(FIND, "$quoted_find_command | $quoted_sort_command |") or die "open: $!";
270 $/ = "\0";
271
272 # Input is sorted so that all weak keys are contiguous.
273 # When the key changes, we have to process all files we previously know about.
274 my $current_key = -1;
275
276 # $inode_to_file_name{$inode} = [@file_names]
277 my %inode_to_file_name = ();
278
279 # Link files
280 sub link_files {
281         my ($from, $to) = (@_);
282
283         my $quoted_from = tick_quote($from);
284         my $quoted_to = tick_quote($to);
285         print STDERR "\n" if $progress;
286         print STDERR "ln -f $quoted_from $quoted_to\n";
287
288         return if $dry_run;
289
290         my $inode_dir = $to;
291         my $inode_base = $to;
292         $inode_dir =~ s:[^/]*$::o;
293         $inode_base =~ s:^.*/::os;
294         my $tmp_to = File::Temp::tempnam($inode_dir, ".$inode_base.");
295         print STDERR "\tlink: $from -> $tmp_to\n" if $debug;
296         print STDERR 'L' if $progress;
297         link($from, $tmp_to) or die "link: $from -> $tmp_to: $!";
298         print STDERR "\trename: $tmp_to -> $to\n" if $debug;
299         print STDERR 'R' if $progress;
300         unless (rename($tmp_to, $to)) {
301                 my $saved_bang = $!;
302                 print STDERR 'U' if $progress;
303                 unlink($tmp_to) or warn "unlink: $tmp_to: $!";  # Try, possibly in vain, to clean up
304                 die "rename: $tmp_to -> $from: $saved_bang";
305         }
306 }
307
308 # Convert $dev,$ino into a single string where lexical and numeric orderings are equivalent
309 sub format_inode ($$) {
310         my ($dev, $ino) = @_;
311         # 64 bits ought to be enough for everybody!
312         return sprintf('%016x:%016x', $dev, $ino);
313 }
314
315 # Process all known files so far.
316 sub merge_files {
317         $merges_attempted++;
318
319         my %hash_to_inode;
320         # Used to stop link retry loops (there is a goto in here!  Actually two...)
321         my %stop_loop;
322
323         my @candidate_list = keys(%inode_to_file_name);
324         $input_files += @candidate_list;
325         if (@candidate_list < 2) {
326                 print STDERR "Merging...only one candidate to merge..." if $debug;
327                 $trivially_unique++;
328                 goto end_merge;
329         }
330
331         print STDERR "Merging...\n" if $debug;
332         foreach my $candidate (sort @candidate_list) {
333                 print STDERR "\tDigesting candidate $candidate\n" if $debug;
334                 my $ok = 0;
335                 my $digest;
336
337 hash_file:
338
339                 foreach my $filename (sort keys(%{$inode_to_file_name{$candidate}})) {
340                         print STDERR "\t\tDigesting file $filename\n" if $debug;
341                         if ((-l $filename) || ! -f _) {
342                                 warn "Bogon file " . tick_quote($filename);
343                                 $surprises++;
344                                 next;
345                         }
346                         eval { 
347                                 $digest = digest($filename); 
348                         };
349                         if ($@) {
350                                 warn "Digest($filename)(#$candidate) failed: $@";
351                                 $hash_errors++;
352                         } else {
353                                 $ok = 1;
354                                 last hash_file;
355                         }
356                 }
357                 if ($ok) {
358                         print STDERR "\t\tDigest is $digest\n" if $debug;
359
360                         my $incumbent_list = ($hash_to_inode{$digest} ||= []);
361                         my $incumbent_matched = 0;
362                         for my $incumbent (sort @$incumbent_list) {
363                                 print STDERR "\t\tInodes $incumbent and $candidate have same hash\n" if $debug;
364
365                                 my $finished = 0;
366
367 link_start:
368
369                                 until ($finished) {
370                                         my @incumbent_names = sort keys(%{$inode_to_file_name{$incumbent}});
371                                         my @candidate_names = sort keys(%{$inode_to_file_name{$candidate}});
372                                         print STDERR "\t\tLinks to $incumbent:", join("\n\t\t\t", '', @incumbent_names), "\n" if $debug;
373                                         print STDERR "\t\tLinks to $candidate:", join("\n\t\t\t", '', @candidate_names), "\n" if $debug;
374
375 incumbent_file:
376
377                                         foreach my $incumbent_file (@incumbent_names) {
378                                                 print STDERR 'S' if $progress;
379                                                 my ($incumbent_dev,$incumbent_ino,$incumbent_mode,$incumbent_nlink,$incumbent_uid,$incumbent_gid,$incumbent_rdev,$incumbent_size,$incumbent_atime,$incumbent_mtime,$incumbent_ctime,$incumbent_blksize,$incumbent_blocks) = lstat($incumbent_file);
380                                                 print STDERR "\t\tINCUMBENT dev=$incumbent_dev ino=$incumbent_ino mode=$incumbent_mode nlink=$incumbent_nlink uid=$incumbent_uid gid=$incumbent_gid rdev=$incumbent_rdev size=$incumbent_size atime=$incumbent_atime mtime=$incumbent_mtime ctime=$incumbent_ctime blksize=$incumbent_blksize blocks=$incumbent_blocks _=$incumbent_file\n" if $debug;
381
382                                                 if (!defined($incumbent_blocks)) {
383                                                         warn "lstat: $incumbent_file: $!";
384                                                         $surprises++;
385                                                         next incumbent_file;
386                                                 }
387
388                                                 if (format_inode($incumbent_dev, $incumbent_ino) ne $incumbent) {
389                                                         warn "$incumbent_file: expected inode $incumbent, found $incumbent_dev:$incumbent_ino";
390                                                         $surprises++;
391                                                         next incumbent_file;
392                                                 }
393
394                                                 my $at_least_one_link_done = 0;
395
396 candidate_file:
397
398                                                 foreach my $candidate_file (@candidate_names) {
399                                                         print STDERR 's' if $progress;
400                                                         my ($candidate_dev,$candidate_ino,$candidate_mode,$candidate_nlink,$candidate_uid,$candidate_gid,$candidate_rdev,$candidate_size,$candidate_atime,$candidate_mtime,$candidate_ctime,$candidate_blksize,$candidate_blocks) = lstat($candidate_file);
401                                                         print STDERR "\t\t\tCANDIDATE dev=$candidate_dev ino=$candidate_ino mode=$candidate_mode nlink=$candidate_nlink uid=$candidate_uid gid=$candidate_gid rdev=$candidate_rdev size=$candidate_size atime=$candidate_atime mtime=$candidate_mtime ctime=$candidate_ctime blksize=$candidate_blksize blocks=$candidate_blocks _=$candidate_file\n" if $debug;
402
403                                                         if (!defined($candidate_blocks)) {
404                                                                 warn "lstat: $candidate_file: $!";
405                                                                 $surprises++;
406                                                                 next candidate_file;
407                                                         }
408
409                                                         if (format_inode($candidate_dev, $candidate_ino) ne $candidate) {
410                                                                 warn "$candidate_file: expected inode $candidate, found $candidate_dev:$candidate_ino";
411                                                                 $surprises++;
412                                                                 next candidate_file;
413                                                         }
414
415                                                         if ($candidate_size != $incumbent_size) {
416                                                                 warn "$candidate_file, $incumbent_file: file sizes are different";
417                                                                 $surprises++;
418                                                                 next candidate_file;
419                                                         }
420
421                                                         my $identical;
422
423                                                         eval {
424                                                                 if ($skip_compares) {
425                                                                         print STDERR "\t\t\t\tSkipping compare!\n" if $debug;
426                                                                         $identical = 1;
427                                                                 } else {
428                                                                         my $quoted_incumbent_file = tick_quote($incumbent_file);
429                                                                         my $quoted_candidate_file = tick_quote($candidate_file);
430                                                                         print STDERR "cmp $quoted_incumbent_file $quoted_candidate_file\n" if $debug;
431                                                                         print STDERR 'C' if $progress;
432                                                                         if (compare($incumbent_file, $candidate_file)) {
433                                                                                 $compare_differences++;
434                                                                                 $identical = 0;
435                                                                                 # It is significant for two non-identical files to have identical SHA1 or MD5 hashes.
436                                                                                 # Some kind of I/O error is more likely, so this message cannot be turned off.
437                                                                                 # On the other hand, if we're skipping hashes, _all_ files will have the same hash,
438                                                                                 # so the warning in that case is quite silly.  Hmmm.
439                                                                                 print STDERR "$quoted_incumbent_file and $quoted_candidate_file have same hash but do not compare equal!\n" unless $skip_hashes;
440                                                                         } else {
441                                                                                 $identical = 1;
442                                                                                 $incumbent_matched = 1;
443                                                                         }
444                                                                         $compare_count++;
445                                                                         $compare_bytes += $incumbent_size;
446                                                                 }
447                                                         };
448                                                         if ($@) {
449                                                                 warn $@;
450                                                                 $compare_errors++;
451                                                                 next candidate_file;
452                                                         }
453
454                                                         if ($identical) {
455                                                                 print STDERR "\t\t\t\tincumbent_nlink=$incumbent_nlink, candidate_nlink=$candidate_nlink\n" if $debug;
456
457                                                                 # We have to do this to break out of a possible infinite loop.
458                                                                 # Given file A, with hardlinks A1 and A2, and file B, with hardlink B1,
459                                                                 # such that A1 and B1 are in non-writable directories, we will loop
460                                                                 # forever hardlinking A2 with A and B.
461                                                                 # To break the loop, we never attempt to hardlink any files X and Y twice.
462
463                                                                 if (defined($stop_loop{$incumbent_file}->{$candidate_file}) ||
464                                                                     defined($stop_loop{$candidate_file}->{$incumbent_file})) {
465                                                                         print STDERR "Already considered linking '$incumbent_file' and '$candidate_file', not trying again now\n";
466                                                                 } else {
467                                                                         $stop_loop{$incumbent_file}->{$candidate_file} = 1;
468                                                                         $stop_loop{$candidate_file}->{$incumbent_file} = 1;
469
470                                                                         my $link_done = 0;
471
472                                                                         my ($from_file, $to_file, $from_inode, $to_inode, $from_nlink, $to_nlink);
473
474                                                                         # If the candidate has more links than incumbent, replace incumbent with candidate.
475                                                                         # If the incumbent has more links than candidate, replace candidate with incumbent.
476                                                                         # If the link counts are equal, we saw incumbent first, so keep the incumbent.
477                                                                         # "We saw incumbent first" is significant because we explicitly sort the inodes.
478                                                                         # Thank Johannes Niess for this idea.
479                                                                         if ($candidate_nlink > $incumbent_nlink) {
480                                                                                 $from_file = $candidate_file;
481                                                                                 $to_file = $incumbent_file;
482                                                                                 $from_inode = $candidate;
483                                                                                 $to_inode = $incumbent;
484                                                                                 $from_nlink = $candidate_nlink;
485                                                                                 $to_nlink = $incumbent_nlink;
486                                                                         } else {
487                                                                                 $to_file = $candidate_file;
488                                                                                 $from_file = $incumbent_file;
489                                                                                 $to_inode = $candidate;
490                                                                                 $from_inode = $incumbent;
491                                                                                 $to_nlink = $candidate_nlink;
492                                                                                 $from_nlink = $incumbent_nlink;
493                                                                         }
494
495                                                                         eval {
496                                                                                 link_files($from_file, $to_file);
497                                                                                 $link_done = 1;
498                                                                         };
499
500                                                                         if ($@) {
501                                                                                 warn $@;
502                                                                                 $link_errors++;
503
504                                                                                 print STDERR "\t\t\t\t...retrying with swapped from/to files...\n" if $debug;
505                                                                                 $link_retries++;
506
507                                                                                 eval {
508                                                                                         ($from_file, $to_file) = ($to_file, $from_file);
509                                                                                         ($from_inode, $to_inode) = ($to_inode, $from_inode);
510                                                                                         ($from_nlink, $to_nlink) = ($to_nlink, $from_nlink);
511                                                                                         link_files($from_file, $to_file);
512                                                                                         $link_done = 1;
513                                                                                 };
514
515                                                                                 if ($@) {
516                                                                                         warn $@;
517                                                                                         $link_errors++;
518                                                                                 }
519                                                                         }
520
521                                                                         # Note since the files are presumably identical, they both have the same size.
522                                                                         # My random number generator chooses the incumbent's size.
523
524                                                                         if ($link_done) {
525                                                                                 delete $inode_to_file_name{$to_inode}->{$to_file};
526                                                                                 $inode_to_file_name{$from_inode}->{$to_file} = undef;
527                                                                                 $hash_to_inode{$digest} = [ $from_inode ];
528
529                                                                                 $hard_links++;
530                                                                                 if ($to_nlink == 1) {
531                                                                                         $recovered_files++;
532                                                                                         $recovered_bytes += $incumbent_size;
533                                                                                 }
534
535                                                                                 # FIXME:  Now we're really confused for some reason.
536                                                                                 # Start over to rebuild state.
537                                                                                 next link_start;
538                                                                         } else {
539                                                                                 warn "Could not hardlink '$incumbent_file' and '$candidate_file'";
540
541                                                                                 # FIXME:  This is a lame heuristic.  We really need to know if we've
542                                                                                 # tried all possible ways to hardlink the file out of existence first;
543                                                                                 # however, that is complex and only benefits a silly statistic.
544                                                                                 if ($to_nlink == 1 || $from_nlink == 1) {
545                                                                                         $lost_files++;
546                                                                                         $lost_bytes += $incumbent_size;
547                                                                                 }
548                                                                         }
549                                                                 }
550                                                         }
551                                                 }
552                                         }
553                                         $finished = 1;
554                                 }
555                         }
556                         unless ($incumbent_matched) {
557                                 print STDERR "\t\tNew hash entered\n" if $debug;
558                                 push(@$incumbent_list, $candidate);
559                         }
560                 } else {
561                         warn "No digests found for inode $candidate\n";
562                         delete $inode_to_file_name{$candidate};
563                 }
564         }
565
566 end_merge:
567
568         print STDERR '.' if $progress;
569         print STDERR "Merge done.\n" if $debug;
570         undef %inode_to_file_name;
571 }
572
573 while (<FIND>) {
574         my ($weak_key, $dev, $ino, $name) = m/^(\d+ \d+ \d+ \d+ -?[\d.]+) (\d+) (\d+) (.+)\0$/so;
575         die "read error: $!\nLast input line was '$_'" unless defined($name);
576
577         my $inode = format_inode($dev, $ino);
578
579         print STDERR "weak_key=$weak_key inode=$inode name=$name\n" if $debug;
580
581         unless (! (-l $name) && (-f _)) {
582                 warn "Bogon file " . tick_quote($name);
583                 $input_bogons++;
584                 next;
585         }
586
587         $input_links++;
588         merge_files if $weak_key ne $current_key;
589         $current_key = $weak_key;
590
591         $inode_to_file_name{$inode}->{$name} = undef;
592
593         print STDERR "$name\n" if $verbose;
594 }
595
596 merge_files;
597
598 my $stats_blob = <<STATS;
599 compare_bytes           $compare_bytes
600 compare_count           $compare_count
601 compare_differences     $compare_differences
602 compare_errors          $compare_errors
603 hard_links              $hard_links
604 hash_bytes              $hash_bytes
605 hash_errors             $hash_errors
606 hash_files              $hash_files
607 input_bogons            $input_bogons
608 input_files             $input_files
609 input_links             $input_links
610 link_errors             $link_errors
611 link_retries            $link_retries
612 lost_bytes              $lost_bytes
613 lost_files              $lost_files
614 merges_attempted        $merges_attempted
615 recovered_bytes         $recovered_bytes
616 recovered_files         $recovered_files
617 surprises               $surprises
618 trivially_unique        $trivially_unique
619 STATS
620
621 if ($humane) {
622         my $max_num_len = 0;
623
624         sub measure_numbers {
625                 my ($num) = @_;
626                 my $len = length($num);
627                 $len += int( (length($num) - 1) / 3);
628                 $max_num_len = $len if $len > $max_num_len;
629         }
630
631         (my $dummy = $stats_blob) =~ s/\d+/measure_numbers($&)/geos;
632
633         sub space_numbers {
634                 my ($num) = @_;
635                 1 while $num =~ s/(\d)(\d\d\d)( \d\d\d)*$/$1 $2$3/os;
636                 $num = ' ' x ($max_num_len - length($num)) . $num;
637                 return $num;
638         }
639
640         $stats_blob =~ s/\d+/space_numbers($&)/geos;
641 }
642
643 $stats_blob =~ s/([^\n]*\n[^\n]*? )(\s+)( [^\n]*\n)/$1 . ('.' x length($2)) . $3/oemg;
644
645 print STDERR $stats_blob;
646
647 exit(0);
648
649 __END__
650
651 #################################################################################
652 #                     GNU GENERAL PUBLIC LICENSE                                #
653 #                        Version 2, June 1991                                   #
654 #                                                                               #
655 #  Copyright (C) 1989, 1991 Free Software Foundation, Inc.                      #
656 #      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                  #
657 #  Everyone is permitted to copy and distribute verbatim copies                 #
658 #  of this license document, but changing it is not allowed.                    #
659 #                                                                               #
660 #                             Preamble                                          #
661 #                                                                               #
662 #   The licenses for most software are designed to take away your               #
663 # freedom to share and change it.  By contrast, the GNU General Public          #
664 # License is intended to guarantee your freedom to share and change free        #
665 # software--to make sure the software is free for all its users.  This          #
666 # General Public License applies to most of the Free Software                   #
667 # Foundation's software and to any other program whose authors commit to        #
668 # using it.  (Some other Free Software Foundation software is covered by        #
669 # the GNU Library General Public License instead.)  You can apply it to         #
670 # your programs, too.                                                           #
671 #                                                                               #
672 #   When we speak of free software, we are referring to freedom, not            #
673 # price.  Our General Public Licenses are designed to make sure that you        #
674 # have the freedom to distribute copies of free software (and charge for        #
675 # this service if you wish), that you receive source code or can get it         #
676 # if you want it, that you can change the software or use pieces of it          #
677 # in new free programs; and that you know you can do these things.              #
678 #                                                                               #
679 #   To protect your rights, we need to make restrictions that forbid            #
680 # anyone to deny you these rights or to ask you to surrender the rights.        #
681 # These restrictions translate to certain responsibilities for you if you       #
682 # distribute copies of the software, or if you modify it.                       #
683 #                                                                               #
684 #   For example, if you distribute copies of such a program, whether            #
685 # gratis or for a fee, you must give the recipients all the rights that         #
686 # you have.  You must make sure that they, too, receive or can get the          #
687 # source code.  And you must show them these terms so they know their           #
688 # rights.                                                                       #
689 #                                                                               #
690 #   We protect your rights with two steps: (1) copyright the software, and      #
691 # (2) offer you this license which gives you legal permission to copy,          #
692 # distribute and/or modify the software.                                        #
693 #                                                                               #
694 #   Also, for each author's protection and ours, we want to make certain        #
695 # that everyone understands that there is no warranty for this free             #
696 # software.  If the software is modified by someone else and passed on, we      #
697 # want its recipients to know that what they have is not the original, so       #
698 # that any problems introduced by others will not reflect on the original       #
699 # authors' reputations.                                                         #
700 #                                                                               #
701 #   Finally, any free program is threatened constantly by software              #
702 # patents.  We wish to avoid the danger that redistributors of a free           #
703 # program will individually obtain patent licenses, in effect making the        #
704 # program proprietary.  To prevent this, we have made it clear that any         #
705 # patent must be licensed for everyone's free use or not licensed at all.       #
706 #                                                                               #
707 #   The precise terms and conditions for copying, distribution and              #
708 # modification follow.                                                          #
709 #                                                                               #
710 #                     GNU GENERAL PUBLIC LICENSE                                #
711 #    TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION            #
712 #                                                                               #
713 #   0. This License applies to any program or other work which contains         #
714 # a notice placed by the copyright holder saying it may be distributed          #
715 # under the terms of this General Public License.  The "Program", below,        #
716 # refers to any such program or work, and a "work based on the Program"         #
717 # means either the Program or any derivative work under copyright law:          #
718 # that is to say, a work containing the Program or a portion of it,             #
719 # either verbatim or with modifications and/or translated into another          #
720 # language.  (Hereinafter, translation is included without limitation in        #
721 # the term "modification".)  Each licensee is addressed as "you".               #
722 #                                                                               #
723 # Activities other than copying, distribution and modification are not          #
724 # covered by this License; they are outside its scope.  The act of              #
725 # running the Program is not restricted, and the output from the Program        #
726 # is covered only if its contents constitute a work based on the                #
727 # Program (independent of having been made by running the Program).             #
728 # Whether that is true depends on what the Program does.                        #
729 #                                                                               #
730 #   1. You may copy and distribute verbatim copies of the Program's             #
731 # source code as you receive it, in any medium, provided that you               #
732 # conspicuously and appropriately publish on each copy an appropriate           #
733 # copyright notice and disclaimer of warranty; keep intact all the              #
734 # notices that refer to this License and to the absence of any warranty;        #
735 # and give any other recipients of the Program a copy of this License           #
736 # along with the Program.                                                       #
737 #                                                                               #
738 # You may charge a fee for the physical act of transferring a copy, and         #
739 # you may at your option offer warranty protection in exchange for a fee.       #
740 #                                                                               #
741 #   2. You may modify your copy or copies of the Program or any portion         #
742 # of it, thus forming a work based on the Program, and copy and                 #
743 # distribute such modifications or work under the terms of Section 1            #
744 # above, provided that you also meet all of these conditions:                   #
745 #                                                                               #
746 #     a) You must cause the modified files to carry prominent notices           #
747 #     stating that you changed the files and the date of any change.            #
748 #                                                                               #
749 #     b) You must cause any work that you distribute or publish, that in        #
750 #     whole or in part contains or is derived from the Program or any           #
751 #     part thereof, to be licensed as a whole at no charge to all third         #
752 #     parties under the terms of this License.                                  #
753 #                                                                               #
754 #     c) If the modified program normally reads commands interactively          #
755 #     when run, you must cause it, when started running for such                #
756 #     interactive use in the most ordinary way, to print or display an          #
757 #     announcement including an appropriate copyright notice and a              #
758 #     notice that there is no warranty (or else, saying that you provide        #
759 #     a warranty) and that users may redistribute the program under             #
760 #     these conditions, and telling the user how to view a copy of this         #
761 #     License.  (Exception: if the Program itself is interactive but            #
762 #     does not normally print such an announcement, your work based on          #
763 #     the Program is not required to print an announcement.)                    #
764 #                                                                               #
765 # These requirements apply to the modified work as a whole.  If                 #
766 # identifiable sections of that work are not derived from the Program,          #
767 # and can be reasonably considered independent and separate works in            #
768 # themselves, then this License, and its terms, do not apply to those           #
769 # sections when you distribute them as separate works.  But when you            #
770 # distribute the same sections as part of a whole which is a work based         #
771 # on the Program, the distribution of the whole must be on the terms of         #
772 # this License, whose permissions for other licensees extend to the             #
773 # entire whole, and thus to each and every part regardless of who wrote it.     #
774 #                                                                               #
775 # Thus, it is not the intent of this section to claim rights or contest         #
776 # your rights to work written entirely by you; rather, the intent is to         #
777 # exercise the right to control the distribution of derivative or               #
778 # collective works based on the Program.                                        #
779 #                                                                               #
780 # In addition, mere aggregation of another work not based on the Program        #
781 # with the Program (or with a work based on the Program) on a volume of         #
782 # a storage or distribution medium does not bring the other work under          #
783 # the scope of this License.                                                    #
784 #                                                                               #
785 #   3. You may copy and distribute the Program (or a work based on it,          #
786 # under Section 2) in object code or executable form under the terms of         #
787 # Sections 1 and 2 above provided that you also do one of the following:        #
788 #                                                                               #
789 #     a) Accompany it with the complete corresponding machine-readable          #
790 #     source code, which must be distributed under the terms of Sections        #
791 #     1 and 2 above on a medium customarily used for software interchange; or,  #
792 #                                                                               #
793 #     b) Accompany it with a written offer, valid for at least three            #
794 #     years, to give any third party, for a charge no more than your            #
795 #     cost of physically performing source distribution, a complete             #
796 #     machine-readable copy of the corresponding source code, to be             #
797 #     distributed under the terms of Sections 1 and 2 above on a medium         #
798 #     customarily used for software interchange; or,                            #
799 #                                                                               #
800 #     c) Accompany it with the information you received as to the offer         #
801 #     to distribute corresponding source code.  (This alternative is            #
802 #     allowed only for noncommercial distribution and only if you               #
803 #     received the program in object code or executable form with such          #
804 #     an offer, in accord with Subsection b above.)                             #
805 #                                                                               #
806 # The source code for a work means the preferred form of the work for           #
807 # making modifications to it.  For an executable work, complete source          #
808 # code means all the source code for all modules it contains, plus any          #
809 # associated interface definition files, plus the scripts used to               #
810 # control compilation and installation of the executable.  However, as a        #
811 # special exception, the source code distributed need not include               #
812 # anything that is normally distributed (in either source or binary             #
813 # form) with the major components (compiler, kernel, and so on) of the          #
814 # operating system on which the executable runs, unless that component          #
815 # itself accompanies the executable.                                            #
816 #                                                                               #
817 # If distribution of executable or object code is made by offering              #
818 # access to copy from a designated place, then offering equivalent              #
819 # access to copy the source code from the same place counts as                  #
820 # distribution of the source code, even though third parties are not            #
821 # compelled to copy the source along with the object code.                      #
822 #                                                                               #
823 #   4. You may not copy, modify, sublicense, or distribute the Program          #
824 # except as expressly provided under this License.  Any attempt                 #
825 # otherwise to copy, modify, sublicense or distribute the Program is            #
826 # void, and will automatically terminate your rights under this License.        #
827 # However, parties who have received copies, or rights, from you under          #
828 # this License will not have their licenses terminated so long as such          #
829 # parties remain in full compliance.                                            #
830 #                                                                               #
831 #   5. You are not required to accept this License, since you have not          #
832 # signed it.  However, nothing else grants you permission to modify or          #
833 # distribute the Program or its derivative works.  These actions are            #
834 # prohibited by law if you do not accept this License.  Therefore, by           #
835 # modifying or distributing the Program (or any work based on the               #
836 # Program), you indicate your acceptance of this License to do so, and          #
837 # all its terms and conditions for copying, distributing or modifying           #
838 # the Program or works based on it.                                             #
839 #                                                                               #
840 #   6. Each time you redistribute the Program (or any work based on the         #
841 # Program), the recipient automatically receives a license from the             #
842 # original licensor to copy, distribute or modify the Program subject to        #
843 # these terms and conditions.  You may not impose any further                   #
844 # restrictions on the recipients' exercise of the rights granted herein.        #
845 # You are not responsible for enforcing compliance by third parties to          #
846 # this License.                                                                 #
847 #                                                                               #
848 #   7. If, as a consequence of a court judgment or allegation of patent         #
849 # infringement or for any other reason (not limited to patent issues),          #
850 # conditions are imposed on you (whether by court order, agreement or           #
851 # otherwise) that contradict the conditions of this License, they do not        #
852 # excuse you from the conditions of this License.  If you cannot                #
853 # distribute so as to satisfy simultaneously your obligations under this        #
854 # License and any other pertinent obligations, then as a consequence you        #
855 # may not distribute the Program at all.  For example, if a patent              #
856 # license would not permit royalty-free redistribution of the Program by        #
857 # all those who receive copies directly or indirectly through you, then         #
858 # the only way you could satisfy both it and this License would be to           #
859 # refrain entirely from distribution of the Program.                            #
860 #                                                                               #
861 # If any portion of this section is held invalid or unenforceable under         #
862 # any particular circumstance, the balance of the section is intended to        #
863 # apply and the section as a whole is intended to apply in other                #
864 # circumstances.                                                                #
865 #                                                                               #
866 # It is not the purpose of this section to induce you to infringe any           #
867 # patents or other property right claims or to contest validity of any          #
868 # such claims; this section has the sole purpose of protecting the              #
869 # integrity of the free software distribution system, which is                  #
870 # implemented by public license practices.  Many people have made               #
871 # generous contributions to the wide range of software distributed              #
872 # through that system in reliance on consistent application of that             #
873 # system; it is up to the author/donor to decide if he or she is willing        #
874 # to distribute software through any other system and a licensee cannot         #
875 # impose that choice.                                                           #
876 #                                                                               #
877 # This section is intended to make thoroughly clear what is believed to         #
878 # be a consequence of the rest of this License.                                 #
879 #                                                                               #
880 #   8. If the distribution and/or use of the Program is restricted in           #
881 # certain countries either by patents or by copyrighted interfaces, the         #
882 # original copyright holder who places the Program under this License           #
883 # may add an explicit geographical distribution limitation excluding            #
884 # those countries, so that distribution is permitted only in or among           #
885 # countries not thus excluded.  In such case, this License incorporates         #
886 # the limitation as if written in the body of this License.                     #
887 #                                                                               #
888 #   9. The Free Software Foundation may publish revised and/or new versions     #
889 # of the General Public License from time to time.  Such new versions will      #
890 # be similar in spirit to the present version, but may differ in detail to      #
891 # address new problems or concerns.                                             #
892 #                                                                               #
893 # Each version is given a distinguishing version number.  If the Program        #
894 # specifies a version number of this License which applies to it and "any       #
895 # later version", you have the option of following the terms and conditions     #
896 # either of that version or of any later version published by the Free          #
897 # Software Foundation.  If the Program does not specify a version number of     #
898 # this License, you may choose any version ever published by the Free Software  #
899 # Foundation.                                                                   #
900 #                                                                               #
901 #   10. If you wish to incorporate parts of the Program into other free         #
902 # programs whose distribution conditions are different, write to the author     #
903 # to ask for permission.  For software which is copyrighted by the Free         #
904 # Software Foundation, write to the Free Software Foundation; we sometimes      #
905 # make exceptions for this.  Our decision will be guided by the two goals       #
906 # of preserving the free status of all derivatives of our free software and     #
907 # of promoting the sharing and reuse of software generally.                     #
908 #                                                                               #
909 #                             NO WARRANTY                                       #
910 #                                                                               #
911 #   11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY    #
912 # FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN      #
913 # OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES        #
914 # PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED    #
915 # OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF          #
916 # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS     #
917 # TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE        #
918 # PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,      #
919 # REPAIR OR CORRECTION.                                                         #
920 #                                                                               #
921 #   12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING   #
922 # WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR           #
923 # REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,    #
924 # INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING   #
925 # OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED     #
926 # TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY      #
927 # YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER    #
928 # PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE         #
929 # POSSIBILITY OF SUCH DAMAGES.                                                  #
930 #                                                                               #
931 #                      END OF TERMS AND CONDITIONS                              #
932 #                                                                               #
933 #             How to Apply These Terms to Your New Programs                     #
934 #                                                                               #
935 #   If you develop a new program, and you want it to be of the greatest         #
936 # possible use to the public, the best way to achieve this is to make it        #
937 # free software which everyone can redistribute and change under these terms.   #
938 #                                                                               #
939 #   To do so, attach the following notices to the program.  It is safest        #
940 # to attach them to the start of each source file to most effectively           #
941 # convey the exclusion of warranty; and each file should have at least          #
942 # the "copyright" line and a pointer to where the full notice is found.         #
943 #                                                                               #
944 #     <one line to give the program's name and a brief idea of what it does.>   #
945 #     Copyright (C) <year>  <name of author>                                    #
946 #                                                                               #
947 #     This program is free software; you can redistribute it and/or modify      #
948 #     it under the terms of the GNU General Public License as published by      #
949 #     the Free Software Foundation; either version 2 of the License, or         #
950 #     (at your option) any later version.                                       #
951 #                                                                               #
952 #     This program is distributed in the hope that it will be useful,           #
953 #     but WITHOUT ANY WARRANTY; without even the implied warranty of            #
954 #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
955 #     GNU General Public License for more details.                              #
956 #                                                                               #
957 #     You should have received a copy of the GNU General Public License         #
958 #     along with this program; if not, write to the Free Software               #
959 #     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA #
960 #                                                                               #
961 #                                                                               #
962 # Also add information on how to contact you by electronic and paper mail.      #
963 #                                                                               #
964 # If the program is interactive, make it output a short notice like this        #
965 # when it starts in an interactive mode:                                        #
966 #                                                                               #
967 #     Gnomovision version 69, Copyright (C) year  name of author                #
968 #     Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. #
969 #     This is free software, and you are welcome to redistribute it             #
970 #     under certain conditions; type `show c' for details.                      #
971 #                                                                               #
972 # The hypothetical commands `show w' and `show c' should show the appropriate   #
973 # parts of the General Public License.  Of course, the commands you use may     #
974 # be called something other than `show w' and `show c'; they could even be      #
975 # mouse-clicks or menu items--whatever suits your program.                      #
976 #                                                                               #
977 # You should also get your employer (if you work as a programmer) or your       #
978 # school, if any, to sign a "copyright disclaimer" for the program, if          #
979 # necessary.  Here is a sample; alter the names:                                #
980 #                                                                               #
981 #   Yoyodyne, Inc., hereby disclaims all copyright interest in the program      #
982 #   `Gnomovision' (which makes passes at compilers) written by James Hacker.    #
983 #                                                                               #
984 #   <signature of Ty Coon>, 1 April 1989                                        #
985 #   Ty Coon, President of Vice                                                  #
986 #                                                                               #
987 # This General Public License does not permit incorporating your program into   #
988 # proprietary programs.  If your program is a subroutine library, you may       #
989 # consider it more useful to permit linking proprietary applications with the   #
990 # library.  If this is what you want to do, use the GNU Library General         #
991 # Public License instead of this License.                                       #
992 #################################################################################