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