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