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

import 'package:args/args.dart';
import 'package:args/command_runner.dart';
7
import 'package:completion/completion.dart';
8
import 'package:file/file.dart';
9

10
import '../artifacts.dart';
11
import '../base/common.dart';
12
import '../base/context.dart';
13
import '../base/file_system.dart';
14
import '../base/terminal.dart';
15
import '../base/user_messages.dart';
16
import '../base/utils.dart';
17
import '../cache.dart';
18
import '../convert.dart';
19
import '../globals.dart' as globals;
20
import '../tester/flutter_tester.dart';
21
import '../web/web_device.dart';
22

Ian Hickson's avatar
Ian Hickson committed
23 24 25
const String kFlutterRootEnvironmentVariableName = 'FLUTTER_ROOT'; // should point to //flutter/ (root of flutter/flutter repo)
const String kFlutterEngineEnvironmentVariableName = 'FLUTTER_ENGINE'; // should point to //engine/src/ (root of flutter/engine repo)
const String kSnapshotFileName = 'flutter_tools.snapshot'; // in //flutter/bin/cache/
26
const String kFlutterToolsScriptFileName = 'flutter_tools.dart'; // in //flutter/packages/flutter_tools/bin/
Ian Hickson's avatar
Ian Hickson committed
27 28
const String kFlutterEnginePackageName = 'sky_engine';

29
class FlutterCommandRunner extends CommandRunner<void> {
30
  FlutterCommandRunner({ bool verboseHelp = false }) : super(
Devon Carew's avatar
Devon Carew committed
31
    'flutter',
32 33
    'Manage your Flutter app development.\n'
      '\n'
34
      'Common commands:\n'
35 36 37 38 39
      '\n'
      '  flutter create <output directory>\n'
      '    Create a new Flutter project in the specified directory.\n'
      '\n'
      '  flutter run [options]\n'
40
      '    Run your Flutter application on an attached device or in an emulator.',
Devon Carew's avatar
Devon Carew committed
41
  ) {
42 43 44
    argParser.addFlag('verbose',
        abbr: 'v',
        negatable: false,
45 46
        help: 'Noisy logging, including all shell commands executed.\n'
              'If used with --help, shows hidden options.');
47 48 49 50
    argParser.addFlag('prefixed-errors',
        negatable: false,
        hide: true,
        defaultsTo: false);
51 52 53 54
    argParser.addFlag('quiet',
        negatable: false,
        hide: !verboseHelp,
        help: 'Reduce the amount of output from some commands.');
55 56 57 58 59 60 61
    argParser.addFlag('wrap',
        negatable: true,
        hide: !verboseHelp,
        help: 'Toggles output word wrapping, regardless of whether or not the output is a terminal.',
        defaultsTo: true);
    argParser.addOption('wrap-column',
        hide: !verboseHelp,
62 63 64
        help: 'Sets the output wrap column. If not set, uses the width of the terminal. No '
            'wrapping occurs if not writing to a terminal. Use --no-wrap to turn off wrapping '
            'when connected to a terminal.',
65
        defaultsTo: null);
Devon Carew's avatar
Devon Carew committed
66 67
    argParser.addOption('device-id',
        abbr: 'd',
68
        help: 'Target device id or name (prefixes allowed).');
69 70 71
    argParser.addFlag('version',
        negatable: false,
        help: 'Reports the version of this tool.');
72
    argParser.addFlag('machine',
73
        negatable: false,
74 75
        hide: !verboseHelp,
        help: 'When used with the --version flag, outputs the information using JSON.');
76 77 78
    argParser.addFlag('color',
        negatable: true,
        hide: !verboseHelp,
79 80
        help: 'Whether to use terminal colors (requires support for ANSI escape sequences).',
        defaultsTo: true);
81 82 83 84 85
    argParser.addFlag('version-check',
        negatable: true,
        defaultsTo: true,
        hide: !verboseHelp,
        help: 'Allow Flutter to check for updates when this command runs.');
86 87 88
    argParser.addFlag('suppress-analytics',
        negatable: false,
        help: 'Suppress analytics reporting when this command runs.');
89
    argParser.addOption('packages',
90 91
        hide: !verboseHelp,
        help: 'Path to your "package_config.json" file.');
92
    if (verboseHelp) {
Devon Carew's avatar
Devon Carew committed
93
      argParser.addSeparator('Local build selection options (not normally required):');
94
    }
95

96
    argParser.addOption('local-engine-src-path',
Devon Carew's avatar
Devon Carew committed
97
        hide: !verboseHelp,
98
        help: 'Path to your engine src directory, if you are building Flutter locally.\n'
99 100
              'Defaults to \$$kFlutterEngineEnvironmentVariableName if set, otherwise defaults to '
              'the path given in your pubspec.yaml dependency_overrides for $kFlutterEnginePackageName, '
101
              'if any.');
102

103 104
    argParser.addOption('local-engine',
        hide: !verboseHelp,
105 106 107 108
        help: 'Name of a build output within the engine out directory, if you are building Flutter locally.\n'
              'Use this to select a specific version of the engine if you have built multiple engine targets.\n'
              'This path is relative to --local-engine-src-path/out.');

109
    if (verboseHelp) {
110
      argParser.addSeparator('Options for testing the "flutter" tool itself:');
111
    }
112 113 114
    argParser.addFlag('show-test-device',
        negatable: false,
        hide: !verboseHelp,
115
        help: "List the special 'flutter-tester' device in device listings. "
116
              'This headless device is used to\ntest Flutter tooling.');
117 118 119 120 121
    argParser.addFlag('show-web-server-device',
        negatable: false,
        hide: !verboseHelp,
        help: "List the special 'web-server' device in device listings. "
    );
122 123
  }

124 125
  @override
  ArgParser get argParser => _argParser;
126 127
  final ArgParser _argParser = ArgParser(
    allowTrailingOptions: false,
128
    usageLineLength: globals.outputPreferences.wrapText ? globals.outputPreferences.wrapColumn : null,
129
  );
130

131
  @override
Hixie's avatar
Hixie committed
132
  String get usageFooter {
133
    return wrapText('Run "flutter help -v" for verbose help output, including less commonly used options.',
134 135
      columnWidth: globals.outputPreferences.wrapColumn,
      shouldWrap: globals.outputPreferences.wrapText,
136
    );
137 138 139 140 141
  }

