9c159eec69ac48863a4e392a258ba767822bab81
[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) 2002-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                                 $input_bogons++;
344                                 delete $inode_to_file_name{$candidate}->{$filename};
345                                 next;
346                         }
347                         eval {
348                                 $digest = digest($filename); 
349                         };
350                         if ($@) {
351                                 warn "Digest($filename)(#$candidate) failed: $@";
352                                 $hash_errors++;
353                         } else {
354                                 $ok = 1;
355                                 last hash_file;
356                         }
357                 }
358                 if ($ok) {
359                         print STDERR "\t\tDigest is $digest\n" if $debug;
360
361                         my $incumbent_list = ($hash_to_inode{$digest} ||= []);
362                         my $incumbent_matched = 0;
363                         for my $incumbent (sort @$incumbent_list) {
364                                 print STDERR "\t\tInodes $incumbent and $candidate have same hash\n" if $debug;
365
366                                 my $finished = 0;
367
368 link_start:
369
370                                 until ($finished) {
371                                         my @incumbent_names = sort keys(%{$inode_to_file_name{$incumbent}});
372                                         my @candidate_names = sort keys(%{$inode_to_file_name{$candidate}});
373                                         print STDERR "\t\tLinks to $incumbent:", join("\n\t\t\t", '', @incumbent_names), "\n" if $debug;
374                                         print STDERR "\t\tLinks to $candidate:", join("\n\t\t\t", '', @candidate_names), "\n" if $debug;
375
376 incumbent_file:
377
378                                         foreach my $incumbent_file (@incumbent_names) {
379                                                 print STDERR 'S' if $progress;
380                                                 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);
381                                                 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;
382
383                                                 if (!defined($incumbent_blocks)) {
384                                                         warn "lstat: $incumbent_file: $!";
385                                                         $surprises++;
386                                                         next incumbent_file;
387                                                 }
388
389                                                 if (format_inode($incumbent_dev, $incumbent_ino) ne $incumbent) {
390                                                         warn "$incumbent_file: expected inode $incumbent, found $incumbent_dev:$incumbent_ino";
391                                                         $surprises++;
392                                                         next incumbent_file;
393                                                 }
394
395                                                 my $at_least_one_link_done = 0;
396
397 candidate_file:
398
399                                                 foreach my $candidate_file (@candidate_names) {
400                                                         print STDERR 's' if $progress;
401                                                         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);
402                                                         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;
403
404                                                         if (!defined($candidate_blocks)) {
405                                                                 warn "lstat: $candidate_file: $!";
406                                                                 $surprises++;
407                                                                 next candidate_file;
408                                                         }
409
410                                                         if (format_inode($candidate_dev, $candidate_ino) ne $candidate) {
411                                                                 warn "$candidate_file: expected inode $candidate, found $candidate_dev:$candidate_ino";
412                                                                 $surprises++;
413                                                                 next candidate_file;
414                                                         }
415
416                                                         if ($candidate_size != $incumbent_size) {
417                                                                 warn "$candidate_file, $incumbent_file: file sizes are different";
418                                                                 $surprises++;
419                                                                 next candidate_file;
420                                                         }
421
422                                                         my $identical;
423
424                                                         eval {
425                                                                 if ($skip_compares) {
426                                                                         print STDERR "\t\t\t\tSkipping compare!\n" if $debug;
427                                                                         $identical = 1;
428                                                                 } else {
429                                                                         my $quoted_incumbent_file = tick_quote($incumbent_file);
430                                                                         my $quoted_candidate_file = tick_quote($candidate_file);
431                                                                         print STDERR "cmp $quoted_incumbent_file $quoted_candidate_file\n" if $debug;
432                                                                         print STDERR 'C' if $progress;
433                                                                         if (compare($incumbent_file, $candidate_file)) {
434                                                                                 $compare_differences++;
435                                                                                 $identical = 0;
436                                                                                 # It is significant for two non-identical files to have identical SHA1 or MD5 hashes.
437                                                                                 # Some kind of I/O error is more likely, so this message cannot be turned off.
438                                                                                 # On the other hand, if we're skipping hashes, _all_ files will have the same hash,
439                                                                                 # so the warning in that case is quite silly.  Hmmm.
440                                                                                 print STDERR "$quoted_incumbent_file and $quoted_candidate_file have same hash but do not compare equal!\n" unless $skip_hashes;
441                                                                         } else {
442                                                                                 $identical = 1;
443                                                                                 $incumbent_matched = 1;
444                                                                         }
445                                                                         $compare_count++;
446                                                                         $compare_bytes += $incumbent_size;
447                                                                 }
448                                                         };
449                                                         if ($@) {
450                                                                 warn $@;
451                                                                 $compare_errors++;
452                                                                 next candidate_file;
453                                                         }
454
455                                                         if ($identical) {
456                                                                 print STDERR "\t\t\t\tincumbent_nlink=$incumbent_nlink, candidate_nlink=$candidate_nlink\n" if $debug;
457
458                                                                 # We have to do this to break out of a possible infinite loop.
459                                                                 # Given file A, with hardlinks A1 and A2, and file B, with hardlink B1,
460                                                                 # such that A1 and B1 are in non-writable directories, we will loop
461                                                                 # forever hardlinking A2 with A and B.
462                                                                 # To break the loop, we never attempt to hardlink any files X and Y twice.
463
464                                                                 if (defined($stop_loop{$incumbent_file}->{$candidate_file}) ||
465                                                                     defined($stop_loop{$candidate_file}->{$incumbent_file})) {
466                                                                         print STDERR "Already considered linking '$incumbent_file' and '$candidate_file', not trying again now\n";
467                                                                 } else {
468                                                                         $stop_loop{$incumbent_file}->{$candidate_file} = 1;
469                                                                         $stop_loop{$candidate_file}->{$incumbent_file} = 1;
470
471                                                                         my $link_done = 0;
472
473                                                                         my ($from_file, $to_file, $from_inode, $to_inode, $from_nlink, $to_nlink);
474
475                                                                         # If the candidate has more links than incumbent, replace incumbent with candidate.
476                                                                         # If the incumbent has more links than candidate, replace candidate with incumbent.
477                                                                         # If the link counts are equal, we saw incumbent first, so keep the incumbent.
478                                                                         # "We saw incumbent first" is significant because we explicitly sort the inodes.
479                                                                         # Thank Johannes Niess for this idea.
480                                                                         if ($candidate_nlink > $incumbent_nlink) {
481                                                                                 $from_file = $candidate_file;
482                                                                                 $to_file = $incumbent_file;
483                                                                                 $from_inode = $candidate;
484                                                                                 $to_inode = $incumbent;
485                                                                                 $from_nlink = $candidate_nlink;
486                                                                                 $to_nlink = $incumbent_nlink;
487                                                                         } else {
488                                                                                 $to_file = $candidate_file;
489                                                                                 $from_file = $incumbent_file;
490                                                                                 $to_inode = $candidate;
491                                                                                 $from_inode = $incumbent;
492                                                                                 $to_nlink = $candidate_nlink;
493                                                                                 $from_nlink = $incumbent_nlink;
494                                                                         }
495
496                                                                         eval {
497                                                                                 link_files($from_file, $to_file);
498                                                                                 $link_done = 1;
499                                                                         };
500
501                                                                         if ($@) {
502                                                                                 warn $@;
503                                                                                 $link_errors++;
504
505                                                                                 print STDERR "\t\t\t\t...retrying with swapped from/to files...\n" if $debug;
506                                                                                 $link_retries++;
507
508                                                                                 eval {
509                                                                                         ($from_file, $to_file) = ($to_file, $from_file);
510                                                                                         ($from_inode, $to_inode) = ($to_inode, $from_inode);
511                                                                                         ($from_nlink, $to_nlink) = ($to_nlink, $from_nlink);
512                                                                                         link_files($from_file, $to_file);
513                                                                                         $link_done = 1;
514                                                                                 };
515
516                                                                                 if ($@) {
517                                                                                         warn $@;
518                                                                                         $link_errors++;
519                                                                                 }
520                                                                         }
521
522                                                                         # Note since the files are presumably identical, they both have the same size.
523                                                                         # My random number generator chooses the incumbent's size.
524
525                                                                         if ($link_done) {
526                                                                                 delete $inode_to_file_name{$to_inode}->{$to_file};
527                                                                                 $inode_to_file_name{$from_inode}->{$to_file} = undef;
528                                                                                 $hash_to_inode{$digest} = [ $from_inode ];
529
530                                                                                 $hard_links++;
531                                                                                 if ($to_nlink == 1) {
532                                                                                         $recovered_files++;
533                                                                                         $recovered_bytes += $incumbent_size;
534                                                                                 }
535
536                                                                                 # FIXME:  Now we're really confused for some reason.
537                                                                                 # Start over to rebuild state.
538                                                                                 next link_start;
539                                                                         } else {
540                                                                                 warn "Could not hardlink '$incumbent_file' and '$candidate_file'";
541
542                                                                                 # FIXME:  This is a lame heuristic.  We really need to know if we've
543                                                                                 # tried all possible ways to hardlink the file out of existence first;
544                                                                                 # however, that is complex and only benefits a silly statistic.
545                                                                                 if ($to_nlink == 1 || $from_nlink == 1) {
546                                                                                         $lost_files++;
547                                                                                         $lost_bytes += $incumbent_size;
548                                                                                 }
549                                                                         }
550                                                                 }
551                                                         }
552                                                 }
553                                         }
554                                         $finished = 1;
555                                 }
556                         }
557                         unless ($incumbent_matched) {
558                                 print STDERR "\t\tNew hash entered\n" if $debug;
559                                 push(@$incumbent_list, $candidate);
560                         }
561                 } else {
562                         warn "No digests found for inode $candidate\n";
563                         delete $inode_to_file_name{$candidate};
564                 }
565         }
566         print STDERR '.' if $progress;
567
568 end_merge:
569
570         print STDERR "Merge done.\n" if $debug;
571         undef %inode_to_file_name;
572 }
573
574 while (<FIND>) {
575         my ($weak_key, $dev, $ino, $name) = m/^(\d+ \d+ \d+ \d+ -?[\d.]+) (\d+) (\d+) (.+)\0$/so;
576         die "read error: $!\nLast input line was '$_'" unless defined($name);
577
578         my $inode = format_inode($dev, $ino);
579
580         print STDERR "weak_key=$weak_key inode=$inode name=$name\n" if $debug;
581
582         $input_links++;
583         merge_files if $weak_key ne $current_key;
584         $current_key = $weak_key;
585
586         $inode_to_file_name{$inode}->{$name} = undef;
587
588         print STDERR "$name\n" if $verbose;
589 }
590
591 merge_files;
592
593 my $stats_blob = <<STATS;
594 compare_bytes           $compare_bytes
595 compare_count           $compare_count
596 compare_differences     $compare_differences
597 compare_errors          $compare_errors
598 hard_links              $hard_links
599 hash_bytes              $hash_bytes
600 hash_errors             $hash_errors
601 hash_files              $hash_files
602 input_bogons            $input_bogons
603 input_files             $input_files
604 input_links             $input_links
605 link_errors             $link_errors
606 link_retries            $link_retries
607 lost_bytes              $lost_bytes
608 lost_files              $lost_files
609 merges_attempted        $merges_attempted
610 recovered_bytes         $recovered_bytes
611 recovered_files         $recovered_files
612 surprises               $surprises
613 trivially_unique        $trivially_unique
614 STATS
615
616 if ($humane) {
617         my $max_num_len = 0;
618
619         sub measure_numbers {
620                 my ($num) = @_;
621                 my $len = length($num);
622                 $len += int( (length($num) - 1) / 3);
623                 $max_num_len = $len if $len > $max_num_len;
624         }
625
626         (my $dummy = $stats_blob) =~ s/\d+/measure_numbers($&)/geos;
627
628         sub space_numbers {
629                 my ($num) = @_;
630                 1 while $num =~ s/(\d)(\d\d\d)( \d\d\d)*$/$1 $2$3/os;
631                 $num = ' ' x ($max_num_len - length($num)) . $num;
632                 return $num;
633         }
634
635         $stats_blob =~ s/\d+/space_numbers($&)/geos;
636 }
637
638 $stats_blob =~ s/([^\n]*\n[^\n]*? )(\s+)( [^\n]*\n)/$1 . ('.' x length($2)) . $3/oemg;
639
640 print STDERR "\n" if $progress;
641 print STDERR $stats_blob;
642
643 exit(0);
644
645 __END__
646
647 #################################################################################
648 #                     GNU GENERAL PUBLIC LICENSE                                #
649 #                        Version 2, June 1991                                   #
650 #                                                                               #
651 #  Copyright (C) 1989, 1991 Free Software Foundation, Inc.                      #
652 #      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                  #
653 #  Everyone is permitted to copy and distribute verbatim copies                 #
654 #  of this license document, but changing it is not allowed.                    #
655 #                                                                               #
656 #                             Preamble                                          #
657 #                                                                               #
658 #   The licenses for most software are designed to take away your               #
659 # freedom to share and change it.  By contrast, the GNU General Public          #
660 # License is intended to guarantee your freedom to share and change free        #
661 # software--to make sure the software is free for all its users.  This          #
662 # General Public License applies to most of the Free Software                   #
663 # Foundation's software and to any other program whose authors commit to        #
664 # using it.  (Some other Free Software Foundation software is covered by        #
665 # the GNU Library General Public License instead.)  You can apply it to         #
666 # your programs, too.                                                           #
667 #                                                                               #
668 #   When we speak of free software, we are referring to freedom, not            #
669 # price.  Our General Public Licenses are designed to make sure that you        #
670 # have the freedom to distribute copies of free software (and charge for        #
671 # this service if you wish), that you receive source code or can get it         #
672 # if you want it, that you can change the software or use pieces of it          #
673 # in new free programs; and that you know you can do these things.              #
674 #                                                                               #
675 #   To protect your rights, we need to make restrictions that forbid            #
676 # anyone to deny you these rights or to ask you to surrender the rights.        #
677 # These restrictions translate to certain responsibilities for you if you       #
678 # distribute copies of the software, or if you modify it.                       #
679 #                                                                               #
680 #   For example, if you distribute copies of such a program, whether            #
681 # gratis or for a fee, you must give the recipients all the rights that         #
682 # you have.  You must make sure that they, too, receive or can get the          #
683 # source code.  And you must show them these terms so they know their           #
684 # rights.                                                                       #
685 #                                                                               #
686 #   We protect your rights with two steps: (1) copyright the software, and      #
687 # (2) offer you this license which gives you legal permission to copy,          #
688 # distribute and/or modify the software.                                        #
689 #                                                                               #
690 #   Also, for each author's protection and ours, we want to make certain        #
691 # that everyone understands that there is no warranty for this free             #
692 # software.  If the software is modified by someone else and passed on, we      #
693 # want its recipients to know that what they have is not the original, so       #
694 # that any problems introduced by others will not reflect on the original       #
695 # authors' reputations.                                                         #
696 #                                                                               #
697 #   Finally, any free program is threatened constantly by software              #
698 # patents.  We wish to avoid the danger that redistributors of a free           #
699 # program will individually obtain patent licenses, in effect making the        #
700 # program proprietary.  To prevent this, we have made it clear that any         #
701 # patent must be licensed for everyone's free use or not licensed at all.       #
702 #                                                                               #
703 #   The precise terms and conditions for copying, distribution and              #
704 # modification follow.                                                          #
705 #                                                                               #
706 #                     GNU GENERAL PUBLIC LICENSE                                #
707 #    TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION            #
708 #                                                                               #
709 #   0. This License applies to any program or other work which contains         #
710 # a notice placed by the copyright holder saying it may be distributed          #
711 # under the terms of this General Public License.  The "Program", below,        #
712 # refers to any such program or work, and a "work based on the Program"         #
713 # means either the Program or any derivative work under copyright law:          #
714 # that is to say, a work containing the Program or a portion of it,             #
715 # either verbatim or with modifications and/or translated into another          #
716 # language.  (Hereinafter, translation is included without limitation in        #
717 # the term "modification".)  Each licensee is addressed as "you".               #
718 #                                                                               #
719 # Activities other than copying, distribution and modification are not          #
720 # covered by this License; they are outside its scope.  The act of              #
721 # running the Program is not restricted, and the output from the Program        #
722 # is covered only if its contents constitute a work based on the                #
723 # Program (independent of having been made by running the Program).             #
724 # Whether that is true depends on what the Program does.                        #
725 #                                                                               #
726 #   1. You may copy and distribute verbatim copies of the Program's             #
727 # source code as you receive it, in any medium, provided that you               #
728 # conspicuously and appropriately publish on each copy an appropriate           #
729 # copyright notice and disclaimer of warranty; keep intact all the              #
730 # notices that refer to this License and to the absence of any warranty;        #
731 # and give any other recipients of the Program a copy of this License           #
732 # along with the Program.                                                       #
733 #                                                                               #
734 # You may charge a fee for the physical act of transferring a copy, and         #
735 # you may at your option offer warranty protection in exchange for a fee.       #
736 #                                                                               #
737 #   2. You may modify your copy or copies of the Program or any portion         #
738 # of it, thus forming a work based on the Program, and copy and                 #
739 # distribute such modifications or work under the terms of Section 1            #
740 # above, provided that you also meet all of these conditions:                   #
741 #                                                                               #
742 #     a) You must cause the modified files to carry prominent notices           #
743 #     stating that you changed the files and the date of any change.            #
744 #                                                                               #
745 #     b) You must cause any work that you distribute or publish, that in        #
746 #     whole or in part contains or is derived from the Program or any           #
747 #     part thereof, to be licensed as a whole at no charge to all third         #
748 #     parties under the terms of this License.                                  #
749 #                                                                               #
750 #     c) If the modified program normally reads commands interactively          #
751 #     when run, you must cause it, when started running for such                #
752 #     interactive use in the most ordinary way, to print or display an          #
753 #     announcement including an appropriate copyright notice and a              #
754 #     notice that there is no warranty (or else, saying that you provide        #
755 #     a warranty) and that users may redistribute the program under             #
756 #     these conditions, and telling the user how to view a copy of this         #
757 #     License.  (Exception: if the Program itself is interactive but            #
758 #     does not normally print such an announcement, your work based on          #
759 #     the Program is not required to print an announcement.)                    #
760 #                                                                               #
761 # These requirements apply to the modified work as a whole.  If                 #
762 # identifiable sections of that work are not derived from the Program,          #
763 # and can be reasonably considered independent and separate works in            #
764 # themselves, then this License, and its terms, do not apply to those           #
765 # sections when you distribute them as separate works.  But when you            #
766 # distribute the same sections as part of a whole which is a work based         #
767 # on the Program, the distribution of the whole must be on the terms of         #
768 # this License, whose permissions for other licensees extend to the             #
769 # entire whole, and thus to each and every part regardless of who wrote it.     #
770 #                                                                               #
771 # Thus, it is not the intent of this section to claim rights or contest         #
772 # your rights to work written entirely by you; rather, the intent is to         #
773 # exercise the right to control the distribution of derivative or               #
774 # collective works based on the Program.                                        #
775 #                                                                               #
776 # In addition, mere aggregation of another work not based on the Program        #
777 # with the Program (or with a work based on the Program) on a volume of         #
778 # a storage or distribution medium does not bring the other work under          #
779 # the scope of this License.                                                    #
780 #                                                                               #
781 #   3. You may copy and distribute the Program (or a work based on it,          #
782 # under Section 2) in object code or executable form under the terms of         #
783 # Sections 1 and 2 above provided that you also do one of the following:        #
784 #                                                                               #
785 #     a) Accompany it with the complete corresponding machine-readable          #
786 #     source code, which must be distributed under the terms of Sections        #
787 #     1 and 2 above on a medium customarily used for software interchange; or,  #
788 #                                                                               #
789 #     b) Accompany it with a written offer, valid for at least three            #
790 #     years, to give any third party, for a charge no more than your            #
791 #     cost of physically performing source distribution, a complete             #
792 #     machine-readable copy of the corresponding source code, to be             #
793 #     distributed under the terms of Sections 1 and 2 above on a medium         #
794 #     customarily used for software interchange; or,                            #
795 #                                                                               #
796 #     c) Accompany it with the information you received as to the offer         #
797 #     to distribute corresponding source code.  (This alternative is            #
798 #     allowed only for noncommercial distribution and only if you               #
799 #     received the program in object code or executable form with such          #
800 #     an offer, in accord with Subsection b above.)                             #
801 #                                                                               #
802 # The source code for a work means the preferred form of the work for           #
803 # making modifications to it.  For an executable work, complete source          #
804 # code means all the source code for all modules it contains, plus any          #
805 # associated interface definition files, plus the scripts used to               #
806 # control compilation and installation of the executable.  However, as a        #
807 # special exception, the source code distributed need not include               #
808 # anything that is normally distributed (in either source or binary             #
809 # form) with the major components (compiler, kernel, and so on) of the          #
810 # operating system on which the executable runs, unless that component          #
811 # itself accompanies the executable.                                            #
812 #                                                                               #
813 # If distribution of executable or object code is made by offering              #
814 # access to copy from a designated place, then offering equivalent              #
815 # access to copy the source code from the same place counts as                  #
816 # distribution of the source code, even though third parties are not            #
817 # compelled to copy the source along with the object code.                      #
818 #                                                                               #
819 #   4. You may not copy, modify, sublicense, or distribute the Program          #
820 # except as expressly provided under this License.  Any attempt                 #
821 # otherwise to copy, modify, sublicense or distribute the Program is            #
822 # void, and will automatically terminate your rights under this License.        #
823 # However, parties who have received copies, or rights, from you under          #
824 # this License will not have their licenses terminated so long as such          #
825 # parties remain in full compliance.                                            #
826 #                                                                               #
827 #   5. You are not required to accept this License, since you have not          #
828 # signed it.  However, nothing else grants you permission to modify or          #
829 # distribute the Program or its derivative works.  These actions are            #
830 # prohibited by law if you do not accept this License.  Therefore, by           #
831 # modifying or distributing the Program (or any work based on the               #
832 # Program), you indicate your acceptance of this License to do so, and          #
833 # all its terms and conditions for copying, distributing or modifying           #
834 # the Program or works based on it.                                             #
835 #                                                                               #
836 #   6. Each time you redistribute the Program (or any work based on the         #
837 # Program), the recipient automatically receives a license from the             #
838 # original licensor to copy, distribute or modify the Program subject to        #
839 # these terms and conditions.  You may not impose any further                   #
840 # restrictions on the recipients' exercise of the rights granted herein.        #
841 # You are not responsible for enforcing compliance by third parties to          #
842 # this License.                                                                 #
843 #                                                                               #
844 #   7. If, as a consequence of a court judgment or allegation of patent         #
845 # infringement or for any other reason (not limited to patent issues),          #
846 # conditions are imposed on you (whether by court order, agreement or           #
847 # otherwise) that contradict the conditions of this License, they do not        #
848 # excuse you from the conditions of this License.  If you cannot                #
849 # distribute so as to satisfy simultaneously your obligations under this        #
850 # License and any other pertinent obligations, then as a consequence you        #
851 # may not distribute the Program at all.  For example, if a patent              #
852 # license would not permit royalty-free redistribution of the Program by        #
853 # all those who receive copies directly or indirectly through you, then         #
854 # the only way you could satisfy both it and this License would be to           #
855 # refrain entirely from distribution of the Program.                            #
856 #                                                                               #
857 # If any portion of this section is held invalid or unenforceable under         #
858 # any particular circumstance, the balance of the section is intended to        #
859 # apply and the section as a whole is intended to apply in other                #
860 # circumstances.                                                                #
861 #                                                                               #
862 # It is not the purpose of this section to induce you to infringe any           #
863 # patents or other property right claims or to contest validity of any          #
864 # such claims; this section has the sole purpose of protecting the              #
865 # integrity of the free software distribution system, which is                  #
866 # implemented by public license practices.  Many people have made               #
867 # generous contributions to the wide range of software distributed              #
868 # through that system in reliance on consistent application of that             #
869 # system; it is up to the author/donor to decide if he or she is willing        #
870 # to distribute software through any other system and a licensee cannot         #
871 # impose that choice.                                                           #
872 #                                                                               #
873 # This section is intended to make thoroughly clear what is believed to         #
874 # be a consequence of the rest of this License.                                 #
875 #                                                                               #
876 #   8. If the distribution and/or use of the Program is restricted in           #
877 # certain countries either by patents or by copyrighted interfaces, the         #
878 # original copyright holder who places the Program under this License           #
879 # may add an explicit geographical distribution limitation excluding            #
880 # those countries, so that distribution is permitted only in or among           #
881 # countries not thus excluded.  In such case, this License incorporates         #
882 # the limitation as if written in the body of this License.                     #
883 #                                                                               #
884 #   9. The Free Software Foundation may publish revised and/or new versions     #
885 # of the General Public License from time to time.  Such new versions will      #
886 # be similar in spirit to the present version, but may differ in detail to      #
887 # address new problems or concerns.                                             #
888 #                                                                               #
889 # Each version is given a distinguishing version number.  If the Program        #
890 # specifies a version number of this License which applies to it and "any       #
891 # later version", you have the option of following the terms and conditions     #
892 # either of that version or of any later version published by the Free          #
893 # Software Foundation.  If the Program does not specify a version number of     #
894 # this License, you may choose any version ever published by the Free Software  #
895 # Foundation.                                                                   #
896 #                                                                               #
897 #   10. If you wish to incorporate parts of the Program into other free         #
898 # programs whose distribution conditions are different, write to the author     #
899 # to ask for permission.  For software which is copyrighted by the Free         #
900 # Software Foundation, write to the Free Software Foundation; we sometimes      #
901 # make exceptions for this.  Our decision will be guided by the two goals       #
902 # of preserving the free status of all derivatives of our free software and     #
903 # of promoting the sharing and reuse of software generally.                     #
904 #                                                                               #
905 #                             NO WARRANTY                                       #
906 #                                                                               #
907 #   11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY    #
908 # FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN      #
909 # OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES        #
910 # PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED    #
911 # OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF          #
912 # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS     #
913 # TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE        #
914 # PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,      #
915 # REPAIR OR CORRECTION.                                                         #
916 #                                                                               #
917 #   12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING   #
918 # WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR           #
919 # REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,    #
920 # INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING   #
921 # OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED     #
922 # TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY      #
923 # YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER    #
924 # PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE         #
925 # POSSIBILITY OF SUCH DAMAGES.                                                  #
926 #                                                                               #
927 #                      END OF TERMS AND CONDITIONS                              #
928 #                                                                               #
929 #             How to Apply These Terms to Your New Programs                     #
930 #                                                                               #
931 #   If you develop a new program, and you want it to be of the greatest         #
932 # possible use to the public, the best way to achieve this is to make it        #
933 # free software which everyone can redistribute and change under these terms.   #
934 #                                                                               #
935 #   To do so, attach the following notices to the program.  It is safest        #
936 # to attach them to the start of each source file to most effectively           #
937 # convey the exclusion of warranty; and each file should have at least          #
938 # the "copyright" line and a pointer to where the full notice is found.         #
939 #                                                                               #
940 #     <one line to give the program's name and a brief idea of what it does.>   #
941 #     Copyright (C) <year>  <name of author>                                    #
942 #                                                                               #
943 #     This program is free software; you can redistribute it and/or modify      #
944 #     it under the terms of the GNU General Public License as published by      #
945 #     the Free Software Foundation; either version 2 of the License, or         #
946 #     (at your option) any later version.                                       #
947 #                                                                               #
948 #     This program is distributed in the hope that it will be useful,           #
949 #     but WITHOUT ANY WARRANTY; without even the implied warranty of            #
950 #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
951 #     GNU General Public License for more details.                              #
952 #                                                                               #
953 #     You should have received a copy of the GNU General Public License         #
954 #     along with this program; if not, write to the Free Software               #
955 #     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA #
956 #                                                                               #
957 #                                                                               #
958 # Also add information on how to contact you by electronic and paper mail.      #
959 #                                                                               #
960 # If the program is interactive, make it output a short notice like this        #
961 # when it starts in an interactive mode:                                        #
962 #                                                                               #
963 #     Gnomovision version 69, Copyright (C) year  name of author                #
964 #     Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. #
965 #     This is free software, and you are welcome to redistribute it             #
966 #     under certain conditions; type `show c' for details.                      #
967 #                                                                               #
968 # The hypothetical commands `show w' and `show c' should show the appropriate   #
969 # parts of the General Public License.  Of course, the commands you use may     #
970 # be called something other than `show w' and `show c'; they could even be      #
971 # mouse-clicks or menu items--whatever suits your program.                      #
972 #                                                                               #
973 # You should also get your employer (if you work as a programmer) or your       #
974 # school, if any, to sign a "copyright disclaimer" for the program, if          #
975 # necessary.  Here is a sample; alter the names:                                #
976 #                                                                               #
977 #   Yoyodyne, Inc., hereby disclaims all copyright interest in the program      #
978 #   `Gnomovision' (which makes passes at compilers) written by James Hacker.    #
979 #                                                                               #
980 #   <signature of Ty Coon>, 1 April 1989                                        #
981 #   Ty Coon, President of Vice                                                  #
982 #                                                                               #
983 # This General Public License does not permit incorporating your program into   #
984 # proprietary programs.  If your program is a subroutine library, you may       #
985 # consider it more useful to permit linking proprietary applications with the   #
986 # library.  If this is what you want to do, use the GNU Library General         #
987 # Public License instead of this License.                                       #
988 #################################################################################