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

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

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

102 103
    argParser.addOption('local-engine',
        hide: !verboseHelp,
104 105
        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'
106
              'This path is relative to "--local-engine-src-path" or "--local-engine-src-out" (q.v.).');
107

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

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

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

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

148 149 150 151 152 153 154
  @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.
155
      return tryArgsCompletion(args.toList(), argParser);
156 157 158 159 160
    } on ArgParserException catch (error) {
      if (error.commands.isEmpty) {
        usageException(error.message);
      }

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

      command.usageException(error.message);
    }
  }

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

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

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

185 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
    // 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,
    );

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

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

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

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

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

247
        globals.flutterVersion.ensureVersionFile();
248
        final bool machineFlag = topLevelResults['machine'] as bool;
249
        final bool ci = await globals.botDetector.isRunningOnBot;
250 251 252
        final bool redirectedCompletion = !globals.stdio.hasTerminal &&
            (topLevelResults.command?.name ?? '').endsWith('-completion');
        final bool isMachine = machineFlag || ci || redirectedCompletion;
253 254 255 256
        final bool versionCheckFlag = topLevelResults['version-check'] as bool;
        final bool explicitVersionCheckPassed = topLevelResults.wasParsed('version-check') && versionCheckFlag;

        if (topLevelResults.command?.name != 'upgrade' &&
257
            (explicitVersionCheckPassed || (versionCheckFlag && !isMachine))) {
258
          await globals.flutterVersion.checkFlutterVersionFreshness();
259 260 261
        }

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

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

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

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

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

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


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

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

    return projectPaths;
327
  }
328
}