-
Notifications
You must be signed in to change notification settings - Fork 45
/
cloc-1.00.pl
3960 lines (3620 loc) · 149 KB
/
cloc-1.00.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 <[email protected]>
# 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 = 1.00;
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 File::Path;
use IO::File;
# Digest::MD5 isn't in the standard distribution. Use it only if installed.
my $HAVE_Digest_MD5 = 0;
eval "use Digest::MD5;";
if (defined $Digest::MD5::VERSION) {
$HAVE_Digest_MD5 = 1;
} else {
warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
}
my $HAVE_Rexexp_Common;
# Regexp::Common also isn't in the standard distribution. It will
# be installed in a temp directory if necessary.
BEGIN {
if (eval "use Regexp::Common;") {
$HAVE_Rexexp_Common = 1;
} else {
$HAVE_Rexexp_Common = 0;
}
}
# Uncomment next two lines when building Windows executable with perl2exe
# or if running on a system that already has Regexp::Common.
#use Regexp::Common;
#$HAVE_Rexexp_Common = 1;
#perl2exe_include "Regexp/Common/whitespace.pm"
#perl2exe_include "Regexp/Common/URI.pm"
#perl2exe_include "Regexp/Common/URI/fax.pm"
#perl2exe_include "Regexp/Common/URI/file.pm"
#perl2exe_include "Regexp/Common/URI/ftp.pm"
#perl2exe_include "Regexp/Common/URI/gopher.pm"
#perl2exe_include "Regexp/Common/URI/http.pm"
#perl2exe_include "Regexp/Common/URI/pop.pm"
#perl2exe_include "Regexp/Common/URI/prospero.pm"
#perl2exe_include "Regexp/Common/URI/news.pm"
#perl2exe_include "Regexp/Common/URI/tel.pm"
#perl2exe_include "Regexp/Common/URI/telnet.pm"
#perl2exe_include "Regexp/Common/URI/tv.pm"
#perl2exe_include "Regexp/Common/URI/wais.pm"
#perl2exe_include "Regexp/Common/CC.pm"
#perl2exe_include "Regexp/Common/SEN.pm"
#perl2exe_include "Regexp/Common/number.pm"
#perl2exe_include "Regexp/Common/delimited.pm"
#perl2exe_include "Regexp/Common/profanity.pm"
#perl2exe_include "Regexp/Common/net.pm"
#perl2exe_include "Regexp/Common/zip.pm"
#perl2exe_include "Regexp/Common/comment.pm"
#perl2exe_include "Regexp/Common/balanced.pm"
#perl2exe_include "Regexp/Common/lingua.pm"
#perl2exe_include "Regexp/Common/list.pm"
#perl2exe_include "File/Glob.pm"
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 /.cvs/ 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).
--force-lang=<lang>,<ext> Process all files that have a <ext> extension
with the counter for language <lang>. For
example, to count all .f files with the
Fortran 90 counter (which expects files to
end with .f90) instead of the default Fortran 77
counter, use
--force-lang=\"Fortran 90\",f
The language name is case insensitive. This
option can be specified multiple times.
--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>.
--no3 Suppress third-generation language output.
This option can cause report summation to fail
if some reports were produced with this option
while others were produced without it.
--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.
--sdir=<dir> Use <dir> as the scratch directory instead of
letting File::Temp chose the location. Files
written to this location are not removed at
the end of the run (as they are with File::Temp).
--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 cumulative 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.
--csv Write the results as comma separated values.
--xml Write the results in XML.
--yaml Write the results in YAML.
";
$| = 1; # flush STDOUT
my $start_time = time();
my (
$opt_categorized ,
$opt_found ,
@opt_force_lang ,
$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_sdir ,
$opt_sum_reports ,
$opt_no3 ,
$opt_extract_with ,
$opt_by_file ,
$opt_xml ,
$opt_yaml ,
$opt_csv ,
);
GetOptions(
"by_file" => \$opt_by_file ,
"by-file" => \$opt_by_file ,
"categorized=s" => \$opt_categorized ,
"counted=s" => \$opt_counted ,
"exclude_lang=s" => \$opt_exclude_lang ,
"exclude-lang=s" => \$opt_exclude_lang ,
"exclude_dir=s" => \$opt_exclude_dir ,
"exclude-dir=s" => \$opt_exclude_dir ,
"extract_with=s" => \$opt_extract_with ,
"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 ,
"read-lang-def=s" => \$opt_read_lang_def ,
"show_ext:s" => \$opt_show_ext ,
"show-ext:s" => \$opt_show_ext ,
"show_lang:s" => \$opt_show_lang ,
"show-lang:s" => \$opt_show_lang ,
"progress_rate=i" => \$opt_progress_rate ,
"progress-rate=i" => \$opt_progress_rate ,
"print_filter_stages" => \$opt_print_filter_stages ,
"print-filter-stages" => \$opt_print_filter_stages ,
"report_file=s" => \$opt_report_file ,
"report-file=s" => \$opt_report_file ,
"sdir=s" => \$opt_sdir ,
"strip_comments=s" => \$opt_strip_comments ,
"strip-comments=s" => \$opt_strip_comments ,
"sum_reports" => \$opt_sum_reports ,
"sum-reports" => \$opt_sum_reports ,
"no3" => \$opt_no3 ,
"v:i" => \$opt_v ,
"version" => \$opt_version ,
"write_lang_def=s" => \$opt_write_lang_def ,
"write-lang-def=s" => \$opt_write_lang_def ,
"xml" => \$opt_xml ,
"force_lang=s" => \@opt_force_lang ,
"force-lang=s" => \@opt_force_lang ,
"yaml" => \$opt_yaml ,
"csv" => \$opt_csv ,
);
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_version or
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 $ON_WINDOWS = 0;
$ON_WINDOWS = 1 if ($^O =~ /^MSWin/) or ($^O eq "Windows_NT");
$ON_WINDOWS = 0 if $ENV{'SHELL'}; # make Cygwin look like Unix
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, %Known_Binary_Archives,
);
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
\%Known_Binary_Archives, # Known_Binary_Archives{.tar} = 1
);
}
# Process command line provided extention-to-language mapping overrides.
# Make a hash of known languages in lower case for easier matching.
my %Recognized_Language_lc = (); # key = language name in lc, value = true name
foreach my $language (keys %Filters_by_Language) {
my $lang_lc = lc $language;
$Recognized_Language_lc{$lang_lc} = $language;
}
my %Forced_Extension = (); # file name extensions which user wants to count
foreach my $pair (@opt_force_lang) {
my ($lang, $extension) = split(',', $pair);
$Forced_Extension{$extension} = $lang;
my $lang_lc = lc $lang;
die "Unknown language '$lang' used with --force-lang option. " .
"The command\n $script --show-lang\n" .
"will print all recognized languages.\n"
unless $Recognized_Language_lc{$lang_lc};
$Language_by_Extension{$extension} = $Recognized_Language_lc{$lang_lc};
}
# 1}}}
# Step 2: Early exits for display, summation. {{{1
#
if ($opt_version) {
printf "%.2f\n", $VERSION;
exit;
}
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);
# Windows doesn't expand wildcards. Use code from Sean M. Burke's
# Win32::Autoglob module to do this.
#print "Before glob have [", join(",", @ARGV), "]\n";
@ARGV = map {;
( defined($_) and m/[\*\?]/ ) ? sort(glob($_)) : $_
} @ARGV if $ON_WINDOWS;
;
#print "after glob have [", join(",", @ARGV), "]\n";
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.
#
my @binary_archive = ();
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 => 1 ); # 1 = delete on exit
chdir $extract_dir;
print "Using temp dir [$extract_dir] to extract $bin_file\n"
if $opt_v;
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;
}
# It is possible that the binary archive itself contains additional
# files compressed the same way (true for Java .ear files). Go
# through all the files that were extracted, see if they are binary
# archives and try to extract them. Lather, rinse, repeat.
my $binary_archives_exist = 1;
my $count_binary_archives = 0;
my $previous_count = 0;
while ($binary_archives_exist) {
@binary_archive = ();
foreach my $dir (@extract_location) {
find(\&archive_files, $dir); # populates global @binary_archive
}
foreach my $archive (@binary_archive) {
(my $extract_cmd = $opt_extract_with )
=~ s/>FILE</$archive/g;
my $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
chdir $extract_dir;
print $extract_cmd, "\n";
system $extract_cmd;
push @extract_location, $extract_dir;
unlink $archive; # otherwise will be extracting it forever
}
$count_binary_archives = scalar @binary_archive;
if ($count_binary_archives == $previous_count) {
$binary_archives_exist = 0;
}
$previous_count = $count_binary_archives;
}
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);
# make_file_list populates global variable @file_list via call to
# File::Find's find() which in turn calls files()
# 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;
#use YAML; print YAML::Dump(\%Results_by_Language); die;
my @results = ();
unless ($opt_by_file) {
@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"; }
} else {
@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
( # next four entries missing with -nno3
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' } += $7 unless $opt_no3;
} 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' } += $7 unless $opt_no3;
}
}
}
}
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 $languages = ();
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 $spacing_1 = 13;
my $spacing_2 = 9;
my $spacing_3 = 17;
if ($opt_no3) {
$spacing_1 = 19;
$spacing_2 = 14;
$spacing_3 = 28;
}
my %Format = (
'1' => { 'xml' => 'name="%s" ',
'txt' => '%-23s ' ,
},
'2' => { 'xml' => 'name="%s" ',
'txt' => "\%-${spacing_3}s ",
},
'3' => { 'xml' => 'files_count="%d" ',
'txt' => '%5d ',
},
'4' => { 'xml' => 'blank="%d" comment="%d" code="%d" ',
'txt' => "\%${spacing_2}d \%${spacing_2}d \%${spacing_2}d",
},
'5' => { 'xml' => 'factor="%.2f" scaled="%.2f" ',
'txt' => ' x %6.2f = %14.2f',
},
);
my $Style = "txt";
$Style = "xml" if $opt_xml ;
$Style = "xml" if $opt_yaml; # not a typo; just set to anything but txt
$Style = "xml" if $opt_csv ; # not a typo; just set to anything but txt
my $URL = "http://cloc.sourceforge.net";
my $hyphen_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;
if ($opt_xml) {
push @results, "<?xml version=\"1.0\"?>";
push @results, "<results>";
push @results, "<header>$header_line</header>";
} elsif ($opt_yaml) {
push @results, "---\n# $header_line";
} elsif ($opt_csv) {
# append the header to the end of the column headers
# to keep the output a bit cleaner from a spreadsheet
# perspective
} else {
push @results, $header_line;
push @results, $hyphen_line;
}
if ($Style eq "txt") {
# column headers
$data_line = sprintf "%-${spacing_1}s ", $first_column;
if ($BY_FILE) {
$data_line .= sprintf "%${spacing_2}s " , " " ;
} else {
$data_line .= sprintf "%${spacing_2}s " , "files";
}
$data_line .= sprintf "%${spacing_2}s %${spacing_2}s %${spacing_2}s",
"blank" ,
"comment" ,
"code";
$data_line .= sprintf " %8s %14s",
"scale" ,
"3rd gen. equiv"
unless $opt_no3;
push @results, $data_line;
push @results, $hyphen_line;
}
if ($opt_csv) {
my $header2 = " ,";
$header2 = " ,files" unless $BY_FILE;
$header2 .= ",blank,comment,code";
$header2 .= ",scale,3rd gen. equiv" unless $opt_no3;
$header2 .= ',"' . $header_line . '"';
push @results, $header2;
}
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 {
if (!defined $rhh_count->{$lang_or_file}{'scaled'}) {
$opt_no3 = 1;
# If we're summing together files previously generated
# with --no3 then rhh_count->{$lang_or_file}{'scaled'}
# this variable will be undefined. That should only
# happen when summing together by file however.
} elsif ($BY_LANGUAGE) {
warn "Missing scaled language info for $lang_or_file\n";
}
unless ($opt_no3) {
$scaled = $rhh_count->{$lang_or_file}{'scaled'};
$factor = $scaled/$rhh_count->{$lang_or_file}{'code'};
}
}
if ($BY_FILE) {
$data_line = sprintf $Format{'1'}{$Style}, $lang_or_file;
} else {
$data_line = sprintf $Format{'2'}{$Style}, $lang_or_file;
}
$data_line .= sprintf $Format{3}{$Style} ,
$rhh_count->{$lang_or_file}{'nFiles'} unless $BY_FILE;
$data_line .= sprintf $Format{4}{$Style} ,
$rhh_count->{$lang_or_file}{'blank'} ,
$rhh_count->{$lang_or_file}{'comment'},
$rhh_count->{$lang_or_file}{'code'} ;
$data_line .= sprintf $Format{5}{$Style} ,
$factor ,
$scaled unless $opt_no3;
$sum_scaled += $scaled unless $opt_no3;
if ($opt_xml) {
if (defined $rhh_count->{$lang_or_file}{'lang'}) {
my $lang = $rhh_count->{$lang_or_file}{'lang'};
if (!defined $languages->{$lang}) {
$languages->{$lang} = $lang;
}
$data_line.=' language="' . $lang . '" ';
}
if ($BY_FILE) {
push @results, "<file " . $data_line . "/>";
} else {
push @results, "<language " . $data_line . "/>";
}
} elsif ($opt_yaml) {
push @results, $lang_or_file . ":";
push @results, " nFiles: " .$rhh_count->{$lang_or_file}{'nFiles'} ;
push @results, " blank: " .$rhh_count->{$lang_or_file}{'blank'} ;
push @results, " comment: ".$rhh_count->{$lang_or_file}{'comment'};
push @results, " code: " .$rhh_count->{$lang_or_file}{'code'}
unless $BY_FILE;
if (!$opt_no3) {
push @results, " scaled: " . $scaled;
push @results, " factor: " . $factor;
}
} elsif ($opt_csv) {
my $extra_3 = "";
$extra_3 = ",$factor,$scaled" unless $opt_no3;
push @results, $lang_or_file . "," .
$rhh_count->{$lang_or_file}{'nFiles'} . "," .
$rhh_count->{$lang_or_file}{'blank'} . "," .
$rhh_count->{$lang_or_file}{'comment'}. "," .
$rhh_count->{$lang_or_file}{'code'} .
$extra_3;
} else {
push @results, $data_line;
}
}
my $avg_scale = 1; # weighted average of scale factors
$avg_scale = sprintf("%.2f", $sum_scaled / $sum_code)
if $sum_code and !$opt_no3;
if ($opt_xml) {
$data_line = "";
if (!$BY_FILE) {
$data_line .= sprintf "sum_files=\"%d\" ", $sum_files;
}
$data_line .= sprintf $Format{'4'}{$Style},
$sum_blank ,
$sum_comment ,
$sum_code ;
$data_line .= sprintf $Format{'5'}{$Style},
$avg_scale ,
$sum_scaled unless $opt_no3;
push @results, "<total " . $data_line . "/>";
push @results, "<languages>";
foreach my $language (keys %{$languages}) {
push @results, '<language name="' . $language . '"/>';
}
push @results, "</languages>";
push @results, "</results>";
} elsif ($opt_yaml) {
push @results, "SUM:";
push @results, " blank: " . $sum_blank ;
push @results, " code: " . $sum_code ;
push @results, " comment: ". $sum_comment;
push @results, " nFiles: " . $sum_files unless $BY_FILE;
if (!$opt_no3) {
push @results, " scaled: " . $sum_scaled;
push @results, " factor: " . $avg_scale ;
}
} elsif ($opt_csv) {
# do nothing
} else {
if ($BY_FILE) {
$data_line = sprintf "%-23s ", "SUM:" ;
} else {
$data_line = sprintf "%-${spacing_1}s ", "SUM:" ;
$data_line .= sprintf "%${spacing_2}d ", $sum_files;
}
$data_line .= sprintf $Format{'4'}{$Style},
$sum_blank ,
$sum_comment ,
$sum_code ;
$data_line .= sprintf $Format{'5'}{$Style},
$avg_scale ,
$sum_scaled unless $opt_no3;
push @results, $hyphen_line if $sum_files > 1;
push @results, $data_line if $sum_files > 1;
push @results, $hyphen_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/Objective C/MUMPS";
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;
}