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

Commit 9bb534b

Browse files
chore: fix prefer moving to variable issues (#787)
* feat: add static code diagnostic prefer-moving-to-variable * fix: cover edge-cases * chore: fix new rule issue * chore: fix analyzer issues * Update CHANGELOG.md Co-authored-by: Dmitry Krutskikh <dmitry.krutskikh@gmail.com>
1 parent 44ff119 commit 9bb534b

File tree

30 files changed

+176
-150
lines changed

30 files changed

+176
-150
lines changed

CHANGELOG.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
* feat: add static code diagnostic [`prefer-commenting-analyzer-ignores`](https://dartcodemetrics.dev/docs/rules/common/prefer-commenting-analyzer-ignores).
66
* feat: add static code diagnostic [`prefer-moving-to-variable`](https://dartcodemetrics.dev/docs/rules/common/prefer-moving-to-variable).
77
* fix: add check for supertypes for [`avoid-non-null-assertions`](https://dartcodemetrics.dev/docs/rules/common/avoid-non-null-assertion) rule.
8+
* fix: correctly handle nullable types of collections for [`avoid-collection-methods-with-unrelated-types`](https://dartcodemetrics.dev/docs/rules/common/avoid-collection-methods-with-unrelated-types).
89
* fix: cover more cases in [`prefer-immediate-return`](https://dartcodemetrics.dev/docs/rules/common/prefer-immediate-return) rule
910
* fix: support index expressions for [`no-magic-number`](https://dartcodemetrics.dev/docs/rules/common/no-magic-number) rule.
10-
* chore: restrict `analyzer` version to `>=2.4.0 <3.4.0`.
11-
* fix: correctly handle nullable types of collections for [`avoid-collection-methods-with-unrelated-types`](https://dartcodemetrics.dev/docs/rules/common/avoid-collection-methods-with-unrelated-types)
1211
* docs: update `prefer-async-await` rule.
12+
* chore: `fix prefer-moving-to-variable` issues.
13+
* chore: restrict `analyzer` version to `>=2.4.0 <3.4.0`.
1314

1415
## 4.13.0
1516

lib/src/analyzer_plugin/analyzer_plugin.dart

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,14 @@ class AnalyzerPlugin extends ServerPlugin {
154154
return plugin.EditGetFixesResult([]);
155155
}
156156

157-
final fixes = _check(driver, analysisResult)
158-
.where((fix) =>
159-
fix.error.location.file == parameters.file &&
160-
fix.error.location.offset <= parameters.offset &&
161-
parameters.offset <=
162-
fix.error.location.offset + fix.error.location.length &&
163-
fix.fixes.isNotEmpty)
164-
.toList();
157+
final fixes = _check(driver, analysisResult).where((fix) {
158+
final location = fix.error.location;
159+
160+
return location.file == parameters.file &&
161+
location.offset <= parameters.offset &&
162+
parameters.offset <= location.offset + location.length &&
163+
fix.fixes.isNotEmpty;
164+
}).toList();
165165

166166
return plugin.EditGetFixesResult(fixes);
167167
} on Exception catch (e, stackTrace) {

lib/src/analyzer_plugin/analyzer_plugin_utils.dart

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,22 @@ plugin.AnalysisErrorFixes codeIssueToAnalysisErrorFixes(
1414
ResolvedUnitResult? unitResult,
1515
) {
1616
final fileWithIssue = uriToPath(issue.location.sourceUrl) ?? '';
17+
final location = issue.location;
18+
final locationStart = location.start;
19+
final locationEnd = location.end;
1720

1821
return plugin.AnalysisErrorFixes(
1922
plugin.AnalysisError(
2023
_severityMapping[issue.severity]!,
2124
plugin.AnalysisErrorType.LINT,
2225
plugin.Location(
2326
fileWithIssue,
24-
issue.location.start.offset,
25-
issue.location.length,
26-
issue.location.start.line,
27-
issue.location.start.column,
28-
endLine: issue.location.end.line,
29-
endColumn: issue.location.end.column,
27+
locationStart.offset,
28+
location.length,
29+
locationStart.line,
30+
locationStart.column,
31+
endLine: locationEnd.line,
32+
endColumn: locationEnd.column,
3033
),
3134
issue.message,
3235
issue.ruleId,
@@ -47,8 +50,8 @@ plugin.AnalysisErrorFixes codeIssueToAnalysisErrorFixes(
4750
unitResult.exists ? 0 : -1,
4851
edits: [
4952
plugin.SourceEdit(
50-
issue.location.start.offset,
51-
issue.location.length,
53+
locationStart.offset,
54+
location.length,
5255
issue.suggestion!.replacement,
5356
),
5457
],

lib/src/analyzers/lint_analyzer/metrics/metrics_list/halstead_volume/halstead_volume_ast_visitor.dart

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ class HalsteadVolumeAstVisitor extends RecursiveAstVisitor<void> {
4545
var token = firstToken;
4646
while (token != lastToken && token != null) {
4747
if (token.isOperator) {
48-
_operators[token.type.name] = (_operators[token.type.name] ?? 0) + 1;
48+
final name = token.type.name;
49+
_operators[name] = (_operators[name] ?? 0) + 1;
4950
}
5051

5152
if (token.isIdentifier) {

lib/src/analyzers/lint_analyzer/metrics/metrics_list/maximum_nesting_level/nesting_level_visitor.dart

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,17 @@ class NestingLevelVisitor extends RecursiveAstVisitor<void> {
2020

2121
AstNode? astNode = node;
2222
do {
23+
final parent = astNode?.parent;
24+
final grandParent = parent?.parent;
2325
if (astNode is Block &&
24-
(astNode.parent is! BlockFunctionBody ||
25-
astNode.parent?.parent is ConstructorDeclaration ||
26-
astNode.parent?.parent is FunctionExpression ||
27-
astNode.parent?.parent is MethodDeclaration)) {
26+
(parent is! BlockFunctionBody ||
27+
grandParent is ConstructorDeclaration ||
28+
grandParent is FunctionExpression ||
29+
grandParent is MethodDeclaration)) {
2830
nestedNodesChain.add(astNode);
2931
}
3032

31-
astNode = astNode?.parent;
33+
astNode = parent;
3234
} while (astNode?.parent != _functionNode);
3335

3436
if (nestedNodesChain.length > _deepestNestedNodesChain.length) {

lib/src/analyzers/lint_analyzer/models/suppression.dart

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,9 @@ class Suppression {
2424
final ids = match.group(1)!.split(',').map(_canonicalize);
2525
final location = info.getLocation(match.start);
2626
final lineNumber = location.lineNumber;
27-
final beforeMatch = content.substring(
28-
info.getOffsetOfLine(lineNumber - 1),
29-
info.getOffsetOfLine(lineNumber - 1) + location.columnNumber - 1,
30-
);
27+
final offset = info.getOffsetOfLine(lineNumber - 1);
28+
final beforeMatch =
29+
content.substring(offset, offset + location.columnNumber - 1);
3130

3231
// If comment sits next to code, so it refers to its own line, otherwise it refers to the next line.
3332
final ignoredNextLine = beforeMatch.trim().isEmpty;

lib/src/analyzers/lint_analyzer/reporters/reporters_list/checkstyle/lint_checkstyle_reporter.dart

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,13 @@ class LintCheckstyleReporter extends CheckstyleReporter<LintFileReport,
4242
final issues = [...record.issues, ...record.antiPatternCases];
4343

4444
for (final issue in issues) {
45+
final locationStart = issue.location.start;
4546
builder.element(
4647
'error',
4748
attributes: {
48-
'line': '${issue.location.start.line}',
49-
if (issue.location.start.column > 0)
50-
'column': '${issue.location.start.column}',
49+
'line': '${locationStart.line}',
50+
if (locationStart.column > 0)
51+
'column': '${locationStart.column}',
5152
'severity': _severityMapping[issue.severity] ?? 'ignore',
5253
'message': issue.message,
5354
'source': issue.ruleId,

lib/src/analyzers/lint_analyzer/reporters/reporters_list/console/lint_console_reporter_helper.dart

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ class LintConsoleReporterHelper {
3232
/// Converts an [issue] to the issue message string.
3333
Iterable<String> getIssueMessage(Issue issue, String relativePath) {
3434
final severity = _getSeverity(issue.severity);
35+
final locationStart = issue.location.start;
3536
final location = _linkPen(
36-
'$relativePath:${issue.location.start.line}:${issue.location.start.column}',
37+
'$relativePath:${locationStart.line}:${locationStart.column}',
3738
);
3839
final tabulation = _normalize('');
3940

lib/src/analyzers/lint_analyzer/reporters/reporters_list/html/lint_html_reporter.dart

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -349,9 +349,12 @@ class LintHtmlReporter extends HtmlReporter<LintFileReport,
349349
final complexityValueElement = Element.tag('div')
350350
..classes.add('metrics-source-code__text');
351351

352-
final classReport = record.classes.entries.firstWhereOrNull((report) =>
353-
report.value.location.start.line <= lineIndex &&
354-
report.value.location.end.line >= lineIndex);
352+
final classReport = record.classes.entries.firstWhereOrNull((report) {
353+
final location = report.value.location;
354+
355+
return location.start.line <= lineIndex &&
356+
location.end.line >= lineIndex;
357+
});
355358
if (classReport != null &&
356359
classReport.value.location.start.line == lineIndex) {
357360
complexityValueElement
@@ -435,6 +438,8 @@ class LintHtmlReporter extends HtmlReporter<LintFileReport,
435438
cyclomaticValues.append(complexityValueElement);
436439
}
437440

441+
final from = p.dirname(record.relativePath);
442+
438443
final codeBlock = Element.tag('td')
439444
..classes.add('metrics-source-code__code')
440445
..append(Element.tag('pre')
@@ -445,13 +450,12 @@ class LintHtmlReporter extends HtmlReporter<LintFileReport,
445450
..append(Element.tag('h1')
446451
..classes.add('metric-header')
447452
..append(Element.tag('a')
448-
..attributes['href'] =
449-
p.relative('index.html', from: p.dirname(record.relativePath))
453+
..attributes['href'] = p.relative('index.html', from: from)
450454
..text = 'All files')
451455
..append(Element.tag('span')..text = ' : ')
452456
..append(Element.tag('a')
453457
..attributes['href'] = 'index.html'
454-
..text = p.dirname(record.relativePath))
458+
..text = from)
455459
..append(
456460
Element.tag('span')..text = '/${p.basename(record.relativePath)}',
457461
))
@@ -488,20 +492,16 @@ class LintHtmlReporter extends HtmlReporter<LintFileReport,
488492
..append(Element.tag('meta')..attributes['charset'] = 'utf-8')
489493
..append(Element.tag('link')
490494
..attributes['rel'] = 'stylesheet'
491-
..attributes['href'] =
492-
p.relative('variables.css', from: p.dirname(record.relativePath)))
495+
..attributes['href'] = p.relative('variables.css', from: from))
493496
..append(Element.tag('link')
494497
..attributes['rel'] = 'stylesheet'
495-
..attributes['href'] =
496-
p.relative('normalize.css', from: p.dirname(record.relativePath)))
498+
..attributes['href'] = p.relative('normalize.css', from: from))
497499
..append(Element.tag('link')
498500
..attributes['rel'] = 'stylesheet'
499-
..attributes['href'] =
500-
p.relative('base.css', from: p.dirname(record.relativePath)))
501+
..attributes['href'] = p.relative('base.css', from: from))
501502
..append(Element.tag('link')
502503
..attributes['rel'] = 'stylesheet'
503-
..attributes['href'] =
504-
p.relative('main.css', from: p.dirname(record.relativePath)));
504+
..attributes['href'] = p.relative('main.css', from: from));
505505

506506
final html = Element.tag('html')
507507
..attributes['lang'] = 'en'

lib/src/analyzers/lint_analyzer/reporters/reporters_list/html/utility_functions.dart

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,55 +43,59 @@ Element renderSummaryMetric(
4343
}
4444

4545
Element renderTableRecord(ReportTableRecord record) {
46+
final report = record.report;
4647
final recordHaveCyclomaticComplexityViolations =
47-
record.report.cyclomaticComplexityViolations > 0;
48+
report.cyclomaticComplexityViolations > 0;
4849
final recordHaveSourceLinesOfCodeViolations =
49-
record.report.sourceLinesOfCodeViolations > 0;
50+
report.sourceLinesOfCodeViolations > 0;
5051
final recordHaveMaintainabilityIndexViolations =
51-
record.report.maintainabilityIndexViolations > 0;
52+
report.maintainabilityIndexViolations > 0;
5253
final recordHaveArgumentsCountViolations =
53-
record.report.argumentsCountViolations > 0;
54+
report.argumentsCountViolations > 0;
5455
final recordHaveMaximumNestingLevelViolations =
55-
record.report.maximumNestingLevelViolations > 0;
56+
report.maximumNestingLevelViolations > 0;
5657
final recordHaveTechDebtViolations =
5758
record.report.technicalDebtViolations > 0;
5859

60+
final averageMaintainabilityIndex =
61+
report.averageMaintainabilityIndex.toInt();
62+
5963
return Element.tag('tr')
6064
..append(Element.tag('td')
6165
..append(Element.tag('a')
6266
..attributes['href'] = record.link
6367
..text = record.title))
6468
..append(Element.tag('td')
6569
..text = recordHaveCyclomaticComplexityViolations
66-
? '${record.report.totalCyclomaticComplexity} / ${record.report.cyclomaticComplexityViolations}'
67-
: '${record.report.totalCyclomaticComplexity}'
70+
? '${report.totalCyclomaticComplexity} / ${report.cyclomaticComplexityViolations}'
71+
: '${report.totalCyclomaticComplexity}'
6872
..classes.add(
6973
recordHaveCyclomaticComplexityViolations ? 'with-violations' : '',
7074
))
7175
..append(Element.tag('td')
7276
..text = recordHaveSourceLinesOfCodeViolations
73-
? '${record.report.totalSourceLinesOfCode} / ${record.report.sourceLinesOfCodeViolations}'
74-
: '${record.report.totalSourceLinesOfCode}'
77+
? '${report.totalSourceLinesOfCode} / ${report.sourceLinesOfCodeViolations}'
78+
: '${report.totalSourceLinesOfCode}'
7579
..classes.add(
7680
recordHaveSourceLinesOfCodeViolations ? 'with-violations' : '',
7781
))
7882
..append(Element.tag('td')
7983
..text = recordHaveMaintainabilityIndexViolations
80-
? '${record.report.averageMaintainabilityIndex.toInt()} / ${record.report.maintainabilityIndexViolations}'
81-
: '${record.report.averageMaintainabilityIndex.toInt()}'
84+
? '$averageMaintainabilityIndex / ${record.report.maintainabilityIndexViolations}'
85+
: '$averageMaintainabilityIndex'
8286
..classes.add(
8387
recordHaveMaintainabilityIndexViolations ? 'with-violations' : '',
8488
))
8589
..append(Element.tag('td')
8690
..text = recordHaveArgumentsCountViolations
87-
? '${record.report.averageArgumentsCount} / ${record.report.argumentsCountViolations}'
88-
: '${record.report.averageArgumentsCount}'
91+
? '${report.averageArgumentsCount} / ${report.argumentsCountViolations}'
92+
: '${report.averageArgumentsCount}'
8993
..classes
9094
.add(recordHaveArgumentsCountViolations ? 'with-violations' : ''))
9195
..append(Element.tag('td')
9296
..text = recordHaveMaximumNestingLevelViolations
93-
? '${record.report.averageMaximumNestingLevel} / ${record.report.maximumNestingLevelViolations}'
94-
: '${record.report.averageMaximumNestingLevel}'
97+
? '${report.averageMaximumNestingLevel} / ${report.maximumNestingLevelViolations}'
98+
: '${report.averageMaximumNestingLevel}'
9599
..classes.add(
96100
recordHaveMaximumNestingLevelViolations ? 'with-violations' : '',
97101
))

0 commit comments

Comments
 (0)