runner.dart 7.88 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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 11 12 13 14 15 16 17 18
import 'package:meta/meta.dart';

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';
import 'src/base/utils.dart';
19
import 'src/context_runner.dart';
20 21
import 'src/doctor.dart';
import 'src/globals.dart';
22
import 'src/reporting/reporting.dart';
23 24 25 26 27 28 29 30
import 'src/runner/flutter_command.dart';
import 'src/runner/flutter_command_runner.dart';
import 'src/version.dart';

/// Runs the Flutter tool with support for the specified list of [commands].
Future<int> run(
  List<String> args,
  List<FlutterCommand> commands, {
31 32 33
  bool muteCommandLogging = false,
  bool verbose = false,
  bool verboseHelp = false,
34 35
  bool reportCrashes,
  String flutterVersion,
36
  Map<Type, Generator> overrides,
37
}) {
38 39
  reportCrashes ??= !isRunningOnBot;

40 41 42
  if (muteCommandLogging) {
    // Remove the verbose option; for help and doctor, users don't need to see
    // verbose logs.
43
    args = List<String>.from(args);
44 45 46
    args.removeWhere((String option) => option == '-v' || option == '--verbose');
  }

47
  final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp);
48 49
  commands.forEach(runner.addCommand);

50
  return runInContext<int>(() async {
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 ?? FlutterVersion.instance.getVersionString(redactUnknownBranches: true);
59 60
    Object firstError;
    StackTrace firstStackTrace;
61 62 63 64 65
    return await runZoned<Future<int>>(() async {
      try {
        await runner.run(args);
        return await _exit(0);
      } catch (error, stackTrace) {
66 67
        firstError = error;
        firstStackTrace = stackTrace;
68 69 70 71
        return await _handleToolError(
            error, stackTrace, verbose, args, reportCrashes, getVersion);
      }
    }, onError: (Object error, StackTrace stackTrace) async {
72 73 74 75 76 77
      // 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.
      final Object e = firstError ?? error;
      final StackTrace s = firstStackTrace ?? stackTrace;
      await _handleToolError(e, s, verbose, args, reportCrashes, getVersion);
78
    });
79
  }, overrides: overrides);
80 81 82
}

Future<int> _handleToolError(
83 84 85 86 87 88 89
  dynamic error,
  StackTrace stackTrace,
  bool verbose,
  List<String> args,
  bool reportCrashes,
  String getFlutterVersion(),
) async {
90
  if (error is UsageException) {
91 92
    printError('${error.message}\n');
    printError("Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.");
93 94 95
    // Argument error exit code.
    return _exit(64);
  } else if (error is ToolExit) {
96
    if (error.message != null) {
97
      printError(error.message);
98 99
    }
    if (verbose) {
100
      printError('\n$stackTrace\n');
101
    }
102 103 104 105 106 107 108 109 110 111 112
    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.
113
    stderr.writeln();
114 115 116

    if (!reportCrashes) {
      // Print the stack trace on the bots - don't write a crash report.
117 118
      stderr.writeln('$error');
      stderr.writeln(stackTrace.toString());
119
      return _exit(1);
120
    }
121

122 123 124 125 126 127 128 129
    // Report to both [Usage] and [CrashReportSender].
    flutterUsage.sendException(error);
    await CrashReportSender.instance.sendReport(
      error: error,
      stackTrace: stackTrace,
      getFlutterVersion: getFlutterVersion,
      command: args.join(' '),
    );
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    if (error is String) {
      stderr.writeln('Oops; flutter has exited unexpectedly: "$error".');
    } else {
      stderr.writeln('Oops; flutter has exited unexpectedly.');
    }

    try {
      final File file = await _createLocalCrashReport(args, error, stackTrace);
      stderr.writeln(
        'Crash report written to ${file.path};\n'
            'please let us know at https://github.com/flutter/flutter/issues.',
      );
      return _exit(1);
    } catch (error) {
      stderr.writeln(
        'Unable to generate crash report due to secondary error: $error\n'
            'please let us know at https://github.com/flutter/flutter/issues.',
      );
      // Any exception throw here (including one thrown by `_exit()`) will
      // 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);
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    }
  }
}

/// File system used by the crash reporting logic.
///
/// We do not want to use the file system stored in the context because it may
/// be recording. Additionally, in the case of a crash we do not trust the
/// integrity of the [AppContext].
@visibleForTesting
FileSystem crashFileSystem = const LocalFileSystem();

/// Saves the crash report to a local file.
Future<File> _createLocalCrashReport(List<String> args, dynamic error, StackTrace stackTrace) async {
  File crashFile = getUniqueFile(crashFileSystem.currentDirectory, 'flutter', 'log');

170
  final StringBuffer buffer = StringBuffer();
171 172 173 174 175 176 177 178 179 180 181 182 183 184

  buffer.writeln('Flutter crash report; please file at https://github.com/flutter/flutter/issues.\n');

  buffer.writeln('## command\n');
  buffer.writeln('flutter ${args.join(' ')}\n');

  buffer.writeln('## exception\n');
  buffer.writeln('${error.runtimeType}: $error\n');
  buffer.writeln('```\n$stackTrace```\n');

  buffer.writeln('## flutter doctor\n');
  buffer.writeln('```\n${await _doctorText()}```');

  try {
185
    crashFile.writeAsStringSync(buffer.toString());
186 187 188 189
  } on FileSystemException catch (_) {
    // Fallback to the system temporary directory.
    crashFile = getUniqueFile(crashFileSystem.systemTempDirectory, 'flutter', 'log');
    try {
190
      crashFile.writeAsStringSync(buffer.toString());
191 192 193 194 195 196 197 198 199 200 201
    } on FileSystemException catch (e) {
      printError('Could not write crash report to disk: $e');
      printError(buffer.toString());
    }
  }

  return crashFile;
}

Future<String> _doctorText() async {
  try {
202
    final BufferLogger logger = BufferLogger();
203

204
    await context.run<bool>(
205 206 207 208 209
      body: () => doctor.diagnose(verbose: true),
      overrides: <Type, Generator>{
        Logger: () => logger,
      },
    );
210 211 212 213 214 215 216 217

    return logger.statusText;
  } catch (error, trace) {
    return 'encountered exception: $error\n\n${trace.toString().trim()}\n';
  }
}

Future<int> _exit(int code) async {
218
  if (flutterUsage.isFirstRun) {
219
    flutterUsage.printWelcome();
220
  }
221 222 223 224

  // Send any last analytics calls that are in progress without overly delaying
  // the tool's exit (we wait a maximum of 250ms).
  if (flutterUsage.enabled) {
225
    final Stopwatch stopwatch = Stopwatch()..start();
226 227 228 229 230 231 232
    await flutterUsage.ensureAnalyticsSent();
    printTrace('ensureAnalyticsSent: ${stopwatch.elapsedMilliseconds}ms');
  }

  // Run shutdown hooks before flushing logs
  await runShutdownHooks();

233
  final Completer<void> completer = Completer<void>();
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

  // Give the task / timer queue one cycle through before we hard exit.
  Timer.run(() {
    try {
      printTrace('exiting with code $code');
      exit(code);
      completer.complete();
    } catch (error, stackTrace) {
      completer.completeError(error, stackTrace);
    }
  });

  await completer.future;
  return code;
}