format.dart 1.69 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
import 'package:args/args.dart';

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

class FormatCommand extends FlutterCommand {
13
  FormatCommand({required this.verboseHelp});
14 15 16 17 18

  @override
  ArgParser argParser = ArgParser.allowAnything();

  final bool verboseHelp;
19

20 21 22 23 24 25 26
  @override
  final String name = 'format';

  @override
  List<String> get aliases => const <String>['dartfmt'];

  @override
27
  final String description = 'Format one or more Dart files.';
28

29 30 31
  @override
  String get category => FlutterCommandCategory.project;

32
  @override
33
  String get invocation => '${runner?.executableName} $name <one or more paths>';
34

35 36
  @override
  Future<FlutterCommandResult> runCommand() async {
37
    final String dartBinary = globals.artifacts!.getHostArtifact(HostArtifact.engineDartBinary).path;
38
    final List<String> command = <String>[
39
      dartBinary,
40
      'format',
41
    ];
42 43
    final List<String> rest = argResults?.rest ?? <String>[];
    if (rest.isEmpty) {
44 45 46 47 48 49
      globals.printError(
        'No files specified to be formatted.'
      );
      command.add('-h');
    } else {
      command.addAll(<String>[
50
        for (String arg in rest)
51 52
          if (arg == '--dry-run' || arg == '-n')
            '--output=none'
53 54 55 56
          else
            arg
      ]);
    }
57

58
    final int result = await globals.processUtils.stream(command);
59
    if (result != 0) {
60
      throwToolExit('Formatting failed: $result', exitCode: result);
61
    }
62

63
    return FlutterCommandResult.success();
64 65
  }
}