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