format.dart 2.25 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import '../base/common.dart';
8
import '../base/process.dart';
9
import '../dart/sdk.dart';
10 11 12
import '../runner/flutter_command.dart';

class FormatCommand extends FlutterCommand {
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
  FormatCommand() {
    argParser.addFlag('dry-run',
      abbr: 'n',
      help: 'Show which files would be modified but make no changes.',
      defaultsTo: false,
      negatable: false,
    );
    argParser.addFlag('set-exit-if-changed',
      help: 'Return exit code 1 if there are any formatting changes.',
      defaultsTo: false,
      negatable: false,
    );
    argParser.addFlag('machine',
      abbr: 'm',
      help: 'Produce machine-readable JSON output.',
      defaultsTo: false,
      negatable: false,
    );
  }

33 34 35 36 37 38 39 40 41
  @override
  final String name = 'format';

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

  @override
  final String description = 'Format one or more dart files.';

42 43 44 45 46
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
    DevelopmentArtifact.universal,
  };

47
  @override
48
  String get invocation => '${runner.executableName} $name <one or more paths>';
49 50

  @override
51
  Future<FlutterCommandResult> runCommand() async {
52
    if (argResults.rest.isEmpty) {
53 54 55 56 57 58 59 60
      throwToolExit(
        'No files specified to be formatted.\n'
        '\n'
        'To format all files in the current directory tree:\n'
        '${runner.executableName} $name .\n'
        '\n'
        '$usage'
      );
61 62
    }

63
    final String dartfmt = sdkBinaryName('dartfmt');
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    final List<String> command = <String>[dartfmt];

    if (argResults['dry-run']) {
      command.add('-n');
    }
    if (argResults['machine']) {
      command.add('-m');
    }
    if (!argResults['dry-run'] && !argResults['machine']) {
      command.add('-w');
    }

    if (argResults['set-exit-if-changed']) {
      command.add('--set-exit-if-changed');
    }

    command..addAll(argResults.rest);

    final int result = await runCommandAndStreamOutput(command);
83 84
    if (result != 0)
      throwToolExit('Formatting failed: $result', exitCode: result);
85 86

    return null;
87 88
  }
}