  @override
  String get usage {
    final String usageWithoutDescription = super.usage.substring(description.length + 2);
142
    final String prefix = wrapText(description,
143 144
      shouldWrap: globals.outputPreferences.wrapText,
      columnWidth: globals.outputPreferences.wrapColumn,
145 146
    );
    return '$prefix\n\n$usageWithoutDescription';
Hixie's avatar
Hixie committed
147
  }
Devon Carew's avatar
Devon Carew committed
148

149 150 151 152 153 154 155
  @override
  ArgResults parse(Iterable<String> args) {
    try {
      // This is where the CommandRunner would call argParser.parse(args). We
      // override this function so we can call tryArgsCompletion instead, so the
      // completion package can interrogate the argParser, and as part of that,
      // it calls argParser.parse(args) itself and returns the result.
156
      return tryArgsCompletion(args.toList(), argParser);
157 158 159 160 161
    } on ArgParserException catch (error) {
      if (error.commands.isEmpty) {
        usageException(error.message);
      }

162
      Command<void> command = commands[error.commands.first];
163
      for (final String commandName in error.commands.skip(1)) {
164 165 166 167 168 169 170 171
        command = command.subcommands[commandName];
      }

      command.usageException(error.message);
      return null;
    }
  }

172
  @override
173
  Future<void> run(Iterable<String> args) {
174
    // Have an invocation of 'build' print out it's sub-commands.
175
    // TODO(ianh): Move this to the Build command itself somehow.
176
    if (args.length == 1 && args.first == 'build') {
177
      args = <String>['build', '-h'];
178
    }
179

180
    return super.run(args);
Devon Carew's avatar
Devon Carew committed
181 182
  }

183
  @override
184
  Future<void> runCommand(ArgResults topLevelResults) async {
Jonah Williams's avatar
Jonah Williams committed
185
    final Map<Type, dynamic> contextOverrides = <Type, dynamic>{};
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    // Don't set wrapColumns unless the user said to: if it's set, then all
    // wrapping will occur at this width explicitly, and won't adapt if the
    // terminal size changes during a run.
    int wrapColumn;
    if (topLevelResults.wasParsed('wrap-column')) {
      try {
        wrapColumn = int.parse(topLevelResults['wrap-column'] as String);
        if (wrapColumn < 0) {
          throwToolExit(userMessages.runnerWrapColumnInvalid(topLevelResults['wrap-column']));
        }
      } on FormatException {
        throwToolExit(userMessages.runnerWrapColumnParseError(topLevelResults['wrap-column']));
      }
    }

    // If we're not writing to a terminal with a defined width, then don't wrap
    // anything, unless the user explicitly said to.
    final bool useWrapping = topLevelResults.wasParsed('wrap')
        ? topLevelResults['wrap'] as bool
        : globals.stdio.terminalColumns != null && topLevelResults['wrap'] as bool;
    contextOverrides[OutputPreferences] = OutputPreferences(
      wrapText: useWrapping,
      showColor: topLevelResults['color'] as bool,
      wrapColumn: wrapColumn,
    );

213
    if (topLevelResults['show-test-device'] as bool ||
214 215 216
        topLevelResults['device-id'] == FlutterTesterDevices.kTesterDeviceId) {
      FlutterTesterDevices.showFlutterTesterDevice = true;
    }
217 218 219 220
    if (topLevelResults['show-web-server-device'] as bool ||
        topLevelResults['device-id'] == WebServerDevice.kWebServerDeviceId) {
      WebServerDevice.showWebServerDevice = true;
    }
221

222
    // Set up the tooling configuration.
223 224
    final EngineBuildPaths engineBuildPaths = await globals.localEngineLocator.findEnginePath(
      topLevelResults['local-engine-src-path'] as String,
225 226
      topLevelResults['local-engine'] as String,
      topLevelResults['packages'] as String,
227 228
    );
    if (engineBuildPaths != null) {
229
      contextOverrides.addAll(<Type, dynamic>{
230
        Artifacts: Artifacts.getLocalEngine(engineBuildPaths),
231
      });
232 233
    }

234
    await context.run<void>(
235
      overrides: contextOverrides.map<Type, Generator>((Type type, dynamic value) {
236
        return MapEntry<Type, Generator>(type, () => value);
237 238
      }),
      body: () async {
239
        globals.logger.quiet = topLevelResults['quiet'] as bool;
240

241
        if (globals.platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') {
242
          await globals.cache.lock();
243
        }
244

245
        if (topLevelResults['suppress-analytics'] as bool) {
246
          globals.flutterUsage.suppressAnalytics = true;
247
        }
248

249
        globals.flutterVersion.ensureVersionFile();
250 251
        final bool machineFlag = topLevelResults['machine'] as bool;
        if (topLevelResults.command?.name != 'upgrade' && topLevelResults['version-check'] as bool && !machineFlag) {
252
          await globals.flutterVersion.checkFlutterVersionFreshness();
253 254 255
        }

        // See if the user specified a specific device.
256
        globals.deviceManager.specifiedDeviceId = topLevelResults['device-id'] as String;
257

258
        if (topLevelResults['version'] as bool) {
259
          globals.flutterUsage.sendCommand('version');
260
          globals.flutterVersion.fetchTagsAndUpdate();
261
          String status;
262
          if (machineFlag) {
263 264 265 266 267
            final Map<String, Object> jsonOut = globals.flutterVersion.toJson();
            if (jsonOut != null) {
              jsonOut['flutterRoot'] = Cache.flutterRoot;
            }
            status = const JsonEncoder.withIndent('  ').convert(jsonOut);
268
          } else {
269
            status = globals.flutterVersion.toString();
270
          }
271
          globals.printStatus(status);
272 273 274
          return;
        }

275
        if (machineFlag) {
276 277 278 279 280
          throwToolExit('The --machine flag is only valid with the --version flag.', exitCode: 2);
        }
        await super.runCommand(topLevelResults);
      },
    );
Adam Barth's avatar
Adam Barth committed
281 282
  }

283 284
  /// Get the root directories of the repo - the directories containing Dart packages.
  List<String> getRepoRoots() {
285
    final String root = globals.fs.path.absolute(Cache.flutterRoot);
286
    // not bin, and not the root
287
    return <String>['dev', 'examples', 'packages'].map<String>((String item) {
288
      return globals.fs.path.join(root, item);
289 290 291 292 293 294 295
    }).toList();
  }

  /// Get all pub packages in the Flutter repo.
  List<Directory> getRepoPackages() {
    return getRepoRoots()
      .expand<String>((String root) => _gatherProjectPaths(root))
296
      .map<Directory>((String dir) => globals.fs.directory(dir))
297 298 299 300
      .toList();
  }

  static List<String> _gatherProjectPaths(String rootPath) {
301
    if (globals.fs.isFileSync(globals.fs.path.join(rootPath, '.dartignore'))) {
302
      return <String>[];
303
    }
304 305


306
    final List<String> projectPaths = globals.fs.directory(rootPath)
307 308
      .listSync(followLinks: false)
      .expand((FileSystemEntity entity) {
309
        if (entity is Directory && !globals.fs.path.split(entity.path).contains('.dart_tool')) {
310 311 312
          return _gatherProjectPaths(entity.path);
        }
        return <String>[];
313 314
      })
      .toList();
315

316
    if (globals.fs.isFileSync(globals.fs.path.join(rootPath, 'pubspec.yaml'))) {
317
      projectPaths.add(rootPath);
318
    }
319 320

    return projectPaths;
321
  }
322
}