flutter_command_runner.dart 12.5 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
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
9
import 'package:completion/completion.dart';
10
import 'package:file/file.dart';
11

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

Ian Hickson's avatar
Ian Hickson committed
25 26 27
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/
28
const String kFlutterToolsScriptFileName = 'flutter_tools.dart'; // in //flutter/packages/flutter_tools/bin/
Ian Hickson's avatar
Ian Hickson committed
29 30
const String kFlutterEnginePackageName = 'sky_engine';

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

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

108 109
    argParser.addOption('local-engine',
        hide: !verboseHelp,
110 111
        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'
112
              'This path is relative to "--local-engine-src-path" or "--local-engine-src-out" (q.v.).');
113

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

129 130
  @override
  ArgParser get argParser => _argParser;
131 132
  final ArgParser _argParser = ArgParser(
    allowTrailingOptions: false,
133
    usageLineLength: globals.outputPreferences.wrapText ? globals.outputPreferences.wrapColumn : null,
134
  );
135

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

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

154 155 156 157 158 159 160
  @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.
161
      return tryArgsCompletion(args.toList(), argParser);
162 163 164 165 166
    } on ArgParserException catch (error) {
      if (error.commands.isEmpty) {
        usageException(error.message);
      }

167
      Command<void> command = commands[error.commands.first];
168
      for (final String commandName in error.commands.skip(1)) {
169 170 171 172 173 174 175 176
        command = command.subcommands[commandName];
      }

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

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

185
    return super.run(args);
Devon Carew's avatar
Devon Carew committed
186 187
  }

188
  @override
189
  Future<void> runCommand(ArgResults topLevelResults) async {
Jonah Williams's avatar
Jonah Williams committed
190
    final Map<Type, dynamic> contextOverrides = <Type, dynamic>{};
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    // 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,
    );

218
    if (topLevelResults['show-test-device'] as bool ||
219 220 221
        topLevelResults['device-id'] == FlutterTesterDevices.kTesterDeviceId) {
      FlutterTesterDevices.showFlutterTesterDevice = true;
    }
222 223 224 225
    if (topLevelResults['show-web-server-device'] as bool ||
        topLevelResults['device-id'] == WebServerDevice.kWebServerDeviceId) {
      WebServerDevice.showWebServerDevice = true;
    }
226

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

239
    await context.run<void>(
240
      overrides: contextOverrides.map<Type, Generator>((Type type, dynamic value) {
241
        return MapEntry<Type, Generator>(type, () => value);
242 243
      }),
      body: () async {
244
        globals.logger.quiet = topLevelResults['quiet'] as bool;
245

246
        if (globals.platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') {
247
          await globals.cache.lock();
248
        }
249

250
        if (topLevelResults['suppress-analytics'] as bool) {
251
          globals.flutterUsage.suppressAnalytics = true;
252
        }
253

254
        globals.flutterVersion.ensureVersionFile();
255 256
        final bool machineFlag = topLevelResults['machine'] as bool;
        if (topLevelResults.command?.name != 'upgrade' && topLevelResults['version-check'] as bool && !machineFlag) {
257
          await globals.flutterVersion.checkFlutterVersionFreshness();
258 259 260
        }

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

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

280
        if (machineFlag) {
281
          throwToolExit('The "--machine" flag is only valid with the "--version" flag.', exitCode: 2);
282 283 284 285
        }
        await super.runCommand(topLevelResults);
      },
    );
Adam Barth's avatar
Adam Barth committed
286 287
  }

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

  /// Get all pub packages in the Flutter repo.
  List<Directory> getRepoPackages() {
    return getRepoRoots()
      .expand<String>((String root) => _gatherProjectPaths(root))
301
      .map<Directory>((String dir) => globals.fs.directory(dir))
302 303 304 305
      .toList();
  }

  static List<String> _gatherProjectPaths(String rootPath) {
306
    if (globals.fs.isFileSync(globals.fs.path.join(rootPath, '.dartignore'))) {
307
      return <String>[];
308
    }
309 310


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

321
    if (globals.fs.isFileSync(globals.fs.path.join(rootPath, 'pubspec.yaml'))) {
322
      projectPaths.add(rootPath);
323
    }
324 325

    return projectPaths;
326
  }
327
}