This repository has been archived by the owner on Nov 9, 2018. It is now read-only.
/
dart_fix.dart
289 lines (234 loc) · 8.38 KB
/
dart_fix.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) 2018, 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:async';
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:cli_util/cli_logging.dart';
import 'package:dart2_fix/src/changes.dart';
import 'package:dart2_fix/src/deprecation_analysis_server.dart';
import 'package:dart2_fix/src/model.dart';
import 'package:intl/intl.dart';
import 'package:path/path.dart' as p;
final NumberFormat _nf = new NumberFormat('0.0');
Future<ExitResult> dartFix(List<String> args) async {
ArgParser argParser = new ArgParser();
argParser.addFlag('help',
negatable: false, abbr: 'h', help: 'Display usage help.');
argParser.addFlag('apply',
abbr: 'w',
negatable: false,
help: "Apply the refactoring changes to the project's source files.");
argParser.addOption('check-package',
help:
'Retrieve the source for the given hosted package and run checks on '
'it\n(this command is not typically run by users).',
valueHelp: 'package name');
argParser.addFlag('verbose',
negatable: false, help: 'Print verbose logging information.');
argParser.addFlag('color',
help: 'Use ansi colors when printing messages.',
defaultsTo: Ansi.terminalSupportsAnsi);
ArgResults results;
try {
results = argParser.parse(args);
if (results['help']) {
_printUsage(argParser);
return ExitResult.ok;
}
} on FormatException catch (e) {
stderr.writeln(e.message);
print('');
_printUsage(argParser);
return new ExitResult(1);
}
List<Directory> dirs = results.rest.isEmpty
? [Directory.current]
: results.rest.map((s) => new Directory(s)).toList();
for (Directory dir in dirs) {
if (!dir.existsSync()) {
return new ExitResult(
1, "'${dir.path}' does not exist or is not a directory.");
}
}
final bool verbose = results['verbose'];
Ansi ansi = new Ansi(results.wasParsed('color')
? results['color']
: Ansi.terminalSupportsAnsi);
Logger logger = verbose
? new Logger.verbose(ansi: ansi)
: new Logger.standard(ansi: ansi);
final bool performDryRun = !results['apply'];
final String packageName = results['check-package'];
if (packageName != null) {
return await checkPackage(logger, packageName, performDryRun);
} else {
return await dartFixInternal(logger, dirs, performDryRun);
}
}
// public for testing
Future<ExitResult> dartFixInternal(
Logger logger, List<Directory> dirs, bool performDryRun) async {
final Ansi ansi = logger.ansi;
Progress progress;
if (performDryRun) {
progress =
logger.progress('Checking ${dirs.map((d) => d.path).join(', ')}');
} else {
progress =
logger.progress('Updating ${dirs.map((d) => d.path).join(', ')}');
}
Stopwatch stopwatch = new Stopwatch()..start();
DeprecationLocator locator = new DeprecationLocator(logger);
final DeprecationResults issues =
await locator.locateIssues(dirs.map((d) => d.path).toList());
progress.finish();
logger.stdout('');
if (issues.errors.isNotEmpty) {
for (Issue issue in issues.errors) {
logger.stdout('${issue.severity.toLowerCase()} ${ansi.bullet} ${issue
.shortPath}:${issue
.line} ${ansi
.bullet} ${ansi.emphasized(issue.shortMessage)}');
}
logger.stdout('');
String suffix = performDryRun ? '' : '; no changes applied';
double seconds = stopwatch.elapsedMilliseconds / 1000.0;
return new ExitResult(
1,
'Found ${issues.errors.length} analysis ${_pluralize(
issues.errors.length, 'error', 'errors')}$suffix (in ${_nf.format(
seconds)}s).');
}
ChangeManager changeManager = ChangeManager.create();
Map<String, List<Change>> changes = {};
int count = 0;
for (Issue issue in issues.deprecations) {
final Change change = changeManager.getChangeFor(issue);
if (change != null) {
count++;
changes.putIfAbsent(issue.path, () => []);
changes[issue.path].add(change);
}
}
if (performDryRun) {
List<String> paths = changes.keys.toList();
paths.sort();
for (String path in paths) {
logger.stdout(p.relative(path));
List<Change> fileChanges = changes[path];
fileChanges.sort();
for (Change change in fileChanges) {
logger.stdout(' line ${change.line} ${ansi.bullet} ${ansi.emphasized(
change.describe)}');
}
logger.stdout('');
}
double seconds = stopwatch.elapsedMilliseconds / 1000.0;
logger.stdout('Found ${count} fixes in ${_nf.format(seconds)}s.');
if (count > 0) {
logger.stdout('');
logger.stdout(
'To apply these fixes, run again using the --apply argument.');
}
} else {
List<String> paths = changes.keys.toList();
paths.sort();
for (String path in paths) {
logger.stdout(p.relative(path));
List<Change> fileChanges = changes[path];
fileChanges.sort();
File file = new File(path);
String contents = file.readAsStringSync();
Map<String, int> fixCounts = {};
for (Change change in fileChanges.reversed) {
contents = change.applyTo(contents);
String description = change.describe;
fixCounts.putIfAbsent(description, () => 0);
fixCounts[description] = fixCounts[description] + 1;
}
file.writeAsStringSync(contents);
for (String desc in fixCounts.keys) {
logger.stdout(' ${fixCounts[desc]} ${_pluralize(
fixCounts[desc], 'fix', 'fixes')} applied for ${ansi.emphasized(
desc)}');
}
logger.stdout('');
}
double seconds = stopwatch.elapsedMilliseconds / 1000.0;
logger
.stdout('Applied ${count} ${_pluralize(count, 'fix', 'fixes')} in ${_nf
.format(seconds)}s.');
}
return ExitResult.ok;
}
Future<ExitResult> checkPackage(
Logger logger, String packageName, bool performDryRun) async {
String jsonData =
await _uriDownload('https://pub.dartlang.org/api/packages/$packageName/');
Map json = jsonDecode(jsonData);
Map pubspec = json['latest']['pubspec'];
String homepage = pubspec['homepage'];
if (homepage == null) {
return new ExitResult(1, 'No homepage definied for package $packageName.');
}
Uri homepageUri = Uri.parse(homepage);
if (homepageUri.host != 'github.com') {
return new ExitResult(
1, "Homepage is '$homepage', but we require it to be a github repo.");
}
if (homepageUri.path.substring(1).split('/').length > 2) {
return new ExitResult(
1,
'Unsupported homepage reference: $homepage.\n'
'This tool only supports a homepage reference that points to the root of a repo.');
}
Directory dir = new Directory(packageName);
dir.createSync();
Progress progress;
if (performDryRun) {
progress = logger.progress('Cloning $homepage into $packageName');
try {
await gitClone(homepageUri, dir);
} finally {
progress.finish();
}
progress = logger.progress('Running pub get');
try {
await pubGet(dir);
} finally {
progress.finish();
}
}
return await dartFixInternal(logger, [dir], performDryRun);
}
Future gitClone(Uri uri, Directory dir) async {
Process process = await Process.start('git', ['clone', uri.toString(), '.'],
workingDirectory: dir.path);
return process.exitCode;
}
Future pubGet(Directory dir) async {
String pubPath = p.join(p.dirname(Platform.resolvedExecutable), 'pub');
Process process =
await Process.start(pubPath, ['get'], workingDirectory: dir.path);
return process.exitCode;
}
String _pluralize(int count, String singular, String plural) =>
count == 1 ? singular : plural;
void _printUsage(ArgParser argParser) {
print('usage: dart2_fix [options...] <directories>');
print('');
print(argParser.usage);
}
Future<String> _uriDownload(String uri) async {
HttpClient client = new HttpClient();
HttpClientRequest request = await client.getUrl(Uri.parse(uri));
HttpClientResponse response = await request.close();
Completer<String> completer = new Completer<String>();
StringBuffer contents = new StringBuffer();
response.transform(utf8.decoder).listen((String data) {
contents.write(data);
}, onDone: () => completer.complete(contents.toString()));
return completer.future;
}