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