Login
Updated docs about EPIC
[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
0bce889d 223 my ( $opts_ref, @files ) = @_;
a609ec83 224 @files || 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
f03e8867 241 for my $file (@files) {
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
457 );
59b05e08
JRT
458}
459
db1213c6 460#-----------------------------------------------------------------------------
01625a50 461
faa35de4
JRT
462sub _colorize_by_severity {
463 my (@violations) = @_;
faa35de4
JRT
464 return @violations if _this_is_windows();
465 return @violations if not eval { require Term::ANSIColor };
466
05b5f925
ES
467 my %color_of = (
468 $SEVERITY_HIGHEST => 'bold red',
1ffd2487 469 $SEVERITY_HIGH => 'magenta',
05b5f925 470 );
faa35de4
JRT
471 return map { _colorize( "$_", $color_of{$_->severity()} ) } @violations;
472
473}
474
475#-----------------------------------------------------------------------------
476
477sub _colorize {
478 my ($string, $color) = @_;
479 return $string if not defined $color;
480 return Term::ANSIColor::colored( $string, $color );
481}
482
483#-----------------------------------------------------------------------------
484
485sub _this_is_windows {
f135623f 486 return 1 if $OSNAME =~ m/MSWin32/xms;
faa35de4
JRT
487 return 0;
488}
489
490#-----------------------------------------------------------------------------
491
492sub _at_tty {
385d181e 493 return -t STDOUT; ## no critic 'ProhibitInteractiveTest';
faa35de4 494}
faa35de4 495
e68db767 496#-----------------------------------------------------------------------------
faa35de4 497
fd5bd7b5 498sub render_policy_listing {
fdfe1e54 499
c2018d77 500 require Perl::Critic::PolicyListing;
606ea80c 501 require Perl::Critic;
e68db767 502
05b5f925 503 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
504 my @policies = Perl::Critic->new( %pc_params )->policies();
505 my $listing = Perl::Critic::PolicyListing->new( -policies => \@policies );
89b50090 506 out $listing;
71ef7d49
ES
507 exit 0;
508}
509
510#-----------------------------------------------------------------------------
511
512sub render_theme_listing {
513 require Perl::Critic::ThemeListing;
514 require Perl::Critic;
515
516 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
517 my @policies = Perl::Critic->new( %pc_params )->policies();
518 my $listing = Perl::Critic::ThemeListing->new( -policies => \@policies );
89b50090 519 out $listing;
d6950ab1 520 exit 0;
fd5bd7b5
JRT
521}
522
523#-----------------------------------------------------------------------------
524
525sub render_profile_prototype {
526
527 require Perl::Critic::ProfilePrototype;
606ea80c 528 require Perl::Critic;
fd5bd7b5 529
05b5f925 530 my %pc_params = (-profile => $EMPTY, -severity => $SEVERITY_LOWEST);
71ef7d49
ES
531 my @policies = Perl::Critic->new( %pc_params )->policies();
532 my $prototype = Perl::Critic::ProfilePrototype->new( -policies => \@policies );
89b50090 533 out $prototype;
d6950ab1 534 exit 0;
faa35de4
JRT
535}
536
6332a5f1
JRT
537#-----------------------------------------------------------------------------
538
539sub policy_docs {
540
385d181e
JRT
541 my (%opts) = @_;
542 my $pattern = delete $opts{-doc};
543
606ea80c 544 require Perl::Critic;
385d181e
JRT
545 $critic = Perl::Critic->new(%opts);
546 set_up_pager($critic->config()->pager());
6332a5f1 547
385d181e
JRT
548 require Perl::Critic::PolicyFactory;
549 my @site_policies = Perl::Critic::PolicyFactory->site_policy_names();
550 my @matching_policies = grep { $_ =~ m/$pattern/ixms } @site_policies;
551
552 # "-T" means don't send to pager
553 my @perldoc_output = map {`perldoc -T $_`} @matching_policies; ## no critic ProhibitBacktick
554 out @perldoc_output;
6332a5f1 555
6332a5f1
JRT
556 exit 0;
557}
558
59b05e08
JRT
5591;
560
561__END__
562
01625a50 563#-----------------------------------------------------------------------------
1e7b8681 564
59b05e08
JRT
565=pod
566
2849151b
ES
567=for stopwords DGR INI-style vim-fu minibuffer -noprofile API
568-profileproto -profile-proto ben Jore formatter Peshak pbp Komodo
c296c678 569screenshots tty emacs gVIM plugin Perlish templating ActiveState
821d0eb5 570
59b05e08
JRT
571=head1 NAME
572
13c1001a 573C<perlcritic> - Command-line interface to critique Perl source.
59b05e08 574
11f53956 575
59b05e08
JRT
576=head1 SYNOPSIS
577
e7ae8f62
ES
578 perlcritic [-12345 | --brutal | --cruel | --harsh | --stern | --gentle]
579 [--severity number | name] [--profile file | --noprofile]
580 [--top [ number ]] [--theme expression] [--include pattern]
2849151b
ES
581 [--exclude pattern] [{-s | --single-policy} pattern]
582 [--only | --noonly] [--profile-strictness {warn|fatal|quiet}]
583 [--force | --noforce] [--statistics] [--statistics-only]
584 [--count | -C] [--verbose {number | format}]
385d181e
JRT
585 [--color | --nocolor] [--pager pager] [--quiet]
586 {FILE | DIRECTORY | STDIN}
05b913fd 587
e7ae8f62 588 perlcritic --profile-proto
05b913fd 589
71ef7d49 590 perlcritic { --list | --list-themes | --doc pattern [...] }
9f12283e 591
eb4540f0 592 perlcritic { --help | --options | --man | --version }
59b05e08 593
11f53956 594
59b05e08
JRT
595=head1 DESCRIPTION
596
597C<perlcritic> is a Perl source code analyzer. It is the executable
11f53956
ES
598front-end to the L<Perl::Critic|Perl::Critic> engine, which attempts
599to identify awkward, hard to read, error-prone, or unconventional
600constructs in your code. Most of the rules are based on Damian
601Conway's book B<Perl Best Practices>. However, C<perlcritic> is
602B<not> limited to enforcing PBP, and it will even support rules that
603contradict Conway. All rules can easily be configured or disabled to
604your liking.
59b05e08 605
e7ae8f62
ES
606This documentation only covers how to drive this command. For all
607other information, including how to persistently configure this
11f53956
ES
608command so that you don't have to say so much on the command-line, see
609the documentation for L<Perl::Critic|Perl::Critic> itself.
0304068a 610
8d36cd6f 611
d2843fb4
JRT
612=head1 USAGE EXAMPLES
613
25a6e413 614Before getting into all the gory details, here are some basic usage
b2c7354a 615examples to help get you started.
d2843fb4 616
11f53956
ES
617 # Report only most severe violations (severity = 5)
618 perlcritic YourModule.pm
619
620 # Same as above, but read input from STDIN
621 perlcritic
25a6e413 622
11f53956
ES
623 # Recursively process all Perl files beneath directory
624 perlcritic /some/directory
db1213c6 625
11f53956
ES
626 # Report slightly less severe violations too (severity >= 4)
627 perlcritic -4 YourModule.pm
d2843fb4 628
11f53956
ES
629 # Same as above, but using named severity level
630 perlcritic --stern YourModule.pm
d2843fb4 631
11f53956
ES
632 # Report all violations, regardless of severity (severity >= 1)
633 perlcritic -1 YourModule.pm
0bcb38c0 634
11f53956
ES
635 # Same as above, but using named severity level
636 perlcritic --brutal YourModule.pm
d2843fb4 637
11f53956
ES
638 # Report only violations of things from "Perl Best Practices"
639 perlcritic --theme pbp YourModule.pm
e7ae8f62 640
11f53956
ES
641 # Report top 20 most severe violations (severity >= 1)
642 perlcritic --top YourModule.pm
0bcb38c0 643
f135623f 644 # Report additional violations of Policies that match m/variables/xms
11f53956 645 perlcritic --include variables YourModule.pm
4a24d03a 646
11f53956
ES
647 # Use defaults from somewhere other than ~/.perlcriticrc
648 perlcriticrc --profile project/specific/perlcriticrc YourModule.pm
25a6e413 649
d2843fb4 650
59b05e08
JRT
651=head1 ARGUMENTS
652
653The arguments are paths to the files you wish to analyze. You may
c165f991 654specify multiple files. If an argument is a directory, C<perlcritic>
11f53956
ES
655will analyze all Perl files below the directory. If no arguments are
656specified, then input is read from STDIN.
657
59b05e08
JRT
658
659=head1 OPTIONS
660
661Option names can be abbreviated to uniqueness and can be stated with
662singe or double dashes, and option values can be separated from the
11f53956
ES
663option name by a space or '=' (as with L<Getopt::Long|Getopt::Long>).
664Option names are also case-sensitive.
59b05e08
JRT
665
666=over 8
667
e7ae8f62 668=item C<--profile FILE>
59b05e08 669
11f53956
ES
670Directs C<perlcritic> to use a profile named by FILE rather than
671looking for the default F<.perlcriticrc> file in the current directory
672or your home directory. See L<Perl::Critic/"CONFIGURATION"> for more
673information.
59b05e08 674
e7ae8f62 675=item C<--noprofile>
59b05e08 676
11f53956
ES
677Directs C<perlcritic> not to load any configuration file, thus
678reverting to the default configuration for all Policies.
59b05e08 679
e7ae8f62 680=item C<--severity N>
59b05e08 681
11f53956
ES
682Directs C<perlcritic> to only apply Policies with a severity greater
683than C<N>. Severity values are integers ranging from 1 (least severe)
684to 5 (most severe). The default is 5. For a given C<--profile>,
685decreasing the C<--severity> will usually produce more violations.
686You can set the default value for this option in your F<.perlcriticrc>
687file. You can also redefine the C<severity> for any Policy in your
688F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
59b05e08 689
faa35de4 690=item C<-5 | -4 | -3 | -2 | -1>
d2843fb4 691
11f53956
ES
692These are numeric shortcuts for setting the C<--severity> option. For
693example, C<"-4"> is equivalent to C<"--severity 4">. If multiple
694shortcuts are specified, then the most restrictive one wins. If an
695explicit C<--severity> option is also given, then all shortcut options
696are silently ignored. NOTE: Be careful not to put one of the number
697severity shortcut options immediately after the C<--top> flag or
698C<perlcritic> will interpret it as the number of violations to report.
0bcb38c0 699
e7ae8f62 700=item C<--severity NAME>
0bcb38c0 701
11f53956
ES
702If it is difficult for you to remember whether severity "5" is the
703most or least restrictive level, then you can use one of these named
704values:
0bcb38c0 705
7711a331 706 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
0bcb38c0 707 --------------------------------------------------------
e7ae8f62
ES
708 --severity gentle --severity 5
709 --severity stern --severity 4
710 --severity harsh --severity 3
711 --severity cruel --severity 2
712 --severity brutal --severity 1
0bcb38c0 713
e7ae8f62 714=item C<--gentle | --stern | --harsh | --cruel | --brutal>
0bcb38c0 715
11f53956
ES
716These are named shortcuts for setting the C<--severity> option. For
717example, C<"--cruel"> is equivalent to C<"--severity 2">. If multiple
718shortcuts are specified, then the most restrictive one wins. If an
719explicit C<--severity> option is also given, then all shortcut options
720are silently ignored.
d2843fb4 721
e7ae8f62 722=item C<--theme RULE>
a0934394 723
11f53956
ES
724Directs C<perlcritic> to apply only Policies with themes that satisfy
725the C<RULE>. Themes are arbitrary names for groups of related
726policies. You can combine theme names with boolean operators to
727create an arbitrarily complex C<RULE>. For example, the following
728would apply only Policies that have a 'bugs' AND 'pbp' theme:
1c5955e4 729
11f53956 730 $> perlcritic --theme='bugs && pbp' MyModule.pm
1c5955e4 731
11f53956
ES
732Unless the C<--severity> option is explicitly given, setting
733C<--theme> silently causes the C<--severity> to be set to 1. You can
734set the default value for this option in your F<.perlcriticrc> file.
735See L<Perl::Critic/"POLICY THEMES"> for more information about themes.
faa35de4 736
e7ae8f62 737=item C<--include PATTERN>
59b05e08 738
11f53956
ES
739Directs C<perlcritic> to apply additional Policies that match the
740regex C</PATTERN/imx>. Use this option to temporarily override your
741profile and/or the severity settings at the command-line. For
742example:
6bf9b465 743
11f53956 744 perlcritic --include=layout my_file.pl
6bf9b465 745
11f53956
ES
746This would cause C<perlcritic> to apply all the C<CodeLayout::*>
747policies even if they have a severity level that is less than the
748default level of 5, or have been disabled in your F<.perlcriticrc>
749file. You can specify multiple C<--include> options and you can use
750it in conjunction with the C<--exclude> option. Note that
751C<--exclude> takes precedence over C<--include> when a Policy matches
752both patterns. You can set the default value for this option in your
77de3405 753F<.perlcriticrc> file.
59b05e08 754
e7ae8f62 755=item C<--exclude PATTERN>
59b05e08 756
77de3405 757Directs C<perlcritic> to not apply any Policy that matches the regex
11f53956
ES
758C</PATTERN/imx>. Use this option to temporarily override your profile
759and/or the severity settings at the command-line. For example:
6bf9b465 760
11f53956 761 perlcritic --exclude=strict my_file.pl
6bf9b465 762
11f53956
ES
763This would cause C<perlcritic> to not apply the C<RequireUseStrict>
764and C<ProhibitNoStrict> Policies even though they have the highest
765severity level. You can specify multiple C<--exclude> options and you
766can use it in conjunction with the C<--include> option. Note that
767C<--exclude> takes precedence over C<--include> when a Policy matches
768both patterns. You can set the default value for this option in your
769F<.perlcriticrc> file.
59b05e08 770
e7ae8f62 771=item C<--single-policy PATTERN>
585ddee1 772
2849151b
ES
773=item C<-s PATTERN>
774
11f53956 775Directs C<perlcritic> to apply just one Policy module matching the
f135623f 776regex C</PATTERN/ixms>, and exclude all other Policies. This option
11f53956
ES
777has precedence over the C<--severity>, C<--theme>, C<--include>,
778C<--exclude>, and C<--only> options. For example:
585ddee1 779
11f53956 780 perlcritic --single-policy=nowarnings my_file.pl
585ddee1 781
11f53956
ES
782This would cause C<perlcritic> to apply just the C<ProhibitNoWarnings>
783Policy, regardless of the severity level setting. No other Policies
784would be applied.
585ddee1 785
77de3405 786This is equivalent to what one might intend by...
585ddee1 787
11f53956 788 perlcritic --exclude=. --include=nowarnings my_file.pl
585ddee1 789
e7ae8f62
ES
790... but this won't work because the C<--exclude> option overrides the
791C<--include> option.
585ddee1 792
11f53956
ES
793The equivalent of this option can be accomplished by creating a custom
794profile containing only the desired policy and then running...
585ddee1 795
11f53956 796 perlcritic --profile=customprofile --only my_file.pl
585ddee1 797
e7ae8f62 798=item C<--top [ N ]>
faa35de4 799
11f53956
ES
800Directs C<perlcritic> to report only the top C<N> Policy violations in
801each file, ranked by their severity. If C<N> is not specified, it
802defaults to 20. If the C<--severity> option (or one of the shortcuts)
803is not explicitly given, the C<--top> option implies that the minimum
804severity level is "1" (i.e. "brutal"). Users can redefine the severity
805for any Policy in their F<.perlcriticrc> file. See L<"CONFIGURATION">
806for more information. You can set the default value for this option
807in your F<.perlcriticrc> file. NOTE: Be careful not to put one of the
808severity shortcut options immediately after the C<--top> flag or
809C<perlcritic> will interpret it as the number of violations to report.
faa35de4 810
e7ae8f62 811=item C<--force>
59b05e08 812
11f53956
ES
813Directs C<perlcritic> to ignore the magical C<"## no critic">
814pseudo-pragmas in the source code. See L<"BENDING THE RULES"> for more
815information. You can set the default value for this option in your
816F<.perlcriticrc> file.
59b05e08 817
e7ae8f62 818=item C<--statistics>
576f6411 819
11f53956
ES
820Causes several statistics about the code being scanned and the
821violations found to be reported after any other output.
576f6411 822
e7ae8f62 823=item C<--statistics-only>
cb43b040 824
11f53956
ES
825Like the C<--statistics> option, but suppresses normal output and only
826shows the statistics.
cb43b040 827
e7ae8f62 828=item C<--verbose N | FORMAT>
59b05e08 829
11f53956
ES
830Sets the verbosity level or format for reporting violations. If given
831a number (C<N>), C<perlcritic> reports violations using one of the
832predefined formats described below. If given a string (C<FORMAT>), it
833is interpreted to be an actual format specification. If the
834C<--verbose> option is not specified, it defaults to either 4 or 5,
835depending on whether multiple files were given as arguments to
836C<perlcritic>. You can set the default value for this option in your
837F<.perlcriticrc> file.
838
839 Verbosity Format Specification
840 ----------- -------------------------------------------------------
841 1 "%f:%l:%c:%m\n",
842 2 "%f: (%l:%c) %m\n",
843 3 "%m at %f line %l\n",
844 4 "%m at line %l, column %c. %e. (Severity: %s)\n",
845 5 "%f: %m at line %l, column %c. %e. (Severity: %s)\n",
846 6 "%m at line %l, near '%r'. (Severity: %s)\n",
847 7 "%f: %m at line %l near '%r'. (Severity: %s)\n",
848 8 "[%p] %m at line %l, column %c. (Severity: %s)\n",
849 9 "[%p] %m at line %l, near '%r'. (Severity: %s)\n",
850 10 "%m at line %l, column %c.\n %p (Severity: %s)\n%d\n",
851 11 "%m at line %l, near '%r'.\n %p (Severity: %s)\n%d\n"
852
853Formats are a combination of literal and escape characters similar to
854the way C<sprintf> works. See L<String::Format|String::Format> for a
855full explanation of the formatting capabilities. Valid escape
856characters are:
857
858 Escape Meaning
859 ------- ------------------------------------------------------------
860 %c Column number where the violation occurred
861 %d Full diagnostic discussion of the violation
862 %e Explanation of violation or page numbers in PBP
863 %F Just the name of the file where the violation occurred.
864 %f Path to the file where the violation occurred.
865 %l Line number where the violation occurred
866 %m Brief description of the violation
867 %P Full name of the Policy module that created the violation
868 %p Name of the Policy without the Perl::Critic::Policy:: prefix
869 %r The string of source code that caused the violation
870 %s The severity level of the violation
871
872The purpose of these formats is to provide some compatibility with
873text editors that have an interface for parsing certain kinds of
874input. See L<"EDITOR INTEGRATION"> for more information about that.
59b05e08 875
e7ae8f62 876=item C<--list>
122d73f6 877
11f53956
ES
878Displays a condensed listing of all the
879L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
880this machine. For each Policy, the name, default severity and default
881themes are shown.
64eea91f 882
71ef7d49
ES
883=item C<--list-themes>
884
11f53956
ES
885Displays a list of all the themes of the
886L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
887this machine.
71ef7d49 888
e7ae8f62 889=item C<--profile-proto>
64eea91f 890
11f53956
ES
891Displays an expanded listing of all the
892L<Perl::Critic::Policy|Perl::Critic::Policy> modules that are found on
893this machine. For each Policy, the name, default severity and default
894themes are shown, as well as the name of any additional parameters
895that the Policy supports. The format is suitable as a prototype for
896your F<.perlcriticrc> file.
122d73f6 897
e7ae8f62 898=item C<--only>
e967596d 899
11f53956
ES
900Directs perlcritic to apply only Policies that are explicitly
901mentioned in your F<.perlcriticrc> file. This is useful if you want
902to use just a small subset of Policies without having to disable all
903the others. You can set the default value for this option in your
904F<.perlcriticrc> file.
e967596d 905
e7ae8f62 906=item C<--profile-strictness {warn|fatal|quiet}>
66186ba3 907
11f53956
ES
908Directs perlcritic how to treat certain recoverable problems found in
909a F<.perlcriticrc> or file specified via the C<--profile> option.
910Valid values are C<warn> (the default), C<fatal>, and C<quiet>. For
911example, perlcritic normally only warns about profiles referring to
912non-existent Policies, but this option can make this situation fatal.
913You can set the default value for this option in your F<.perlcriticrc>
914file.
66186ba3 915
e7ae8f62 916=item C<--count>
faa35de4 917
0bcb38c0
JRT
918=item C<-C>
919
11f53956
ES
920Display only the number of violations for each file. Use this feature
921to get a quick handle on where a large pile of code might need the
922most attention.
faa35de4 923
e7ae8f62 924=item C<--Safari>
59b05e08
JRT
925
926Report "Perl Best Practice" citations as section numbers from
11f53956
ES
927L<http://safari.oreilly.com> instead of page numbers from the actual
928book. NOTE: This feature is not implemented yet.
59b05e08 929
e7ae8f62 930=item C<--color>
faa35de4 931
89b50090
ES
932This option is on when outputting to a tty. When set, Severity 5 and 4 are
933colored red and yellow, respectively. Colorization only happens if
934L<Term::ANSIColor|Term::ANSIColor> is installed and it only works on
935non-Windows environments. Negate this switch to disable color. You can set
936the default value for this option in your F<.perlcriticrc> file.
faa35de4 937
ae9b3404
ES
938Can also be specified as C<--colour>.
939
385d181e 940=item C<--pager PAGER_COMMAND_STRING>
89b50090 941
385d181e
JRT
942If set, perlcritic will pipe it's output to the given PAGER_COMMAND_STRING.
943You can set the default value for this option in your F<.perlcriticrc> file.
89b50090
ES
944
945Setting a pager turns off color by default. You will have to turn color on
385d181e
JRT
946explicitly. If you want color, you'll probably also want to tell your pager
947to display raw characters. For C<less> and C<more>, use the -R switch.
89b50090 948
e7ae8f62 949=item C<--doc PATTERN>
6332a5f1 950
11f53956
ES
951Displays the perldoc for all
952L<Perl::Critic::Policy|Perl::Critic::Policy> modules that match
f135623f 953C<m/PATTERN/ixms>. Since Policy modules tend to have rather long
11f53956
ES
954names, this just provides a more convenient way to say something like:
955C<"perldoc Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator">
6332a5f1
JRT
956at the command prompt.
957
e7ae8f62 958=item C<--quiet>
8b5892fc 959
1c5955e4 960Suppress the "source OK" message when no violations are found.
8b5892fc 961
e7ae8f62 962=item C<--help>
59b05e08 963
faa35de4 964=item C<-?>
59b05e08 965
0bcb38c0
JRT
966=item C<-H>
967
59b05e08
JRT
968Displays a brief summary of options and exits.
969
e7ae8f62 970=item C<--options>
bbcf8061 971
11f53956
ES
972Displays the descriptions of the options and exits. While this output
973is long, it it nowhere near the length of the output of C<--man>.
bbcf8061 974
e7ae8f62 975=item C<--man>
59b05e08 976
c165f991 977Displays the complete C<perlcritic> manual and exits.
59b05e08 978
eb4540f0 979=item C<--version>
59b05e08 980
faa35de4 981=item C<-V>
59b05e08 982
c165f991 983Displays the version number of C<perlcritic> and exits.
59b05e08
JRT
984
985=back
986
987=head1 CONFIGURATION
988
11f53956
ES
989Most of the settings for Perl::Critic and each of the Policy modules
990can be controlled by a configuration file. The default configuration
991file is called F<.perlcriticrc>. C<perlcritic> will look for this
992file in the current directory first, and then in your home directory.
993Alternatively, you can set the C<PERLCRITIC> environment variable to
994explicitly point to a different file in another location. If none of
995these files exist, and the C<--profile> option is not given on the
996command-line, then all Policies will be loaded with their default
997configuration.
998
999The format of the configuration file is a series of INI-style blocks
1000that contain key-value pairs separated by "=". Comments should start
1001with "#" and can be placed on a separate line or after the name-value
1002pairs if you desire.
1003
1004Default settings for perlcritic itself can be set B<before the first
1005named block.> For example, putting any or all of these at the top of
1006your F<.perlcriticrc> file will set the default value for the
1007corresponding command-line argument.
1008
1009 severity = 3 #Integer or named level
1010 only = 1 #Zero or One
1011 force = 0 #Zero or One
1012 verbose = 4 #Integer or format spec
1013 top = 50 #A positive integer
1014 theme = (pbp + security) * bugs #A theme expression
1015 include = NamingConventions ClassHierarchies #Space-delimited list
1016 exclude = Variables Modules::RequirePackage #Space-delimited list
4a24d03a 1017
7711a331 1018The remainder of the configuration file is a series of blocks like this:
59b05e08 1019
11f53956
ES
1020 [Perl::Critic::Policy::Category::PolicyName]
1021 severity = 1
1022 set_themes = foo bar
1023 add_themes = baz
1024 arg1 = value1
1025 arg2 = value2
1026
1027C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
1028module that implements the policy. The Policy modules distributed
1029with Perl::Critic have been grouped into categories according to the
1030table of contents in Damian Conway's book B<Perl Best Practices>. For
1031brevity, you can omit the C<'Perl::Critic::Policy'> part of the module
1032name.
1033
1034C<severity> is the level of importance you wish to assign to the
1035Policy. All Policy modules are defined with a default severity value
1036ranging from 1 (least severe) to 5 (most severe). However, you may
1037disagree with the default severity and choose to give it a higher or
1038lower severity, based on your own coding philosophy. You can set the
1039C<severity> to an integer from 1 to 5, or use one of the equivalent
1040names:
1041
1042 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
1043 ----------------------------------------------------
1044 gentle 5
1045 stern 4
1046 harsh 3
1047 cruel 2
1048 brutal 1
1049
1050C<set_themes> sets the theme for the Policy and overrides its default
1051theme. The argument is a string of one or more whitespace-delimited
1052alphanumeric words. Themes are case-insensitive. See L<"POLICY
1053THEMES"> for more information.
1054
1055C<add_themes> appends to the default themes for this Policy. The
1056argument is a string of one or more whitespace-delimited words.
1057Themes are case-insensitive. See L<"POLICY THEMES"> for more
faa35de4
JRT
1058information.
1059
11f53956
ES
1060The remaining key-value pairs are configuration parameters that will
1061be passed into the constructor of that Policy. The constructors for
1062most Policy modules do not support arguments, and those that do should
1063have reasonable defaults. See the documentation on the appropriate
1064Policy module for more details.
faa35de4 1065
11f53956
ES
1066Instead of redefining the severity for a given Policy, you can
1067completely disable a Policy by prepending a '-' to the name of the
1068module in your configuration file. In this manner, the Policy will
1069never be loaded, regardless of the C<--severity> given on the command
1070line.
59b05e08 1071
1e7b8681 1072A simple configuration might look like this:
59b05e08 1073
11f53956
ES
1074 #--------------------------------------------------------------
1075 # I think these are really important, so always load them
1076
1077 [TestingAndDebugging::RequireUseStrict]
1078 severity = 5
59b05e08 1079
11f53956
ES
1080 [TestingAndDebugging::RequireUseWarnings]
1081 severity = 5
59b05e08 1082
11f53956
ES
1083 #--------------------------------------------------------------
1084 # I think these are less important, so only load when asked
59b05e08 1085
11f53956
ES
1086 [Variables::ProhibitPackageVars]
1087 severity = 2
59b05e08 1088
11f53956
ES
1089 [ControlStructures::ProhibitPostfixControls]
1090 allow = if unless # My custom configuration
1091 severity = cruel # Same as "severity = 2"
59b05e08 1092
11f53956
ES
1093 #--------------------------------------------------------------
1094 # Give these policies a custom theme. I can activate just
1095 # these policies by saying "perlcritic --theme 'larry || curly'"
59b05e08 1096
11f53956
ES
1097 [Modules::RequireFilenameMatchesPackage]
1098 add_themes = larry
7b84ff16 1099
11f53956
ES
1100 [TestingAndDebugging::RequireTestLabels]
1101 add_themes = curly moe
7b84ff16 1102
11f53956
ES
1103 #--------------------------------------------------------------
1104 # I do not agree with these at all, so never load them
7b84ff16 1105
11f53956
ES
1106 [-NamingConventions::ProhibitMixedCaseVars]
1107 [-NamingConventions::ProhibitMixedCaseSubs]
59b05e08 1108
11f53956
ES
1109 #--------------------------------------------------------------
1110 # For all other Policies, I accept the default severity,
1111 # so no additional configuration is required for them.
59b05e08 1112
11f53956
ES
1113Note that all policies included with the Perl::Critic distribution
1114that have integer parameters accept underscores ("_") in their values,
1115as with Perl numeric literals. For example,
1e7b8681 1116
11f53956
ES
1117 [ValuesAndExpressions::RequireNumberSeparators]
1118 min_value = 1_000
ced050bc 1119
11f53956
ES
1120For additional configuration examples, see the F<perlcriticrc> file
1121that is included in this F<examples> directory of this distribution.
ced050bc 1122
11f53956
ES
1123Damian Conway's own Perl::Critic configuration is also included in
1124this distribution as F<examples/perlcriticrc-conway>.
b87fc7eb 1125
75d77367 1126
59b05e08
JRT
1127=head1 THE POLICIES
1128
11f53956
ES
1129A large number of Policy modules are distributed with Perl::Critic.
1130They are described briefly in the companion document
1131L<Perl::Critic::PolicySummary|Perl::Critic::PolicySummary> and in more
1132detail in the individual modules themselves. Say C<"perlcritic --doc
1133PATTERN"> to see the perldoc for all Policy modules that match the
f135623f 1134regex C<m/PATTERN/ixms>
11f53956
ES
1135
1136There are a number of distributions of additional policies on CPAN.
1137If L<Perl::Critic|Perl::Critic> doesn't contain a policy that you
1138want, some one may have already written it. See L<Perl::Critic/"SEE
1139ALSO"> for a list of some of these distributions.
e7ff023b 1140
a41e8614 1141
faa35de4
JRT
1142=head1 POLICY THEMES
1143
11f53956
ES
1144Each Policy is defined with one or more "themes". Themes can be used
1145to create arbitrary groups of Policies. They are intended to provide
1146an alternative mechanism for selecting your preferred set of Policies.
1147For example, you may wish disable a certain set of Policies when
1148analyzing test scripts. Conversely, you may wish to enable only a
1149specific subset of Policies when analyzing modules.
1150
1151The Policies that ship with Perl::Critic are have been divided into
1152the following themes. This is just our attempt to provide some basic
1153logical groupings. You are free to invent new themes that suit your
1154needs.
1155
1156 THEME DESCRIPTION
1157 ------------------------------------------------------------------------
1158 core All policies that ship with Perl::Critic
1159 pbp Policies that come directly from "Perl Best Practices"
1160 bugs Policies that that prevent or reveal bugs
1161 maintenance Policies that affect the long-term health of the code
1162 cosmetic Policies that only have a superficial effect
1163 complexity Policies that specificaly relate to code complexity
1164 security Policies that relate to security issues
1165 tests Policies that are specific to test scripts
1166
1167Say C<"perlcritic --list"> to get a listing of all available policies
1168and the themes that are associated with each one. You can also change
1169the theme for any Policy in your F<.perlcriticrc> file. See the
1170L<"CONFIGURATION"> section for more information about that.
1171
1172Using the C<--theme> command-line option, you can create an
1173arbitrarily complex rule that determines which Policies to apply.
1174Precedence is the same as regular Perl code, and you can use
1175parentheses to enforce precedence as well. Supported operators are:
1176
1177 Operator Altertative Example
1178 -----------------------------------------------------------------
1179 && and 'pbp && core'
1180 || or 'pbp || (bugs && security)'
1181 ! not 'pbp && ! (portability || complexity)'
1182
1183Theme names are case-insensitive. If the C<--theme> is set to an
1184empty string, then it evaluates as true all Policies.
1185
faa35de4 1186
59b05e08
JRT
1187=head1 BENDING THE RULES
1188
59b05e08
JRT
1189Perl::Critic takes a hard-line approach to your code: either you
1190comply or you don't. In the real world, it is not always practical
1191(or even possible) to fully comply with coding standards. In such
1192cases, it is wise to show that you are knowingly violating the
1193standards and that you have a Damn Good Reason (DGR) for doing so.
1194
1195To help with those situations, you can direct Perl::Critic to ignore
1196certain lines or blocks of code by using pseudo-pragmas:
1197
67a7fe92
ES
1198 require 'LegacyLibaray1.pl'; ## no critic
1199 require 'LegacyLibrary2.pl'; ## no critic
59b05e08 1200
67a7fe92 1201 for my $element (@list) {
59b05e08 1202
67a7fe92 1203 ## no critic
59b05e08 1204
67a7fe92
ES
1205 $foo = ""; #Violates 'ProhibitEmptyQuotes'
1206 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
1207 #Some more evil code...
59b05e08 1208
67a7fe92 1209 ## use critic
59b05e08 1210
67a7fe92
ES
1211 #Some good code...
1212 do_something($_);
1213 }
59b05e08 1214
11f53956
ES
1215The C<"## no critic"> comments direct Perl::Critic to ignore the
1216remaining lines of code until the end of the current block, or until a
1217C<"## use critic"> comment is found (whichever comes first). If the
1218C<"## no critic"> comment is on the same line as a code statement,
1219then only that line of code is overlooked. To direct perlcritic to
1220ignore the C<"## no critic"> comments, use the C<--force> option.
77de3405 1221
11f53956
ES
1222A bare C<"## no critic"> comment disables all the active Policies. If
1223you wish to disable only specific Policies, add a list of Policy names
1224as arguments just as you would for the C<"no strict"> or C<"no
1225warnings"> pragma. For example, this would disable the
1226C<ProhibitEmptyQuotes> and C<ProhibitPostfixControls> policies until
1227the end of the block or until the next C<"## use critic"> comment
1228(whichever comes first):
c70a9ff6 1229
11f53956 1230 ## no critic (EmptyQuotes, PostfixControls);
c70a9ff6 1231
11f53956
ES
1232 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
1233 $foo = "";
64eea91f 1234
11f53956
ES
1235 # Now exempt ControlStructures::ProhibitPostfixControls
1236 $barf = bar() if $foo;
64eea91f 1237
11f53956
ES
1238 # Still subject to ValuesAndExpression::RequireNumberSeparators
1239 $long_int = 10000000000;
c70a9ff6 1240
11f53956
ES
1241Since the Policy names are matched against the C<"## no critic">
1242arguments as regular expressions, you can abbreviate the Policy names
1243or disable an entire family of Policies in one shot like this:
c70a9ff6 1244
11f53956 1245 ## no critic (NamingConventions)
c70a9ff6 1246
11f53956
ES
1247 # Now exempt from NamingConventions::ProhibitMixedCaseVars
1248 my $camelHumpVar = 'foo';
64eea91f 1249
11f53956
ES
1250 # Now exempt from NamingConventions::ProhibitMixedCaseSubs
1251 sub camelHumpSub {}
c70a9ff6 1252
11f53956
ES
1253The argument list must be enclosed in parentheses and must contain one
1254or more comma-separated barewords (i.e. don't use quotes). The C<"##
1255no critic"> pragmas can be nested, and Policies named by an inner
1256pragma will be disabled along with those already disabled an outer
1257pragma.
c70a9ff6 1258
11f53956
ES
1259Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to
1260an entire block of code. In those cases, C<"## no critic"> must
1261appear on the line where the violation is reported. For example:
35892a39 1262
11f53956
ES
1263 sub complicated_function { ## no critic (ProhibitExcessComplexity)
1264 # Your code here...
1265 }
1266
1267Some Policies like C<Documentation::RequirePodSections> apply to the
1268entire document, in which case violations are reported at line 1. But
1269if the file requires a shebang line, it is impossible to put C<"## no
1270critic"> on the first line of the file. This is a known limitation
1271and it will be addressed in a future release. As a workaround, you
1272can disable the affected policies at the command-line or in your
1273F<.perlcriticrc> file. But beware that this will affect the analysis
1274of B<all> files.
35892a39 1275
11f53956
ES
1276Use this feature wisely. C<"## no critic"> should be used in the
1277smallest possible scope, or only on individual lines of code. And you
1278should always be as specific as possible about which policies you want
1279to disable (i.e. never use a bare C<"## no critic">). If Perl::Critic
1280complains about your code, try and find a compliant solution before
1281resorting to this feature.
35892a39 1282
1c5955e4 1283
59b05e08
JRT
1284=head1 EDITOR INTEGRATION
1285
11f53956
ES
1286For ease-of-use, C<perlcritic> can be integrated with your favorite
1287text editor. The output-formatting capabilities of C<perlcritic> are
1288specifically intended for use with the "grep" or "compile" modes
1289available in editors like C<emacs> and C<vim>. In these modes, you
1290can run an arbitrary command and the editor will parse the output into
1291an interactive buffer that you can click on and jump to the relevant
1292line of code.
59b05e08 1293
fb87b5f0
JRT
1294The Perl::Critic team thanks everyone who has helped integrate Perl-Critic
1295with their favorite editor. Your contributions in particular have made
1296Perl-Critic a convenient and user-friendly tool for Perl developers of all
1297stripes. We sincerely appreciate your hard work.
1298
11f53956 1299
59b05e08
JRT
1300=head2 EMACS
1301
11f53956
ES
1302Joshua ben Jore has authored a minor-mode for emacs that allows you to
1303run perlcritic on the current region or buffer. You can run it on
1304demand, or configure it to run automatically when you save the buffer.
1305The output appears in a hot-linked compiler buffer. The code and
1306installation instructions can be found in the F<extras> directory
1307inside this distribution.
1308
59b05e08
JRT
1309
1310=head2 VIM
1311
77de3405
JRT
1312Scott Peshak has published F<perlchecker.vim>, which is available at
1313L<http://www.vim.org/scripts/script.php?script_id=1731>.
59b05e08 1314
11f53956 1315
57d6a8e3
JRT
1316=head2 gVIM
1317
11f53956
ES
1318Fritz Mehner recently added support for C<perlcritic> to his fantastic
1319gVIM plugin. In addition to providing a very Perlish IDE, Fritz's
1320plugin enables one-click access to C<perlcritic> and many other very
1321useful utilities. And all is seamlessly integrated into the editor.
1322See L<http://lug.fh-swf.de/vim/vim-perl/screenshots-en.html> for
1323complete details.
1324
57d6a8e3 1325
5b0502a0
JRT
1326=head2 EPIC
1327
11f53956 1328EPIC is an open source Perl IDE based on the Eclipse platform.
10e82cde
JRT
1329Features include syntax highlighting, on-the-fly syntax check,
1330content assist, code completion, perldoc support, source formatting
1331with L<Perl::Tidy>, code templates, a regular expression editing tool,
1332and integration with the Perl debugger. Recent versions of EPIC also
1333have built-in support for Perl::Critic. At least one Perl::Critic
1334contributor swears by EPIC. Go to L<http://e-p-i-c.sourceforge.net>
1335for more information about EPIC.
5b0502a0 1336
fb87b5f0
JRT
1337=head2 BBEdit
1338
11f53956
ES
1339Josh Clark has produced an excellent Perl-Critic plugin for BBEdit. A
1340copy is included in this distribution at
1341F<extras/perl_critic_for_bbedit-1_0.zip>. See
1342L<http://beta.bigmedium.com/projects/bbedit-perl-critic/index.shtml>
1343for screenshots and additional installation info. Apple users
1344rejoice!
1345
775df202
JRT
1346
1347=head2 Komodo
1348
11f53956
ES
1349Komodo is a proprietary IDE for Perl and several other dynamic
1350languages. Free trial copies of Komodo can be obtained from the
1351ActiveState website at L<http://www.activestate.com>. For instructions
1352on integrating F<perlcritic> with Komodo, see
1353F<extras/KomodoIntegration.pod> in this distribution.
1354
fb87b5f0 1355
59b05e08
JRT
1356=head1 EXIT STATUS
1357
11f53956
ES
1358If C<perlcritic> has any errors itself, exits with status == 1. If
1359there are no errors, but C<perlcritic> finds Policy violations in your
1360source code, exits with status == 2. If there were no errors and no
1361violations were found, exits with status == 0.
1362
59b05e08 1363
11f53956 1364=head1 THE L<Perl::Critic|Perl::Critic> PHILOSOPHY
b87b00dd 1365
67a7fe92
ES
1366=over
1367
11f53956
ES
1368Coding standards are deeply personal and highly subjective. The goal
1369of Perl::Critic is to help you write code that conforms with a set of
1370best practices. Our primary goal is not to dictate what those
1371practices are, but rather, to implement the practices discovered by
1372others. Ultimately, you make the rules -- Perl::Critic is merely a
1373tool for encouraging consistency. If there is a policy that you think
1374is important or that we have overlooked, we would be very grateful for
1375contributions, or you can simply load your own private set of policies
1376into Perl::Critic.
67a7fe92
ES
1377
1378=back
b87b00dd 1379
11f53956 1380
4d19da19 1381=head1 EXTENDING THE CRITIC
5deaba5e 1382
11f53956
ES
1383The modular design of Perl::Critic is intended to facilitate the
1384addition of new Policies. You'll need to have some understanding of
1385L<PPI|PPI>, but most Policy modules are pretty straightforward and
1386only require about 20 lines of code, and half of those lines are
1387simple use statements and simple declarations.. Please see the
1388L<Perl::Critic::DEVELOPER|Perl::Critic::DEVELOPER> file included in
1389this distribution for a step-by-step demonstration of how to create
1390new Policy modules.
1391
1392If you develop any new Policy modules, feel free to send them to C<<
1393<thaljef@cpan.org> >> and I'll be happy to put them into the
1394Perl::Critic distribution. Or if you would like to work on the
1395Perl::Critic project directly, check out our repository at
1396L<http://perlcritic.tigris.org>. To subscribe to our mailing list,
1397send a message to C<< <dev-subscribe@perlcritic.tigris.org> >>.
1398
1399The Perl::Critic team is also available for hire. If your
1400organization has its own coding standards, we can create custom
1401Policies to enforce your local guidelines. Or if your code base is
1402prone to a particular defect pattern, we can design Policies that will
1403help you catch those costly defects B<before> they go into production.
1404To discuss your needs with the Perl::Critic team, just contact C<<
1405<thaljef@cpan.org> >>.
1406
5deaba5e 1407
25e89cf1
ES
1408=head1 CONTACTING THE DEVELOPMENT TEAM
1409
1410You are encouraged to subscribe to the mailing list; send a message to
1411C<< <users-subscribe@perlcritic.tigris.org> >>. See also
1412L<the archives|http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
1413You can also contact the author at C<< <thaljef@cpan.org> >>.
1414
11f53956
ES
1415At least one member of the development team has started hanging around
1416in L<irc://irc.perl.org/#perlcritic>.
1417
098d393b 1418
3123bf46
ES
1419=head1 SEE ALSO
1420
11f53956
ES
1421There are a number of distributions of additional Policies available.
1422A few are listed here:
3123bf46 1423
11f53956
ES
1424L<Perl::Critic::More|Perl::Critic::More>
1425L<Perl::Critic::Bangs|Perl::Critic::Bangs>
1426L<Perl::Critic::Lax|Perl::Critic::Lax>
1427L<Perl::Critic::StricterSubs|Perl::Critic::StricterSubs>
1428L<Perl::Critic::Swift|Perl::Critic::Swift>
3123bf46 1429
d032ff5e
JRT
1430These distributions enable you to use Perl::Critic in your unit tests:
1431
11f53956
ES
1432L<Test::Perl::Critic|Test::Perl::Critic>
1433L<Test::Perl::Critic::Progressive|Test::Perl::Critic::Progressive>
d032ff5e 1434
3123bf46
ES
1435There are also a couple of distributions that will install all the
1436Perl::Critic related modules known to the development team:
1437
11f53956
ES
1438L<Bundle::Perl::Critic|Bundle::Perl::Critic>
1439L<Task::Perl::Critic|Task::Perl::Critic>
1440
3123bf46 1441
59b05e08
JRT
1442=head1 BUGS
1443
11f53956
ES
1444Scrutinizing Perl code is hard for humans, let alone machines. If you
1445find any bugs, particularly false-positives or false-negatives from a
59b05e08
JRT
1446Perl::Critic::Policy, please submit them to
1447L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
1448
fc0fffee
ES
1449Most policies will produce false-negatives if they cannot understand a
1450particular block of code.
1451
11f53956 1452
59b05e08
JRT
1453=head1 CREDITS
1454
11f53956
ES
1455Adam Kennedy - For creating L<PPI|PPI>, the heart and soul of
1456L<Perl::Critic|Perl::Critic>.
59b05e08 1457
b87b00dd 1458Damian Conway - For writing B<Perl Best Practices>, finally :)
59b05e08 1459
b87b00dd 1460Chris Dolan - For contributing the best features and Policy modules.
59b05e08 1461
7711a331
JRT
1462Andy Lester - Wise sage and master of all-things-testing.
1463
1464Elliot Shank - The self-proclaimed quality freak.
1465
b87b00dd 1466Giuseppe Maxia - For all the great ideas and positive encouragement.
59b05e08 1467
b87b00dd 1468and Sharon, my wife - For putting up with my all-night code sessions.
59b05e08 1469
11f53956 1470
59b05e08
JRT
1471=head1 AUTHOR
1472
1473Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1474
11f53956 1475
59b05e08
JRT
1476=head1 COPYRIGHT
1477
20dfddeb 1478Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
59b05e08 1479
11f53956
ES
1480This program is free software; you can redistribute it and/or modify
1481it under the same terms as Perl itself. The full text of this license
1482can be found in the LICENSE file included with this module.
59b05e08
JRT
1483
1484=cut
737d3b65 1485
7711a331 1486##############################################################################
737d3b65
CD
1487# Local Variables:
1488# mode: cperl
1489# cperl-indent-level: 4
1490# fill-column: 78
1491# indent-tabs-mode: nil
1492# c-indentation-style: bsd
1493# End:
96fed375 1494# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :