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

import 'package:completion/completion.dart';

import '../base/common.dart';
import '../base/file_system.dart';
9
import '../globals.dart' as globals;
10 11 12
import '../runner/flutter_command.dart';

class ShellCompletionCommand extends FlutterCommand {
13
  ShellCompletionCommand() {
14 15 16 17 18 19 20 21 22 23 24
    argParser.addFlag(
      'overwrite',
      help: 'Causes the given shell completion setup script to be overwritten if it already exists.',
    );
  }

  @override
  final String name = 'bash-completion';

  @override
  final String description = 'Output command line shell completion setup scripts.\n\n'
25 26 27
      'This command prints the flutter command line completion setup script for Bash and Zsh. To '
      'use it, specify an output file and follow the instructions in the generated output file to '
      'install it in your shell environment. Once it is sourced, your shell will be able to '
28 29
      'complete flutter commands and options.';

30 31 32
  @override
  final String category = FlutterCommandCategory.sdk;

33 34 35 36 37 38 39 40
  @override
  final List<String> aliases = <String>['zsh-completion'];

  @override
  bool get shouldUpdateCache => false;

  /// Return null to disable analytics recording of the `bash-completion` command.
  @override
41
  Future<String?> get usagePath async => null;
42 43

  @override
44
  Future<FlutterCommandResult> runCommand() async {
45 46
    final List<String> rest = argResults?.rest ?? <String>[];
    if (rest.length > 1) {
47 48 49
      throwToolExit('Too many arguments given to bash-completion command.', exitCode: 1);
    }

50
    if (rest.isEmpty || rest.first == '-') {
51
      final String script = generateCompletionScript(<String>['flutter']);
52
      globals.stdio.stdoutWrite(script);
53
      return FlutterCommandResult.warning();
54 55
    }

56
    final File outputFile = globals.fs.file(rest.first);
57
    if (outputFile.existsSync() && !boolArg('overwrite')) {
58 59 60 61 62 63 64 65 66 67 68
      throwToolExit(
        'Output file ${outputFile.path} already exists, will not overwrite. '
            'Use --overwrite to force overwriting existing output file.',
        exitCode: 1,
      );
    }
    try {
      outputFile.writeAsStringSync(generateCompletionScript(<String>['flutter']));
    } on FileSystemException catch (error) {
      throwToolExit('Unable to write shell completion setup script.\n$error', exitCode: 1);
    }
69

70
    return FlutterCommandResult.success();
71 72
  }
}