Login
Consolidated the ProhibitExit policies into a single Policy.
[gknop/Perl-Critic.git] / bin / perlcritic
CommitLineData
59b05e08
JRT
1#!/usr/bin/perl
2
6036a254 3##############################################################################
3915361f
JRT
4# $URL$
5# $Date$
6# $Author$
7# $Revision$
e68db767 8##############################################################################
3915361f 9
59b05e08
JRT
10package main;
11
df6dee2b 12use 5.006001;
59b05e08
JRT
13use strict;
14use warnings;
a79d19f4
ES
15
16use English qw< -no_match_vars >;
05b5f925
ES
17use Readonly;
18
a79d19f4
ES
19use Getopt::Long qw< GetOptions >;
20use List::Util qw< first >;
21use Pod::Usage qw< pod2usage >;
e68db767 22
94472d4a 23use Perl::Critic::Exception::Parse ();
a79d19f4 24use Perl::Critic::Utils qw<
70f3f307 25 :characters :severities policy_short_name
05b5f925 26 $DEFAULT_VERBOSITY $DEFAULT_VERBOSITY_WITH_FILE_NAME
a79d19f4
ES
27>;
28use Perl::Critic::Violation qw<>;
05b5f925 29
7807e1bf 30#-----------------------------------------------------------------------------
59b05e08 31
4742d43c 32our $VERSION = '1.095_001';
db1213c6 33
05b5f925
ES
34Readonly::Scalar my $DEFAULT_VIOLATIONS_FOR_TOP => 20;
35
a79d19f4
ES
36Readonly::Scalar my $EXIT_SUCCESS => 0;
37Readonly::Scalar my $EXIT_NO_FILES => 1;
38Readonly::Scalar my $EXIT_HAD_VIOLATIONS => 2;
39Readonly::Scalar my $EXIT_HAD_FILE_PROBLEMS => 3;
40
4268e673
JRT
41#-----------------------------------------------------------------------------
42# Begin script. Don't run when loaded as a library
43
a6677e04
ES
44my @files = ();
45my $critic = undef;
46my $output = \*STDOUT;
72d248e0
RS
47
48# This %ENV check is to allow perlcritic to function when bundled under PAR,
49# which invokes this program not as the top stack frame. -- rjbs, 2008-08-11
a6677e04 50exit run() if not caller or $ENV{PAR_0};
59b05e08 51
db1213c6 52#-----------------------------------------------------------------------------
4268e673 53# Begin subroutines
af1acfa2 54
385d181e
JRT
55sub out {
56 my @lines = @_;
57 return print {$output} @lines;
89b50090
ES
58}
59
a6677e04 60#-----------------------------------------------------------------------------
89b50090 61
4268e673 62sub run {
55ae7242 63 my %options = get_options();
a6677e04 64 @files = get_input(@ARGV);
a79d19f4 65
a6677e04 66 my ($violations, $had_error_in_file) = critique(\%options, @files);
a79d19f4
ES
67
68 return $EXIT_HAD_FILE_PROBLEMS if $had_error_in_file;
69 return $EXIT_NO_FILES if not defined $violations;
70 return $EXIT_HAD_VIOLATIONS if $violations;
71
72 return $EXIT_SUCCESS;
af1acfa2 73}
59b05e08 74
db1213c6 75#-----------------------------------------------------------------------------
59b05e08 76
6e7d6c9f 77sub get_options {
59b05e08 78
55ae7242
JRT
79 my %opts = _parse_command_line();
80 _dispatch_special_requests( %opts );
81 _validate_options( %opts );
82
83 # Convert severity shortcut options. If multiple shortcuts
e7ae8f62 84 # are given, the lowest one wins. If an explicit --severity
0bcb38c0
JRT
85 # option has been given, then the shortcuts are ignored. The
86 # @SEVERITY_NAMES variable is exported by Perl::Critic::Utils.
385d181e
JRT
87 $opts{-severity} ||= first { exists $opts{"-$_"} } @SEVERITY_NAMES;
88 $opts{-severity} ||= first { exists $opts{"-$_"} } ($SEVERITY_LOWEST .. $SEVERITY_HIGHEST);
55ae7242
JRT
89
90
e7ae8f62 91 # If --top is specified, default the severity level to 1, unless an
55ae7242
JRT
92 # explicit severity is defined. This provides us flexibility to
93 # report top-offenders across just some or all of the severity levels.
e7ae8f62 94 # We also default the --top count to twenty if none is given
385d181e
JRT
95 if ( exists $opts{-top} ) {
96 $opts{-severity} ||= 1;
97 $opts{-top} ||= $DEFAULT_VIOLATIONS_FOR_TOP;
55ae7242
JRT
98 }
99
e7ae8f62 100 #Override profile, if --noprofile is specified
385d181e
JRT
101 if ( exists $opts{-noprofile} ) {
102 $opts{-profile} = $EMPTY;
55ae7242
JRT
103 }
104
385d181e 105 return %opts;
55ae7242
JRT
106}
107
108#-----------------------------------------------------------------------------
109
110sub _parse_command_line {
89b50090 111 my %opts;
faa35de4 112 my @opt_specs = _get_option_specification();
59b05e08 113 Getopt::Long::Configure('no_ignore_case');
55ae7242 114 GetOptions( \%opts, @opt_specs ) || pod2usage(); #Exits
385d181e
JRT
115
116 # I've adopted the convention of using key-value pairs for
117 # arguments to most functions. And to increase legibility,
118 # I have also adopted the familiar command-line practice
119 # of denoting argument names with a leading dash (-).
120 my %dashed_opts = map { ( "-$_" => $opts{$_} ) } keys %opts;
121 return %dashed_opts;
55ae7242 122}
59b05e08 123
55ae7242
JRT
124#-----------------------------------------------------------------------------
125
126sub _dispatch_special_requests {
127 my (%opts) = @_;
385d181e
JRT
128 if ( $opts{-help} ) { pod2usage( -verbose => 0 ) } #Exits
129 if ( $opts{-options} ) { pod2usage( -verbose => 1 ) } #Exits
130 if ( $opts{-man} ) { pod2usage( -verbose => 2 ) } #Exits
3f9ba540 131 if ( $opts{-version} ) { display_version() } #Exits
385d181e
JRT
132 if ( $opts{-list} ) { render_policy_listing(); } #Exits
133 if ( $opts{'-list-themes'} ) { render_theme_listing(); } #Exits
134 if ( $opts{'-profile-proto'} ) { render_profile_prototype(); } #Exits
3f9ba540 135 if ( $opts{-doc} ) { policy_docs( %opts ); } #Exits
55ae7242
JRT
136 return 1;
137}
138
139#-----------------------------------------------------------------------------
140
141sub _validate_options {
142 my (%opts) = @_;
f135623f 143 my $msg = $EMPTY;
122d73f6 144
122d73f6 145
385d181e 146 if ( $opts{-noprofile} && $opts{-profile} ) {
faa35de4 147 $msg .= qq{Warning: Cannot use -noprofile with -profile option.\n};
59b05e08
JRT
148 }
149
385d181e
JRT
150 if ( $opts{-verbose} && $opts{-verbose} !~ m{(?: \d+ | %[mfFlcedrpPs] )}xms) {
151 $msg .= qq<Warning: --verbose arg "$opts{-verbose}" looks odd. >;
152 $msg .= qq<Perhaps you meant to say "--verbose 3 $opts{-verbose}."\n>;
6bf9b465
JRT
153 }
154
385d181e
JRT
155 if ( exists $opts{-top} && $opts{-top} < 0 ) {
156 $msg .= qq<Warning: --top argument "$opts{-top}" is negative. >;
157 $msg .= qq<Perhaps you meant to say "$opts{-top} --top".\n>;
d2843fb4
JRT
158 }
159
05b5f925 160 if (
385d181e 161 exists $opts{-severity}
05b5f925 162 && (
385d181e
JRT
163 $opts{-severity} < $SEVERITY_LOWEST
164 || $opts{-severity} > $SEVERITY_HIGHEST
05b5f925
ES
165 )
166 ) {
385d181e 167 $msg .= qq<Warning: --severity arg "$opts{-severity}" out of range. >;
b8d28f35
ES
168 $msg .= qq<Severities range from "$SEVERITY_LOWEST" (lowest) to >;
169 $msg .= qq<"$SEVERITY_HIGHEST" (highest).\n>;
59b05e08
JRT
170 }
171
55ae7242
JRT
172
173 if ( $msg ) {
174 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0); #Exits
175 }
176
177
178 return 1;
179}
180
db1213c6 181#-----------------------------------------------------------------------------
1e7b8681 182
59b05e08
JRT
183sub get_input {
184
8001b0a7
CD
185 my @args = @_;
186
187 if ( !@args || (@args == 1 && $args[0] eq q{-}) ) {
ada28359
JRT
188
189 # Reading code from STDIN. All the code is slurped into
190 # a string. PPI will barf if the string is just whitespace.
191 my $code_string = do { local $RS = undef; <STDIN> };
192
193 # Notice if STDIN was closed (pipe error, etc)
194 if ( ! defined $code_string ) {
f135623f 195 $code_string = $EMPTY;
ada28359
JRT
196 }
197
f135623f 198 $code_string =~ m{ \S+ }xms || die qq{Nothing to critique.\n};
ada28359
JRT
199 return \$code_string; #Convert to SCALAR ref for PPI
200 }
201 else {
59b05e08 202
55ae7242
JRT
203 # Test to make sure all the specified files or directories
204 # actually exist. If any one of them is bogus, then die.
dc4552db
JRT
205 if ( my $nonexistent = first { ! -e $_ } @args ) {
206 my $msg = qq{No such file or directory: '$nonexistent'};
dfbe98be
JRT
207 pod2usage( -exitstatus => 1, -message => $msg, -verbose => 0);
208 }
209
fdfe1e54
JRT
210 # Reading code from files or dirs. If argument is a file,
211 # then we process it as-is (even though it may not actually
212 # be Perl code). If argument is a directory, recursively
213 # search the directory for files that look like Perl code.
8001b0a7 214 return map { -d $_ ? Perl::Critic::Utils::all_perl_files($_) : $_ } @args;
59b05e08 215 }
59b05e08
JRT
216}
217
adc2e250 218#------------------------------------------------------------------------------
1e7b8681 219
59b05e08 220sub critique {
1e7b8681 221
f491464e
CD
222 my ( $opts_ref, @files_to_critique ) = @_;
223 @files_to_critique || die "No perl files were found.\n";
59b05e08 224
db1213c6
JRT
225 # Perl::Critic has lots of dependencies, so loading is delayed
226 # until it is really needed. This hack reduces startup time for
227 # doing other things like getting the version number or dumping
228 # the man page. Arguably, those things are pretty rare, but hey,
229 # why not save a few seconds if you can.
230
fdfe1e54 231 require Perl::Critic;
a6677e04
ES
232 $critic = Perl::Critic->new( %{$opts_ref} );
233 $critic->policies() || die "No policies selected.\n";
d032ff5e 234
385d181e 235 set_up_pager($critic->config()->pager());
89b50090 236
576f6411 237 my $number_of_violations = undef;
a79d19f4 238 my $had_error_in_file = 0;
576f6411 239
f491464e 240 for my $file (@files_to_critique) {
adc2e250 241
f03e8867 242 eval {
a6677e04 243 my @violations = $critic->critique($file);
576f6411 244 $number_of_violations += scalar @violations;
cb43b040 245
738830ba 246 if (not $opts_ref->{'-statistics-only'}) {
cb43b040
ES
247 render_report( $file, $opts_ref, @violations )
248 }
62d2fc9e 249 1;
a79d19f4 250 }
62d2fc9e
ES
251 or do {
252 if ( my $exception = Perl::Critic::Exception::Parse->caught() ) {
253 $had_error_in_file = 1;
254 warn qq<Problem while critiquing "$file": $EVAL_ERROR\n>;
255 }
256 elsif ($EVAL_ERROR) {
257 # P::C::Exception::Fatal includes the stack trace in its
258 # stringification.
259 die qq<Fatal error while critiquing "$file": $EVAL_ERROR\n>;
260 }
261 else {
262 die qq<Fatal error while critiquing "$file". Unfortunately, >,
263 q<$@/$EVAL_ERROR >, ## no critic (RequireInterpolationOfMetachars)
264 qq<is empty, so the reason can't be shown.\n>;
265 }
94472d4a 266 }
f03e8867 267 }
db1213c6 268
738830ba 269 if ( $opts_ref->{-statistics} or $opts_ref->{'-statistics-only'} ) {
a6677e04 270 my $stats = $critic->statistics();
2ce0b9ee 271 report_statistics( $opts_ref, $stats );
576f6411
ES
272 }
273
a79d19f4 274 return $number_of_violations, $had_error_in_file;
576f6411
ES
275}
276
277#------------------------------------------------------------------------------
278
7f2081ac
JRT
279sub render_report {
280
55ae7242 281 my ( $file, $opts_ref, @violations ) = @_;
7f2081ac 282
faa35de4 283 # Only report the number of violations, if asked.
d032ff5e 284 my $number_of_violations = scalar @violations;
faa35de4 285 if( $opts_ref->{-count} ){
89b50090
ES
286 ref $file || out "$file: ";
287 out "$number_of_violations\n";
d032ff5e 288 return $number_of_violations;
faa35de4 289 }
1e7b8681 290
faa35de4 291 # Hail all-clear unless we should shut up.
6eb4058e 292 if( !@violations && !$opts_ref->{-quiet} ) {
89b50090
ES
293 ref $file || out "$file ";
294 out "source OK\n";
6eb4058e 295 return 0;
2bfd3a79
JRT
296 }
297
faa35de4 298 # Otherwise, format and print violations
a6677e04 299 my $verbosity = $critic->config->verbose();
3c16210a 300 # $verbosity can be numeric or string, so use "eq" for comparison;
05b5f925 301 $verbosity =
a6677e04 302 ($verbosity eq $DEFAULT_VERBOSITY && @files > 1)
05b5f925
ES
303 ? $DEFAULT_VERBOSITY_WITH_FILE_NAME
304 : $verbosity;
7b177782 305 my $fmt = Perl::Critic::Utils::verbosity_to_format( $verbosity );
f135623f 306 if (not -f $file) { $fmt =~ s< \%[fF] ><STDIN>xms; } #HACK!
7b84ff16 307 Perl::Critic::Violation::set_format( $fmt );
faa35de4 308
a6677e04 309 my $color = $critic->config->color();
89b50090 310 out $color ? _colorize_by_severity(@violations) : @violations;
25792f52 311
d032ff5e 312 return $number_of_violations;
faa35de4 313}
576f6411 314
a6677e04 315#-----------------------------------------------------------------------------
89b50090
ES
316
317sub set_up_pager {
385d181e
JRT
318 my ($pager_command) = @_;
319 return if not $pager_command;
a6677e04
ES
320 return if not _at_tty();
321
385d181e
JRT
322 open my $pager, q<|->, $pager_command ## no critic (InputOutput::RequireBriefOpen)
323 or die qq<Unable to pipe to pager "$pager_command": $ERRNO\n>;
a6677e04
ES
324
325 $output = $pager;
89b50090 326
a6677e04 327 return;
89b50090
ES
328}
329
576f6411
ES
330#-----------------------------------------------------------------------------
331
332sub report_statistics {
333 my ($opts_ref, $statistics) = @_;
576f6411
ES
334
335 if (
738830ba 336 not $opts_ref->{'-statistics-only'}
cb43b040
ES
337 and (
338 $statistics->total_violations()
339 or not $opts_ref->{-quiet} and $statistics->modules()
340 )
576f6411 341 ) {
89b50090 342 out "\n"; # There's prior output that we want to separate from.
576f6411
ES
343 }
344
89b50090
ES
345 out _commaify($statistics->modules()), " files.\n";
346 out _commaify($statistics->subs()), " subroutines/methods.\n";
347 out _commaify($statistics->statements_other_than_subs()), " statements.\n";
348 out _commaify($statistics->lines()), " lines.\n";
fb1d7f95 349
35541a80
ES
350 my $average_sub_mccabe = $statistics->average_sub_mccabe();
351 if (defined $average_sub_mccabe) {
89b50090 352 out sprintf
35541a80
ES
353 "\nAverage McCabe score of subroutines was %.2f.\n",
354 $average_sub_mccabe;
355 }
356
89b50090 357 out "\n";
576f6411 358
89b50090 359 out _commaify($statistics->total_violations()), " violations.\n";
576f6411 360
da1c78d8
ES
361 my $violations_per_file = $statistics->violations_per_file();
362 if (defined $violations_per_file) {
89b50090 363 out sprintf
da1c78d8
ES
364 "Violations per file was %.3f.\n",
365 $violations_per_file;
366 }
367 my $violations_per_statement = $statistics->violations_per_statement();
368 if (defined $violations_per_statement) {
89b50090 369 out sprintf
da1c78d8
ES
370 "Violations per statement was %.3f.\n",
371 $violations_per_statement;
372 }
35541a80
ES
373 my $violations_per_line = $statistics->violations_per_line_of_code();
374 if (defined $violations_per_line) {
89b50090 375 out sprintf
35541a80
ES
376 "Violations per line of code was %.3f.\n",
377 $violations_per_line;
378 }
379
fb1d7f95 380 if ( $statistics->total_violations() ) {
89b50090 381 out "\n";
576f6411 382
ee9c1726 383 my %severity_violations = %{ $statistics->violations_by_severity() };
fb1d7f95 384 foreach my $severity ( reverse sort keys %severity_violations ) {
89b50090 385 out
fb1d7f95
ES
386 _commaify($severity_violations{$severity}),
387 " severity $severity violations.\n";
576f6411
ES
388 }
389
89b50090 390 out "\n";
576f6411 391
ee9c1726 392 my %policy_violations = %{ $statistics->violations_by_policy() };
fb1d7f95 393 foreach my $policy ( sort keys %policy_violations ) {
89b50090 394 out
fb1d7f95
ES
395 _commaify($policy_violations{$policy}),
396 ' violations of ',
576f6411
ES
397 policy_short_name($policy),
398 ".\n";
399 }
400 }
401
402 return;
403}
404
faa35de4
JRT
405#-----------------------------------------------------------------------------
406
35541a80 407# Only works for integers.
fb1d7f95
ES
408sub _commaify {
409 my ( $number ) = @_;
410
411 while ($number =~ s/ \A ( [-+]? \d+ ) ( \d{3} ) /$1,$2/xms) {
412 # nothing
413 }
414
415 return $number;
416}
417
418#-----------------------------------------------------------------------------
419
faa35de4
JRT
420sub _get_option_specification {
421
422 return qw(
423 5 4 3 2 1
424 Safari
eb4540f0 425 version
0bcb38c0 426 brutal
5176884d 427 count|C
0bcb38c0 428 cruel
6332a5f1 429 doc=s
faa35de4 430 exclude=s@
410cf90b 431 force!
0bcb38c0
JRT
432 gentle
433 harsh
5176884d 434 help|?|H
faa35de4
JRT
435 include=s@
436 list
71ef7d49 437 list-themes
faa35de4 438 man
ae9b3404 439 color|colour!
faa35de4 440 noprofile
7b84ff16 441 only!
bbcf8061 442 options
89b50090 443 pager=s
faa35de4 444 profile=s
738830ba 445 profile-proto
faa35de4
JRT
446 quiet
447 severity=i
2849151b 448 single-policy|s=s
0bcb38c0 449 stern
576f6411 450 statistics!
738830ba 451 statistics-only!
9f12283e 452 profile-strictness=s
410cf90b 453 theme=s
faa35de4
JRT
454 top:i
455 verbose=s
1e417435
TW
456 color-severity-highest|colour-severity-highest|color-severity-5|colour-severity-5=s
457 color-severity-high|colour-severity-high|color-severity-4|colour-severity-4=s
458 color-severity-medium|colour-severity-medium|color-severity-3|colour-severity-3=s
459 color-severity-low|colour-severity-low|color-severity-2|colour-severity-2=s
460 color-severity-lowest|colour-severity-lowest|color-severity-1|colour-severity-1=s
faa35de4 461 );
59b05e08
JRT
462}
463
db1213c6 464#-----------------------------------------------------------------------------
01625a50 465
faa35de4 466sub _colorize_by_severity {
6c891509 467 my @violations = @_;
faa35de4 468 return @violations if _this_is_windows();
172f00ec
TW
469 return @violations if not eval { require Term::ANSIColor; 1; };
470
471 my $config = $critic->config();
472 my %color_of = (
473 $SEVERITY_HIGHEST => $config->color_severity_highest(),
474 $SEVERITY_HIGH => $config->color_severity_high(),
475 $SEVERITY_MEDIUM => $config->color_severity_medium(),
476 $SEVERITY_LOW => $config->color_severity_low(),
477 $SEVERITY_LOWEST => $config->color_severity_lowest(),
478 );
faa35de4 479
faa35de4
JRT
480 return map { _colorize( "$_", $color_of{$_->severity()} ) } @violations;
481
482}
483
484#-----------------------------------------------------------------------------
485
486sub _colorize {
487 my ($string, $color) = @_;
488 return $string if not defined $color;
172f00ec
TW
489 return $string if $color eq $EMPTY;
490 # $terminator is a purely cosmetic change to make the color end at the end
491 # of the line rather than right before the next line. It is here because
492 # if you use background colors, some console windows display a little
493 # fragment of colored background before the next uncolored (or
494 # differently-colored) line.
495 my $terminator = chomp $string ? "\n" : $EMPTY;
496 return Term::ANSIColor::colored( $string, $color ) . $terminator;
faa35de4
JRT
497}
498
499#-----------------------------------------------------------------------------
500
501sub _this_is_windows {
f135623f 502 return 1 if $OSNAME =~ m/MSWin32/xms;
faa35de4
JRT
503 return 0;
504}
505
506#-----------------------------------------------------------------------------
507
508sub _at_tty {
2201928f 509 return -t STDOUT; ## no critic (ProhibitInteractiveTest);
faa35de4 510}
faa35de4 511
e68db767 512#-----------------------------------------------------------------------------
faa35de4 513
fd5bd7b5 514sub render_policy_listing {
fdfe1e54 515
c2018d77 516 require Perl::Critic::PolicyListing;
606ea80c 517 require Perl::Critic;
e68db767 518
05b5f925 519 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
520 my @policies = Perl::Critic->new( %pc_params )->policies();
521 my $listing = Perl::Critic::PolicyListing->new( -policies => \@policies );
89b50090 522 out $listing;
3f9ba540
JRT
523
524 exit $EXIT_SUCCESS; ## no critic qw(ProhibitExit)
71ef7d49
ES
525}
526
527#-----------------------------------------------------------------------------
528
529sub render_theme_listing {
3f9ba540 530
71ef7d49
ES
531 require Perl::Critic::ThemeListing;
532 require Perl::Critic;
533
534 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
535 my @policies = Perl::Critic->new( %pc_params )->policies();
536 my $listing = Perl::Critic::ThemeListing->new( -policies => \@policies );
89b50090 537 out $listing;
572056d2 538
3f9ba540 539 exit $EXIT_SUCCESS; ## no critic qw(ProhibitExit)
fd5bd7b5
JRT
540}
541
542#-----------------------------------------------------------------------------
543
544sub render_profile_prototype {
545
546 require Perl::Critic::ProfilePrototype;
606ea80c 547 require Perl::Critic;
fd5bd7b5 548
05b5f925 549 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
550 my @policies = Perl::Critic->new( %pc_params )->policies();
551 my $prototype = Perl::Critic::ProfilePrototype->new( -policies => \@policies );
89b50090 552 out $prototype;
572056d2 553
3f9ba540 554 exit $EXIT_SUCCESS; ## no critic qw(ProhibitExit)
faa35de4
JRT
555}
556
6332a5f1
JRT
557#-----------------------------------------------------------------------------
558
559sub policy_docs {
560
385d181e
JRT
561 my (%opts) = @_;
562 my $pattern = delete $opts{-doc};
563
606ea80c 564 require Perl::Critic;
385d181e
JRT
565 $critic = Perl::Critic->new(%opts);
566 set_up_pager($critic->config()->pager());
6332a5f1 567
385d181e
JRT
568 require Perl::Critic::PolicyFactory;
569 my @site_policies = Perl::Critic::PolicyFactory->site_policy_names();
570 my @matching_policies = grep { $_ =~ m/$pattern/ixms } @site_policies;
571
3be4796c 572 # "-T" means don't send to pager
2201928f 573 my @perldoc_output = map {`perldoc -T $_`} @matching_policies; ## no critic (ProhibitBacktick)
385d181e 574 out @perldoc_output;
6332a5f1 575
3f9ba540 576 exit $EXIT_SUCCESS; ## no critic qw(ProhibitExit)
6332a5f1
JRT
577}
578
3f9ba540
JRT
579#-----------------------------------------------------------------------------
580
581sub display_version {
582 out "$VERSION\n";
583 exit $EXIT_SUCCESS; ## no critic qw(ProhibitExit)
584}
585
586#-----------------------------------------------------------------------------
59b05e08
JRT
5871;
588
589__END__
590
01625a50 591#-----------------------------------------------------------------------------
1e7b8681 592
59b05e08
JRT
593=pod
594
2849151b
ES
595=for stopwords DGR INI-style vim-fu minibuffer -noprofile API
596-profileproto -profile-proto ben Jore formatter Peshak pbp Komodo
c296c678 597screenshots tty emacs gVIM plugin Perlish templating ActiveState
821d0eb5 598
59b05e08
JRT
599=head1 NAME
600
13c1001a 601C<perlcritic> - Command-line interface to critique Perl source.
59b05e08 602
11f53956 603
59b05e08
JRT
604=head1 SYNOPSIS
605
e7ae8f62
ES
606 perlcritic [-12345 | --brutal | --cruel | --harsh | --stern | --gentle]
607 [--severity number | name] [--profile file | --noprofile]
608 [--top [ number ]] [--theme expression] [--include pattern]
2849151b
ES
609 [--exclude pattern] [{-s | --single-policy} pattern]
610 [--only | --noonly] [--profile-strictness {warn|fatal|quiet}]
611 [--force | --noforce] [--statistics] [--statistics-only]
612 [--count | -C] [--verbose {number | format}]
385d181e 613 [--color | --nocolor] [--pager pager] [--quiet]
1e417435
TW
614 [--color-severity-highest color_specification]
615 [--color-severity-high color_specification]
616 [--color-severity-medium color_specification]
617 [--color-severity-low color_specification]
618 [--color-severity-lowest color_specification]
385d181e 619 {FILE | DIRECTORY | STDIN}
05b913fd 620
e7ae8f62 621 perlcritic --profile-proto
05b913fd 622
71ef7d49 623 perlcritic { --list | --list-themes | --doc pattern [...] }
9f12283e 624
eb4540f0 625 perlcritic { --help | --options | --man | --version }
59b05e08 626
11f53956 627
59b05e08
JRT
628=head1 DESCRIPTION
629
630C<perlcritic> is a Perl source code analyzer. It is the executable
11f53956
ES
631front-end to the L<Perl::Critic|Perl::Critic> engine, which attempts
632to identify awkward, hard to read, error-prone, or unconventional
633constructs in your code. Most of the rules are based on Damian
634Conway's book B<Perl Best Practices>. However, C<perlcritic> is
635B<not> limited to enforcing PBP, and it will even support rules that
636contradict Conway. All rules can easily be configured or disabled to
637your liking.
59b05e08 638
e7ae8f62
ES
639This documentation only covers how to drive this command. For all
640other information, including how to persistently configure this
11f53956
ES
641command so that you don't have to say so much on the command-line, see
642the documentation for L<Perl::Critic|Perl::Critic> itself.
0304068a 643
8d36cd6f 644
d2843fb4
JRT
645=head1 USAGE EXAMPLES
646
25a6e413 647Before getting into all the gory details, here are some basic usage
b2c7354a 648examples to help get you started.
d2843fb4 649
11f53956
ES
650 # Report only most severe violations (severity = 5)
651 perlcritic YourModule.pm
652
653 # Same as above, but read input from STDIN
654 perlcritic
25a6e413 655
11f53956
ES
656 # Recursively process all Perl files beneath directory
657 perlcritic /some/directory
db1213c6 658
11f53956
ES
659 # Report slightly less severe violations too (severity >= 4)
660 perlcritic -4 YourModule.pm
d2843fb4 661
11f53956
ES
662 # Same as above, but using named severity level
663 perlcritic --stern YourModule.pm
d2843fb4 664
11f53956
ES
665 # Report all violations, regardless of severity (severity >= 1)
666 perlcritic -1 YourModule.pm
0bcb38c0 667
11f53956
ES
668 # Same as above, but using named severity level
669 perlcritic --brutal YourModule.pm
d2843fb4 670
11f53956
ES
671 # Report only violations of things from "Perl Best Practices"
672 perlcritic --theme pbp YourModule.pm
e7ae8f62 673
11f53956
ES
674 # Report top 20 most severe violations (severity >= 1)
675 perlcritic --top YourModule.pm
0bcb38c0 676
f135623f 677 # Report additional violations of Policies that match m/variables/xms
11f53956 678 perlcritic --include variables YourModule.pm
4a24d03a 679
11f53956
ES
680 # Use defaults from somewhere other than ~/.perlcriticrc
681 perlcriticrc --profile project/specific/perlcriticrc YourModule.pm
25a6e413 682
d2843fb4 683
59b05e08
JRT
684=head1 ARGUMENTS
685
686The arguments are paths to the files you wish to analyze. You may
c165f991 687specify multiple files. If an argument is a directory, C<perlcritic>
11f53956
ES
688will analyze all Perl files below the directory. If no arguments are
689specified, then input is read from STDIN.
690
59b05e08
JRT
691
692=head1 OPTIONS
693
694Option names can be abbreviated to uniqueness and can be stated with
695singe or double dashes, and option values can be separated from the
11f53956
ES
696option name by a space or '=' (as with L<Getopt::Long|Getopt::Long>).
697Option names are also case-sensitive.
59b05e08 698
8bd925c8 699=over
59b05e08 700
e7ae8f62 701=item C<--profile FILE>
59b05e08 702
11f53956
ES
703Directs C<perlcritic> to use a profile named by FILE rather than
704looking for the default F<.perlcriticrc> file in the current directory
705or your home directory. See L<Perl::Critic/"CONFIGURATION"> for more
706information.
59b05e08 707
e7ae8f62 708=item C<--noprofile>
59b05e08 709
11f53956
ES
710Directs C<perlcritic> not to load any configuration file, thus
711reverting to the default configuration for all Policies.
59b05e08 712
e7ae8f62 713=item C<--severity N>
59b05e08 714
11f53956
ES
715Directs C<perlcritic> to only apply Policies with a severity greater
716than C<N>. Severity values are integers ranging from 1 (least severe)
717to 5 (most severe). The default is 5. For a given C<--profile>,
718decreasing the C<--severity> will usually produce more violations.
719You can set the default value for this option in your F<.perlcriticrc>
720file. You can also redefine the C<severity> for any Policy in your
721F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
59b05e08 722
faa35de4 723=item C<-5 | -4 | -3 | -2 | -1>
d2843fb4 724
11f53956
ES
725These are numeric shortcuts for setting the C<--severity> option. For
726example, C<"-4"> is equivalent to C<"--severity 4">. If multiple
727shortcuts are specified, then the most restrictive one wins. If an
728explicit C<--severity> option is also given, then all shortcut options
729are silently ignored. NOTE: Be careful not to put one of the number
730severity shortcut options immediately after the C<--top> flag or
731C<perlcritic> will interpret it as the number of violations to report.
0bcb38c0 732
e7ae8f62 733=item C<--severity NAME>
0bcb38c0 734
11f53956
ES
735If it is difficult for you to remember whether severity "5" is the
736most or least restrictive level, then you can use one of these named
737values:
0bcb38c0 738
7711a331 739 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
0bcb38c0 740 --------------------------------------------------------
e7ae8f62
ES
741 --severity gentle --severity 5
742 --severity stern --severity 4
743 --severity harsh --severity 3
744 --severity cruel --severity 2
745 --severity brutal --severity 1
0bcb38c0 746
e7ae8f62 747=item C<--gentle | --stern | --harsh | --cruel | --brutal>
0bcb38c0 748
11f53956
ES
749These are named shortcuts for setting the C<--severity> option. For
750example, C<"--cruel"> is equivalent to C<"--severity 2">. If multiple
751shortcuts are specified, then the most restrictive one wins. If an
752explicit C<--severity> option is also given, then all shortcut options
753are silently ignored.
d2843fb4 754
e7ae8f62 755=item C<--theme RULE>
a0934394 756
11f53956
ES
757Directs C<perlcritic> to apply only Policies with themes that satisfy
758the C<RULE>. Themes are arbitrary names for groups of related
759policies. You can combine theme names with boolean operators to
760create an arbitrarily complex C<RULE>. For example, the following
761would apply only Policies that have a 'bugs' AND 'pbp' theme:
1c5955e4 762
11f53956 763 $> perlcritic --theme='bugs && pbp' MyModule.pm
1c5955e4 764
11f53956
ES
765Unless the C<--severity> option is explicitly given, setting
766C<--theme> silently causes the C<--severity> to be set to 1. You can
767set the default value for this option in your F<.perlcriticrc> file.
768See L<Perl::Critic/"POLICY THEMES"> for more information about themes.
faa35de4 769
e7ae8f62 770=item C<--include PATTERN>
59b05e08 771
11f53956
ES
772Directs C<perlcritic> to apply additional Policies that match the
773regex C</PATTERN/imx>. Use this option to temporarily override your
774profile and/or the severity settings at the command-line. For
775example:
6bf9b465 776
11f53956 777 perlcritic --include=layout my_file.pl
6bf9b465 778
11f53956
ES
779This would cause C<perlcritic> to apply all the C<CodeLayout::*>
780policies even if they have a severity level that is less than the
781default level of 5, or have been disabled in your F<.perlcriticrc>
782file. You can specify multiple C<--include> options and you can use
783it in conjunction with the C<--exclude> option. Note that
784C<--exclude> takes precedence over C<--include> when a Policy matches
785both patterns. You can set the default value for this option in your
77de3405 786F<.perlcriticrc> file.
59b05e08 787
e7ae8f62 788=item C<--exclude PATTERN>
59b05e08 789
77de3405 790Directs C<perlcritic> to not apply any Policy that matches the regex
11f53956
ES
791C</PATTERN/imx>. Use this option to temporarily override your profile
792and/or the severity settings at the command-line. For example:
6bf9b465 793
11f53956 794 perlcritic --exclude=strict my_file.pl
6bf9b465 795
11f53956
ES
796This would cause C<perlcritic> to not apply the C<RequireUseStrict>
797and C<ProhibitNoStrict> Policies even though they have the highest
798severity level. You can specify multiple C<--exclude> options and you
799can use it in conjunction with the C<--include> option. Note that
800C<--exclude> takes precedence over C<--include> when a Policy matches
801both patterns. You can set the default value for this option in your
802F<.perlcriticrc> file.
59b05e08 803
e7ae8f62 804=item C<--single-policy PATTERN>
585ddee1 805
2849151b
ES
806=item C<-s PATTERN>
807
11f53956 808Directs C<perlcritic> to apply just one Policy module matching the
f135623f 809regex C</PATTERN/ixms>, and exclude all other Policies. This option
11f53956
ES
810has precedence over the C<--severity>, C<--theme>, C<--include>,
811C<--exclude>, and C<--only> options. For example:
585ddee1 812
11f53956 813 perlcritic --single-policy=nowarnings my_file.pl
585ddee1 814
11f53956
ES
815This would cause C<perlcritic> to apply just the C<ProhibitNoWarnings>
816Policy, regardless of the severity level setting. No other Policies
817would be applied.
585ddee1 818
77de3405 819This is equivalent to what one might intend by...
585ddee1 820
11f53956 821 perlcritic --exclude=. --include=nowarnings my_file.pl
585ddee1 822
e7ae8f62
ES
823... but this won't work because the C<--exclude> option overrides the
824C<--include> option.
585ddee1 825
11f53956
ES
826The equivalent of this option can be accomplished by creating a custom
827profile containing only the desired policy and then running...
585ddee1 828
11f53956 829 perlcritic --profile=customprofile --only my_file.pl
585ddee1 830
e7ae8f62 831=item C<--top [ N ]>
faa35de4 832
11f53956
ES
833Directs C<perlcritic> to report only the top C<N> Policy violations in
834each file, ranked by their severity. If C<N> is not specified, it
835defaults to 20. If the C<--severity> option (or one of the shortcuts)
836is not explicitly given, the C<--top> option implies that the minimum
837severity level is "1" (i.e. "brutal"). Users can redefine the severity
838for any Policy in their F<.perlcriticrc> file. See L<"CONFIGURATION">
839for more information. You can set the default value for this option
840in your F<.perlcriticrc> file. NOTE: Be careful not to put one of the
841severity shortcut options immediately after the C<--top> flag or
842C<perlcritic> will interpret it as the number of violations to report.
faa35de4 843
e7ae8f62 844=item C<--force>
59b05e08 845
11f53956 846Directs C<perlcritic> to ignore the magical C<"## no critic">
d1237298 847annotations in the source code. See L<"BENDING THE RULES"> for more
11f53956
ES
848information. You can set the default value for this option in your
849F<.perlcriticrc> file.
59b05e08 850
e7ae8f62 851=item C<--statistics>
576f6411 852
11f53956
ES
853Causes several statistics about the code being scanned and the
854violations found to be reported after any other output.
576f6411 855
e7ae8f62 856=item C<--statistics-only>
cb43b040 857
11f53956
ES
858Like the C<--statistics> option, but suppresses normal output and only
859shows the statistics.
cb43b040 860
e7ae8f62 861=item C<--verbose N | FORMAT>
59b05e08 862
11f53956
ES
863Sets the verbosity level or format for reporting violations. If given
864a number (C<N>), C<perlcritic> reports violations using one of the
865predefined formats described below. If given a string (C<FORMAT>), it
866is interpreted to be an actual format specification. If the
867C<--verbose> option is not specified, it defaults to either 4 or 5,
868depending on whether multiple files were given as arguments to
869C<perlcritic>. You can set the default value for this option in your
870F<.perlcriticrc> file.
871
872 Verbosity Format Specification
873 ----------- -------------------------------------------------------
874 1 "%f:%l:%c:%m\n",
875 2 "%f: (%l:%c) %m\n",
876 3 "%m at %f line %l\n",
877 4 "%m at line %l, column %c. %e. (Severity: %s)\n",
878 5 "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
879 6 "%m at line %l, near '%r'. (Severity: %s)\n",
880 7 "%f: %m at line %l near '%r'. (Severity: %s)\n",
881 8 "[%p] %m at line %l, column %c. (Severity: %s)\n",
882 9 "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
883 10 "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
884 11 "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n"
885
886Formats are a combination of literal and escape characters similar to
887the way C<sprintf> works. See L<String::Format|String::Format> for a
888full explanation of the formatting capabilities. Valid escape
889characters are:
890
891 Escape Meaning
892 ------- ------------------------------------------------------------
893 %c Column number where the violation occurred
894 %d Full diagnostic discussion of the violation
895 %e Explanation of violation or page numbers in PBP
896 %F Just the name of the file where the violation occurred.
897 %f Path to the file where the violation occurred.
898 %l Line number where the violation occurred
899 %m Brief description of the violation
900 %P Full name of the Policy module that created the violation
901 %p Name of the Policy without the Perl::Critic::Policy:: prefix
902 %r The string of source code that caused the violation
903 %s The severity level of the violation
904
905The purpose of these formats is to provide some compatibility with
906text editors that have an interface for parsing certain kinds of
907input. See L<"EDITOR INTEGRATION"> for more information about that.
59b05e08 908
e7ae8f62 909=item C<--list>
122d73f6 910
11f53956
ES
911Displays a condensed listing of all the
912L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
913this machine. For each Policy, the name, default severity and default
914themes are shown.
64eea91f 915
71ef7d49
ES
916=item C<--list-themes>
917
11f53956
ES
918Displays a list of all the themes of the
919L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
920this machine.
71ef7d49 921
e7ae8f62 922=item C<--profile-proto>
64eea91f 923
11f53956
ES
924Displays an expanded listing of all the
925L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
926this machine. For each Policy, the name, default severity and default
927themes are shown, as well as the name of any additional parameters
928that the Policy supports. The format is suitable as a prototype for
929your F<.perlcriticrc> file.
122d73f6 930
e7ae8f62 931=item C<--only>
e967596d 932
11f53956
ES
933Directs perlcritic to apply only Policies that are explicitly
934mentioned in your F<.perlcriticrc> file. This is useful if you want
935to use just a small subset of Policies without having to disable all
936the others. You can set the default value for this option in your
937F<.perlcriticrc> file.
e967596d 938
e7ae8f62 939=item C<--profile-strictness {warn|fatal|quiet}>
66186ba3 940
11f53956
ES
941Directs perlcritic how to treat certain recoverable problems found in
942a F<.perlcriticrc> or file specified via the C<--profile> option.
943Valid values are C<warn> (the default), C<fatal>, and C<quiet>. For
944example, perlcritic normally only warns about profiles referring to
945non-existent Policies, but this option can make this situation fatal.
946You can set the default value for this option in your F<.perlcriticrc>
947file.
66186ba3 948
e7ae8f62 949=item C<--count>
faa35de4 950
0bcb38c0
JRT
951=item C<-C>
952
11f53956
ES
953Display only the number of violations for each file. Use this feature
954to get a quick handle on where a large pile of code might need the
955most attention.
faa35de4 956
e7ae8f62 957=item C<--Safari>
59b05e08
JRT
958
959Report "Perl Best Practice" citations as section numbers from
11f53956
ES
960L<http://safari.oreilly.com> instead of page numbers from the actual
961book. NOTE: This feature is not implemented yet.
59b05e08 962
e7ae8f62 963=item C<--color>
faa35de4 964
89b50090
ES
965This option is on when outputting to a tty. When set, Severity 5 and 4 are
966colored red and yellow, respectively. Colorization only happens if
967L<Term::ANSIColor|Term::ANSIColor> is installed and it only works on
968non-Windows environments. Negate this switch to disable color. You can set
969the default value for this option in your F<.perlcriticrc> file.
faa35de4 970
ae9b3404
ES
971Can also be specified as C<--colour>.
972
385d181e 973=item C<--pager PAGER_COMMAND_STRING>
89b50090 974
385d181e
JRT
975If set, perlcritic will pipe it's output to the given PAGER_COMMAND_STRING.
976You can set the default value for this option in your F<.perlcriticrc> file.
89b50090
ES
977
978Setting a pager turns off color by default. You will have to turn color on
385d181e
JRT
979explicitly. If you want color, you'll probably also want to tell your pager
980to display raw characters. For C<less> and C<more>, use the -R switch.
89b50090 981
1e417435
TW
982=item C<--color-severity-highest COLOR_SPECIFICATION>
983
984Specifies the color to be used for highest severity violations, as a
985Term::ANSIColor color specification. Can also be specified as
986C<--colour-severity-highest>, C<--color-severity-5>, or
987C<--colour-severity-5>.
988
989=item C<--color-severity-high COLOR_SPECIFICATION>
990
991Specifies the color to be used for high severity violations, as a
992Term::ANSIColor color specification. Can also be specified as
993C<--colour-severity-high>, C<--color-severity-4>, or
994C<--colour-severity-4>.
995
996=item C<--color-severity-medium COLOR_SPECIFICATION>
997
998Specifies the color to be used for medium severity violations, as a
999Term::ANSIColor color specification. Can also be specified as
1000C<--colour-severity-medium>, C<--color-severity-3>, or
1001C<--colour-severity-3>.
1002
1003=item C<--color-severity-low COLOR_SPECIFICATION>
1004
1005Specifies the color to be used for low severity violations, as a
1006Term::ANSIColor color specification. Can also be specified as
1007C<--colour-severity-low>, C<--color-severity-2>, or
1008C<--colour-severity-2>.
1009
1010=item C<--color-severity-lowest COLOR_SPECIFICATION>
1011
1012Specifies the color to be used for lowest severity violations, as a
1013Term::ANSIColor color specification. Can also be specified as
1014C<--colour-severity-lowest>, C<--color-severity-1>, or
1015C<--colour-severity-1>.
1016
e7ae8f62 1017=item C<--doc PATTERN>
6332a5f1 1018
11f53956
ES
1019Displays the perldoc for all
1020L<Perl::Critic::Policy|Perl::Critic::Policy> modules that match
f135623f 1021C<m/PATTERN/ixms>. Since Policy modules tend to have rather long
11f53956
ES
1022names, this just provides a more convenient way to say something like:
1023C<"perldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator">
6332a5f1
JRT
1024at the command prompt.
1025
e7ae8f62 1026=item C<--quiet>
8b5892fc 1027
1c5955e4 1028Suppress the "source OK" message when no violations are found.
8b5892fc 1029
e7ae8f62 1030=item C<--help>
59b05e08 1031
faa35de4 1032=item C<-?>
59b05e08 1033
0bcb38c0
JRT
1034=item C<-H>
1035
59b05e08
JRT
1036Displays a brief summary of options and exits.
1037
e7ae8f62 1038=item C<--options>
bbcf8061 1039
11f53956
ES
1040Displays the descriptions of the options and exits. While this output
1041is long, it it nowhere near the length of the output of C<--man>.
bbcf8061 1042
e7ae8f62 1043=item C<--man>
59b05e08 1044
c165f991 1045Displays the complete C<perlcritic> manual and exits.
59b05e08 1046
eb4540f0 1047=item C<--version>
59b05e08 1048
faa35de4 1049=item C<-V>
59b05e08 1050
c165f991 1051Displays the version number of C<perlcritic> and exits.
59b05e08
JRT
1052
1053=back
1054
1055=head1 CONFIGURATION
1056
11f53956
ES
1057Most of the settings for Perl::Critic and each of the Policy modules
1058can be controlled by a configuration file. The default configuration
1059file is called F<.perlcriticrc>. C<perlcritic> will look for this
1060file in the current directory first, and then in your home directory.
1061Alternatively, you can set the C<PERLCRITIC> environment variable to
1062explicitly point to a different file in another location. If none of
1063these files exist, and the C<--profile> option is not given on the
1064command-line, then all Policies will be loaded with their default
1065configuration.
1066
1067The format of the configuration file is a series of INI-style blocks
1068that contain key-value pairs separated by "=". Comments should start
1069with "#" and can be placed on a separate line or after the name-value
1070pairs if you desire.
1071
1072Default settings for perlcritic itself can be set B<before the first
1073named block.> For example, putting any or all of these at the top of
1074your F<.perlcriticrc> file will set the default value for the
1075corresponding command-line argument.
1076
1077 severity = 3 #Integer or named level
1078 only = 1 #Zero or One
1079 force = 0 #Zero or One
1080 verbose = 4 #Integer or format spec
1081 top = 50 #A positive integer
1082 theme = (pbp + security) * bugs #A theme expression
1083 include = NamingConventions ClassHierarchies #Space-delimited list
1084 exclude = Variables Modules::RequirePackage #Space-delimited list
4a24d03a 1085
7711a331 1086The remainder of the configuration file is a series of blocks like this:
59b05e08 1087
11f53956
ES
1088 [Perl::Critic::Policy::Category::PolicyName]
1089 severity = 1
1090 set_themes = foo bar
1091 add_themes = baz
1092 arg1 = value1
1093 arg2 = value2
1094
1095C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
1096module that implements the policy. The Policy modules distributed
1097with Perl::Critic have been grouped into categories according to the
1098table of contents in Damian Conway's book B<Perl Best Practices>. For
1099brevity, you can omit the C<'Perl::Critic::Policy'> part of the module
1100name.
1101
1102C<severity> is the level of importance you wish to assign to the
1103Policy. All Policy modules are defined with a default severity value
1104ranging from 1 (least severe) to 5 (most severe). However, you may
1105disagree with the default severity and choose to give it a higher or
1106lower severity, based on your own coding philosophy. You can set the
1107C<severity> to an integer from 1 to 5, or use one of the equivalent
1108names:
1109
1110 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
1111 ----------------------------------------------------
1112 gentle 5
1113 stern 4
1114 harsh 3
1115 cruel 2
1116 brutal 1
1117
1118C<set_themes> sets the theme for the Policy and overrides its default
1119theme. The argument is a string of one or more whitespace-delimited
1120alphanumeric words. Themes are case-insensitive. See L<"POLICY
1121THEMES"> for more information.
1122
1123C<add_themes> appends to the default themes for this Policy. The
1124argument is a string of one or more whitespace-delimited words.
1125Themes are case-insensitive. See L<"POLICY THEMES"> for more
faa35de4
JRT
1126information.
1127
11f53956
ES
1128The remaining key-value pairs are configuration parameters that will
1129be passed into the constructor of that Policy. The constructors for
1130most Policy modules do not support arguments, and those that do should
1131have reasonable defaults. See the documentation on the appropriate
1132Policy module for more details.
faa35de4 1133
11f53956
ES
1134Instead of redefining the severity for a given Policy, you can
1135completely disable a Policy by prepending a '-' to the name of the
1136module in your configuration file. In this manner, the Policy will
1137never be loaded, regardless of the C<--severity> given on the command
1138line.
59b05e08 1139
1e7b8681 1140A simple configuration might look like this:
59b05e08 1141
11f53956
ES
1142 #--------------------------------------------------------------
1143 # I think these are really important, so always load them
1144
1145 [TestingAndDebugging::RequireUseStrict]
1146 severity = 5
59b05e08 1147
11f53956
ES
1148 [TestingAndDebugging::RequireUseWarnings]
1149 severity = 5
59b05e08 1150
11f53956
ES
1151 #--------------------------------------------------------------
1152 # I think these are less important, so only load when asked
59b05e08 1153
11f53956
ES
1154 [Variables::ProhibitPackageVars]
1155 severity = 2
59b05e08 1156
11f53956
ES
1157 [ControlStructures::ProhibitPostfixControls]
1158 allow = if unless # My custom configuration
1159 severity = cruel # Same as "severity = 2"
59b05e08 1160
11f53956
ES
1161 #--------------------------------------------------------------
1162 # Give these policies a custom theme. I can activate just
1163 # these policies by saying "perlcritic --theme 'larry || curly'"
59b05e08 1164
11f53956
ES
1165 [Modules::RequireFilenameMatchesPackage]
1166 add_themes = larry
7b84ff16 1167
11f53956
ES
1168 [TestingAndDebugging::RequireTestLabels]
1169 add_themes = curly moe
7b84ff16 1170
11f53956
ES
1171 #--------------------------------------------------------------
1172 # I do not agree with these at all, so never load them
7b84ff16 1173
d5ff35da
ES
1174 [-NamingConventions::Capitalization]
1175 [-ValuesAndExpressions::ProhibitMagicNumbers]
59b05e08 1176
11f53956
ES
1177 #--------------------------------------------------------------
1178 # For all other Policies, I accept the default severity,
1179 # so no additional configuration is required for them.
59b05e08 1180
11f53956
ES
1181Note that all policies included with the Perl::Critic distribution
1182that have integer parameters accept underscores ("_") in their values,
1183as with Perl numeric literals. For example,
1e7b8681 1184
11f53956
ES
1185 [ValuesAndExpressions::RequireNumberSeparators]
1186 min_value = 1_000
ced050bc 1187
11f53956
ES
1188For additional configuration examples, see the F<perlcriticrc> file
1189that is included in this F<examples> directory of this distribution.
ced050bc 1190
11f53956
ES
1191Damian Conway's own Perl::Critic configuration is also included in
1192this distribution as F<examples/perlcriticrc-conway>.
b87fc7eb 1193
75d77367 1194
59b05e08
JRT
1195=head1 THE POLICIES
1196
11f53956
ES
1197A large number of Policy modules are distributed with Perl::Critic.
1198They are described briefly in the companion document
1199L<Perl::Critic::PolicySummary|Perl::Critic::PolicySummary> and in more
1200detail in the individual modules themselves. Say C<"perlcritic --doc
1201PATTERN"> to see the perldoc for all Policy modules that match the
f135623f 1202regex C<m/PATTERN/ixms>
11f53956
ES
1203
1204There are a number of distributions of additional policies on CPAN.
1205If L<Perl::Critic|Perl::Critic> doesn't contain a policy that you
1206want, some one may have already written it. See L<Perl::Critic/"SEE
1207ALSO"> for a list of some of these distributions.
e7ff023b 1208
a41e8614 1209
faa35de4
JRT
1210=head1 POLICY THEMES
1211
11f53956
ES
1212Each Policy is defined with one or more "themes". Themes can be used
1213to create arbitrary groups of Policies. They are intended to provide
1214an alternative mechanism for selecting your preferred set of Policies.
1215For example, you may wish disable a certain set of Policies when
1216analyzing test scripts. Conversely, you may wish to enable only a
1217specific subset of Policies when analyzing modules.
1218
1219The Policies that ship with Perl::Critic are have been divided into
1220the following themes. This is just our attempt to provide some basic
1221logical groupings. You are free to invent new themes that suit your
1222needs.
1223
1224 THEME DESCRIPTION
1225 ------------------------------------------------------------------------
1226 core All policies that ship with Perl::Critic
1227 pbp Policies that come directly from "Perl Best Practices"
1228 bugs Policies that that prevent or reveal bugs
1229 maintenance Policies that affect the long-term health of the code
1230 cosmetic Policies that only have a superficial effect
1231 complexity Policies that specificaly relate to code complexity
1232 security Policies that relate to security issues
1233 tests Policies that are specific to test scripts
1234
1235Say C<"perlcritic --list"> to get a listing of all available policies
1236and the themes that are associated with each one. You can also change
1237the theme for any Policy in your F<.perlcriticrc> file. See the
1238L<"CONFIGURATION"> section for more information about that.
1239
1240Using the C<--theme> command-line option, you can create an
1241arbitrarily complex rule that determines which Policies to apply.
1242Precedence is the same as regular Perl code, and you can use
1243parentheses to enforce precedence as well. Supported operators are:
1244
1245 Operator Altertative Example
1246 -----------------------------------------------------------------
1247 && and 'pbp && core'
1248 || or 'pbp || (bugs && security)'
1249 ! not 'pbp && ! (portability || complexity)'
1250
1251Theme names are case-insensitive. If the C<--theme> is set to an
1252empty string, then it evaluates as true all Policies.
1253
faa35de4 1254
59b05e08
JRT
1255=head1 BENDING THE RULES
1256
59b05e08
JRT
1257Perl::Critic takes a hard-line approach to your code: either you
1258comply or you don't. In the real world, it is not always practical
1259(or even possible) to fully comply with coding standards. In such
1260cases, it is wise to show that you are knowingly violating the
1261standards and that you have a Damn Good Reason (DGR) for doing so.
1262
1263To help with those situations, you can direct Perl::Critic to ignore
d1237298 1264certain lines or blocks of code by using annotations:
59b05e08 1265
67a7fe92
ES
1266 require 'LegacyLibaray1.pl'; ## no critic
1267 require 'LegacyLibrary2.pl'; ## no critic
59b05e08 1268
67a7fe92 1269 for my $element (@list) {
59b05e08 1270
67a7fe92 1271 ## no critic
59b05e08 1272
67a7fe92
ES
1273 $foo = ""; #Violates 'ProhibitEmptyQuotes'
1274 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
1275 #Some more evil code...
59b05e08 1276
67a7fe92 1277 ## use critic
59b05e08 1278
67a7fe92
ES
1279 #Some good code...
1280 do_something($_);
1281 }
59b05e08 1282
d1237298 1283The C<"## no critic"> annotations direct Perl::Critic to ignore the
11f53956 1284remaining lines of code until the end of the current block, or until a
d1237298
JRT
1285C<"## use critic"> annotation is found (whichever comes first). If the
1286C<"## no critic"> annotation is on the same line as a code statement,
11f53956 1287then only that line of code is overlooked. To direct perlcritic to
d1237298 1288ignore the C<"## no critic"> annotations, use the C<--force> option.
77de3405 1289
d1237298 1290A bare C<"## no critic"> annotation disables all the active Policies. If
11f53956
ES
1291you wish to disable only specific Policies, add a list of Policy names
1292as arguments just as you would for the C<"no strict"> or C<"no
1293warnings"> pragma. For example, this would disable the
1294C<ProhibitEmptyQuotes> and C<ProhibitPostfixControls> policies until
d1237298 1295the end of the block or until the next C<"## use critic"> annotation
11f53956 1296(whichever comes first):
c70a9ff6 1297
11f53956 1298 ## no critic (EmptyQuotes, PostfixControls);
c70a9ff6 1299
11f53956
ES
1300 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
1301 $foo = "";
64eea91f 1302
11f53956
ES
1303 # Now exempt ControlStructures::ProhibitPostfixControls
1304 $barf = bar() if $foo;
64eea91f 1305
11f53956
ES
1306 # Still subject to ValuesAndExpression::RequireNumberSeparators
1307 $long_int = 10000000000;
c70a9ff6 1308
11f53956
ES
1309Since the Policy names are matched against the C<"## no critic">
1310arguments as regular expressions, you can abbreviate the Policy names
1311or disable an entire family of Policies in one shot like this:
c70a9ff6 1312
11f53956 1313 ## no critic (NamingConventions)
c70a9ff6 1314
d5ff35da 1315 # Now exempt from NamingConventions::Capitalization
11f53956 1316 my $camelHumpVar = 'foo';
64eea91f 1317
d5ff35da 1318 # Now exempt from NamingConventions::Capitalization
11f53956 1319 sub camelHumpSub {}
c70a9ff6 1320
11f53956
ES
1321The argument list must be enclosed in parentheses and must contain one
1322or more comma-separated barewords (i.e. don't use quotes). The C<"##
d1237298
JRT
1323no critic"> annotations can be nested, and Policies named by an inner
1324annotation will be disabled along with those already disabled an outer
1325annotation.
c70a9ff6 1326
11f53956
ES
1327Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to
1328an entire block of code. In those cases, C<"## no critic"> must
1329appear on the line where the violation is reported. For example:
35892a39 1330
11f53956
ES
1331 sub complicated_function { ## no critic (ProhibitExcessComplexity)
1332 # Your code here...
1333 }
1334
1335Some Policies like C<Documentation::RequirePodSections> apply to the
1336entire document, in which case violations are reported at line 1. But
1337if the file requires a shebang line, it is impossible to put C<"## no
1338critic"> on the first line of the file. This is a known limitation
1339and it will be addressed in a future release. As a workaround, you
1340can disable the affected policies at the command-line or in your
1341F<.perlcriticrc> file. But beware that this will affect the analysis
1342of B<all> files.
35892a39 1343
11f53956
ES
1344Use this feature wisely. C<"## no critic"> should be used in the
1345smallest possible scope, or only on individual lines of code. And you
1346should always be as specific as possible about which policies you want
1347to disable (i.e. never use a bare C<"## no critic">). If Perl::Critic
1348complains about your code, try and find a compliant solution before
1349resorting to this feature.
35892a39 1350
1c5955e4 1351
59b05e08
JRT
1352=head1 EDITOR INTEGRATION
1353
11f53956
ES
1354For ease-of-use, C<perlcritic> can be integrated with your favorite
1355text editor. The output-formatting capabilities of C<perlcritic> are
1356specifically intended for use with the "grep" or "compile" modes
1357available in editors like C<emacs> and C<vim>. In these modes, you
1358can run an arbitrary command and the editor will parse the output into
1359an interactive buffer that you can click on and jump to the relevant
1360line of code.
59b05e08 1361
fb87b5f0
JRT
1362The Perl::Critic team thanks everyone who has helped integrate Perl-Critic
1363with their favorite editor. Your contributions in particular have made
1364Perl-Critic a convenient and user-friendly tool for Perl developers of all
1365stripes. We sincerely appreciate your hard work.
1366
11f53956 1367
59b05e08
JRT
1368=head2 EMACS
1369
11f53956
ES
1370Joshua ben Jore has authored a minor-mode for emacs that allows you to
1371run perlcritic on the current region or buffer. You can run it on
1372demand, or configure it to run automatically when you save the buffer.
1373The output appears in a hot-linked compiler buffer. The code and
1374installation instructions can be found in the F<extras> directory
1375inside this distribution.
1376
59b05e08
JRT
1377
1378=head2 VIM
1379
77de3405
JRT
1380Scott Peshak has published F<perlchecker.vim>, which is available at
1381L<http://www.vim.org/scripts/script.php?script_id=1731>.
59b05e08 1382
11f53956 1383
57d6a8e3
JRT
1384=head2 gVIM
1385
11f53956
ES
1386Fritz Mehner recently added support for C<perlcritic> to his fantastic
1387gVIM plugin. In addition to providing a very Perlish IDE, Fritz's
1388plugin enables one-click access to C<perlcritic> and many other very
1389useful utilities. And all is seamlessly integrated into the editor.
1390See L<http://lug.fh-swf.de/vim/vim-perl/screenshots-en.html> for
1391complete details.
1392
57d6a8e3 1393
5b0502a0
JRT
1394=head2 EPIC
1395
11f53956 1396EPIC is an open source Perl IDE based on the Eclipse platform.
10e82cde 1397Features include syntax highlighting, on-the-fly syntax check,
fcb2381b
ES
1398content assist, code completion, perldoc support, source formatting
1399with L<Perl::Tidy>, code templates, a regular expression editing tool,
1400and integration with the Perl debugger. Recent versions of EPIC also
10e82cde 1401have built-in support for Perl::Critic. At least one Perl::Critic
fcb2381b 1402contributor swears by EPIC. Go to L<http://e-p-i-c.sourceforge.net>
10e82cde 1403for more information about EPIC.
5b0502a0 1404
fb87b5f0
JRT
1405=head2 BBEdit
1406
11f53956
ES
1407Josh Clark has produced an excellent Perl-Critic plugin for BBEdit. A
1408copy is included in this distribution at
1409F<extras/perl_critic_for_bbedit-1_0.zip>. See
1410L<http://beta.bigmedium.com/projects/bbedit-perl-critic/index.shtml>
1411for screenshots and additional installation info. Apple users
1412rejoice!
1413
775df202
JRT
1414
1415=head2 Komodo
1416
11f53956
ES
1417Komodo is a proprietary IDE for Perl and several other dynamic
1418languages. Free trial copies of Komodo can be obtained from the
1419ActiveState website at L<http://www.activestate.com>. For instructions
1420on integrating F<perlcritic> with Komodo, see
1421F<extras/KomodoIntegration.pod> in this distribution.
1422
fb87b5f0 1423
59b05e08
JRT
1424=head1 EXIT STATUS
1425
11f53956
ES
1426If C<perlcritic> has any errors itself, exits with status == 1. If
1427there are no errors, but C<perlcritic> finds Policy violations in your
1428source code, exits with status == 2. If there were no errors and no
1429violations were found, exits with status == 0.
1430
59b05e08 1431
11f53956 1432=head1 THE L<Perl::Critic|Perl::Critic> PHILOSOPHY
b87b00dd 1433
67a7fe92
ES
1434=over
1435
11f53956
ES
1436Coding standards are deeply personal and highly subjective. The goal
1437of Perl::Critic is to help you write code that conforms with a set of
1438best practices. Our primary goal is not to dictate what those
1439practices are, but rather, to implement the practices discovered by
1440others. Ultimately, you make the rules -- Perl::Critic is merely a
1441tool for encouraging consistency. If there is a policy that you think
1442is important or that we have overlooked, we would be very grateful for
1443contributions, or you can simply load your own private set of policies
1444into Perl::Critic.
67a7fe92
ES
1445
1446=back
b87b00dd 1447
11f53956 1448
4d19da19 1449=head1 EXTENDING THE CRITIC
5deaba5e 1450
11f53956
ES
1451The modular design of Perl::Critic is intended to facilitate the
1452addition of new Policies. You'll need to have some understanding of
1453L<PPI|PPI>, but most Policy modules are pretty straightforward and
1454only require about 20 lines of code, and half of those lines are
1455simple use statements and simple declarations.. Please see the
1456L<Perl::Critic::DEVELOPER|Perl::Critic::DEVELOPER> file included in
1457this distribution for a step-by-step demonstration of how to create
1458new Policy modules.
1459
1460If you develop any new Policy modules, feel free to send them to C<<
1461<thaljef@cpan.org> >> and I'll be happy to put them into the
1462Perl::Critic distribution. Or if you would like to work on the
1463Perl::Critic project directly, check out our repository at
1464L<http://perlcritic.tigris.org>. To subscribe to our mailing list,
1465send a message to C<< <dev-subscribe@perlcritic.tigris.org> >>.
1466
1467The Perl::Critic team is also available for hire. If your
1468organization has its own coding standards, we can create custom
1469Policies to enforce your local guidelines. Or if your code base is
1470prone to a particular defect pattern, we can design Policies that will
1471help you catch those costly defects B<before> they go into production.
1472To discuss your needs with the Perl::Critic team, just contact C<<
1473<thaljef@cpan.org> >>.
1474
5deaba5e 1475
25e89cf1
ES
1476=head1 CONTACTING THE DEVELOPMENT TEAM
1477
1478You are encouraged to subscribe to the mailing list; send a message to
1479C<< <users-subscribe@perlcritic.tigris.org> >>. See also
1480L<the archives|http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
1481You can also contact the author at C<< <thaljef@cpan.org> >>.
1482
11f53956
ES
1483At least one member of the development team has started hanging around
1484in L<irc://irc.perl.org/#perlcritic>.
1485
098d393b 1486
3123bf46
ES
1487=head1 SEE ALSO
1488
11f53956
ES
1489There are a number of distributions of additional Policies available.
1490A few are listed here:
3123bf46 1491
11f53956
ES
1492L<Perl::Critic::More|Perl::Critic::More>
1493L<Perl::Critic::Bangs|Perl::Critic::Bangs>
1494L<Perl::Critic::Lax|Perl::Critic::Lax>
1495L<Perl::Critic::StricterSubs|Perl::Critic::StricterSubs>
1496L<Perl::Critic::Swift|Perl::Critic::Swift>
3123bf46 1497
d032ff5e
JRT
1498These distributions enable you to use Perl::Critic in your unit tests:
1499
11f53956
ES
1500L<Test::Perl::Critic|Test::Perl::Critic>
1501L<Test::Perl::Critic::Progressive|Test::Perl::Critic::Progressive>
d032ff5e 1502
3123bf46
ES
1503There are also a couple of distributions that will install all the
1504Perl::Critic related modules known to the development team:
1505
11f53956
ES
1506L<Bundle::Perl::Critic|Bundle::Perl::Critic>
1507L<Task::Perl::Critic|Task::Perl::Critic>
1508
3123bf46 1509
59b05e08
JRT
1510=head1 BUGS
1511
11f53956
ES
1512Scrutinizing Perl code is hard for humans, let alone machines. If you
1513find any bugs, particularly false-positives or false-negatives from a
59b05e08
JRT
1514Perl::Critic::Policy, please submit them to
1515L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
1516
fc0fffee
ES
1517Most policies will produce false-negatives if they cannot understand a
1518particular block of code.
1519
11f53956 1520
59b05e08
JRT
1521=head1 CREDITS
1522
11f53956
ES
1523Adam Kennedy - For creating L<PPI|PPI>, the heart and soul of
1524L<Perl::Critic|Perl::Critic>.
59b05e08 1525
b87b00dd 1526Damian Conway - For writing B<Perl Best Practices>, finally :)
59b05e08 1527
b87b00dd 1528Chris Dolan - For contributing the best features and Policy modules.
59b05e08 1529
7711a331
JRT
1530Andy Lester - Wise sage and master of all-things-testing.
1531
1532Elliot Shank - The self-proclaimed quality freak.
1533
b87b00dd 1534Giuseppe Maxia - For all the great ideas and positive encouragement.
59b05e08 1535
b87b00dd 1536and Sharon, my wife - For putting up with my all-night code sessions.
59b05e08 1537
11f53956 1538
59b05e08
JRT
1539=head1 AUTHOR
1540
1541Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1542
11f53956 1543
59b05e08
JRT
1544=head1 COPYRIGHT
1545
20dfddeb 1546Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08 1547
11f53956
ES
1548This program is free software; you can redistribute it and/or modify
1549it under the same terms as Perl itself. The full text of this license
1550can be found in the LICENSE file included with this module.
59b05e08
JRT
1551
1552=cut
737d3b65 1553
7711a331 1554##############################################################################
737d3b65
CD
1555# Local Variables:
1556# mode: cperl
1557# cperl-indent-level: 4
1558# fill-column: 78
1559# indent-tabs-mode: nil
1560# c-indentation-style: bsd
1561# End:
96fed375 1562# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :