Class SuppressionCommentFilter
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter
-
- All Implemented Interfaces:
Configurable,Contextualizable,TreeWalkerFilter
public class SuppressionCommentFilter extends AutomaticBean implements TreeWalkerFilter
Filter
SuppressionCommentFilteruses pairs of comments to suppress audit events.Rationale: Sometimes there are legitimate reasons for violating a check. When this is a matter of the code in question and not personal preference, the best place to override the policy is in the code itself. Semi-structured comments can be associated with the check. This is sometimes superior to a separate suppressions file, which must be kept up-to-date as the source file is edited.
Note that the suppression comment should be put before the violation. You can use more than one suppression comment each on separate line.
Attention: This filter may only be specified within the TreeWalker module (
<module name="TreeWalker"/>) and only applies to checks which are also defined within this module. To filter non-TreeWalker checks likeRegexpSingleline, a SuppressWithPlainTextCommentFilter or similar filter must be used.offCommentFormatandonCommentFormatmust have equal paren counts.SuppressionCommentFilter can suppress Checks that have Treewalker as parent module.
-
Property
offCommentFormat- Specify comment pattern to trigger filter to begin suppression. Type isjava.util.regex.Pattern. Default value is"CHECKSTYLE:OFF". -
Property
onCommentFormat- Specify comment pattern to trigger filter to end suppression. Type isjava.util.regex.Pattern. Default value is"CHECKSTYLE:ON". -
Property
checkFormat- Specify check pattern to suppress. Type isjava.util.regex.Pattern. Default value is".*". -
Property
messageFormat- Specify message pattern to suppress. Type isjava.util.regex.Pattern. Default value isnull. -
Property
idFormat- Specify check ID pattern to suppress. Type isjava.util.regex.Pattern. Default value isnull. -
Property
checkCPP- Control whether to check C++ style comments (//). Type isboolean. Default value istrue. -
Property
checkC- Control whether to check C style comments (/* ... */). Type isboolean. Default value istrue.
To configure a filter to suppress audit events between a comment containing
CHECKSTYLE:OFFand a comment containingCHECKSTYLE:ON:<module name="TreeWalker"> ... <module name="SuppressionCommentFilter"/> ... </module>To configure a filter to suppress audit events between a comment containing line
BEGIN GENERATED CODEand a comment containing lineEND GENERATED CODE:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="BEGIN GENERATED CODE"/> <property name="onCommentFormat" value="END GENERATED CODE"/> </module>
//BEGIN GENERATED CODE @Override public boolean equals(Object obj) { ... } // No violation events will be reported @Override public int hashCode() { ... } // No violation events will be reported //END GENERATED CODE . . .To configure a filter so that
// stop constant checkand// resume constant checkmarks legitimate constant names:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="stop constant check"/> <property name="onCommentFormat" value="resume constant check"/> <property name="checkFormat" value="ConstantNameCheck"/> </module>
//stop constant check public static final int someConstant; // won't warn here //resume constant check public static final int someConstant; // will warn here as constant's name doesn't match the // pattern "^[A-Z][A-Z0-9]*$"
To configure a filter so that
UNUSED OFF: <i>var</i>andUNUSED ON: <i>var</i>marks a variable or parameter known not to be used by the code by matching the variable name in the message:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="UNUSED OFF\: (\w+)"/> <property name="onCommentFormat" value="UNUSED ON\: (\w+)"/> <property name="checkFormat" value="Unused"/> <property name="messageFormat" value="^Unused \w+ '$1'.$"/> </module>
private static void foo(int a, int b) // UNUSED OFF: b { System.out.println(a); } private static void foo1(int a, int b) // UNUSED ON: b { System.out.println(a); }To configure a filter so that name of suppressed check mentioned in comment
CSOFF: <i>regexp</i>andCSON: <i>regexp</i>mark a matching check:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/> <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/> <property name="checkFormat" value="$1"/> </module>
public static final int lowerCaseConstant; // CSOFF: ConstantNameCheck public static final int lowerCaseConstant1; // CSON: ConstantNameCheck
To configure a filter to suppress all audit events between a comment containing
CHECKSTYLE_OFF: ALMOST_ALLand a comment containingCHECKSTYLE_OFF: ALMOST_ALLexcept for the EqualsHashCode check:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="CHECKSTYLE_OFF: ALMOST_ALL"/> <property name="onCommentFormat" value="CHECKSTYLE_ON: ALMOST_ALL"/> <property name="checkFormat" value="^((?!(EqualsHashCode)).)*$"/> </module>
public static final int array []; // CHECKSTYLE_OFF: ALMOST_ALL private String [] strArray; private int array1 []; // CHECKSTYLE_ON: ALMOST_ALL
To configure a filter to suppress Check's violation message which matches specified message in messageFormat (so suppression will be not only by Check's name, but by message text additionally, as the same Check could report different by message format violations) between a comment containing
stopand comment containingresume:<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="stop"/> <property name="onCommentFormat" value="resume"/> <property name="checkFormat" value="IllegalTypeCheck"/> <property name="messageFormat" value="^Declaring variables, return values or parameters of type 'GregorianCalendar' is not allowed.$"/> </module>Code before filter above is applied with Check's audit events:
... // Warning below: Declaring variables, return values or parameters of type 'GregorianCalendar' // is not allowed. GregorianCalendar calendar; // Warning below here: Declaring variables, return values or parameters of type 'HashSet' // is not allowed. HashSet hashSet; ...
Code after filter is applied:
... //stop GregorianCalendar calendar; // No warning here as it is suppressed by filter. HashSet hashSet; // Warning above here: Declaring variables, return values or parameters of type 'HashSet' //is not allowed. //resume ...
It is possible to specify an ID of checks, so that it can be leveraged by the SuppressionCommentFilter to skip validations. The following examples show how to skip validations near code that is surrounded with
// CSOFF <ID> (reason)and// CSON <ID>, where ID is the ID of checks you want to suppress.Examples of Checkstyle checks configuration:
<module name="RegexpSinglelineJava"> <property name="id" value="ignore"/> <property name="format" value="^.*@Ignore\s*$"/> <property name="message" value="@Ignore should have a reason."/> </module> <module name="RegexpSinglelineJava"> <property name="id" value="systemout"/> <property name="format" value="^.*System\.(out|err).*$"/> <property name="message" value="Don't use System.out/err, use SLF4J instead."/> </module>
Example of SuppressionCommentFilter configuration (checkFormat which is set to '$1' points that ID of the checks is in the first group of offCommentFormat and onCommentFormat regular expressions):
<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="CSOFF (\w+) \(\w+\)"/> <property name="onCommentFormat" value="CSON (\w+)"/> <property name="idFormat" value="$1"/> </module>
// CSOFF ignore (test has not been implemented yet) @Ignore // should NOT fail RegexpSinglelineJava @Test public void testMethod() { } // CSON ignore // CSOFF systemout (debug) public static void foo() { System.out.println("Debug info."); // should NOT fail RegexpSinglelineJava } // CSON systemoutExample of how to configure the check to suppress more than one checks.
<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="@cs-\: ([\w\|]+)"/> <property name="checkFormat" value="$1"/> </module>
// @cs-: ClassDataAbstractionCoupling // @cs-: MagicNumber @Service // no violations from ClassDataAbstractionCoupling here @Transactional public class UserService { private int value = 10022; // no violations from MagicNumber here }Parent is
com.puppycrawl.tools.checkstyle.TreeWalker- Since:
- 3.5
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classSuppressionCommentFilter.TagA Tag holds a suppression comment and its location, and determines whether the suppression turns checkstyle reporting on or off.static classSuppressionCommentFilter.TagTypeEnum to be used for switching checkstyle reporting for tags.-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private booleancheckCControl whether to check C style comments (/* ... */).private booleancheckCPPControl whether to check C++ style comments (//).private java.lang.StringcheckFormatSpecify check pattern to suppress.private static java.lang.StringDEFAULT_CHECK_FORMATControl all checks.private static java.lang.StringDEFAULT_OFF_FORMATTurns checkstyle reporting off.private static java.lang.StringDEFAULT_ON_FORMATTurns checkstyle reporting on.private java.lang.ref.WeakReference<FileContents>fileContentsReferenceReferences the current FileContents for this filter.private java.lang.StringidFormatSpecify check ID pattern to suppress.private java.lang.StringmessageFormatSpecify message pattern to suppress.private java.util.regex.PatternoffCommentFormatSpecify comment pattern to trigger filter to begin suppression.private java.util.regex.PatternonCommentFormatSpecify comment pattern to trigger filter to end suppression.private java.util.List<SuppressionCommentFilter.Tag>tagsTagged comments.
-
Constructor Summary
Constructors Constructor Description SuppressionCommentFilter()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanaccept(TreeWalkerAuditEvent event)Determines whether or not a filteredTreeWalkerAuditEventis accepted.private voidaddTag(java.lang.String text, int line, int column, SuppressionCommentFilter.TagType reportingOn)Adds aTagto the list of all tags.private SuppressionCommentFilter.TagfindNearestMatch(TreeWalkerAuditEvent event)Finds the nearest comment text tag that matches an audit event.protected voidfinishLocalSetup()Provides a hook to finish the part of this component's setup that was not handled by the bean introspection.private FileContentsgetFileContents()Returns FileContents for this filter.voidsetCheckC(boolean checkC)Setter to control whether to check C style comments (/* ... */).voidsetCheckCPP(boolean checkCpp)Setter to control whether to check C++ style comments (//).voidsetCheckFormat(java.lang.String format)Setter to specify check pattern to suppress.voidsetFileContents(FileContents fileContents)Set the FileContents for this filter.voidsetIdFormat(java.lang.String format)Setter to specify check ID pattern to suppress.voidsetMessageFormat(java.lang.String format)Setter to specify message pattern to suppress.voidsetOffCommentFormat(java.util.regex.Pattern pattern)Setter to specify comment pattern to trigger filter to begin suppression.voidsetOnCommentFormat(java.util.regex.Pattern pattern)Setter to specify comment pattern to trigger filter to end suppression.private voidtagCommentLine(java.lang.String text, int line, int column)Tags a string if it matches the format for turning checkstyle reporting on or the format for turning reporting off.private voidtagSuppressions()Collects all the suppression tags for all comments into a list and sorts the list.private voidtagSuppressions(java.util.Collection<TextBlock> comments)Appends the suppressions in a collection of comments to the full set of suppression tags.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
DEFAULT_OFF_FORMAT
private static final java.lang.String DEFAULT_OFF_FORMAT
Turns checkstyle reporting off.- See Also:
- Constant Field Values
-
DEFAULT_ON_FORMAT
private static final java.lang.String DEFAULT_ON_FORMAT
Turns checkstyle reporting on.- See Also:
- Constant Field Values
-
DEFAULT_CHECK_FORMAT
private static final java.lang.String DEFAULT_CHECK_FORMAT
Control all checks.- See Also:
- Constant Field Values
-
tags
private final java.util.List<SuppressionCommentFilter.Tag> tags
Tagged comments.
-
checkC
private boolean checkC
Control whether to check C style comments (/* ... */).
-
checkCPP
private boolean checkCPP
Control whether to check C++ style comments (//).
-
offCommentFormat
private java.util.regex.Pattern offCommentFormat
Specify comment pattern to trigger filter to begin suppression.
-
onCommentFormat
private java.util.regex.Pattern onCommentFormat
Specify comment pattern to trigger filter to end suppression.
-
checkFormat
private java.lang.String checkFormat
Specify check pattern to suppress.
-
messageFormat
private java.lang.String messageFormat
Specify message pattern to suppress.
-
idFormat
private java.lang.String idFormat
Specify check ID pattern to suppress.
-
fileContentsReference
private java.lang.ref.WeakReference<FileContents> fileContentsReference
References the current FileContents for this filter. Since this is a weak reference to the FileContents, the FileContents can be reclaimed as soon as the strong references in TreeWalker are reassigned to the next FileContents, at which time filtering for the current FileContents is finished.
-
-
Constructor Detail
-
SuppressionCommentFilter
public SuppressionCommentFilter()
-
-
Method Detail
-
setOffCommentFormat
public final void setOffCommentFormat(java.util.regex.Pattern pattern)
Setter to specify comment pattern to trigger filter to begin suppression.- Parameters:
pattern- a pattern.
-
setOnCommentFormat
public final void setOnCommentFormat(java.util.regex.Pattern pattern)
Setter to specify comment pattern to trigger filter to end suppression.- Parameters:
pattern- a pattern.
-
getFileContents
private FileContents getFileContents()
Returns FileContents for this filter.- Returns:
- the FileContents for this filter.
-
setFileContents
public void setFileContents(FileContents fileContents)
Set the FileContents for this filter.- Parameters:
fileContents- the FileContents for this filter.
-
setCheckFormat
public final void setCheckFormat(java.lang.String format)
Setter to specify check pattern to suppress.- Parameters:
format- aStringvalue
-
setMessageFormat
public void setMessageFormat(java.lang.String format)
Setter to specify message pattern to suppress.- Parameters:
format- aStringvalue
-
setIdFormat
public void setIdFormat(java.lang.String format)
Setter to specify check ID pattern to suppress.- Parameters:
format- aStringvalue
-
setCheckCPP
public void setCheckCPP(boolean checkCpp)
Setter to control whether to check C++ style comments (//).- Parameters:
checkCpp-trueif C++ comments are checked.
-
setCheckC
public void setCheckC(boolean checkC)
Setter to control whether to check C style comments (/* ... */).- Parameters:
checkC-trueif C comments are checked.
-
finishLocalSetup
protected void finishLocalSetup()
Description copied from class:AutomaticBeanProvides a hook to finish the part of this component's setup that was not handled by the bean introspection.The default implementation does nothing.
- Specified by:
finishLocalSetupin classAutomaticBean
-
accept
public boolean accept(TreeWalkerAuditEvent event)
Description copied from interface:TreeWalkerFilterDetermines whether or not a filteredTreeWalkerAuditEventis accepted.- Specified by:
acceptin interfaceTreeWalkerFilter- Parameters:
event- the TreeWalkerAuditEvent to filter.- Returns:
- true if the event is accepted.
-
findNearestMatch
private SuppressionCommentFilter.Tag findNearestMatch(TreeWalkerAuditEvent event)
Finds the nearest comment text tag that matches an audit event. The nearest tag is before the line and column of the event.- Parameters:
event- theTreeWalkerAuditEventto match.- Returns:
- The
Tagnearest event.
-
tagSuppressions
private void tagSuppressions()
Collects all the suppression tags for all comments into a list and sorts the list.
-
tagSuppressions
private void tagSuppressions(java.util.Collection<TextBlock> comments)
Appends the suppressions in a collection of comments to the full set of suppression tags.- Parameters:
comments- the set of comments.
-
tagCommentLine
private void tagCommentLine(java.lang.String text, int line, int column)
Tags a string if it matches the format for turning checkstyle reporting on or the format for turning reporting off.- Parameters:
text- the string to tag.line- the line number of text.column- the column number of text.
-
addTag
private void addTag(java.lang.String text, int line, int column, SuppressionCommentFilter.TagType reportingOn)
Adds aTagto the list of all tags.- Parameters:
text- the text of the tag.line- the line number of the tag.column- the column number of the tag.reportingOn-trueif the tag turns checkstyle reporting on.
-
-