1// Copyright 2016 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'dart:async'; 6 7import '../base/common.dart'; 8import '../base/process.dart'; 9import '../dart/sdk.dart'; 10import '../runner/flutter_command.dart'; 11 12class FormatCommand extends FlutterCommand { 13 FormatCommand() { 14 argParser.addFlag('dry-run', 15 abbr: 'n', 16 help: 'Show which files would be modified but make no changes.', 17 defaultsTo: false, 18 negatable: false, 19 ); 20 argParser.addFlag('set-exit-if-changed', 21 help: 'Return exit code 1 if there are any formatting changes.', 22 defaultsTo: false, 23 negatable: false, 24 ); 25 argParser.addFlag('machine', 26 abbr: 'm', 27 help: 'Produce machine-readable JSON output.', 28 defaultsTo: false, 29 negatable: false, 30 ); 31 argParser.addOption('line-length', 32 abbr: 'l', 33 help: 'Wrap lines longer than this length. Defaults to 80 characters.', 34 defaultsTo: '80', 35 ); 36 } 37 38 @override 39 final String name = 'format'; 40 41 @override 42 List<String> get aliases => const <String>['dartfmt']; 43 44 @override 45 final String description = 'Format one or more dart files.'; 46 47 @override 48 Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{ 49 DevelopmentArtifact.universal, 50 }; 51 52 @override 53 String get invocation => '${runner.executableName} $name <one or more paths>'; 54 55 @override 56 Future<FlutterCommandResult> runCommand() async { 57 if (argResults.rest.isEmpty) { 58 throwToolExit( 59 'No files specified to be formatted.\n' 60 '\n' 61 'To format all files in the current directory tree:\n' 62 '${runner.executableName} $name .\n' 63 '\n' 64 '$usage' 65 ); 66 } 67 68 final String dartfmt = sdkBinaryName('dartfmt'); 69 final List<String> command = <String>[ 70 dartfmt, 71 if (argResults['dry-run']) '-n', 72 if (argResults['machine']) '-m', 73 if (argResults['line-length'] != null) '-l ${argResults['line-length']}', 74 if (!argResults['dry-run'] && !argResults['machine']) '-w', 75 if (argResults['set-exit-if-changed']) '--set-exit-if-changed', 76 ...argResults.rest, 77 ]; 78 79 final int result = await runCommandAndStreamOutput(command); 80 if (result != 0) 81 throwToolExit('Formatting failed: $result', exitCode: result); 82 83 return null; 84 } 85} 86