forked from soarpenguin/perl-scripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloc.pl
executable file
·3463 lines (3119 loc) · 128 KB
/
cloc.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
# cloc -- Count Lines of Code {{{1
# Copyright (C) 2006 Northrop Grumman Corporation
# Author: Al Danial <al.danial@gmail.com>
# First release August 2006
#
# Includes code from:
# - SLOCCount v2.26
# http://www.dwheeler.com/sloccount/
# by David Wheeler.
# - Regexp::Common v2.120
# http://search.cpan.org/~abigail/Regexp-Common-2.120/lib/Regexp/Common.pm
# by Damian Conway and Abigail
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details:
# http://www.gnu.org/licenses/gpl.txt
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# 1}}}
my $VERSION = 0.68;
require 5.006;
# use modules {{{1
use warnings;
use strict;
use Getopt::Long;
use File::Basename;
use File::Temp qw { tempfile tempdir };
use File::Find;
use IO::File;
# Digest::MD5 isn't in the standard distribution. Use it only if installed.
my $HAVE_Digest_MD5;
BEGIN {
if (eval "require Digest::MD5;") {
$HAVE_Digest_MD5 = 1;
} else {
$HAVE_Digest_MD5 = 0;
warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
}
}
# Regexp::Common also isn't in the standard distribution. It will
# be installed in a temp directory if necessary.
my $HAVE_Rexexp_Common;
BEGIN {
if (eval "require Regexp::Common;") {
$HAVE_Rexexp_Common = 1;
} else {
$HAVE_Rexexp_Common = 0;
}
}
use Text::Tabs qw { expand };
#use Data::Dumper::Simple;
#use Data::Dumper;
use Cwd qw { cwd };
# 1}}}
# Usage information, options processing. {{{1
my $script = basename $0;
my $usage = "
Usage: $script [options] <file(s)/dir(s)> | <report files>
Count physical lines of source code in the given files and/or
recursively below the given directories.
Options:
--by_file Report results for every source file encountered
in addition to reporting by language.
--categorized=<file> Save names of categorized files to <file>.
--counted=<file> Save names of processed source files to <file>.
--exclude_dir=<D1>[,D2,] Exclude the given comma separated directories
D1, D2, D3, et cetera, from being scanned. For
example --exclude_dir=.cvs,.svn will skip
all files that have /.csv/ or /.svn/ as part of
their path.
--exclude_lang=<L1>[,L2,] Exclude the given comma separated languages
L1, L2, L3, et cetera, from being counted.
--extract_with=<cmd> Use <cmd> to extract binary archive files (e.g.:
.tar.gz, .zip, .Z). Use the literal '>FILE<' as
a stand-in for the actual file(s) to be
extracted. For example, to count lines of code
in the input files
gcc-4.2.tar.gz perl-5.8.8.tar.gz
on Unix use
--extract_with='gzip -dc >FILE< | tar xfv -'
and on Windows use:
--extract_with=\"\\\"c:\\Program Files\\WinZip\\WinZip32.exe\\\" -e -o >FILE< .\"
(if you have WinZip installed there).
--found=<file> Save names of every file found to <file>.
--ignored=<file> Save names of ignored files and the reason they
were ignored to <file>.
--print_filter_stages Print to STDOUT processed source code before and
after each filter is applied.
--progress_rate=<n> Show progress update after every <n> files are
processed (default <n>=100).
--quiet Suppress all information messages except for
the final report.
--report_file=<file> Write the results to <file> instead of STDOUT.
--read_lang_def=<file> Load from <file> the language processing filters.
(see also --write_lang_def) then use these filters
instead of the built-in filters.
--show_ext[=<ext>] Print information about all known (or just the
given) file extensions and exit.
--show_lang[=<lang>] Print information about all known (or just the
given) languages and exit.
--strip_comments=<ext> For each file processed, write to the current
directory a version of the file which has blank
lines and comments removed. The name of each
stripped file is the original file name with
.<ext> appended to it.
--sum_reports Input arguments are report files previously
created with the --report_file option. Makes
a cummulative set of results containing the
sum of data from the individual report files.
--write_lang_def=<file> Writes to <file. the language processing filters
then exits. Useful as a first step to creating
custom language definitions (see --read_lang_def).
-v[=<n>] Verbose switch (optional numeric value).
--version Print the version of this program and exit.
";
$| = 1; # flush STDOUT
my $start_time = time();
my ($opt_found, $opt_categorized, $opt_ignored,
$opt_counted, $opt_show_ext, $opt_show_lang, $opt_progress_rate,
$opt_print_filter_stages, $opt_v, $opt_version,
$opt_exclude_lang, $opt_exclude_dir,
$opt_read_lang_def, $opt_write_lang_def,
$opt_strip_comments, $opt_quiet, $opt_report_file, $opt_sum_reports,
$opt_extract_with, $opt_by_file,
);
GetOptions(
"by_file" => \$opt_by_file ,
"categorized=s" => \$opt_categorized ,
"counted=s" => \$opt_counted ,
"exclude_lang=s" => \$opt_exclude_lang ,
"exclude_dir=s" => \$opt_exclude_dir ,
"extract_with=s" => \$opt_extract_with ,
"found=s" => \$opt_found ,
"ignored=s" => \$opt_ignored ,
"quiet" => \$opt_quiet ,
"read_lang_def=s" => \$opt_read_lang_def ,
"show_ext:s" => \$opt_show_ext ,
"show_lang:s" => \$opt_show_lang ,
"progress_rate=i" => \$opt_progress_rate ,
"print_filter_stages" => \$opt_print_filter_stages ,
"report_file=s" => \$opt_report_file ,
"strip_comments=s" => \$opt_strip_comments ,
"sum_reports" => \$opt_sum_reports ,
"v:i" => \$opt_v ,
"version" => \$opt_version ,
"write_lang_def=s" => \$opt_write_lang_def ,
);
my %Exclude_Language = ();
%Exclude_Language = map { $_ => 1 } split(/,/, $opt_exclude_lang)
if $opt_exclude_lang;
my %Exclude_Dir = ();
%Exclude_Dir = map { $_ => 1 } split(/,/, $opt_exclude_dir )
if $opt_exclude_dir ;
# Options defaults:
$opt_progress_rate = 100 unless $opt_progress_rate;
$opt_v = 0 unless $opt_v;
die $usage unless defined $opt_show_lang or
defined $opt_show_ext or
defined $opt_write_lang_def or
scalar @ARGV >= 1;
# 1}}}
# Step 1: Initialize global constants. {{{1
#
my $nFiles_Found = 0; # updated in make_file_list
my (%Language_by_Extension, %Language_by_Script,
%Filters_by_Language, %Not_Code_Extension, %Not_Code_Filename,
%Language_by_File, %Scale_Factor,
);
my %Error_Codes = ( 'Unable to read' => -1,
'Neither file nor directory' => -2, );
if ($opt_read_lang_def) {
read_lang_def(
$opt_read_lang_def , # Sample values:
\%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
\%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
\%Language_by_File , # Language_by_File{makefile} = 'Make'
\%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
# [ 'remove_matches' , '^\s*#' ]
\%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
\%Not_Code_Filename , # Not_Code_Filename{README} = 1
\%Scale_Factor , # Scale_Factor{Perl} = 4.0
);
} else {
set_constants( #
\%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
\%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
\%Language_by_File , # Language_by_File{makefile} = 'Make'
\%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
# [ 'remove_matches' , '^\s*#' ]
\%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
\%Not_Code_Filename , # Not_Code_Filename{README} = 1
\%Scale_Factor , # Scale_Factor{Perl} = 4.0
);
}
# 1}}}
# Step 2: Early exits for display, summation. {{{1
#
print_extension_info($opt_show_ext ) if defined $opt_show_ext ;
print_language_info( $opt_show_lang) if defined $opt_show_lang;
exit if (defined $opt_show_ext) or (defined $opt_show_lang);
if ($opt_sum_reports) {
my %Results = ();
foreach my $type( "by language", "by report file" ) {
my $found_lang = combine_results(\@ARGV,
$type,
\%{$Results{ $type }},
\%Filters_by_Language );
next unless %Results;
my $end_time = time();
my @results = generate_report($VERSION, $end_time - $start_time,
$type,
\%{$Results{ $type }}, \%Scale_Factor);
if ($opt_report_file) {
my $ext = ".lang";
$ext = ".file" unless $type eq "by language";
next if !$found_lang and $ext eq ".lang";
write_file($opt_report_file . $ext, @results);
} else {
print "\n", join("\n", @results), "\n";
}
}
exit;
}
if ($opt_write_lang_def) {
write_lang_def($opt_write_lang_def ,
\%Language_by_Extension,
\%Language_by_Script ,
\%Language_by_File ,
\%Filters_by_Language ,
\%Not_Code_Extension ,
\%Not_Code_Filename ,
\%Scale_Factor ,
);
exit;
}
# 1}}}
# Step 3: Create a list of files to consider. {{{1
# a) If inputs are binary archives, first cd to a temp
# directory, expand the archive with the user-given
# extraction tool, then add the temp directory to
# the list of dirs to process.
# b) Create a list of every file that might contain source
# code. Ignore binary files, zero-sized files, and
# any file in a directory the user says to exclude.
# c) Determine the language for each file in the list.
#
if ($opt_extract_with) {
my $cwd = cwd();
#print "cwd main = [$cwd]\n";
my @extract_location = ();
foreach my $bin_file (@ARGV) {
my $extract_dir = tempdir( CLEANUP => 0 ); # 1 = delete on exit
chdir $extract_dir;
print "Using temp dir [$extract_dir] to extract $bin_file\n"
unless $opt_quiet;
my $bin_file_full_path = "";
if (File::Spec->file_name_is_absolute( $bin_file )) {
$bin_file_full_path = $bin_file;
#print "bin_file_full_path (was ful) = [$bin_file_full_path]\n";
} else {
$bin_file_full_path = File::Spec->catfile( $cwd, $bin_file );
#print "bin_file_full_path (was rel) = [$bin_file_full_path]\n";
}
(my $extract_cmd = $opt_extract_with ) =~ s/>FILE</$bin_file_full_path/g;
print $extract_cmd, "\n";
system $extract_cmd;
push @extract_location, $extract_dir;
chdir $cwd;
}
@ARGV = @extract_location;
}
my @Errors = ();
my @file_list = (); # global variable updated in files()
my %Ignored = (); # files that are not counted (language not recognized or
# problems reading the file)
my $fh = make_file_list(\@ARGV, \%Error_Codes, \@Errors, \%Ignored);
# 1}}}
# Step 4: Remove duplicate files. {{{1
#
my %Language = ();
my %unique_source_file = ();
remove_duplicate_files($fh, \%Language , \%unique_source_file,
\%Error_Codes, \@Errors , \%Ignored);
printf "%8d unique file%s. \n",
plural_form(scalar keys %unique_source_file)
unless $opt_quiet;
# 1}}}
# Step 5: Count code, comments, blank lines. {{{1
#
my %Results_by_Language = ();
my %Results_by_File = ();
my $nCounted = 0;
foreach my $file (sort keys %unique_source_file) {
++$nCounted;
printf "Counting: %d\r", $nCounted unless $nCounted % $opt_progress_rate;
next if $Ignored{$file};
if ($Exclude_Language{$Language{$file}}) {
$Ignored{$file} = "--exclude_lang=$Language{$file}";
next;
}
if (!defined @{$Filters_by_Language{$Language{$file}} }) {
if ($Language{$file} eq "(unknown)") {
$Ignored{$file} = "language unknown (#1)";
} else {
$Ignored{$file} = "missing Filters_by_Language{$Language{$file}}";
}
next;
}
my ($all_line_count,
$blank_count ,
$comment_count ,
) = call_counter($file, $Language{$file});
my $code_count = $all_line_count - $blank_count - $comment_count;
if ($opt_by_file) {
$Results_by_File{$file}{'code' } = $code_count ;
$Results_by_File{$file}{'blank' } = $blank_count ;
$Results_by_File{$file}{'comment'} = $comment_count ;
$Results_by_File{$file}{'lang' } = $Language{$file};
$Results_by_File{$file}{'nFiles' } = 1;
}
++$Results_by_Language{$Language{$file}}{'nFiles'};
$Results_by_Language{$Language{$file}}{'code'} += $code_count ;
$Results_by_Language{$Language{$file}}{'blank'} += $blank_count ;
$Results_by_Language{$Language{$file}}{'comment'} += $comment_count;
}
my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
write_file($opt_ignored, @ignored_reasons ) if $opt_ignored;
write_file($opt_counted, sort keys %Language) if $opt_counted;
# 1}}}
# Step 6: Print results. {{{1
#
my $end_time = time();
printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
unless $opt_quiet;
print_errors(\%Error_Codes, \@Errors) if @Errors;
exit unless %Results_by_Language;
my @results = generate_report($VERSION, $end_time - $start_time,
"by language",
\%Results_by_Language, \%Scale_Factor);
if ($opt_report_file) { write_file($opt_report_file, @results); }
else { print "\n", join("\n", @results), "\n"; }
if ($opt_by_file) {
my @results = generate_report($VERSION, $end_time - $start_time,
"by file",
\%Results_by_File, \%Scale_Factor);
if ($opt_report_file) { write_file($opt_report_file, @results); }
else { print "\n", join("\n", @results), "\n"; }
}
# 1}}}
####################################################################
sub combine_results { # {{{1
# returns 1 if the inputs are categorized by language
# 0 if no identifiable language was found
my ($ra_report_files, # in
$report_type , # in "by language" or "by report file"
$rhh_count , # out count{TYPE}{nFiles|code|blank|comment|scaled}
$rhaa_Filters_by_Language , # in
) = @_;
my $found_language = 0;
foreach my $file (@{$ra_report_files}) {
my $IN = new IO::File $file, "r";
if (!defined $IN) {
warn "Unable to read $file; ignoring.\n";
next;
}
while (<$IN>) {
next if /^(http|Language|SUM|-----)/;
if (m{^(.*?)\s+ # language
(\d+)\s+ # files
(\d+)\s+ # blank
(\d+)\s+ # comments
(\d+)\s+ # code
x\s+ # x
\d+\.\d+\s+ # scale
=\s+ # =
(\d+\.\d+)\s* # scaled code
$}x) {
if ($report_type eq "by language") {
next unless defined %{$rhaa_Filters_by_Language->{$1}};
# above test necessary to avoid trying to sum reports
# of reports (which have no language breakdown).
$found_language = 1;
$rhh_count->{$1 }{'nFiles' } += $2;
$rhh_count->{$1 }{'blank' } += $3;
$rhh_count->{$1 }{'comment'} += $4;
$rhh_count->{$1 }{'code' } += $5;
$rhh_count->{$1 }{'scaled' } += $6;
} else {
$rhh_count->{$file}{'nFiles' } += $2;
$rhh_count->{$file}{'blank' } += $3;
$rhh_count->{$file}{'comment'} += $4;
$rhh_count->{$file}{'code' } += $5;
$rhh_count->{$file}{'scaled' } += $6;
}
}
}
}
return $found_language;
} # 1}}}
####################################################################
sub generate_report { # {{{1
# returns an array of lines containing the results
my ($version , # in
$elapsed_sec, # in
$report_type, # in "by language" | "by report file" | "by file"
$rhh_count , # in count{TYPE}{nFiles|code|blank|comment|scaled}
$rh_scale , # in
) = @_;
my @results = ();
my $sum_files = 0;
my $sum_code = 0;
my $sum_blank = 0;
my $sum_comment = 0;
foreach my $language (keys %{$rhh_count}) {
$sum_files += $rhh_count->{$language}{'nFiles'} ;
$sum_blank += $rhh_count->{$language}{'blank'} ;
$sum_comment += $rhh_count->{$language}{'comment'};
$sum_code += $rhh_count->{$language}{'code'} ;
}
my $sum_lines = $sum_blank + $sum_comment + $sum_code;
$elapsed_sec = 0.5 unless $elapsed_sec;
my $URL = "http://cloc.sourceforge.net";
my $hypen_line = sprintf "%s", '-' x 79;
my $data_line = "";
my $first_column;
my $BY_LANGUAGE = 0;
my $BY_FILE = 0;
if ($report_type eq "by language") {
$first_column = "Language";
$BY_LANGUAGE = 1;
} elsif ($report_type eq "by file") {
$first_column = "File";
$BY_FILE = 1;
} else {
$first_column = "Report File";
}
my $header_line = sprintf "%s v %4.2f", $URL, $version;
$header_line .= sprintf(" T=%.1f s (%.1f files/s, %.1f lines/s)",
$elapsed_sec ,
$sum_files/$elapsed_sec,
$sum_lines/$elapsed_sec) unless $opt_sum_reports;
push @results, $header_line;
push @results, $hypen_line;
$data_line = sprintf "%-13s ", $first_column ;
$data_line .= sprintf "%9s " , "files" unless $BY_FILE;
$data_line .= sprintf "%9s %9s %9s %8s %14s",
"blank" ,
"comments" ,
"code" ,
"scale" ,
"3rd gen. equiv";
push @results, $data_line;
push @results, $hypen_line;
my $sum_scaled = 0;
foreach my $lang_or_file (sort {
$rhh_count->{$b}{'code'} <=>
$rhh_count->{$a}{'code'}
}
keys %{$rhh_count}) {
my ($factor, $scaled);
if ($BY_LANGUAGE or $BY_FILE) {
$factor = 1;
if ($BY_LANGUAGE) {
if (defined $rh_scale->{$lang_or_file}) {
$factor = $rh_scale->{$lang_or_file};
} else {
warn "No scale factor for $lang_or_file; using 1.00";
}
} else { # by individual code file
$factor = $rh_scale->{$rhh_count->{$lang_or_file}{'lang'}};
}
$scaled = $factor*$rhh_count->{$lang_or_file}{'code'};
} else {
$scaled = $rhh_count->{$lang_or_file}{'scaled'};
$factor = $scaled/$rhh_count->{$lang_or_file}{'code'};
}
$data_line = sprintf "%-13s ", $lang_or_file;
$data_line .= sprintf "%9d ", $rhh_count->{$lang_or_file}{'nFiles'}
unless $BY_FILE;
$data_line .= sprintf "%9d %9d %9d x %6.2f = %14.2f",
$rhh_count->{$lang_or_file}{'blank'} ,
$rhh_count->{$lang_or_file}{'comment'},
$rhh_count->{$lang_or_file}{'code'} ,
$factor ,
$scaled ;
$sum_scaled += $scaled;
push @results, $data_line;
}
my $avg_scale = 1; # weighted average of scale factors
$avg_scale = $sum_scaled / $sum_code if $sum_code;
push @results, $hypen_line;
$data_line = sprintf "%-13s ", "SUM:" ;
$data_line .= sprintf "%9d ", $sum_files
unless $BY_FILE ;
$data_line .= sprintf "%9d %9d %9d x %6.2f = %14.2f",
$sum_blank ,
$sum_comment ,
$sum_code ,
$avg_scale ,
$sum_scaled ;
push @results, $data_line;
push @results, $hypen_line;
return @results;
} # 1}}}
####################################################################
sub print_errors { # {{{1
my ($rh_Error_Codes, # in
$raa_errors , # in
) = @_;
my %error_string = reverse(%{$rh_Error_Codes});
my $nErrors = scalar @{$raa_errors};
printf "\n%d error%s:\n", plural_form(scalar @Errors);
for (my $i = 0; $i < $nErrors; $i++) {
printf "%s: %s\n",
$error_string{ $raa_errors->[$i][0] },
$raa_errors->[$i][1] ;
}
print "\n";
} # 1}}}
####################################################################
sub write_lang_def { # {{{1
my ($file ,
$rh_Language_by_Extension , # in
$rh_Language_by_Script , # in
$rh_Language_by_File , # in
$rhaa_Filters_by_Language , # in
$rh_Not_Code_Extension , # in
$rh_Not_Code_Filename , # in
$rh_Scale_Factor , # in
) = @_;
my $OUT = new IO::File $file, "w";
die "Unable to write to $file\n" unless defined $OUT;
foreach my $language (sort keys %{$rhaa_Filters_by_Language}) {
next if $language eq "MATLAB or Objective C";
printf $OUT "%s\n", $language;
foreach my $filter (@{$rhaa_Filters_by_Language->{$language}}) {
printf $OUT " filter %s", $filter->[0];
printf $OUT " %s", $filter->[1] if defined $filter->[1];
print $OUT "\n";
}
foreach my $ext (sort keys %{$rh_Language_by_Extension}) {
if ($language eq $rh_Language_by_Extension->{$ext}) {
printf $OUT " extension %s\n", $ext;
}
}
foreach my $filename (sort keys %{$rh_Language_by_File}) {
if ($language eq $rh_Language_by_File->{$filename}) {
printf $OUT " filename %s\n", $filename;
}
}
foreach my $script_exe (sort keys %{$rh_Language_by_Script}) {
if ($language eq $rh_Language_by_Script->{$script_exe}) {
printf $OUT " script_exe %s\n", $script_exe;
}
}
printf $OUT " 3rd_gen_scale %.2f\n", $rh_Scale_Factor->{$language};
}
$OUT->close;
} # 1}}}
####################################################################
sub read_lang_def { # {{{1
my ($file ,
$rh_Language_by_Extension , # out
$rh_Language_by_Script , # out
$rh_Language_by_File , # out
$rhaa_Filters_by_Language , # out
$rh_Not_Code_Extension , # out
$rh_Not_Code_Filename , # out
$rh_Scale_Factor , # out
) = @_;
my $IN = new IO::File $file, "r";
die "Unable to read $file.\n" unless defined $IN;
my $language = "";
while (<$IN>) {
next if /^\s*#/ or /^\s*$/;
if (/^(\w+.*?)\s*$/) {
$language = $1;
next;
}
die "Missing computer language name, line $. of $file\n"
unless $language;
if (/^ filter\s+(\w+)\s*$/) {
push @{$rhaa_Filters_by_Language->{$language}}, [ $1 ]
} elsif (/^ filter\s+(\w+)\s+(.*?)\s*$/) {
push @{$rhaa_Filters_by_Language->{$language}}, [ $1 , $2 ]
} elsif (/^ extension\s+(\S+)\s*$/) {
if (defined $rh_Language_by_Extension->{$1}) {
die "File extension collision: $1 ",
"maps to languages '$rh_Language_by_Extension->{$1}' ",
"and '$language'\n" ,
"Edit $file and remove $1 from one of these two ",
"language definitions.\n";
}
$rh_Language_by_Extension->{$1} = $language;
} elsif (/^ filename\s+(\S+)\s*$/) {
$rh_Language_by_File->{$1} = $language;
} elsif (/^ script_exe\s+(\S+)\s*$/) {
$rh_Language_by_Script->{$1} = $language;
} elsif (/^ 3rd_gen_scale\s+(\S+)\s*$/) {
$rh_Scale_Factor->{$language} = $1;
} else {
die "Unexpected data line $. of $file:\n$_\n";
}
}
$IN->close;
} # 1}}}
####################################################################
sub print_extension_info { # {{{1
my ($extension,) = @_;
if ($extension) { # show information on this extension
foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
# Language_by_Extension{f} = 'Fortran 77'
printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext}
if $ext =~ m{$extension}i;
}
} else { # show information on all extensions
foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
# Language_by_Extension{f} = 'Fortran 77'
printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext};
}
}
} # 1}}}
####################################################################
sub print_language_info { # {{{1
my ($language,) = @_;
my %extensions = (); # the subset matched by the given $language value
if ($language) { # show information on this language
foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
# Language_by_Extension{f} = 'Fortran 77'
push @{$extensions{$Language_by_Extension{$ext}} }, $ext
if $Language_by_Extension{$ext} =~ m{$language}i;
}
} else { # show information on all languages
foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
# Language_by_Extension{f} = 'Fortran 77'
push @{$extensions{$Language_by_Extension{$ext}} }, $ext
}
}
if (%extensions) {
foreach my $lang (sort {lc $a cmp lc $b } keys %extensions) {
printf "%-24s (%s)\n", $lang, join(", ", @{$extensions{$lang}});
}
}
} # 1}}}
####################################################################
sub make_file_list { # {{{1
my ($ra_arg_list, # in file and/or directory names to examine
$rh_Err , # in hash of error codes
$raa_errors , # out errors encountered
$rh_ignored , # out files not recognized as computer languages
) = @_;
my ($fh, $filename);
if ($opt_categorized) {
$filename = $opt_categorized;
$fh = new IO::File $filename, "+>"; # open for read/write
die "Unable to write to $filename: $!\n" unless defined $fh;
} else {
($fh, $filename) = tempfile(UNLINK => 1); # delete file on exit
print "Using temp file list [$filename]\n" unless $opt_quiet;
}
my @dir_list = ();
foreach my $file_or_dir (@{$ra_arg_list}) {
#print "make_file_list file_or_dir=$file_or_dir\n";
my $size_in_bytes = 0;
if (!-r $file_or_dir) {
push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file_or_dir];
next;
}
if (is_file($file_or_dir)) {
if (!(-s $file_or_dir)) { # 0 sized file, named pipe, socket
$rh_ignored->{$file_or_dir} = 'zero sized file';
next;
} elsif (-B $file_or_dir) { # avoid binary files
$rh_ignored->{$file_or_dir} = 'binary file';
next;
}
push @file_list, "$file_or_dir";
} elsif (is_dir ($file_or_dir)) {
push @dir_list, $file_or_dir;
} else {
push @{$raa_errors}, [$rh_Err->{'Neither file nor directory'} , $file_or_dir];
$rh_ignored->{$file_or_dir} = 'not file, not directory';
}
}
foreach my $dir (@dir_list) {
#print "make_file_list dir=$dir\n";
find(\&files, $dir); # populates global variable @file_list
}
$nFiles_Found = scalar @file_list;
printf "%8d text file%s.\n", plural_form($nFiles_Found) unless $opt_quiet;
write_file($opt_found, sort @file_list) if $opt_found;
my $nFiles_Categorized = 0;
foreach my $file (@file_list) {
printf "classifying $file\n" if $opt_v > 2;
my $basename = basename $file;
if ($Not_Code_Filename{$basename}) {
$rh_ignored->{$file} = "listed in " . '$' .
"Not_Code_Filename{$basename}";
next;
} elsif ($basename =~ m{~$}) {
$rh_ignored->{$file} = "temporary editor file";
next;
}
my $size_in_bytes = (stat $file)[7];
my $language = classify_file($file ,
$rh_Err ,
$raa_errors,
$rh_ignored);
die "make_file_list($file) undef size" unless defined $size_in_bytes;
die "make_file_list($file) undef lang" unless defined $language;
printf $fh "%d,%s,%s\n", $size_in_bytes, $language, $file;
++$nFiles_Categorized;
printf "classified %d files\r",
$nFiles_Categorized unless $nFiles_Categorized % $opt_progress_rate;
}
printf "classified %d files\r", $nFiles_Categorized
if !$opt_quiet and $nFiles_Categorized > 1;
return $fh; # handle to the file containing the list of files to process
} # 1}}}
####################################################################
sub remove_duplicate_files { # {{{1
my ($fh , # in
$rh_Language , # out
$rh_unique_source_file, # out
$rh_Err , # in
$raa_errors , # out errors encountered
$rh_ignored , # out
) = @_;
# Check for duplicate files by comparing file sizes.
# Where files are equally sized, compare their MD5 checksums.
my $n = 0;
my %files_by_size = (); # files_by_size{ # bytes } = [ list of files ]
seek($fh, 0, 0); # rewind to beginning of the temp file
while (<$fh>) {
++$n;
my ($size_in_bytes, $language, $file) = split(/,/, $_, 3);
chomp($file);
$rh_Language->{$file} = $language;
push @{$files_by_size{$size_in_bytes}}, $file;
}
if ($n > $opt_progress_rate) {
printf "Duplicate file check %d files (%d known unique)\r",
$n, scalar keys %files_by_size;
}
$n = 0;
foreach my $bytes (sort {$a <=> $b} keys %files_by_size) {
++$n;
printf "Unique: %8d files \r",
$n unless $n % $opt_progress_rate;
$rh_unique_source_file->{$files_by_size{$bytes}[0]} = 1;
next unless scalar @{$files_by_size{$bytes}} > 1;
foreach my $F (different_files(\@{$files_by_size{$bytes}},
$rh_Err ,
$raa_errors ,
$rh_ignored ) ) {
$rh_unique_source_file->{$F} = 1;
}
}
} # 1}}}
####################################################################
sub files { # {{{1
# invoked by File::Find's find() Populates global variable @file_list
if ($opt_exclude_dir) {
my $return = 0;
foreach my $skip_dir (keys %Exclude_Dir) {
if ($File::Find::dir =~ m{/$skip_dir(/|$)} ) {
$Ignored{$File::Find::name} = "--exclude_dir=$skip_dir";
$return = 1;
last;
}
}
return if $return;
}
my $nBytes = -s $_ ;
if (!$nBytes and $opt_v > 5) {
printf "files(%s) zero size\n", $File::Find::name;
}
return unless $nBytes ; # attempting other tests w/pipe or socket will hang
my $is_dir = is_dir($_);
my $is_bin = -B $_ ;
printf "files(%s) size=%d is_dir=%d -B=%d\n",
$File::Find::name, $nBytes, $is_dir, $is_bin if $opt_v > 5;
return if $is_dir or $is_bin;
++$nFiles_Found;
printf "%8d files\r", $nFiles_Found unless $nFiles_Found % $opt_progress_rate;
push @file_list, $File::Find::name;
} # 1}}}
####################################################################
sub is_file { # {{{1
# portable method to test if item is a file
# (-f doesn't work in ActiveState Perl on Windows)
my $item = shift @_;
my $mode = (stat $item)[2];
$mode = 0 unless $mode;
if ($mode & 0100000) { return 1; }
else { return 0; }
} # 1}}}
####################################################################
sub is_dir { # {{{1
# portable method to test if item is a directory
# (-d doesn't work in ActiveState Perl on Windows)
my $item = shift @_;
my $mode = (stat $item)[2];
$mode = 0 unless $mode;
if ($mode & 0040000) { return 1; }
else { return 0; }
} # 1}}}
####################################################################
sub classify_file { # {{{1
my ($full_file , # in
$rh_Err , # in hash of error codes
$raa_errors , # out
$rh_ignored , # out
) = @_;
print "-> classify_file($full_file)\n" if $opt_v > 2;
my $language = "(unknown)";
my $look_at_first_line = 0;
my $file = basename $full_file;
return $language if $Not_Code_Filename{$file}; # (unknown)
return $language if $file =~ m{~$}; # a temp edit file (unknown)
if ($file =~ /\.(\w+)$/) { # has an extension
print "$full_file extension=[$1]\n" if $opt_v > 2;
my $extension = $1;
if ($Not_Code_Extension{$extension}) {
$rh_ignored->{$full_file} =
'listed in $Not_Code_Extension{' . $extension . '}';
return $language;
}
if (defined $Language_by_Extension{$extension}) {
if ($Language_by_Extension{$extension} eq
'MATLAB or Objective C') {
my $lang_M_or_O = "";
matlab_or_objective_C($full_file ,
$rh_Err ,
$raa_errors,
\$lang_M_or_O);
if ($lang_M_or_O) {
return $lang_M_or_O;
} else { # an error happened in matlab_or_objective_C()
$rh_ignored->{$full_file} =
'failure in matlab_or_objective_C()';
return $language; # (unknown)
}
} else {
return $Language_by_Extension{$extension};
}
} else { # has an unmapped file extension
$look_at_first_line = 1;
}
} elsif (defined $Language_by_File{lc $file}) {
return $Language_by_File{lc $file};
} else { # no file extension
$look_at_first_line = 1;
}
if ($look_at_first_line) {
# maybe it is a shell/Perl/Python/Ruby/etc script that
# starts with pound bang:
# #!/usr/bin/perl
# #!/usr/bin/env perl
my $script_language = peek_at_first_line($full_file ,
$rh_Err ,
$raa_errors);
if (!$script_language) {
$rh_ignored->{$full_file} = "language unknown (#2)";
# returns (unknown)
}
if (defined $Language_by_Script{$script_language}) {
if (defined $Filters_by_Language{
$Language_by_Script{$script_language}}) {
$language = $Language_by_Script{$script_language};
} else {
$rh_ignored->{$full_file} =
"undefined: Filters_by_Language{" .
$Language_by_Script{$script_language} .
"} for scripting language $script_language";
# returns (unknown)
}
} else {
$rh_ignored->{$full_file} = "language unknown (#3)";
# returns (unknown)
}
}
print "<- classify_file($full_file)\n" if $opt_v > 2;
return $language;
} # 1}}}
####################################################################
sub peek_at_first_line { # {{{1
my ($file , # in
$rh_Err , # in hash of error codes
$raa_errors , # out
) = @_;
print "-> peek_at_first_line($file)\n" if $opt_v > 2;
my $script_language = "";
if (!-r $file) {
push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
return $script_language;
}
my $IN = new IO::File $file, "r";
if (!defined $IN) {
push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
print "<- peek_at_first_line($file)\n" if $opt_v > 2;
return $script_language;
}
chomp(my $first_line = <$IN>);
if (defined $first_line) {
#print "peek_at_first_line first_line=$first_line\n";
if ($first_line =~ /^#\!(.*?)$/) {
my @pound_bang = split(' ', $1);
#print "peek_at_first_line basename 0=[", basename($pound_bang[0]), "]\n";
if (basename($pound_bang[0]) eq "env" and
scalar @pound_bang > 1) {
$script_language = $pound_bang[1];
#print "peek_at_first_line pound_bang A $pound_bang[1]\n";
} else {
$script_language = basename $pound_bang[0];
#print "peek_at_first_line pound_bang B $script_language\n";
}
}
}
$IN->close;
print "<- peek_at_first_line($file)\n" if $opt_v > 2;
return $script_language;