runner.dart 9.29 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
import 'package:http/http.dart' as http;
11 12
import 'package:intl/intl.dart' as intl;
import 'package:intl/intl_standalone.dart' as intl_standalone;
13

14
import 'src/base/async_guard.dart';
15 16 17 18 19 20
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';
21
import 'src/context_runner.dart';
22
import 'src/doctor.dart';
23
import 'src/globals.dart' as globals;
24
import 'src/reporting/reporting.dart';
25 26 27 28
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].
29 30 31
///
/// [commands] must be either `List<FlutterCommand>` or `List<FlutterCommand> Function()`.
// TODO(jonahwilliams): update command type once g3 has rolled.
32 33
Future<int> run(
  List<String> args,
34
  List<FlutterCommand> Function() commands, {
35 36 37 38 39 40 41
    bool muteCommandLogging = false,
    bool verbose = false,
    bool verboseHelp = false,
    bool reportCrashes,
    String flutterVersion,
    Map<Type, Generator> overrides,
  }) async {
42 43 44
  if (muteCommandLogging) {
    // Remove the verbose option; for help and doctor, users don't need to see
    // verbose logs.
45
    args = List<String>.of(args);
46 47 48
    args.removeWhere((String option) => option == '-v' || option == '--verbose');
  }

49
  return runInContext<int>(() async {
50
    reportCrashes ??= !await globals.isRunningOnBot;
51
    final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp);
52
    commands().forEach(runner.addCommand);
53

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

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

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

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

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

135
    // Report to both [Usage] and [CrashReportSender].
136
    globals.flutterUsage.sendException(error);
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    await asyncGuard(() async {
      final CrashReportSender crashReportSender = CrashReportSender(
        client: http.Client(),
        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');
    });
154

155
    globals.printError('Oops; flutter has exited unexpectedly: "$error".');
156 157

    try {
158 159 160 161 162 163 164 165
      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);
166

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

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

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

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

194
  final StringBuffer buffer = StringBuffer();
195

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

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

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

  buffer.writeln('## flutter doctor\n');
207
  buffer.writeln('```\n${details.doctorText}```');
208 209

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

  return crashFile;
}

Future<String> _doctorText() async {
  try {
231
    final BufferLogger logger = BufferLogger(
232
      terminal: globals.terminal,
233
      outputPreferences: globals.outputPreferences,
234
    );
235

236 237
    final Doctor doctor = Doctor(logger: logger);
    await doctor.diagnose(verbose: true, showColor: false);
238 239

    return logger.statusText;
240
  } on Exception catch (error, trace) {
241 242 243 244 245
    return 'encountered exception: $error\n\n${trace.toString().trim()}\n';
  }
}

Future<int> _exit(int code) async {
246
  // Prints the welcome message if needed.
247
  globals.flutterUsage.printWelcome();
248 249 250

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

  // Run shutdown hooks before flushing logs
258
  await shutdownHooks.runShutdownHooks();
259

260
  final Completer<void> completer = Completer<void>();
261 262 263 264

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

  await completer.future;
  return code;
}