flutter_command.dart 17.3 KB
Newer Older
1 2 3 4 5 6
// 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';

7
import 'package:args/args.dart';
8
import 'package:args/command_runner.dart';
9
import 'package:meta/meta.dart';
10
import 'package:quiver/strings.dart';
11 12

import '../application_package.dart';
13
import '../base/common.dart';
14
import '../base/context.dart';
15
import '../base/file_system.dart';
16
import '../base/utils.dart';
17
import '../build_info.dart';
18
import '../bundle.dart' as bundle;
19
import '../dart/package_map.dart';
20
import '../dart/pub.dart';
21
import '../device.dart';
22
import '../doctor.dart';
23
import '../globals.dart';
24
import '../project.dart';
25
import '../usage.dart';
26 27
import 'flutter_command_runner.dart';

28 29 30 31 32 33 34
enum ExitStatus {
  success,
  warning,
  fail,
}

/// [FlutterCommand]s' subclasses' [FlutterCommand.runCommand] can optionally
35
/// provide a [FlutterCommandResult] to furnish additional information for
36 37
/// analytics.
class FlutterCommandResult {
38
  const FlutterCommandResult(
39
    this.exitStatus, {
40
    this.timingLabelParts,
41
    this.endTimeOverride,
42
  });
43 44 45

  final ExitStatus exitStatus;

46
  /// Optional data that can be appended to the timing event.
47 48
  /// https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#timingLabel
  /// Do not add PII.
49
  final List<String> timingLabelParts;
50

51
  /// Optional epoch time when the command's non-interactive wait time is
52
  /// complete during the command's execution. Use to measure user perceivable
53 54
  /// latency without measuring user interaction time.
  ///
55
  /// [FlutterCommand] will automatically measure and report the command's
56
  /// complete time if not overridden.
57 58 59
  final DateTime endTimeOverride;
}

60 61 62 63
/// Common flutter command line options.
class FlutterOptions {
  static const String kExtraFrontEndOptions = 'extra-front-end-options';
  static const String kExtraGenSnapshotOptions = 'extra-gen-snapshot-options';
64 65
  static const String kFileSystemRoot = 'filesystem-root';
  static const String kFileSystemScheme = 'filesystem-scheme';
66 67
}

68
abstract class FlutterCommand extends Command<Null> {
69 70 71 72 73
  /// The currently executing command (or sub-command).
  ///
  /// Will be `null` until the top-most command has begun execution.
  static FlutterCommand get current => context[FlutterCommand];

74 75 76 77
  @override
  ArgParser get argParser => _argParser;
  final ArgParser _argParser = new ArgParser(allowTrailingOptions: false);

78
  @override
79 80
  FlutterCommandRunner get runner => super.runner;

81 82
  bool _requiresPubspecYaml = false;

83 84 85 86
  /// Whether this command uses the 'target' option.
  bool _usesTargetOption = false;

  bool _usesPubOption = false;
87

88 89
  bool get shouldRunPub => _usesPubOption && argResults['pub'];

90 91
  bool get shouldUpdateCache => true;

92 93
  BuildMode _defaultBuildMode;

94 95 96 97
  void requiresPubspecYaml() {
    _requiresPubspecYaml = true;
  }

98 99 100
  void usesTargetOption() {
    argParser.addOption('target',
      abbr: 't',
101
      defaultsTo: bundle.defaultMainPath,
102 103 104 105
      help: 'The main entry-point file of the application, as run on the device.\n'
            'If the --target option is omitted, but a file name is provided on\n'
            'the command line, then that is used instead.',
      valueHelp: 'path');
106 107 108
    _usesTargetOption = true;
  }

109 110 111 112 113 114
  String get targetFile {
    if (argResults.wasParsed('target'))
      return argResults['target'];
    else if (argResults.rest.isNotEmpty)
      return argResults.rest.first;
    else
115
      return bundle.defaultMainPath;
116 117
  }

118 119 120
  void usesPubOption() {
    argParser.addFlag('pub',
      defaultsTo: true,
121
      help: 'Whether to run "flutter packages get" before executing this command.');
122 123 124
    _usesPubOption = true;
  }

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  void usesBuildNumberOption() {
    argParser.addOption('build-number',
        help: 'An integer used as an internal version number.\n'
              'Each build must have a unique number to differentiate it from previous builds.\n'
              'It is used to determine whether one build is more recent than another, with higher numbers indicating more recent build.\n'
              'On Android it is used as \'versionCode\'.\n'
              'On Xcode builds it is used as \'CFBundleVersion\'',
        valueHelp: 'int');
  }

  void usesBuildNameOption() {
    argParser.addOption('build-name',
        help: 'A "x.y.z" string used as the version number shown to users.\n'
              'For each new version of your app, you will provide a version number to differentiate it from previous versions.\n'
              'On Android it is used as \'versionName\'.\n'
              'On Xcode builds it is used as \'CFBundleShortVersionString\'',
        valueHelp: 'x.y.z');
  }

  void addBuildModeFlags({bool defaultToRelease: true}) {
145
    defaultBuildMode = defaultToRelease ? BuildMode.release : BuildMode.debug;
146

147 148
    argParser.addFlag('debug',
      negatable: false,
149
      help: 'Build a debug version of your app${defaultToRelease ? '' : ' (default mode)'}.');
150 151
    argParser.addFlag('profile',
      negatable: false,
152
      help: 'Build a version of your app specialized for performance profiling.');
153
    argParser.addFlag('release',
154
      negatable: false,
155
      help: 'Build a release version of your app${defaultToRelease ? ' (default mode)' : ''}.');
156 157
  }

158 159
  set defaultBuildMode(BuildMode value) {
    _defaultBuildMode = value;
160 161
  }

162
  BuildMode getBuildMode() {
163
    final List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']];
164
    if (modeFlags.where((bool flag) => flag).length > 1)
165 166 167
      throw new UsageException('Only one of --debug, --profile, or --release can be specified.', null);
    if (argResults['debug'])
      return BuildMode.debug;
168
    if (argResults['profile'])
169
      return BuildMode.profile;
170
    if (argResults['release'])
171 172
      return BuildMode.release;
    return _defaultBuildMode;
173 174
  }

175 176 177 178 179 180 181 182 183 184
  void usesFlavorOption() {
    argParser.addOption(
      'flavor',
      help: 'Build a custom app flavor as defined by platform-specific build setup.\n'
        'Supports the use of product flavors in Android Gradle scripts.\n'
        'Supports the use of custom Xcode schemes.'
    );
  }

  BuildInfo getBuildInfo() {
185 186
    final bool previewDart2 = argParser.options.containsKey('preview-dart-2')
        ? argResults['preview-dart-2']
187
        : true;
188

189 190 191 192 193 194
    TargetPlatform targetPlatform;
    if (argParser.options.containsKey('target-platform') &&
        argResults['target-platform'] != 'default') {
      targetPlatform = getTargetPlatformForName(argResults['target-platform']);
    }

195 196 197 198 199 200 201 202
    final bool trackWidgetCreation = argParser.options.containsKey('track-widget-creation')
        ? argResults['track-widget-creation']
        : false;
    if (trackWidgetCreation == true && previewDart2 == false) {
      throw new UsageException(
          '--track-widget-creation is valid only when --preview-dart-2 is specified.', null);
    }

203 204 205 206 207 208 209 210 211 212
    int buildNumber;
    try {
      buildNumber = argParser.options.containsKey('build-number') && argResults['build-number'] != null
          ? int.parse(argResults['build-number'])
          : null;
    } catch (e) {
      throw new UsageException(
          '--build-number (${argResults['build-number']}) must be an int.', null);
    }

213 214 215 216
    return new BuildInfo(getBuildMode(),
      argParser.options.containsKey('flavor')
        ? argResults['flavor']
        : null,
217
      previewDart2: previewDart2,
218
      trackWidgetCreation: trackWidgetCreation,
219 220 221 222 223
      extraFrontEndOptions: argParser.options.containsKey(FlutterOptions.kExtraFrontEndOptions)
          ? argResults[FlutterOptions.kExtraFrontEndOptions]
          : null,
      extraGenSnapshotOptions: argParser.options.containsKey(FlutterOptions.kExtraGenSnapshotOptions)
          ? argResults[FlutterOptions.kExtraGenSnapshotOptions]
224 225 226
          : null,
      preferSharedLibrary: argParser.options.containsKey('prefer-shared-library')
        ? argResults['prefer-shared-library']
227
        : false,
228 229 230 231 232
      targetPlatform: targetPlatform,
      fileSystemRoots: argParser.options.containsKey(FlutterOptions.kFileSystemRoot)
          ? argResults[FlutterOptions.kFileSystemRoot] : null,
      fileSystemScheme: argParser.options.containsKey(FlutterOptions.kFileSystemScheme)
          ? argResults[FlutterOptions.kFileSystemScheme] : null,
233 234 235 236
      buildNumber: buildNumber,
      buildName: argParser.options.containsKey('build-name')
          ? argResults['build-name']
          : null,
237
    );
238 239
  }

240
  void setupApplicationPackages() {
241
    applicationPackages ??= new ApplicationPackageStore();
242 243
  }

244
  /// The path to send to Google Analytics. Return null here to disable
245
  /// tracking of the command.
246 247 248 249 250 251 252 253 254 255
  Future<String> get usagePath async {
    if (parent is FlutterCommand) {
      final FlutterCommand commandParent = parent;
      final String path = await commandParent.usagePath;
      // Don't report for parents that return null for usagePath.
      return path == null ? null : '$path/$name';
    } else {
      return name;
    }
  }
256

257 258 259
  /// Additional usage values to be sent with the usage ping.
  Future<Map<String, String>> get usageValues async => const <String, String>{};

260 261 262 263 264 265
  /// Runs this command.
  ///
  /// Rather than overriding this method, subclasses should override
  /// [verifyThenRunCommand] to perform any verification
  /// and [runCommand] to execute the command
  /// so that this method can record and report the overall time to analytics.
266
  @override
267
  Future<Null> run() {
268
    final DateTime startTime = clock.now();
Devon Carew's avatar
Devon Carew committed
269

270
    return context.run<Null>(
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
      name: 'command',
      overrides: <Type, Generator>{FlutterCommand: () => this},
      body: () async {
        if (flutterUsage.isFirstRun)
          flutterUsage.printWelcome();

        FlutterCommandResult commandResult;
        try {
          commandResult = await verifyThenRunCommand();
        } on ToolExit {
          commandResult = const FlutterCommandResult(ExitStatus.fail);
          rethrow;
        } finally {
          final DateTime endTime = clock.now();
          printTrace('"flutter $name" took ${getElapsedAsMilliseconds(endTime.difference(startTime))}.');
286 287
          // Note that this is checking the result of the call to 'usagePath'
          // (a Future<String>), and not the result of evaluating the Future.
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
          if (usagePath != null) {
            final List<String> labels = <String>[];
            if (commandResult?.exitStatus != null)
              labels.add(getEnumName(commandResult.exitStatus));
            if (commandResult?.timingLabelParts?.isNotEmpty ?? false)
              labels.addAll(commandResult.timingLabelParts);

            final String label = labels
                .where((String label) => !isBlank(label))
                .join('-');
            flutterUsage.sendTiming(
              'flutter',
              name,
              // If the command provides its own end time, use it. Otherwise report
              // the duration of the entire execution.
              (commandResult?.endTimeOverride ?? endTime).difference(startTime),
              // Report in the form of `success-[parameter1-parameter2]`, all of which
              // can be null if the command doesn't provide a FlutterCommandResult.
              label: label == '' ? null : label,
            );
          }
        }
      },
    );
Devon Carew's avatar
Devon Carew committed
312 313
  }

314 315 316 317 318 319 320 321
  /// Perform validation then call [runCommand] to execute the command.
  /// Return a [Future] that completes with an exit code
  /// indicating whether execution was successful.
  ///
  /// Subclasses should override this method to perform verification
  /// then call this method to execute the command
  /// rather than calling [runCommand] directly.
  @mustCallSuper
322
  Future<FlutterCommandResult> verifyThenRunCommand() async {
323 324
    await validateCommand();

325 326
    // Populate the cache. We call this before pub get below so that the sky_engine
    // package is available in the flutter cache for pub to find.
327 328
    if (shouldUpdateCache)
      await cache.updateAll();
329

330
    if (shouldRunPub) {
331
      await pubGet(context: PubContext.getVerifyContext(name));
332 333
      new FlutterProject(fs.currentDirectory).ensureReadyForPlatformSpecificTooling();
    }
334

335
    setupApplicationPackages();
Devon Carew's avatar
Devon Carew committed
336

337
    final String commandPath = await usagePath;
338 339 340 341 342 343

    if (commandPath != null) {
      final Map<String, String> additionalUsageValues = await usageValues;
      flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues);
    }

344
    return await runCommand();
345 346 347
  }

  /// Subclasses must implement this to execute the command.
348
  /// Optionally provide a [FlutterCommandResult] to send more details about the
349 350
  /// execution for analytics.
  Future<FlutterCommandResult> runCommand();
351

352
  /// Find and return all target [Device]s based upon currently connected
353
  /// devices and criteria entered by the user on the command line.
354
  /// If no device can be found that meets specified criteria,
355
  /// then print an error message and return null.
