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