Login
Added -forced-filename option to the P::C::Document contstructor.
[gknop/Perl-Critic.git] / lib / Perl / Critic.pm
CommitLineData
6036a254 1##############################################################################
aaa8512c
JRT
2# $URL$
3# $Date$
4# $Author$
5# $Revision$
6036a254 6##############################################################################
aaa8512c 7
59b05e08
JRT
8package Perl::Critic;
9
df6dee2b 10use 5.006001;
59b05e08
JRT
11use strict;
12use warnings;
712f83ea 13
c680a9c9 14use English qw(-no_match_vars);
c680a9c9
ES
15use Readonly;
16
f7f62580
JRT
17use base qw(Exporter);
18
59b05e08 19use File::Spec;
8e6c2096 20use List::MoreUtils qw< firstidx >;
8e6c2096 21use Scalar::Util qw< blessed >;
c680a9c9 22
558488f7 23use Perl::Critic::Exception::Configuration::Generic;
59b05e08 24use Perl::Critic::Config;
dc93df4f 25use Perl::Critic::Violation;
5bf96118 26use Perl::Critic::Document;
2ce0b9ee 27use Perl::Critic::Statistics;
8e6c2096 28use Perl::Critic::Utils qw< :characters hashify shebang_line >;
59b05e08 29
6036a254 30#-----------------------------------------------------------------------------
f7f62580 31
e7bc8e2b 32our $VERSION = '1.110';
c680a9c9 33
70f3f307 34Readonly::Array our @EXPORT_OK => qw(critique);
f7f62580 35
d5835ca8
JRT
36#=============================================================================
37# PUBLIC methods
dff08b70 38
59b05e08 39sub new {
59b05e08 40 my ( $class, %args ) = @_;
e01de056 41 my $self = bless {}, $class;
1e7b8681 42 $self->{_config} = $args{-config} || Perl::Critic::Config->new( %args );
2ce0b9ee 43 $self->{_stats} = Perl::Critic::Statistics->new();
59b05e08
JRT
44 return $self;
45}
46
6036a254 47#-----------------------------------------------------------------------------
59b05e08 48
dff08b70
JRT
49sub config {
50 my $self = shift;
51 return $self->{_config};
52}
59b05e08 53
6036a254 54#-----------------------------------------------------------------------------
59b05e08 55
dff08b70
JRT
56sub add_policy {
57 my ( $self, @args ) = @_;
58 #Delegate to Perl::Critic::Config
59 return $self->config()->add_policy( @args );
60}
59b05e08 61
6036a254 62#-----------------------------------------------------------------------------
dff08b70
JRT
63
64sub policies {
65 my $self = shift;
46a3f49d 66
dff08b70
JRT
67 #Delegate to Perl::Critic::Config
68 return $self->config()->policies();
59b05e08
JRT
69}
70
6036a254 71#-----------------------------------------------------------------------------
dff08b70 72
2ce0b9ee
JRT
73sub statistics {
74 my $self = shift;
75 return $self->{_stats};
76}
77
78#-----------------------------------------------------------------------------
79
937b8de0 80sub critique { ## no critic (ArgUnpacking)
7ed796a7 81
f7f62580
JRT
82 #-------------------------------------------------------------------
83 # This subroutine can be called as an object method or as a static
84 # function. In the latter case, the first argument can be a
85 # hashref of configuration parameters that shall be used to create
86 # an object behind the scenes. Note that this object does not
87 # persist. In other words, it is not a singleton. Here are some
88 # of the ways this subroutine might get called:
89 #
90 # #Object style...
91 # $critic->critique( $code );
92 #
93 # #Functional style...
94 # critique( $code );
95 # critique( {}, $code );
96 # critique( {-foo => bar}, $code );
97 #------------------------------------------------------------------
98
99 my ( $self, $source_code ) = @_ >= 2 ? @_ : ( {}, $_[0] );
100 $self = ref $self eq 'HASH' ? __PACKAGE__->new(%{ $self }) : $self;
de2dc641 101 return if not defined $source_code; # If no code, then nothing to do.
59b05e08 102
d533eee5 103 my $config = $self->config();
1b936936
ES
104 my $doc =
105 blessed($source_code) && $source_code->isa('Perl::Critic::Document')
106 ? $source_code
107 : Perl::Critic::Document->new(
108 '-source' => $source_code,
109 '-program-extensions' => [$config->program_extensions_as_regexes()],
110 );
576f6411 111
558488f7
ES
112 if ( 0 == $self->policies() ) {
113 Perl::Critic::Exception::Configuration::Generic->throw(
114 message => 'There are no enabled policies.',
115 )
116 }
117
576f6411
ES
118 return $self->_gather_violations($doc);
119}
120
576f6411 121#=============================================================================
d5835ca8 122# PRIVATE methods
576f6411
ES
123
124sub _gather_violations {
125 my ($self, $doc) = @_;
5bf96118 126
937b8de0 127 # Disable exempt code lines, if desired
dc93df4f 128 if ( not $self->config->force() ) {
d5835ca8 129 $doc->process_annotations();
7ed796a7 130 }
1e7b8681 131
e58ec45b 132 # Evaluate each policy
46a3f49d 133 my @policies = $self->config->policies();
d5835ca8
JRT
134 my @ordered_policies = _futz_with_policy_order(@policies);
135 my @violations = map { _critique($_, $doc) } @ordered_policies;
dc93df4f 136
2ce0b9ee
JRT
137 # Accumulate statistics
138 $self->statistics->accumulate( $doc, \@violations );
139
e58ec45b
JRT
140 # If requested, rank violations by their severity and return the top N.
141 if ( @violations && (my $top = $self->config->top()) ) {
142 my $limit = @violations < $top ? $#violations : $top-1;
143 @violations = Perl::Critic::Violation::sort_by_severity(@violations);
144 @violations = ( reverse @violations )[ 0 .. $limit ]; #Slicing...
145 }
dc93df4f 146
e58ec45b
JRT
147 # Always return violations sorted by location
148 return Perl::Critic::Violation->sort_by_location(@violations);
149}
1bef6e21 150
d5835ca8
JRT
151#=============================================================================
152# PRIVATE functions
c70a9ff6 153
e58ec45b 154sub _critique {
937b8de0 155 my ($policy, $doc) = @_;
bb5a5c57 156
78afb6d4 157 return if not $policy->prepare_to_scan_document($doc);
bb5a5c57 158
6b79d701 159 my $maximum_violations = $policy->get_maximum_violations_per_document();
dd352433 160 return if defined $maximum_violations && $maximum_violations == 0;
c70a9ff6 161
bb5a5c57 162 my @violations = ();
f409e8e7 163
e58ec45b
JRT
164 TYPE:
165 for my $type ( $policy->applies_to() ) {
82c2b90a
ES
166 my @elements;
167 if ($type eq 'PPI::Document') {
168 @elements = ($doc);
169 }
170 else {
171 @elements = @{ $doc->find($type) || [] };
172 }
e01de056 173
e58ec45b 174 ELEMENT:
82c2b90a 175 for my $element (@elements) {
e58ec45b
JRT
176
177 # Evaluate the policy on this $element. A policy may
178 # return zero or more violations. We only want the
179 # violations that occur on lines that have not been
180 # disabled.
181
182 VIOLATION:
183 for my $violation ( $policy->violates( $element, $doc ) ) {
2d2fd196 184
e58ec45b 185 my $line = $violation->location()->[0];
d5835ca8
JRT
186 if ( $doc->line_is_disabled_for_policy($line, $policy) ) {
187 $doc->add_suppressed_violation($violation);
188 next VIOLATION;
189 }
6b79d701 190
e58ec45b 191 push @violations, $violation;
2d2fd196 192 last TYPE if defined $maximum_violations and @violations >= $maximum_violations;
e58ec45b
JRT
193 }
194 }
e01de056
JRT
195 }
196
e58ec45b 197 return @violations;
59b05e08
JRT
198}
199
e58ec45b 200#-----------------------------------------------------------------------------
59b05e08 201
d5835ca8 202sub _futz_with_policy_order {
d5835ca8
JRT
203 # The ProhibitUselessNoCritic policy is another special policy. It
204 # deals with the violations that *other* Policies produce. Therefore
205 # it needs to be run *after* all the other Policies. TODO: find
206 # a way for Policies to express an ordering preference somehow.
207
208 my @policy_objects = @_;
209 my $magical_policy_name = 'Perl::Critic::Policy::Miscellanea::ProhibitUselessNoCritic';
210 my $idx = firstidx {ref $_ eq $magical_policy_name} @policy_objects;
211 push @policy_objects, splice @policy_objects, $idx, 1;
212 return @policy_objects;
213}
214
215#-----------------------------------------------------------------------------
216
1771d650
JRT
2171;
218
219
220
59b05e08
JRT
221__END__
222
223=pod
224
12b6fa9c 225=for stopwords DGR INI-style API -params pbp refactored ActivePerl ben Jore
a166ea66 226Dolan's Twitter Alexandr Ciornii Ciornii's downloadable
821d0eb5 227
59b05e08
JRT
228=head1 NAME
229
c728943a 230Perl::Critic - Critique Perl source code for best-practices.
59b05e08 231
df89052a 232
59b05e08
JRT
233=head1 SYNOPSIS
234
d5ff35da
ES
235 use Perl::Critic;
236 my $file = shift;
237 my $critic = Perl::Critic->new();
238 my @violations = $critic->critique($file);
239 print @violations;
59b05e08 240
df89052a 241
59b05e08
JRT
242=head1 DESCRIPTION
243
11f53956
ES
244Perl::Critic is an extensible framework for creating and applying
245coding standards to Perl source code. Essentially, it is a static
246source code analysis engine. Perl::Critic is distributed with a
247number of L<Perl::Critic::Policy|Perl::Critic::Policy> modules that
248attempt to enforce various coding guidelines. Most Policy modules are
249based on Damian Conway's book B<Perl Best Practices>. However,
250Perl::Critic is B<not> limited to PBP and will even support Policies
251that contradict Conway. You can enable, disable, and customize those
252Polices through the Perl::Critic interface. You can also create new
253Policy modules that suit your own tastes.
254
255For a command-line interface to Perl::Critic, see the documentation
256for L<perlcritic|perlcritic>. If you want to integrate Perl::Critic
257with your build process, L<Test::Perl::Critic|Test::Perl::Critic>
1b936936 258provides an interface that is suitable for test programs. Also,
11f53956
ES
259L<Test::Perl::Critic::Progressive|Test::Perl::Critic::Progressive> is
260useful for gradually applying coding standards to legacy code. For
261the ultimate convenience (at the expense of some flexibility) see the
262L<criticism|criticism> pragma.
263
ee8669e7
ES
264Win32 and ActivePerl users can find PPM distributions of Perl::Critic at
265L<http://theoryx5.uwinnipeg.ca/ppms/> and Alexandr Ciornii's downloadable
266executable at L<http://chorny.net/perl/perlcritic.html>.
11f53956
ES
267
268If you'd like to try L<Perl::Critic|Perl::Critic> without installing
269anything, there is a web-service available at
270L<http://perlcritic.com>. The web-service does not yet support all
271the configuration features that are available in the native
272Perl::Critic API, but it should give you a good idea of what it does.
273You can also invoke the perlcritic web-service from the command-line
274by doing an HTTP-post, such as one of these:
e518ead4 275
d5ff35da
ES
276 $> POST http://perlcritic.com/perl/critic.pl < MyModule.pm
277 $> lwp-request -m POST http://perlcritic.com/perl/critic.pl < MyModule.pm
278 $> wget -q -O - --post-file=MyModule.pm http://perlcritic.com/perl/critic.pl
e518ead4 279
11f53956
ES
280Please note that the perlcritic web-service is still alpha code. The
281URL and interface to the service are subject to change.
8d36cd6f 282
8b8e5bfa
JRT
283Also, the Perl Development Kit (PDK 8.0) from ActiveState includes a very
284slick graphical interface to Perl-Critic. For details, go to
285L<http://www.activestate.com/perl_dev_kit>
286
df89052a 287
4444d94d
ES
288=head1 INTERFACE SUPPORT
289
290This is considered to be a public class. Any changes to its interface
291will go through a deprecation cycle.
292
293
59b05e08
JRT
294=head1 CONSTRUCTOR
295
df89052a 296=over
59b05e08 297
8eda4318 298=item C<< new( [ -profile => $FILE, -severity => $N, -theme => $string, -include => \@PATTERNS, -exclude => \@PATTERNS, -top => $N, -only => $B, -profile-strictness => $PROFILE_STRICTNESS_{WARN|FATAL|QUIET}, -force => $B, -verbose => $N ], -color => $B, -pager => $string, -allow-unsafe => $B, -criticism-fatal => $B) >>
7b84ff16 299
7b84ff16 300=item C<< new() >>
59b05e08 301
11f53956
ES
302Returns a reference to a new Perl::Critic object. Most arguments are
303just passed directly into
304L<Perl::Critic::Config|Perl::Critic::Config>, but I have described
305them here as well. The default value for all arguments can be defined
306in your F<.perlcriticrc> file. See the L<"CONFIGURATION"> section for
307more information about that. All arguments are optional key-value
308pairs as follows:
309
310B<-profile> is a path to a configuration file. If C<$FILE> is not
311defined, Perl::Critic::Config attempts to find a F<.perlcriticrc>
312configuration file in the current directory, and then in your home
313directory. Alternatively, you can set the C<PERLCRITIC> environment
314variable to point to a file in another location. If a configuration
315file can't be found, or if C<$FILE> is an empty string, then all
316Policies will be loaded with their default configuration. See
317L<"CONFIGURATION"> for more information.
318
319B<-severity> is the minimum severity level. Only Policy modules that
320have a severity greater than C<$N> will be applied. Severity values
be6f837f
ES
321are integers ranging from 1 (least severe violations) to 5 (most
322severe violations). The default is 5. For a given C<-profile>,
323decreasing the C<-severity> will usually reveal more Policy violations.
324You can set the default value for this option in your F<.perlcriticrc>
325file. Users can redefine the severity level for any Policy in their
326F<.perlcriticrc> file. See L<"CONFIGURATION"> for more information.
11f53956
ES
327
328If it is difficult for you to remember whether severity "5" is the
329most or least restrictive level, then you can use one of these named
330values:
097f3455 331
7711a331 332 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
097f3455
JRT
333 --------------------------------------------------------
334 -severity => 'gentle' -severity => 5
335 -severity => 'stern' -severity => 4
336 -severity => 'harsh' -severity => 3
337 -severity => 'cruel' -severity => 2
338 -severity => 'brutal' -severity => 1
339
11f53956
ES
340B<-theme> is special expression that determines which Policies to
341apply based on their respective themes. For example, the following
342would load only Policies that have a 'bugs' AND 'pbp' theme:
7b84ff16 343
1c5955e4
JRT
344 my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );
345
11f53956
ES
346Unless the C<-severity> option is explicitly given, setting C<-theme>
347silently causes the C<-severity> to be set to 1. You can set the
348default value for this option in your F<.perlcriticrc> file. See the
349L<"POLICY THEMES"> section for more information about themes.
7b84ff16 350
7b84ff16 351
11f53956 352B<-include> is a reference to a list of string C<@PATTERNS>. Policy
f135623f 353modules that match at least one C<m/$PATTERN/ixms> will always be
11f53956 354loaded, irrespective of all other settings. For example:
6bf9b465 355
d5ff35da 356 my $critic = Perl::Critic->new(-include => ['layout'] -severity => 4);
6bf9b465 357
11f53956
ES
358This would cause Perl::Critic to apply all the C<CodeLayout::*> Policy
359modules even though they have a severity level that is less than 4.
360You can set the default value for this option in your F<.perlcriticrc>
361file. You can also use C<-include> in conjunction with the
362C<-exclude> option. Note that C<-exclude> takes precedence over
363C<-include> when a Policy matches both patterns.
6bf9b465 364
11f53956 365B<-exclude> is a reference to a list of string C<@PATTERNS>. Policy
f135623f 366modules that match at least one C<m/$PATTERN/ixms> will not be loaded,
11f53956 367irrespective of all other settings. For example:
6bf9b465 368
d5ff35da 369 my $critic = Perl::Critic->new(-exclude => ['strict'] -severity => 1);
6bf9b465 370
1edbd692 371This would cause Perl::Critic to not apply the C<RequireUseStrict> and
11f53956
ES
372C<ProhibitNoStrict> Policy modules even though they have a severity
373level that is greater than 1. You can set the default value for this
374option in your F<.perlcriticrc> file. You can also use C<-exclude> in
375conjunction with the C<-include> option. Note that C<-exclude> takes
376precedence over C<-include> when a Policy matches both patterns.
377
378B<-single-policy> is a string C<PATTERN>. Only one policy that
f135623f 379matches C<m/$PATTERN/ixms> will be used. Policies that do not match
11f53956
ES
380will be excluded. This option has precedence over the C<-severity>,
381C<-theme>, C<-include>, C<-exclude>, and C<-only> options. You can
382set the default value for this option in your F<.perlcriticrc> file.
383
384B<-top> is the maximum number of Violations to return when ranked by
385their severity levels. This must be a positive integer. Violations
386are still returned in the order that they occur within the file.
387Unless the C<-severity> option is explicitly given, setting C<-top>
388silently causes the C<-severity> to be set to 1. You can set the
389default value for this option in your F<.perlcriticrc> file.
390
391B<-only> is a boolean value. If set to a true value, Perl::Critic
392will only choose from Policies that are mentioned in the user's
393profile. If set to a false value (which is the default), then
394Perl::Critic chooses from all the Policies that it finds at your site.
395You can set the default value for this option in your F<.perlcriticrc>
396file.
e01de056 397
9f12283e
ES
398B<-profile-strictness> is an enumerated value, one of
399L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_WARN"> (the
400default),
401L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">, and
402L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET">. If set
403to L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_FATAL">,
404Perl::Critic will make certain warnings about problems found in a
405F<.perlcriticrc> or file specified via the B<-profile> option fatal.
406For example, Perl::Critic normally only C<warn>s about profiles
407referring to non-existent Policies, but this value makes this
408situation fatal. Correspondingly,
409L<Perl::Critic::Utils::Constants/"$PROFILE_STRICTNESS_QUIET"> makes
410Perl::Critic shut up about these things.
66186ba3 411
11f53956 412B<-force> is a boolean value that controls whether Perl::Critic
d1237298 413observes the magical C<"## no critic"> annotations in your code.
11f53956
ES
414If set to a true value, Perl::Critic will analyze all code. If set to
415a false value (which is the default) Perl::Critic will ignore code
d1237298 416that is tagged with these annotations. See L<"BENDING THE RULES"> for
11f53956
ES
417more information. You can set the default value for this option in
418your F<.perlcriticrc> file.
59b05e08 419
11f53956
ES
420B<-verbose> can be a positive integer (from 1 to 11), or a literal
421format specification. See
422L<Perl::Critic::Violation|Perl::Critic::Violation> for an explanation
423of format specifications. You can set the default value for this
424option in your F<.perlcriticrc> file.
7b84ff16 425
8d392dd5
JRT
426B<-unsafe> directs Perl::Critic to allow the use of Policies that are marked
427as "unsafe" by the author. Such policies may compile untrusted code or do
428other nefarious things.
429
89b50090 430B<-color> and B<-pager> are not used by Perl::Critic but is provided for the benefit
11f53956 431of L<perlcritic|perlcritic>.
25792f52 432
11f53956
ES
433B<-criticism-fatal> is not used by Perl::Critic but is provided for
434the benefit of L<criticism|criticism>.
badbf753 435
172f00ec
TW
436B<-color-severity-highest>, B<-color-severity-high>,
437B<-color-severity-medium>, B<-color-severity-low>, and
438B<-color-severity-lowest> are not used by Perl::Critic, but are provided for
439the benefit of L<perlcritic|perlcritic>. Each is set to the Term::ANSIColor
440color specification to be used to display violations of the corresponding
441severity.
442
94f7eff2
ES
443B<-files-with-violations> and B<-files-without-violations> are not used by
444Perl::Critic, but are provided for the benefit of L<perlcritic|perlcritic>, to
445cause only the relevant filenames to be displayed.
446
59b05e08
JRT
447=back
448
df89052a 449
59b05e08
JRT
450=head1 METHODS
451
df89052a 452=over
59b05e08 453
6d9feae6 454=item C<critique( $source_code )>
1e7b8681
JRT
455
456Runs the C<$source_code> through the Perl::Critic engine using all the
11f53956
ES
457Policies that have been loaded into this engine. If C<$source_code>
458is a scalar reference, then it is treated as a string of actual Perl
459code. If C<$source_code> is a reference to an instance of
460L<PPI::Document|PPI::Document>, then that instance is used directly.
461Otherwise, it is treated as a path to a local file containing Perl
462code. This method returns a list of
463L<Perl::Critic::Violation|Perl::Critic::Violation> objects for each
464violation of the loaded Policies. The list is sorted in the order
465that the Violations appear in the code. If there are no violations,
466this method returns an empty list.
1e7b8681 467
520f00c6 468=item C<< add_policy( -policy => $policy_name, -params => \%param_hash ) >>
59b05e08 469
11f53956
ES
470Creates a Policy object and loads it into this Critic. If the object
471cannot be instantiated, it will throw a fatal exception. Otherwise,
472it returns a reference to this Critic.
59b05e08 473
11f53956
ES
474B<-policy> is the name of a
475L<Perl::Critic::Policy|Perl::Critic::Policy> subclass module. The
476C<'Perl::Critic::Policy'> portion of the name can be omitted for
477brevity. This argument is required.
59b05e08 478
11f53956
ES
479B<-params> is an optional reference to a hash of Policy parameters.
480The contents of this hash reference will be passed into to the
481constructor of the Policy module. See the documentation in the
482relevant Policy module for a description of the arguments it supports.
59b05e08 483
dc93df4f 484=item C< policies() >
59b05e08 485
11f53956
ES
486Returns a list containing references to all the Policy objects that
487have been loaded into this engine. Objects will be in the order that
488they were loaded.
59b05e08 489
dc93df4f 490=item C< config() >
dff08b70 491
11f53956
ES
492Returns the L<Perl::Critic::Config|Perl::Critic::Config> object that
493was created for or given to this Critic.
dff08b70 494
2ce0b9ee
JRT
495=item C< statistics() >
496
11f53956
ES
497Returns the L<Perl::Critic::Statistics|Perl::Critic::Statistics>
498object that was created for this Critic. The Statistics object
499accumulates data for all files that are analyzed by this Critic.
2ce0b9ee 500
59b05e08
JRT
501=back
502
df89052a 503
f7f62580
JRT
504=head1 FUNCTIONAL INTERFACE
505
11f53956
ES
506For those folks who prefer to have a functional interface, The
507C<critique> method can be exported on request and called as a static
508function. If the first argument is a hashref, its contents are used
509to construct a new Perl::Critic object internally. The keys of that
510hash should be the same as those supported by the C<Perl::Critic::new>
511method. Here are some examples:
f7f62580 512
d5ff35da 513 use Perl::Critic qw(critique);
f7f62580 514
d5ff35da
ES
515 # Use default parameters...
516 @violations = critique( $some_file );
f7f62580 517
d5ff35da
ES
518 # Use custom parameters...
519 @violations = critique( {-severity => 2}, $some_file );
f7f62580 520
d5ff35da
ES
521 # As a one-liner
522 %> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm
d47377d5 523
f7f62580
JRT
524None of the other object-methods are currently supported as static
525functions. Sorry.
526
df89052a 527
59b05e08
JRT
528=head1 CONFIGURATION
529
11f53956
ES
530Most of the settings for Perl::Critic and each of the Policy modules
531can be controlled by a configuration file. The default configuration
532file is called F<.perlcriticrc>. Perl::Critic will look for this file
533in the current directory first, and then in your home directory.
534Alternatively, you can set the C<PERLCRITIC> environment variable to
535explicitly point to a different file in another location. If none of
536these files exist, and the C<-profile> option is not given to the
537constructor, then all the modules that are found in the
7b84ff16
JRT
538Perl::Critic::Policy namespace will be loaded with their default
539configuration.
540
11f53956
ES
541The format of the configuration file is a series of INI-style blocks
542that contain key-value pairs separated by '='. Comments should start
543with '#' and can be placed on a separate line or after the name-value
544pairs if you desire.
7b84ff16 545
11f53956
ES
546Default settings for Perl::Critic itself can be set B<before the first
547named block.> For example, putting any or all of these at the top of
548your configuration file will set the default value for the
549corresponding constructor argument.
7b84ff16 550
097f3455 551 severity = 3 #Integer or named level
c3b1b521
JRT
552 only = 1 #Zero or One
553 force = 0 #Zero or One
554 verbose = 4 #Integer or format spec
555 top = 50 #A positive integer
1edbd692 556 theme = (pbp || security) && bugs #A theme expression
c3b1b521
JRT
557 include = NamingConventions ClassHierarchies #Space-delimited list
558 exclude = Variables Modules::RequirePackage #Space-delimited list
badbf753 559 criticism-fatal = 1 #Zero or One
51ae9d9b 560 color = 1 #Zero or One
8eda4318 561 allow-unsafe = 1 #Zero or One
89b50090 562 pager = less #pager to pipe output to
7b84ff16 563
11f53956
ES
564The remainder of the configuration file is a series of blocks like
565this:
59b05e08 566
7b84ff16
JRT
567 [Perl::Critic::Policy::Category::PolicyName]
568 severity = 1
4cd0567c 569 set_themes = foo bar
c94fb804 570 add_themes = baz
35ab5036 571 maximum_violations_per_document = 57
7b84ff16
JRT
572 arg1 = value1
573 arg2 = value2
59b05e08 574
11f53956
ES
575C<Perl::Critic::Policy::Category::PolicyName> is the full name of a
576module that implements the policy. The Policy modules distributed
577with Perl::Critic have been grouped into categories according to the
578table of contents in Damian Conway's book B<Perl Best Practices>. For
579brevity, you can omit the C<'Perl::Critic::Policy'> part of the module
580name.
581
582C<severity> is the level of importance you wish to assign to the
583Policy. All Policy modules are defined with a default severity value
584ranging from 1 (least severe) to 5 (most severe). However, you may
585disagree with the default severity and choose to give it a higher or
586lower severity, based on your own coding philosophy. You can set the
587C<severity> to an integer from 1 to 5, or use one of the equivalent
588names:
097f3455 589
7711a331 590 SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
097f3455
JRT
591 ----------------------------------------------------
592 gentle 5
593 stern 4
594 harsh 3
595 cruel 2
596 brutal 1
597
11f53956
ES
598C<set_themes> sets the theme for the Policy and overrides its default
599theme. The argument is a string of one or more whitespace-delimited
600alphanumeric words. Themes are case-insensitive. See L<"POLICY
601THEMES"> for more information.
097f3455 602
11f53956
ES
603C<add_themes> appends to the default themes for this Policy. The
604argument is a string of one or more whitespace-delimited words.
605Themes are case-insensitive. See L<"POLICY THEMES"> for more
606information.
59b05e08 607
11f53956
ES
608C<maximum_violations_per_document> limits the number of Violations the
609Policy will return for a given document. Some Policies have a default
610limit; see the documentation for the individual Policies to see
611whether there is one. To force a Policy to not have a limit, specify
612"no_limit" or the empty string for the value of this parameter.
35ab5036 613
11f53956
ES
614The remaining key-value pairs are configuration parameters that will
615be passed into the constructor for that Policy. The constructors for
616most Policy objects do not support arguments, and those that do should
617have reasonable defaults. See the documentation on the appropriate
618Policy module for more details.
59b05e08 619
11f53956
ES
620Instead of redefining the severity for a given Policy, you can
621completely disable a Policy by prepending a '-' to the name of the
622module in your configuration file. In this manner, the Policy will
623never be loaded, regardless of the C<-severity> given to the
624Perl::Critic constructor.
59b05e08
JRT
625
626A simple configuration might look like this:
627
7b84ff16
JRT
628 #--------------------------------------------------------------
629 # I think these are really important, so always load them
630
631 [TestingAndDebugging::RequireUseStrict]
632 severity = 5
59b05e08 633
7b84ff16
JRT
634 [TestingAndDebugging::RequireUseWarnings]
635 severity = 5
59b05e08 636
7b84ff16
JRT
637 #--------------------------------------------------------------
638 # I think these are less important, so only load when asked
59b05e08 639
7b84ff16
JRT
640 [Variables::ProhibitPackageVars]
641 severity = 2
59b05e08 642
7b84ff16 643 [ControlStructures::ProhibitPostfixControls]
097f3455
JRT
644 allow = if unless # My custom configuration
645 severity = cruel # Same as "severity = 2"
59b05e08 646
7b84ff16
JRT
647 #--------------------------------------------------------------
648 # Give these policies a custom theme. I can activate just
649 # these policies by saying `perlcritic -theme larry`
59b05e08 650
7b84ff16 651 [Modules::RequireFilenameMatchesPackage]
c94fb804 652 add_themes = larry
59b05e08 653
7b84ff16 654 [TestingAndDebugging::RequireTestLables]
c94fb804 655 add_themes = larry curly moe
59b05e08 656
7b84ff16
JRT
657 #--------------------------------------------------------------
658 # I do not agree with these at all, so never load them
1e7b8681 659
d5ff35da
ES
660 [-NamingConventions::Capitalization]
661 [-ValuesAndExpressions::ProhibitMagicNumbers]
7b84ff16
JRT
662
663 #--------------------------------------------------------------
664 # For all other Policies, I accept the default severity,
665 # so no additional configuration is required for them.
8bc162ba 666
b87fc7eb 667For additional configuration examples, see the F<perlcriticrc> file
16cfe89e 668that is included in this F<examples> directory of this distribution.
b87fc7eb 669
11f53956
ES
670Damian Conway's own Perl::Critic configuration is also included in
671this distribution as F<examples/perlcriticrc-conway>.
e87a2153 672
df89052a 673
59b05e08
JRT
674=head1 THE POLICIES
675
11f53956
ES
676A large number of Policy modules are distributed with Perl::Critic.
677They are described briefly in the companion document
678L<Perl::Critic::PolicySummary|Perl::Critic::PolicySummary> and in more
679detail in the individual modules themselves. Say C<"perlcritic -doc
680PATTERN"> to see the perldoc for all Policy modules that match the
f135623f 681regex C<m/PATTERN/ixms>
38ce10c1 682
11f53956
ES
683There are a number of distributions of additional policies on CPAN.
684If L<Perl::Critic|Perl::Critic> doesn't contain a policy that you
685want, some one may have already written it. See the L</"SEE ALSO">
686section below for a list of some of these distributions.
a41e8614 687
7b84ff16 688
7711a331 689=head1 POLICY THEMES
2c2751eb 690
11f53956
ES
691Each Policy is defined with one or more "themes". Themes can be used
692to create arbitrary groups of Policies. They are intended to provide
693an alternative mechanism for selecting your preferred set of Policies.
694For example, you may wish disable a certain subset of Policies when
1b936936 695analyzing test programs. Conversely, you may wish to enable only a
11f53956 696specific subset of Policies when analyzing modules.
7b84ff16 697
be6f837f 698The Policies that ship with Perl::Critic have been broken into the
11f53956
ES
699following themes. This is just our attempt to provide some basic
700logical groupings. You are free to invent new themes that suit your
701needs.
c8dbb393
JRT
702
703 THEME DESCRIPTION
704 --------------------------------------------------------------------------
705 core All policies that ship with Perl::Critic
706 pbp Policies that come directly from "Perl Best Practices"
707 bugs Policies that that prevent or reveal bugs
708 maintenance Policies that affect the long-term health of the code
709 cosmetic Policies that only have a superficial effect
710 complexity Policies that specificaly relate to code complexity
7711a331 711 security Policies that relate to security issues
1b936936 712 tests Policies that are specific to test programs
c8dbb393
JRT
713
714
11f53956
ES
715Any Policy may fit into multiple themes. Say C<"perlcritic -list"> to
716get a listing of all available Policies and the themes that are
717associated with each one. You can also change the theme for any
718Policy in your F<.perlcriticrc> file. See the L<"CONFIGURATION">
719section for more information about that.
7b84ff16 720
11f53956
ES
721Using the C<-theme> option, you can create an arbitrarily complex rule
722that determines which Policies will be loaded. Precedence is the same
723as regular Perl code, and you can use parentheses to enforce
724precedence as well. Supported operators are:
7b84ff16 725
d5ff35da
ES
726 Operator Altertative Example
727 -----------------------------------------------------------------
728 && and 'pbp && core'
729 || or 'pbp || (bugs && security)'
730 ! not 'pbp && ! (portability || complexity)'
7b84ff16 731
11f53956
ES
732Theme names are case-insensitive. If the C<-theme> is set to an empty
733string, then it evaluates as true all Policies.
7b84ff16 734
df89052a 735
59b05e08
JRT
736=head1 BENDING THE RULES
737
11f53956
ES
738Perl::Critic takes a hard-line approach to your code: either you
739comply or you don't. In the real world, it is not always practical
740(nor even possible) to fully comply with coding standards. In such
741cases, it is wise to show that you are knowingly violating the
742standards and that you have a Damn Good Reason (DGR) for doing so.
59b05e08 743
11f53956 744To help with those situations, you can direct Perl::Critic to ignore
d1237298 745certain lines or blocks of code by using annotations:
59b05e08
JRT
746
747 require 'LegacyLibaray1.pl'; ## no critic
748 require 'LegacyLibrary2.pl'; ## no critic
749
750 for my $element (@list) {
751
752 ## no critic
753
754 $foo = ""; #Violates 'ProhibitEmptyQuotes'
755 $barf = bar() if $foo; #Violates 'ProhibitPostfixControls'
756 #Some more evil code...
757
758 ## use critic
759
760 #Some good code...
761 do_something($_);
762 }
763
1bb70384
ES
764The C<"## no critic"> annotations direct Perl::Critic to ignore the remaining
765lines of code until a C<"## use critic"> annotation is found. If the C<"## no
766critic"> annotation is on the same line as a code statement, then only that
767line of code is overlooked. To direct perlcritic to ignore the C<"## no
768critic"> annotations, use the C<--force> option.
11f53956 769
d1237298 770A bare C<"## no critic"> annotation disables all the active Policies. If
11f53956
ES
771you wish to disable only specific Policies, add a list of Policy names
772as arguments, just as you would for the C<"no strict"> or C<"no
773warnings"> pragmas. For example, this would disable the
774C<ProhibitEmptyQuotes> and C<ProhibitPostfixControls> policies until
d1237298 775the end of the block or until the next C<"## use critic"> annotation
11f53956 776(whichever comes first):
c70a9ff6 777
d5ff35da 778 ## no critic (EmptyQuotes, PostfixControls)
c70a9ff6 779
d5ff35da
ES
780 # Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
781 $foo = "";
7711a331 782
d5ff35da
ES
783 # Now exempt ControlStructures::ProhibitPostfixControls
784 $barf = bar() if $foo;
c70a9ff6 785
d5ff35da
ES
786 # Still subjected to ValuesAndExpression::RequireNumberSeparators
787 $long_int = 10000000000;
7711a331 788
11f53956
ES
789Since the Policy names are matched against the C<"## no critic">
790arguments as regular expressions, you can abbreviate the Policy names
791or disable an entire family of Policies in one shot like this:
c70a9ff6 792
d5ff35da 793 ## no critic (NamingConventions)
c70a9ff6 794
d5ff35da
ES
795 # Now exempt from NamingConventions::Capitalization
796 my $camelHumpVar = 'foo';
7711a331 797
d5ff35da
ES
798 # Now exempt from NamingConventions::Capitalization
799 sub camelHumpSub {}
c70a9ff6 800
11f53956
ES
801The argument list must be enclosed in parentheses and must contain one
802or more comma-separated barewords (e.g. don't use quotes). The
d1237298
JRT
803C<"## no critic"> annotations can be nested, and Policies named by an
804inner annotation will be disabled along with those already disabled an
805outer annotation.
c70a9ff6 806
11f53956
ES
807Some Policies like C<Subroutines::ProhibitExcessComplexity> apply to
808an entire block of code. In those cases, C<"## no critic"> must
809appear on the line where the violation is reported. For example:
35892a39 810
d5ff35da
ES
811 sub complicated_function { ## no critic (ProhibitExcessComplexity)
812 # Your code here...
813 }
35892a39 814
11f53956
ES
815Policies such as C<Documentation::RequirePodSections> apply to the
816entire document, in which case violations are reported at line 1.
35892a39 817
d1237298 818Use this feature wisely. C<"## no critic"> annotations should be used in the
11f53956 819smallest possible scope, or only on individual lines of code. And you
d1237298 820should always be as specific as possible about which Policies you want
11f53956
ES
821to disable (i.e. never use a bare C<"## no critic">). If Perl::Critic
822complains about your code, try and find a compliant solution before
823resorting to this feature.
1c5955e4 824
1bef6e21 825
11f53956 826=head1 THE L<Perl::Critic|Perl::Critic> PHILOSOPHY
b87b00dd 827
11f53956
ES
828Coding standards are deeply personal and highly subjective. The goal
829of Perl::Critic is to help you write code that conforms with a set of
830best practices. Our primary goal is not to dictate what those
831practices are, but rather, to implement the practices discovered by
832others. Ultimately, you make the rules -- Perl::Critic is merely a
833tool for encouraging consistency. If there is a policy that you think
834is important or that we have overlooked, we would be very grateful for
835contributions, or you can simply load your own private set of policies
836into Perl::Critic.
b87b00dd 837
df89052a 838
59b05e08
JRT
839=head1 EXTENDING THE CRITIC
840
11f53956
ES
841The modular design of Perl::Critic is intended to facilitate the
842addition of new Policies. You'll need to have some understanding of
843L<PPI|PPI>, but most Policy modules are pretty straightforward and
844only require about 20 lines of code. Please see the
845L<Perl::Critic::DEVELOPER|Perl::Critic::DEVELOPER> file included in
846this distribution for a step-by-step demonstration of how to create
847new Policy modules.
59b05e08 848
524bce7c 849If you develop any new Policy modules, feel free to send them to C<<
03887e5e 850<jeff@imaginative-software.com> >> and I'll be happy to put them into the
11f53956
ES
851Perl::Critic distribution. Or if you would like to work on the
852Perl::Critic project directly, check out our repository at
853L<http://perlcritic.tigris.org>. To subscribe to our mailing list,
4aaebfba 854send a message to L<mailto:dev-subscribe@perlcritic.tigris.org>.
524bce7c 855
11f53956
ES
856The Perl::Critic team is also available for hire. If your
857organization has its own coding standards, we can create custom
858Policies to enforce your local guidelines. Or if your code base is
859prone to a particular defect pattern, we can design Policies that will
860help you catch those costly defects B<before> they go into production.
861To discuss your needs with the Perl::Critic team, just contact C<<
03887e5e 862<jeff@imaginative-software.com> >>.
59b05e08 863
df89052a 864
59b05e08
JRT
865=head1 PREREQUISITES
866
867Perl::Critic requires the following modules:
868
11f53956 869L<B::Keywords|B::Keywords>
1edbd692 870
11f53956 871L<Config::Tiny|Config::Tiny>
59b05e08 872
e177ebf8
ES
873L<Email::Address|Email::Address>
874
11f53956 875L<Exception::Class|Exception::Class>
f7bb182e 876
11f53956 877L<File::Spec|File::Spec>
59b05e08 878
11f53956 879L<File::Spec::Unix|File::Spec::Unix>
1e7b8681 880
11f53956 881L<IO::String|IO::String>
59b05e08 882
11f53956 883L<List::MoreUtils|List::MoreUtils>
59b05e08 884
11f53956 885L<List::Util|List::Util>
f7bb182e 886
11f53956 887L<Module::Pluggable|Module::Pluggable>
1e7b8681 888
776c9cd4
ES
889L<Perl::Tidy|Perl::Tidy>
890
891L<Pod::Spell|Pod::Spell>
892
11f53956 893L<PPI|PPI>
1e7b8681 894
11f53956 895L<Pod::PlainText|Pod::PlainText>
a60e94d6 896
8bee2cc0
ES
897L<Pod::Select|Pod::Select>
898
11f53956 899L<Pod::Usage|Pod::Usage>
59b05e08 900
11f53956 901L<Readonly|Readonly>
59b05e08 902
11f53956 903L<Scalar::Util|Scalar::Util>
f7bb182e 904
11f53956 905L<String::Format|String::Format>
59b05e08 906
68e1379b
ES
907L<Task::Weaken|Task::Weaken>
908
776c9cd4 909L<Text::ParseWords|Text::ParseWords>
8bee2cc0 910
11f53956 911L<version|version>
a60e94d6 912
df89052a 913
59b05e08 914The following modules are optional, but recommended for complete
e177ebf8 915functionality:
8bee2cc0 916
11f53956 917L<File::HomeDir|File::HomeDir>
a60e94d6 918
11f53956 919L<File::Which|File::Which>
a60e94d6 920
df89052a 921
25e89cf1
ES
922=head1 CONTACTING THE DEVELOPMENT TEAM
923
924You are encouraged to subscribe to the mailing list; send a message to
4aaebfba
ES
925L<mailto:users-subscribe@perlcritic.tigris.org>. See also the archives at
926L<http://perlcritic.tigris.org/servlets/SummarizeList?listName=users>.
03887e5e 927You can also contact the author at C<< <jeff@imaginative-software.com> >>.
25e89cf1 928
11f53956
ES
929At least one member of the development team has started hanging around
930in L<irc://irc.perl.org/#perlcritic>.
098d393b 931
4aaebfba
ES
932You can also follow Perl::Critic on Twitter, at
933L<https://twitter.com/perlcritic>.
12b6fa9c 934
df89052a 935
3123bf46
ES
936=head1 SEE ALSO
937
11f53956
ES
938There are a number of distributions of additional Policies available.
939A few are listed here:
3123bf46 940
11f53956 941L<Perl::Critic::More|Perl::Critic::More>
a60e94d6 942
11f53956 943L<Perl::Critic::Bangs|Perl::Critic::Bangs>
a60e94d6 944
11f53956 945L<Perl::Critic::Lax|Perl::Critic::Lax>
a60e94d6 946
11f53956 947L<Perl::Critic::StricterSubs|Perl::Critic::StricterSubs>
a60e94d6 948
11f53956 949L<Perl::Critic::Swift|Perl::Critic::Swift>
3123bf46 950
11f53956 951L<Perl::Critic::Tics|Perl::Critic::Tics>
a60e94d6 952
d032ff5e
JRT
953These distributions enable you to use Perl::Critic in your unit tests:
954
11f53956 955L<Test::Perl::Critic|Test::Perl::Critic>
a60e94d6 956
11f53956 957L<Test::Perl::Critic::Progressive|Test::Perl::Critic::Progressive>
d032ff5e 958
4aaebfba
ES
959There is also a distribution that will install all the Perl::Critic related
960modules known to the development team:
a60e94d6 961
11f53956 962L<Task::Perl::Critic|Task::Perl::Critic>
3123bf46 963
4aaebfba 964If you want to make sure you have absolutely everything, you can use this:
a60e94d6 965
11f53956 966L<Task::Perl::Critic::IncludingOptionalDependencies|Task::Perl::Critic::IncludingOptionalDependencies>
a60e94d6 967
df89052a 968
59b05e08
JRT
969=head1 BUGS
970
11f53956
ES
971Scrutinizing Perl code is hard for humans, let alone machines. If you
972find any bugs, particularly false-positives or false-negatives from a
1bef6e21 973Perl::Critic::Policy, please submit them to
59b05e08
JRT
974L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Perl-Critic>. Thanks.
975
fc0fffee
ES
976Most policies will produce false-negatives if they cannot understand a
977particular block of code.
978
df89052a 979
59b05e08
JRT
980=head1 CREDITS
981
11f53956
ES
982Adam Kennedy - For creating L<PPI|PPI>, the heart and soul of
983L<Perl::Critic|Perl::Critic>.
59b05e08 984
b87b00dd 985Damian Conway - For writing B<Perl Best Practices>, finally :)
59b05e08 986
b87b00dd 987Chris Dolan - For contributing the best features and Policy modules.
59b05e08 988
7711a331 989Andy Lester - Wise sage and master of all-things-testing.
9cdbdce6 990
7711a331 991Elliot Shank - The self-proclaimed quality freak.
9cdbdce6 992
7711a331 993Giuseppe Maxia - For all the great ideas and positive encouragement.
9cdbdce6 994
b87b00dd 995and Sharon, my wife - For putting up with my all-night code sessions.
59b05e08 996
11f53956
ES
997Thanks also to the Perl Foundation for providing a grant to support
998Chris Dolan's project to implement twenty PBP policies.
369abea9
CD
999L<http://www.perlfoundation.org/april_1_2007_new_grant_awards>
1000
df89052a 1001
59b05e08
JRT
1002=head1 AUTHOR
1003
03887e5e 1004Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>
59b05e08 1005
df89052a 1006
59b05e08
JRT
1007=head1 COPYRIGHT
1008
072692c8 1009Copyright (c) 2005-2010 Imaginative Software Systems. All rights reserved.
59b05e08 1010
11f53956
ES
1011This program is free software; you can redistribute it and/or modify
1012it under the same terms as Perl itself. The full text of this license
1013can be found in the LICENSE file included with this module.
59b05e08
JRT
1014
1015=cut
737d3b65 1016
7711a331 1017##############################################################################
737d3b65
CD
1018# Local Variables:
1019# mode: cperl
1020# cperl-indent-level: 4
1021# fill-column: 78
1022# indent-tabs-mode: nil
1023# c-indentation-style: bsd
1024# End:
96fed375 1025# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :