runner.dart 8.86 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5

6

7 8 9
import 'dart:async';

import 'package:args/command_runner.dart';
10 11
import 'package:intl/intl.dart' as intl;
import 'package:intl/intl_standalone.dart' as intl_standalone;
12

13
import 'src/base/async_guard.dart';
14 15 16 17 18 19
import 'src/base/common.dart';
import 'src/base/context.dart';
import 'src/base/file_system.dart';
import 'src/base/io.dart';
import 'src/base/logger.dart';
import 'src/base/process.dart';
20
import 'src/context_runner.dart';
21
import 'src/doctor.dart';
22
import 'src/globals.dart' as globals;
23
import 'src/reporting/crash_reporting.dart';
24 25 26 27 28 29
import 'src/runner/flutter_command.dart';
import 'src/runner/flutter_command_runner.dart';

/// Runs the Flutter tool with support for the specified list of [commands].
Future<int> run(
  List<String> args,
30
  List<FlutterCommand> Function() commands, {
31 32 33
    bool muteCommandLogging = false,
    bool verbose = false,
    bool verboseHelp = false,
34 35 36
    bool? reportCrashes,
    String? flutterVersion,
    Map<Type, Generator>? overrides,
37
  }) async {
38 39 40
  if (muteCommandLogging) {
    // Remove the verbose option; for help and doctor, users don't need to see
    // verbose logs.
41
    args = List<String>.of(args);
42
    args.removeWhere((String option) => option == '-vv' || option == '-v' || option == '--verbose');
43 44
  }

45
  return runInContext<int>(() async {
46
    reportCrashes ??= !await globals.isRunningOnBot;
47
    final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp);
48
    commands().forEach(runner.addCommand);
49

50
    // Initialize the system locale.
51 52 53
    final String systemLocale = await intl_standalone.findSystemLocale();
    intl.Intl.defaultLocale = intl.Intl.verifiedLocale(
      systemLocale, intl.NumberFormat.localeExists,
54
      onFailure: (String _) => 'en_US',
55
    );
56

57
    String getVersion() => flutterVersion ?? globals.flutterVersion.getVersionString(redactUnknownBranches: true);
58 59
    Object? firstError;
    StackTrace? firstStackTrace;
60
    return runZoned<Future<int>>(() async {
61 62
      try {
        await runner.run(args);
63 64 65 66 67 68 69 70 71 72

        // Triggering [runZoned]'s error callback does not necessarily mean that
        // we stopped executing the body.  See https://github.com/dart-lang/sdk/issues/42150.
        if (firstError == null) {
          return await _exit(0);
        }

        // We already hit some error, so don't return success.  The error path
        // (which should be in progress) is responsible for calling _exit().
        return 1;
73 74
      } catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
        // This catches all exceptions to send to crash logging, etc.
75 76
        firstError = error;
        firstStackTrace = stackTrace;
77
        return _handleToolError(error, stackTrace, verbose, args, reportCrashes!, getVersion);
78
      }
79
    }, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use
80 81 82
      // If sending a crash report throws an error into the zone, we don't want
      // to re-try sending the crash report with *that* error. Rather, we want
      // to send the original error that triggered the crash report.
83 84
      firstError ??= error;
      firstStackTrace ??= stackTrace;
85
      await _handleToolError(firstError!, firstStackTrace, verbose, args, reportCrashes!, getVersion);
86
    });
87
  }, overrides: overrides);
88 89 90
}

Future<int> _handleToolError(
91 92
  Object error,
  StackTrace? stackTrace,
93 94 95
  bool verbose,
  List<String> args,
  bool reportCrashes,
96
  String Function() getFlutterVersion,
97
) async {
98
  if (error is UsageException) {
99 100
    globals.printError('${error.message}\n');
    globals.printError("Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.");
101 102 103
    // Argument error exit code.
    return _exit(64);
  } else if (error is ToolExit) {
104
    if (error.message != null) {
105
      globals.printError(error.message!);
106 107
    }
    if (verbose) {
108
      globals.printError('\n$stackTrace\n');
109
    }
110 111 112 113 114 115 116 117 118 119 120
    return _exit(error.exitCode ?? 1);
  } else if (error is ProcessExit) {
    // We've caught an exit code.
    if (error.immediate) {
      exit(error.exitCode);
      return error.exitCode;
    } else {
      return _exit(error.exitCode);
    }
  } else {
    // We've crashed; emit a log report.
121
    globals.stdio.stderrWrite('\n');
122 123 124

    if (!reportCrashes) {
      // Print the stack trace on the bots - don't write a crash report.
125 126
      globals.stdio.stderrWrite('$error\n');
      globals.stdio.stderrWrite('$stackTrace\n');
127
      return _exit(1);
128
    }
129

130
    // Report to both [Usage] and [CrashReportSender].
131
    globals.flutterUsage.sendException(error);
132 133 134 135 136 137 138 139 140
    await asyncGuard(() async {
      final CrashReportSender crashReportSender = CrashReportSender(
        usage: globals.flutterUsage,
        platform: globals.platform,
        logger: globals.logger,
        operatingSystemUtils: globals.os,
      );
      await crashReportSender.sendReport(
        error: error,
141
        stackTrace: stackTrace!,
142 143 144 145 146 147
        getFlutterVersion: getFlutterVersion,
        command: args.join(' '),
      );
    }, onError: (dynamic error) {
      globals.printError('Error sending crash report: $error');
    });
148

149
    globals.printError('Oops; flutter has exited unexpectedly: "$error".');
150 151

    try {
152 153 154 155 156 157 158
      final BufferLogger logger = BufferLogger(
        terminal: globals.terminal,
        outputPreferences: globals.outputPreferences,
      );

      final DoctorText doctorText = DoctorText(logger);

159 160 161
      final CrashDetails details = CrashDetails(
        command: _crashCommand(args),
        error: error,
162
        stackTrace: stackTrace!,
163
        doctorText: doctorText,
164 165
      );
      final File file = await _createLocalCrashReport(details);
166
      await globals.crashReporter!.informUser(details, file);
167

168
      return _exit(1);
169
    // This catch catches all exceptions to ensure the message below is printed.
170
    } catch (error, st) { // ignore: avoid_catches_without_on_clauses
171
      globals.stdio.stderrWrite(
172
        'Unable to generate crash report due to secondary error: $error\n$st\n'
173 174
        '${globals.userMessages.flutterToolBugInstructions}\n',
      );
175
      // Any exception thrown here (including one thrown by `_exit()`) will
176 177 178 179
      // get caught by our zone's `onError` handler. In order to avoid an
      // infinite error loop, we throw an error that is recognized above
      // and will trigger an immediate exit.
      throw ProcessExit(1, immediate: true);
180 181 182 183
    }
  }
}

184 185 186 187
String _crashCommand(List<String> args) => 'flutter ${args.join(' ')}';

String _crashException(dynamic error) => '${error.runtimeType}: $error';

188
/// Saves the crash report to a local file.
189
Future<File> _createLocalCrashReport(CrashDetails details) async {
190
  File crashFile = globals.fsUtils.getUniqueFile(
191
    globals.fs.currentDirectory,
192 193 194
    'flutter',
    'log',
  );
195

196
  final StringBuffer buffer = StringBuffer();
197

198 199
  buffer.writeln('Flutter crash report.');
  buffer.writeln('${globals.userMessages.flutterToolBugInstructions}\n');
200 201

  buffer.writeln('## command\n');
202
  buffer.writeln('${details.command}\n');
203 204

  buffer.writeln('## exception\n');
205 206
  buffer.writeln('${_crashException(details.error)}\n');
  buffer.writeln('```\n${details.stackTrace}```\n');
207 208

  buffer.writeln('## flutter doctor\n');
209
  buffer.writeln('```\n${await details.doctorText.text}```');
210 211

  try {
212
    crashFile.writeAsStringSync(buffer.toString());
213 214
  } on FileSystemException catch (_) {
    // Fallback to the system temporary directory.
215
    crashFile = globals.fsUtils.getUniqueFile(
216
      globals.fs.systemTempDirectory,
217 218 219
      'flutter',
      'log',
    );
220
    try {
221
      crashFile.writeAsStringSync(buffer.toString());
222
    } on FileSystemException catch (e) {
223 224
      globals.printError('Could not write crash report to disk: $e');
      globals.printError(buffer.toString());
225 226 227 228 229 230 231
    }
  }

  return crashFile;
}

Future<int> _exit(int code) async {
232
  // Prints the welcome message if needed.
233
  globals.flutterUsage.printWelcome();
234 235 236

  // Send any last analytics calls that are in progress without overly delaying
  // the tool's exit (we wait a maximum of 250ms).
237
  if (globals.flutterUsage.enabled) {
238
    final Stopwatch stopwatch = Stopwatch()..start();
239
    await globals.flutterUsage.ensureAnalyticsSent();
240
    globals.printTrace('ensureAnalyticsSent: ${stopwatch.elapsedMilliseconds}ms');
241 242 243
  }

  // Run shutdown hooks before flushing logs
244
  await globals.shutdownHooks!.runShutdownHooks();
245

246
  final Completer<void> completer = Completer<void>();
247 248 249 250

  // Give the task / timer queue one cycle through before we hard exit.
  Timer.run(() {
    try {
251
      globals.printTrace('exiting with code $code');
252 253
      exit(code);
      completer.complete();
254
    // This catches all exceptions because the error is propagated on the
255 256
    // completer.
    } catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
257 258 259 260 261 262 263
      completer.completeError(error, stackTrace);
    }
  });

  await completer.future;
  return code;
}