356
  Future<List<Device>> findAllTargetDevices() async {
357 358
    if (!doctor.canLaunchAnything) {
      printError("Unable to locate a development device; please run 'flutter doctor' "
359
          'for information about installing additional components.');
360 361 362
      return null;
    }

363
    List<Device> devices = await deviceManager.getDevices().toList();
364 365

    if (devices.isEmpty && deviceManager.hasSpecifiedDeviceId) {
366
      printStatus('No devices found with name or id '
367 368
          "matching '${deviceManager.specifiedDeviceId}'");
      return null;
369
    } else if (devices.isEmpty && deviceManager.hasSpecifiedAllDevices) {
370
      printStatus('No devices found');
371
      return null;
372 373 374 375 376 377 378 379 380 381
    } else if (devices.isEmpty) {
      printNoConnectedDevices();
      return null;
    }

    devices = devices.where((Device device) => device.isSupported()).toList();

    if (devices.isEmpty) {
      printStatus('No supported devices connected.');
      return null;
382
    } else if (devices.length > 1 && !deviceManager.hasSpecifiedAllDevices) {
383
      if (deviceManager.hasSpecifiedDeviceId) {
384
        printStatus('Found ${devices.length} devices with name or id matching '
385 386
            "'${deviceManager.specifiedDeviceId}':");
      } else {
387
        printStatus('More than one device connected; please specify a device with '
388
            "the '-d <deviceId>' flag, or use '-d all' to act on all devices.");
389
        devices = await deviceManager.getAllConnectedDevices().toList();
390 391
      }
      printStatus('');
392
      await Device.printDevices(devices);
393 394
      return null;
    }
395 396 397 398 399 400
    return devices;
  }

  /// Find and return the target [Device] based upon currently connected
  /// devices and criteria entered by the user on the command line.
  /// If a device cannot be found that meets specified criteria,
401
  /// then print an error message and return null.
402 403 404 405 406
  Future<Device> findTargetDevice() async {
    List<Device> deviceList = await findAllTargetDevices();
    if (deviceList == null)
      return null;
    if (deviceList.length > 1) {
407
      printStatus('More than one device connected; please specify a device with '
408 409 410 411 412 413 414
        "the '-d <deviceId>' flag.");
      deviceList = await deviceManager.getAllConnectedDevices().toList();
      printStatus('');
      await Device.printDevices(deviceList);
      return null;
    }
    return deviceList.single;
415 416
  }

417 418 419 420
  void printNoConnectedDevices() {
    printStatus('No connected devices.');
  }

421 422 423 424
  @protected
  @mustCallSuper
  Future<Null> validateCommand() async {
    if (_requiresPubspecYaml && !PackageMap.isUsingCustomPackagesPath) {
425
      // Don't expect a pubspec.yaml file if the user passed in an explicit .packages file path.
426
      if (!fs.isFileSync('pubspec.yaml')) {
427 428
        throw new ToolExit(
          'Error: No pubspec.yaml file found.\n'
429
          'This command should be run from the root of your Flutter project.\n'
430 431 432
          'Do not run this command from the root of your git clone of Flutter.'
        );
      }
433

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
      if (fs.isFileSync('flutter.yaml')) {
        throw new ToolExit(
          'Please merge your flutter.yaml into your pubspec.yaml.\n\n'
          'We have changed from having separate flutter.yaml and pubspec.yaml\n'
          'files to having just one pubspec.yaml file. Transitioning is simple:\n'
          'add a line that just says "flutter:" to your pubspec.yaml file, and\n'
          'move everything from your current flutter.yaml file into the\n'
          'pubspec.yaml file, below that line, with everything indented by two\n'
          'extra spaces compared to how it was in the flutter.yaml file. Then, if\n'
          'you had a "name:" line, move that to the top of your "pubspec.yaml"\n'
          'file (you may already have one there), so that there is only one\n'
          '"name:" line. Finally, delete the flutter.yaml file.\n\n'
          'For an example of what a new-style pubspec.yaml file might look like,\n'
          'check out the Flutter Gallery pubspec.yaml:\n'
          'https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/pubspec.yaml\n'
        );
450
      }
451 452

      // Validate the current package map only if we will not be running "pub get" later.
453
      if (parent?.name != 'packages' && !(_usesPubOption && argResults['pub'])) {
454 455 456 457
        final String error = new PackageMap(PackageMap.globalPackagesPath).checkValid();
        if (error != null)
          throw new ToolExit(error);
      }
458
    }
459 460

    if (_usesTargetOption) {
461
      final String targetPath = targetFile;
462
      if (!fs.isFileSync(targetPath))
463
        throw new ToolExit('Target file "$targetPath" not found.');
464 465
    }
  }
466

467 468
  ApplicationPackageStore applicationPackages;
}