Class SuppressWithNearbyCommentFilter
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter
-
- All Implemented Interfaces:
Configurable,Contextualizable,TreeWalkerFilter
public class SuppressWithNearbyCommentFilter extends AutomaticBean implements TreeWalkerFilter
Filter
SuppressWithNearbyCommentFilteruses nearby comments to suppress audit events.Rationale: Same as
SuppressionCommentFilter. Whereas the SuppressionCommentFilter uses matched pairs of filters to turn on/off comment matching,SuppressWithNearbyCommentFilteruses single comments. This requires fewer lines to mark a region, and may be aesthetically preferable in some contexts.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.SuppressWithNearbyCommentFilter can suppress Checks that have Treewalker as parent module.
-
Property
commentFormat- Specify comment pattern to trigger filter to begin suppression. Type isjava.util.regex.Pattern. Default value is"SUPPRESS CHECKSTYLE (\w+)". -
Property
checkFormat- Specify check pattern to suppress. Type isjava.util.regex.Pattern. Default value is".*". -
Property
messageFormat- Define 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
influenceFormat- Specify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment. Type isjava.lang.String. Default value is"0". -
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 for check on any line with a comment
SUPPRESS CHECKSTYLE <i>check</i>:<module name="SuppressWithNearbyCommentFilter"/>
private int [] array; // SUPPRESS CHECKSTYLE
To configure a filter to suppress all audit events on any line containing the comment
CHECKSTYLE IGNORE THIS LINE:<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="CHECKSTYLE IGNORE THIS LINE"/> <property name="checkFormat" value=".*"/> <property name="influenceFormat" value="0"/> </module>
public static final int lowerCaseConstant; // CHECKSTYLE IGNORE THIS LINE
To configure a filter so that
// OK to catch (Throwable|Exception|RuntimeException) herepermits the current and previous line to avoid generating an IllegalCatch audit event:<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="OK to catch (\w+) here"/> <property name="checkFormat" value="IllegalCatchCheck"/> <property name="messageFormat" value="$1"/> <property name="influenceFormat" value="-1"/> </module>
. . . catch (RuntimeException re) { // OK to catch RuntimeException here } catch (Throwable th) { ... } . . .To configure a filter so that
CHECKSTYLE IGNORE <i>check</i> FOR NEXT <i>var</i> LINESavoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/> <property name="checkFormat" value="$1"/> <property name="influenceFormat" value="$2"/> </module>static final int lowerCaseConstant; // CHECKSTYLE IGNORE ConstantNameCheck FOR NEXT 3 LINES static final int lowerCaseConstant1; static final int lowerCaseConstant2; static final int lowerCaseConstant3; static final int lowerCaseConstant4; // will warn here
To configure a filter to avoid any audits on code like:
<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="ALLOW (\\w+) ON PREVIOUS LINE"/> <property name="checkFormat" value="$1"/> <property name="influenceFormat" value="-1"/> </module>private int D2; // ALLOW MemberName ON PREVIOUS LINE . . .
To configure a filter to allow suppress one or more Checks (separated by "|") and demand comment no less than 14 symbols:
<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="@cs\.suppress \[(\w+(\|\w+)*)\] \w[-\.'`,:;\w ]{14,}"/> <property name="checkFormat" value="$1"/> <property name="influenceFormat" value="1"/> </module>public static final int [] array; // @cs.suppress [ConstantName|NoWhitespaceAfter] A comment here
It is possible to specify an ID of checks, so that it can be leveraged by the SuppressWithNearbyCommentFilter to skip validations. The following examples show how to skip validations near code that has comment like
// @cs-: <ID/> (reason), 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 SuppressWithNearbyCommentFilter configuration (idFormat which is set to '$1' points that ID of the checks is in the first group of commentFormat regular expressions):
<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="@cs-: (\w+) \(.*\)"/> <property name="idFormat" value="$1"/> <property name="influenceFormat" value="0"/> </module>
@Ignore // @cs-: ignore (test has not been implemented yet) @Test public void testMethod() { } public static void foo() { System.out.println("Debug info."); // @cs-: systemout (should not fail RegexpSinglelineJava) }Example of how to configure the check to suppress more than one checks. The influence format format is specified in the second regexp group.
<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="@cs-\: ([\w\|]+) influence (\d+)"/> <property name="checkFormat" value="$1"/> <property name="influenceFormat" value="$2"/> </module>
// @cs-: ClassDataAbstractionCoupling influence 2 // @cs-: MagicNumber influence 4 @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:
- 5.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classSuppressWithNearbyCommentFilter.TagA Tag holds a suppression comment and its location.-
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 java.util.regex.PatterncommentFormatSpecify comment pattern to trigger filter to begin suppression.private static java.lang.StringDEFAULT_CHECK_FORMATDefault regex for checks that should be suppressed.private static java.lang.StringDEFAULT_COMMENT_FORMATFormat to turn checkstyle reporting off.private static java.lang.StringDEFAULT_INFLUENCE_FORMATDefault regex for lines that should be suppressed.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.StringinfluenceFormatSpecify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment.private java.lang.StringmessageFormatDefine message pattern to suppress.private java.util.List<SuppressWithNearbyCommentFilter.Tag>tagsTagged comments.
-
Constructor Summary
Constructors Constructor Description SuppressWithNearbyCommentFilter()
-
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)Adds a comment suppressionTagto the list of all tags.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.private booleanmatchesTag(TreeWalkerAuditEvent event)Whether current event matches any tag fromtags.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.voidsetCommentFormat(java.util.regex.Pattern pattern)Setter to specify comment pattern to trigger filter to begin suppression.voidsetFileContents(FileContents fileContents)Set the FileContents for this filter.voidsetIdFormat(java.lang.String format)Setter to specify check ID pattern to suppress.voidsetInfluenceFormat(java.lang.String format)Setter to specify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment.voidsetMessageFormat(java.lang.String format)Setter to define message pattern to suppress.private voidtagCommentLine(java.lang.String text, int line)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_COMMENT_FORMAT
private static final java.lang.String DEFAULT_COMMENT_FORMAT
Format to turn checkstyle reporting off.- See Also:
- Constant Field Values
-
DEFAULT_CHECK_FORMAT
private static final java.lang.String DEFAULT_CHECK_FORMAT
Default regex for checks that should be suppressed.- See Also:
- Constant Field Values
-
DEFAULT_INFLUENCE_FORMAT
private static final java.lang.String DEFAULT_INFLUENCE_FORMAT
Default regex for lines that should be suppressed.- See Also:
- Constant Field Values
-
tags
private final java.util.List<SuppressWithNearbyCommentFilter.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 (//).
-
commentFormat
private java.util.regex.Pattern commentFormat
Specify comment pattern to trigger filter to begin suppression.
-
checkFormat
private java.lang.String checkFormat
Specify check pattern to suppress.
-
messageFormat
private java.lang.String messageFormat
Define message pattern to suppress.
-
idFormat
private java.lang.String idFormat
Specify check ID pattern to suppress.
-
influenceFormat
private java.lang.String influenceFormat
Specify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment.
-
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
-
SuppressWithNearbyCommentFilter
public SuppressWithNearbyCommentFilter()
-
-
Method Detail
-
setCommentFormat
public final void setCommentFormat(java.util.regex.Pattern pattern)
Setter to specify comment pattern to trigger filter to begin 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 define 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
-
setInfluenceFormat
public final void setInfluenceFormat(java.lang.String format)
Setter to specify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment.- 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.
-
matchesTag
private boolean matchesTag(TreeWalkerAuditEvent event)
Whether current event matches any tag fromtags.
-
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)
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.
-
addTag
private void addTag(java.lang.String text, int line)
Adds a comment suppressionTagto the list of all tags.- Parameters:
text- the text of the tag.line- the line number of the tag.
-
-