-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
dartdev.dart
318 lines (284 loc) · 11.2 KB
/
dartdev.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright (c) 2020, 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.
// Do not call exit() directly. Use VmInteropHandler.exit() instead.
import 'dart:async';
import 'dart:io' as io hide exit;
import 'dart:isolate';
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:cli_util/cli_logging.dart';
import 'package:dart_style/src/cli/format_command.dart';
import 'package:meta/meta.dart';
import 'package:pub/pub.dart';
import 'package:usage/usage.dart';
import 'src/analytics.dart';
import 'src/commands/analyze.dart';
import 'src/commands/build.dart';
import 'src/commands/compilation_server.dart';
import 'src/commands/compile.dart';
import 'src/commands/create.dart';
import 'src/commands/debug_adapter.dart';
import 'src/commands/devtools.dart';
import 'src/commands/doc.dart';
import 'src/commands/fix.dart';
import 'src/commands/info.dart';
import 'src/commands/language_server.dart';
import 'src/commands/run.dart';
import 'src/commands/test.dart';
import 'src/core.dart';
import 'src/events.dart';
import 'src/experiments.dart';
import 'src/unified_analytics.dart';
import 'src/utils.dart';
import 'src/vm_interop_handler.dart';
/// This is typically called from bin/, but given the length of the method and
/// analytics logic, it has been moved here.
Future<void> runDartdev(List<String> args, SendPort? port) async {
int? exitCode = 1;
try {
VmInteropHandler.initialize(port);
if (args.contains('run')) {
// These flags have a format that can't be handled by package:args, so while
// they are valid flags we'll assume the VM has verified them by this point.
args = args
.where(
(element) => !(element.contains('--observe') ||
element.contains('--enable-vm-service') ||
element.contains('--devtools')),
)
.toList();
}
// Finally, call the runner to execute the command; see DartdevRunner.
final runner = DartdevRunner(args, io.Platform.executableArguments);
exitCode = await runner.run(args);
} on UsageException catch (e) {
// TODO(sigurdm): It is unclear when a UsageException gets to here, and
// when it is in DartdevRunner.runCommand.
io.stderr.writeln('$e');
exitCode = 64;
} catch (e, st) {
// Unexpected error encountered.
io.stderr.writeln('An unexpected error was encountered by the Dart CLI.');
io.stderr.writeln('Please file an issue at '
'https://github.com/dart-lang/sdk/issues/new with the following '
'details:\n');
io.stderr.writeln("Invocation: 'dart ${args.join(' ')}'");
io.stderr.writeln("Exception: '$e'");
io.stderr.writeln('Stack Trace:');
io.stderr.writeln(st.toString());
exitCode = 255;
} finally {
VmInteropHandler.exit(exitCode);
}
}
class DartdevRunner extends CommandRunner<int> {
static const String dartdevDescription =
'A command-line utility for Dart development';
@override
late final ArgParser argParser;
final bool verbose;
final List<String> vmEnabledExperiments;
late Analytics _analytics;
DartdevRunner(List<String> args, [List<String> vmArgs = const []])
: verbose = args.contains('-v') || args.contains('--verbose'),
argParser = globalDartdevOptionsParser(
verbose: args.contains('-v') || args.contains('--verbose')),
vmEnabledExperiments = parseVmEnabledExperiments(vmArgs),
super('dart', '$dartdevDescription.') {
addCommand(AnalyzeCommand(verbose: verbose));
addCommand(CompilationServerCommand(verbose: verbose));
final nativeAssetsExperimentEnabled =
nativeAssetsEnabled(vmEnabledExperiments);
if (nativeAssetsExperimentEnabled) {
addCommand(BuildCommand(verbose: verbose));
}
addCommand(CompileCommand(verbose: verbose));
addCommand(CreateCommand(verbose: verbose));
addCommand(DebugAdapterCommand(verbose: verbose));
addCommand(DevToolsCommand(verbose: verbose));
addCommand(DocCommand(verbose: verbose));
addCommand(FixCommand(verbose: verbose));
addCommand(FormatCommand(verbose: verbose));
addCommand(InfoCommand(verbose: verbose));
addCommand(LanguageServerCommand(verbose: verbose));
addCommand(
pubCommand(
analytics: PubAnalytics(
() => analytics,
dependencyKindCustomDimensionName: dependencyKindCustomDimensionName,
),
isVerbose: () => verbose,
),
);
addCommand(RunCommand(
verbose: verbose,
nativeAssetsExperimentEnabled: nativeAssetsExperimentEnabled,
));
addCommand(TestCommand(
nativeAssetsExperimentEnabled: nativeAssetsExperimentEnabled,
));
}
@visibleForTesting
Analytics get analytics => _analytics;
@override
String get invocation =>
'dart ${verbose ? '[vm-options] ' : ''}<command|dart-file> [arguments]';
@override
String get usageFooter =>
'See https://dart.dev/tools/dart-tool for detailed documentation.';
@override
Future<int> runCommand(ArgResults topLevelResults) async {
final stopwatch = Stopwatch()..start();
bool suppressAnalytics =
!topLevelResults['analytics'] || topLevelResults['suppress-analytics'];
if (topLevelResults.wasParsed('analytics')) {
io.stderr.writeln(
'`--[no-]analytics` is deprecated. Use `--suppress-analytics` '
'to disable analytics for one run instead.');
}
// The Analytics instance used to report information back to Google Analytics;
// see lib/src/analytics.dart.
_analytics = createAnalyticsInstance(suppressAnalytics);
// If we have not printed the analyticsNoticeOnFirstRunMessage to stdout,
// the user is on a terminal, and the machine is not a bot, then print the
// disclosure and set analytics.disclosureShownOnTerminal to true.
if (analytics is DartdevAnalytics &&
!(analytics as DartdevAnalytics).disclosureShownOnTerminal &&
io.stdout.hasTerminal &&
!isBot()) {
print(analyticsNoticeOnFirstRunMessage);
(analytics as DartdevAnalytics).disclosureShownOnTerminal = true;
}
// When `--disable-analytics` or `--enable-analytics` are called we perform
// the respective intention and print any notices to standard out and exit.
if (topLevelResults['disable-analytics'] ||
topLevelResults['disable-telemetry']) {
// This block also potentially catches the case of (disableAnalytics &&
// enableAnalytics), in which we favor the disabling of analytics.
analytics.enabled = false;
// Disable sending data via the unified analytics package.
var unifiedAnalytics = createUnifiedAnalytics();
await unifiedAnalytics.setTelemetry(false);
unifiedAnalytics.close();
// Alert the user that analytics has been disabled.
print(analyticsDisabledNoticeMessage);
return 0;
} else if (topLevelResults['enable-analytics']) {
analytics.enabled = true;
// Enable sending data via the unified analytics package.
var unifiedAnalytics = createUnifiedAnalytics();
await unifiedAnalytics.setTelemetry(true);
unifiedAnalytics.close();
// Alert the user again that data will be collected.
print(analyticsNoticeOnFirstRunMessage);
return 0;
}
if (topLevelResults.command == null &&
topLevelResults.arguments.isNotEmpty) {
final firstArg = topLevelResults.arguments.first;
// If we make it this far, it means the VM couldn't find the file on disk.
if (firstArg.endsWith('.dart')) {
io.stderr.writeln(
"Error when reading '$firstArg': No such file or directory.");
// This is the exit code used by the frontend.
return 254;
}
}
if (topLevelResults['diagnostics']) {
log = Logger.verbose(ansi: ansi);
}
var command = topLevelResults.command;
final commandNames = [];
while (command != null) {
commandNames.add(command.name);
if (command.command == null) break;
command = command.command;
}
final path = commandNames.join('/');
// Send the screen view to analytics
unawaited(
analytics.sendScreenView(path, parameters:
// Starts a new analytics session.
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#sc
{'sc': 'start'}),
);
// The exit code for the dartdev process; null indicates that it has not been
// set yet. The value is set in the catch and finally blocks below.
int? exitCode;
// Any caught non-UsageExceptions when running the sub command.
Object? exception;
StackTrace? stackTrace;
try {
exitCode = await super.runCommand(topLevelResults);
if (analytics.enabled) {
// Send the event to analytics
unawaited(
sendUsageEvent(
analytics,
path,
exitCode: exitCode,
commandFlags:
// This finds the options that where explicitly given to the command
// (and not for an eventual subcommand) without including the actual
// value.
//
// Note that this will also conflate short-options and long-options.
command?.options.where(command.wasParsed).toList() ??
const <String>[],
specifiedExperiments: topLevelResults.enabledExperiments,
),
);
}
} on UsageException catch (e) {
io.stderr.writeln('$e');
exitCode = 64;
} catch (e, st) {
// Set the exception and stack trace only for non-UsageException cases:
exception = e;
stackTrace = st;
io.stderr.writeln('$e');
io.stderr.writeln('$st');
exitCode = 1;
} finally {
stopwatch.stop();
if (analytics.enabled) {
unawaited(
analytics.sendTiming(
path,
stopwatch.elapsedMilliseconds,
category: 'commands',
),
);
}
// Set the exitCode, if it wasn't set in the catch block above.
exitCode ??= 0;
// Send analytics before exiting
if (analytics.enabled) {
// And now send the exceptions and events to Google Analytics:
if (exception != null) {
unawaited(
analytics.sendException(
'${exception.runtimeType}\n${sanitizeStacktrace(stackTrace)}',
fatal: true),
);
}
// Use no more than 5% of the running time or 1 second to process
// analytics, whichever is less. Assume a base of 150ms for dart VM
// initialization (not counted by stopwatch).
var ms = stopwatch.elapsedMilliseconds + 150;
var timeout = ms ~/ 20 > 1000 ? 1000 : ms ~/ 20;
await analytics.waitForLastPing(
timeout: Duration(milliseconds: timeout));
}
// Set the enabled flag in the analytics object to true. Note: this will not
// enable the analytics unless the disclosure was shown (terminal detected),
// and the machine is not detected to be a bot.
if (analytics.firstRun) {
analytics.enabled = true;
}
analytics.close();
}
return exitCode;
}
}