runner.dart 9.07 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
// @dart = 2.8

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 34 35 36 37
    bool muteCommandLogging = false,
    bool verbose = false,
    bool verboseHelp = false,
    bool reportCrashes,
    String flutterVersion,
    Map<Type, Generator> overrides,
  }) 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 43 44
    args.removeWhere((String option) => option == '-v' || option == '--verbose');
  }

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
      // This catches all exceptions to send to crash logging, etc.
      } catch (error, stackTrace) {  // ignore: avoid_catches_without_on_clauses
75 76
        firstError = error;
        firstStackTrace = stackTrace;
77
        return _handleToolError(
78 79
            error, stackTrace, verbose, args, reportCrashes, getVersion);
      }
80
    }, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use
81 82 83
      // 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.
84 85 86
      firstError ??= error;
      firstStackTrace ??= stackTrace;
      await _handleToolError(firstError, firstStackTrace, verbose, args, reportCrashes, getVersion);
87
    });
88
  }, overrides: overrides);
89 90 91
}

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

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

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

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

    try {
153 154 155 156 157 158 159 160
      final CrashDetails details = CrashDetails(
        command: _crashCommand(args),
        error: error,
        stackTrace: stackTrace,
        doctorText: await _doctorText(),
      );
      final File file = await _createLocalCrashReport(details);
      await globals.crashReporter.informUser(details, file);
161

162
      return _exit(1);
163 164
    // This catch catches all exceptions to ensure the message below is printed.
    } catch (error) { // ignore: avoid_catches_without_on_clauses
165
      globals.stdio.stderrWrite(
166
        'Unable to generate crash report due to secondary error: $error\n'
167 168
        '${globals.userMessages.flutterToolBugInstructions}\n');
      // Any exception thrown here (including one thrown by `_exit()`) will
169 170 171 172
      // 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);
173 174 175 176
    }
  }
}

177 178 179 180
String _crashCommand(List<String> args) => 'flutter ${args.join(' ')}';

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

181
/// Saves the crash report to a local file.
182
Future<File> _createLocalCrashReport(CrashDetails details) async {
183
  File crashFile = globals.fsUtils.getUniqueFile(
184
    globals.fs.currentDirectory,
185 186 187
    'flutter',
    'log',
  );
188

189
  final StringBuffer buffer = StringBuffer();
190

191 192
  buffer.writeln('Flutter crash report.');
  buffer.writeln('${globals.userMessages.flutterToolBugInstructions}\n');
193 194

  buffer.writeln('## command\n');
195
  buffer.writeln('${details.command}\n');
196 197

  buffer.writeln('## exception\n');
198 199
  buffer.writeln('${_crashException(details.error)}\n');
  buffer.writeln('```\n${details.stackTrace}```\n');
200 201

  buffer.writeln('## flutter doctor\n');
202
  buffer.writeln('```\n${details.doctorText}```');
203 204

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

  return crashFile;
}

Future<String> _doctorText() async {
  try {
226
    final BufferLogger logger = BufferLogger(
227
      terminal: globals.terminal,
228
      outputPreferences: globals.outputPreferences,
229
    );
230

231 232
    final Doctor doctor = Doctor(logger: logger);
    await doctor.diagnose(verbose: true, showColor: false);
233 234

    return logger.statusText;
235
  } on Exception catch (error, trace) {
236 237 238 239 240
    return 'encountered exception: $error\n\n${trace.toString().trim()}\n';
  }
}

Future<int> _exit(int code) async {
241
  // Prints the welcome message if needed.
242
  globals.flutterUsage.printWelcome();
243 244 245

  // Send any last analytics calls that are in progress without overly delaying
  // the tool's exit (we wait a maximum of 250ms).
246
  if (globals.flutterUsage.enabled) {
247
    final Stopwatch stopwatch = Stopwatch()..start();
248
    await globals.flutterUsage.ensureAnalyticsSent();
249
    globals.printTrace('ensureAnalyticsSent: ${stopwatch.elapsedMilliseconds}ms');
250 251 252
  }

  // Run shutdown hooks before flushing logs
253
  await globals.shutdownHooks.runShutdownHooks();
254

255
  final Completer<void> completer = Completer<void>();
256 257 258 259

  // Give the task / timer queue one cycle through before we hard exit.
  Timer.run(() {
    try {
260
      globals.printTrace('exiting with code $code');
261 262
      exit(code);
      completer.complete();
263
    // This catches all exceptions because the error is propagated on the
264 265
    // completer.
    } catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
266 267 268 269 270 271 272
      completer.completeError(error, stackTrace);
    }
  });

  await completer.future;
  return code;
}