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

import 'dart:async';

import 'package:args/command_runner.dart';
8 9
import 'package:intl/intl.dart' as intl;
import 'package:intl/intl_standalone.dart' as intl_standalone;
10
import 'package:http/http.dart' as http;
11 12 13 14 15 16 17

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

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

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

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

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

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

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

132
    // Report to both [Usage] and [CrashReportSender].
133
    globals.flutterUsage.sendException(error);
134 135 136 137 138 139 140 141
    final CrashReportSender crashReportSender = CrashReportSender(
      client: http.Client(),
      usage: globals.flutterUsage,
      platform: globals.platform,
      logger: globals.logger,
      operatingSystemUtils: globals.os,
    );
    await crashReportSender.sendReport(
142 143 144 145 146
      error: error,
      stackTrace: stackTrace,
      getFlutterVersion: getFlutterVersion,
      command: args.join(' '),
    );
147

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

    try {
151 152 153 154 155 156 157 158
      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);
159

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

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

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

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

187
  final StringBuffer buffer = StringBuffer();
188

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

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

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

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

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

  return crashFile;
}

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

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

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

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

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

  // Run shutdown hooks before flushing logs
251
  await shutdownHooks.runShutdownHooks();
252

253
  final Completer<void> completer = Completer<void>();
254 255 256 257

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

  await completer.future;
  return code;
}