Skip to content
This repository was archived by the owner on Jul 16, 2023. It is now read-only.

feat: support ignoring regular comments for format-comment #1110

Merged
merged 1 commit into from
Dec 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

* feat: support ignoring regular comments for [`format-comment`](https://dartcodemetrics.dev/docs/rules/common/format-comment).

## 5.2.1

* fix: avoid null check exception in the analyzer.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ part of 'format_comment_rule.dart';

class _ConfigParser {
static const _ignoredPatternsConfig = 'ignored-patterns';
static const _onlyDocComments = 'only-doc-comments';

static Iterable<RegExp> getIgnoredPatterns(Map<String, Object> config) =>
static Iterable<RegExp> parseIgnoredPatterns(Map<String, Object> config) =>
config[_ignoredPatternsConfig] is Iterable
? List<String>.from(
config[_ignoredPatternsConfig] as Iterable,
).map(RegExp.new)
: const [];

static bool parseOnlyDocComments(Map<String, Object> config) =>
config[_onlyDocComments] == true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ class FormatCommentRule extends CommonRule {
/// match at least one of them.
final Iterable<RegExp> _ignoredPatterns;

final bool _onlyDocComments;

FormatCommentRule([Map<String, Object> config = const {}])
: _ignoredPatterns = _ConfigParser.getIgnoredPatterns(config),
: _ignoredPatterns = _ConfigParser.parseIgnoredPatterns(config),
_onlyDocComments = _ConfigParser.parseOnlyDocComments(config),
super(
id: ruleId,
severity: readSeverity(config, Severity.style),
Expand All @@ -40,13 +43,17 @@ class FormatCommentRule extends CommonRule {
final json = super.toJson();
json[_ConfigParser._ignoredPatternsConfig] =
_ignoredPatterns.map((exp) => exp.pattern).toList();
json[_ConfigParser._onlyDocComments] = _onlyDocComments;

return json;
}

@override
Iterable<Issue> check(InternalResolvedUnitResult source) {
final visitor = _Visitor(_ignoredPatterns)..checkComments(source.unit.root);
final visitor = _Visitor(
_ignoredPatterns,
_onlyDocComments,
)..checkComments(source.unit.root);

return [
for (final comment in visitor.comments)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
part of 'format_comment_rule.dart';

const commentsOperator = {
const _commentsOperator = {
_CommentType.base: '//',
_CommentType.documentation: '///',
};
Expand All @@ -12,8 +12,10 @@ const _ignoreForFileExp = 'ignore_for_file:';

class _Visitor extends RecursiveAstVisitor<void> {
final Iterable<RegExp> _ignoredPatterns;
final bool _onlyDocComments;

_Visitor(this._ignoredPatterns);
// ignore: avoid_positional_boolean_parameters
_Visitor(this._ignoredPatterns, this._onlyDocComments);

final _comments = <_CommentInfo>[];

Expand Down Expand Up @@ -41,15 +43,15 @@ class _Visitor extends RecursiveAstVisitor<void> {
final token = commentToken.toString();
if (token.startsWith('///')) {
_checkCommentByType(commentToken, _CommentType.documentation);
} else if (token.startsWith('//')) {
} else if (token.startsWith('//') && !_onlyDocComments) {
_checkCommentByType(commentToken, _CommentType.base);
}
}
}

void _checkCommentByType(Token commentToken, _CommentType type) {
final commentText =
commentToken.toString().substring(commentsOperator[type]!.length);
commentToken.toString().substring(_commentsOperator[type]!.length);

var text = commentText.trim();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,34 @@ void main() {
);
});

test('reports about found issues only for doc comments', () async {
final unit = await RuleTestHelper.resolveFromFile(_multiline);
final issues = FormatCommentRule(const {
'only-doc-comments': true,
}).check(unit);

RuleTestHelper.verifyIssues(
issues: issues,
startLines: [2, 5, 17],
startColumns: [3, 3, 1],
locationTexts: [
'/// The value this wraps',
'/// true if this box contains a value.',
'/// deletes the file at [path] from the file system.',
],
messages: [
'Prefer formatting comments like sentences.',
'Prefer formatting comments like sentences.',
'Prefer formatting comments like sentences.',
],
replacements: [
'/// The value this wraps.',
'/// True if this box contains a value.',
'/// Deletes the file at [path] from the file system.',
],
);
});

test('reports no issues', () async {
final unit = await RuleTestHelper.resolveFromFile(_withoutIssuePath);
RuleTestHelper.verifyNoIssues(FormatCommentRule().check(unit));
Expand Down
3 changes: 3 additions & 0 deletions website/docs/rules/common/format-comment.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Prefer format comments like sentences.

Use `ignored-patterns` configuration, if you want to ignore comments that match the given regular expressions.

Use `only-doc-comments` configuration, if you want to check only documentation comments (`///`).

### ⚙️ Config example {#config-example}

```yaml
Expand All @@ -14,6 +16,7 @@ dart_code_metrics:
rules:
...
- format-comment:
only-doc-comments: true
ignored-patterns:
- ^ cSpell.* # Ignores all the comments that start with 'cSpell' (for example: '// cSpell:disable-next-line').
```
Expand Down