-
Notifications
You must be signed in to change notification settings - Fork 44
/
static_analysis.dart
215 lines (198 loc) · 6.67 KB
/
static_analysis.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
import 'dart:math' as math;
import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart';
import '../internal_model.dart';
import '../logging.dart';
import '../model.dart';
import '../package_context.dart';
import '../sdk_env.dart';
import '../tool/run_constrained.dart';
import '../utils.dart';
import '_common.dart';
Future<ReportSection> staticAnalysis(PackageContext context) async {
final packageDir = context.packageDir;
final analysisResult = await _analyzePackage(context);
final errors = analysisResult.errors;
final warnings = analysisResult.warnings;
final lints = analysisResult.lints;
// Only try to run dart format if there where no errors.
final formattingIssues = errors.isEmpty
? await _formatPackage(
packageDir,
context.toolEnvironment,
usesFlutter: context.usesFlutter,
lineLength: context.options.lineLength,
)
: <Issue>[];
final status = (errors.isEmpty && warnings.isEmpty)
? (formattingIssues.isEmpty && lints.isEmpty
? ReportStatus.passed
: ReportStatus.partial)
: ReportStatus.failed;
// 30 points: static analysis has 0 errors
// 40 points: static analysis has 0 errors, warnings
// 50 points: static analysis has 0 errors, warnings, lints
var grantedPoints = 0;
if (errors.isEmpty) {
grantedPoints = 30;
if (warnings.isEmpty) {
grantedPoints = 40;
if (lints.isEmpty && formattingIssues.isEmpty) {
grantedPoints = 50;
}
}
}
return makeSection(
id: ReportSectionId.analysis,
title: 'Pass static analysis',
maxPoints: 50,
subsections: [
Subsection(
'code has no errors, warnings, lints, or formatting issues',
[...errors, ...warnings, ...lints, ...formattingIssues],
grantedPoints,
50,
status,
)
],
basePath: packageDir,
);
}
Future<_AnalysisResult> _analyzePackage(PackageContext context) async {
Issue issueFromCodeProblem(CodeProblem codeProblem) {
return Issue(
'${codeProblem.severity}: ${codeProblem.description}',
suggestion:
'To reproduce make sure you are using the [lints_core](https://pub.dev/packages/lints) and '
'run `${context.usesFlutter ? 'flutter analyze' : 'dart analyze'} ${codeProblem.file}`',
spanFn: () => sourceSpanFromFile(
path: p.join(context.packageDir, codeProblem.file),
line: codeProblem.line,
col: codeProblem.col,
length: codeProblem.length,
),
);
}
final dirs = await listFocusDirs(context.packageDir);
try {
final errorMessage = await context.resolveErrorMessage;
if (errorMessage != null) {
String? suggestion;
if (errorMessage.contains('from sdk which doesn\'t match any versions') &&
errorMessage.contains('requires _macros ')) {
suggestion =
'The SDK package `_macros` is an experimental feature which is only available in newer SDKs. '
'Increase your minimum SDK constraint for `pub.dev` to select such SDK for analysis.';
}
return _AnalysisResult(
[Issue(errorMessage, suggestion: suggestion)],
[],
[],
context.usesFlutter ? 'flutter pub get' : 'dart pub get',
);
}
final rs = await context.staticAnalysis;
return _AnalysisResult(
rs.items!
.where((element) => element.isError)
.map(issueFromCodeProblem)
.toList(),
rs.items!
.where((element) => element.isWarning)
.map(issueFromCodeProblem)
.toList(),
rs.items!
.where((element) => element.isInfo)
.map(issueFromCodeProblem)
.toList(),
'dart analyze ${dirs.join(' ')}');
} on ToolException catch (e) {
return _AnalysisResult(
[
Issue('Failed to run `dart analyze`:\n```\n${e.message}\n```\n'),
],
[],
[],
'dart analyze ${dirs.join(' ')}',
);
}
}
FileSpan? sourceSpanFromFile({
required String path,
required int line,
required int col,
required int length,
}) {
final sourceText = File(path).readAsStringSync();
final sourceFile = SourceFile.fromString(sourceText, url: path);
try {
// SourceSpans are 0-based, so we subtract 1 from line and column.
var startOffset = sourceFile.getOffset(line - 1, col - 1);
// making sure that we don't start on CR line terminator
// TODO: Remove this after https://github.com/dart-lang/source_span/issues/79 gets fixed.
while (startOffset < sourceText.length &&
sourceText.codeUnitAt(startOffset) == 13) {
startOffset++;
}
// Limit the maximum length of the source span.
var newLength = math.min(length, maxSourceSpanLength);
newLength = math.min(newLength, sourceText.length - startOffset);
// making sure that we don't end on CR line terminator
// TODO: Remove this after https://github.com/dart-lang/source_span/issues/79 gets fixed.
while (newLength > 0 &&
sourceText.codeUnitAt(startOffset + newLength - 1) == 13) {
newLength--;
}
if (newLength <= 0) {
// Note: this may happen if the span is entirely CR line terminators.
return null;
}
return sourceFile.span(startOffset, startOffset + newLength);
// ignore: avoid_catching_errors
} on RangeError {
// Note: This happens if the file contains CR as line terminators.
// If the range is invalid, then we just return null.
return null;
}
}
class _AnalysisResult {
final List<Issue> errors;
final List<Issue> warnings;
final List<Issue> lints;
final String reproductionCommand;
_AnalysisResult(
this.errors, this.warnings, this.lints, this.reproductionCommand);
}
Future<List<Issue>> _formatPackage(
String packageDir,
ToolEnvironment toolEnvironment, {
required bool usesFlutter,
int? lineLength,
}) async {
try {
final unformattedFiles = await toolEnvironment.filesNeedingFormat(
packageDir,
usesFlutter,
lineLength: lineLength,
);
return unformattedFiles
.map((f) => Issue(
'$f doesn\'t match the Dart formatter.',
suggestion: 'To format your files run: `dart format .`',
))
.toList();
} on ToolException catch (e) {
return [
Issue('Running `dart format` failed:\n```\n${e.message}```'),
];
} catch (e, stack) {
log.severe('`dart format` failed.\n$e', e, stack);
return [
Issue('Running `dart format` failed.'),
];
}
}