Auto-format Framework (#160545)
This auto-formats all *.dart files in the repository outside of the `engine` subdirectory and enforces that these files stay formatted with a presubmit check. **Reviewers:** Please carefully review all the commits except for the one titled "formatted". The "formatted" commit was auto-generated by running `dev/tools/format.sh -a -f`. The other commits were hand-crafted to prepare the repo for the formatting change. I recommend reviewing the commits one-by-one via the "Commits" tab and avoiding Github's "Files changed" tab as it will likely slow down your browser because of the size of this PR. --------- Co-authored-by: Kate Lovett <katelovett@google.com> Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
8e0993eda8
commit
5491c8c146
@@ -17,25 +17,23 @@ import 'dart:io';
|
||||
import 'package:args/args.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
enum GitRevisionStrategy {
|
||||
mergeBase,
|
||||
head,
|
||||
}
|
||||
enum GitRevisionStrategy { mergeBase, head }
|
||||
|
||||
final RegExp _hashRegex = RegExp(r'^([a-fA-F0-9]+)');
|
||||
|
||||
final ArgParser parser = ArgParser()
|
||||
..addOption(
|
||||
'strategy',
|
||||
abbr: 's',
|
||||
allowed: <String>['head', 'mergeBase'],
|
||||
defaultsTo: 'head',
|
||||
allowedHelp: <String, String>{
|
||||
'head': 'hash from git HEAD',
|
||||
'mergeBase': 'hash from the merge-base of HEAD and upstream/master',
|
||||
},
|
||||
)
|
||||
..addFlag('help', abbr: 'h', negatable: false);
|
||||
final ArgParser parser =
|
||||
ArgParser()
|
||||
..addOption(
|
||||
'strategy',
|
||||
abbr: 's',
|
||||
allowed: <String>['head', 'mergeBase'],
|
||||
defaultsTo: 'head',
|
||||
allowedHelp: <String, String>{
|
||||
'head': 'hash from git HEAD',
|
||||
'mergeBase': 'hash from the merge-base of HEAD and upstream/master',
|
||||
},
|
||||
)
|
||||
..addFlag('help', abbr: 'h', negatable: false);
|
||||
|
||||
Never printHelp({String? error}) {
|
||||
final Stdout out = error != null ? stderr : stdout;
|
||||
@@ -65,14 +63,9 @@ Future<int> main(List<String> args) async {
|
||||
final String result;
|
||||
try {
|
||||
result = await engineHash(
|
||||
(List<String> command) => Process.run(
|
||||
command.first,
|
||||
command.sublist(1),
|
||||
stdoutEncoding: utf8,
|
||||
),
|
||||
revisionStrategy: GitRevisionStrategy.values.byName(
|
||||
arguments.option('strategy')!,
|
||||
),
|
||||
(List<String> command) =>
|
||||
Process.run(command.first, command.sublist(1), stdoutEncoding: utf8),
|
||||
revisionStrategy: GitRevisionStrategy.values.byName(arguments.option('strategy')!),
|
||||
);
|
||||
} catch (e) {
|
||||
stderr.writeln('Error calculating engine hash: $e');
|
||||
@@ -95,14 +88,12 @@ Future<String> engineHash(
|
||||
case GitRevisionStrategy.head:
|
||||
base = 'HEAD';
|
||||
case GitRevisionStrategy.mergeBase:
|
||||
final ProcessResult processResult = await runProcess(
|
||||
<String>[
|
||||
'git',
|
||||
'merge-base',
|
||||
'upstream/master',
|
||||
'HEAD',
|
||||
],
|
||||
);
|
||||
final ProcessResult processResult = await runProcess(<String>[
|
||||
'git',
|
||||
'merge-base',
|
||||
'upstream/master',
|
||||
'HEAD',
|
||||
]);
|
||||
|
||||
if (processResult.exitCode != 0) {
|
||||
throw '''
|
||||
@@ -110,8 +101,7 @@ Unable to find merge-base hash of the repository:
|
||||
${processResult.stderr}''';
|
||||
}
|
||||
|
||||
final Match? baseHash =
|
||||
_hashRegex.matchAsPrefix(processResult.stdout as String);
|
||||
final Match? baseHash = _hashRegex.matchAsPrefix(processResult.stdout as String);
|
||||
if (baseHash?.groupCount != 1) {
|
||||
throw '''
|
||||
Unable to parse merge-base hash of the repository
|
||||
@@ -124,9 +114,14 @@ ${processResult.stdout}''';
|
||||
// This is important for future filtering of files, but also do not include
|
||||
// the developer's changes / in flight PRs.
|
||||
// The presence `engine` and `DEPS` are signals that you live in a monorepo world.
|
||||
final ProcessResult processResult = await runProcess(
|
||||
<String>['git', 'ls-tree', '-r', base, 'engine', 'DEPS'],
|
||||
);
|
||||
final ProcessResult processResult = await runProcess(<String>[
|
||||
'git',
|
||||
'ls-tree',
|
||||
'-r',
|
||||
base,
|
||||
'engine',
|
||||
'DEPS',
|
||||
]);
|
||||
|
||||
if (processResult.exitCode != 0) {
|
||||
throw '''
|
||||
@@ -140,8 +135,7 @@ ${processResult.stderr}''';
|
||||
throw 'Not in a monorepo';
|
||||
}
|
||||
|
||||
final Iterable<String> treeLines =
|
||||
LineSplitter.split(processResult.stdout as String);
|
||||
final Iterable<String> treeLines = LineSplitter.split(processResult.stdout as String);
|
||||
|
||||
// We could call `git hash-object --stdin` which would just take the input, calculate the size,
|
||||
// and then sha1sum it like: `blob $size\0$string'. However, that can have different line endings.
|
||||
|
||||
@@ -20,7 +20,8 @@ void log(String message) {
|
||||
|
||||
const String _commitTimestampFormat = '--format=%cI';
|
||||
DateTime _parseTimestamp(String line) => DateTime.parse(line.trim());
|
||||
int _countLines(String output) => output.trim().split('/n').where((String line) => line.isNotEmpty).length;
|
||||
int _countLines(String output) =>
|
||||
output.trim().split('/n').where((String line) => line.isNotEmpty).length;
|
||||
|
||||
String findCommit({
|
||||
required String primaryRepoDirectory,
|
||||
@@ -32,20 +33,49 @@ String findCommit({
|
||||
final DateTime anchor;
|
||||
if (primaryBranch == primaryTrunk) {
|
||||
log('on $primaryTrunk, using last commit time');
|
||||
anchor = _parseTimestamp(git(primaryRepoDirectory, <String>['log', _commitTimestampFormat, '--max-count=1', primaryBranch, '--']));
|
||||
anchor = _parseTimestamp(
|
||||
git(primaryRepoDirectory, <String>[
|
||||
'log',
|
||||
_commitTimestampFormat,
|
||||
'--max-count=1',
|
||||
primaryBranch,
|
||||
'--',
|
||||
]),
|
||||
);
|
||||
} else {
|
||||
final String mergeBase = git(primaryRepoDirectory, <String>['merge-base', primaryBranch, primaryTrunk], allowFailure: true).trim();
|
||||
final String mergeBase =
|
||||
git(primaryRepoDirectory, <String>[
|
||||
'merge-base',
|
||||
primaryBranch,
|
||||
primaryTrunk,
|
||||
], allowFailure: true).trim();
|
||||
if (mergeBase.isEmpty) {
|
||||
throw StateError('Branch $primaryBranch does not seem to have a common history with trunk $primaryTrunk.');
|
||||
throw StateError(
|
||||
'Branch $primaryBranch does not seem to have a common history with trunk $primaryTrunk.',
|
||||
);
|
||||
}
|
||||
anchor = _parseTimestamp(git(primaryRepoDirectory, <String>['log', _commitTimestampFormat, '--max-count=1', mergeBase, '--']));
|
||||
anchor = _parseTimestamp(
|
||||
git(primaryRepoDirectory, <String>[
|
||||
'log',
|
||||
_commitTimestampFormat,
|
||||
'--max-count=1',
|
||||
mergeBase,
|
||||
'--',
|
||||
]),
|
||||
);
|
||||
if (debugLogging) {
|
||||
final int missingTrunkCommits = _countLines(git(primaryRepoDirectory, <String>['rev-list', primaryTrunk, '^$primaryBranch', '--']));
|
||||
final int extraCommits = _countLines(git(primaryRepoDirectory, <String>['rev-list', primaryBranch, '^$primaryTrunk', '--']));
|
||||
final int missingTrunkCommits = _countLines(
|
||||
git(primaryRepoDirectory, <String>['rev-list', primaryTrunk, '^$primaryBranch', '--']),
|
||||
);
|
||||
final int extraCommits = _countLines(
|
||||
git(primaryRepoDirectory, <String>['rev-list', primaryBranch, '^$primaryTrunk', '--']),
|
||||
);
|
||||
if (missingTrunkCommits == 0 && extraCommits == 0) {
|
||||
log('$primaryBranch is even with $primaryTrunk at $mergeBase');
|
||||
} else {
|
||||
log('$primaryBranch branched from $primaryTrunk $missingTrunkCommits commits ago, trunk has advanced by $extraCommits commits since then.');
|
||||
log(
|
||||
'$primaryBranch branched from $primaryTrunk $missingTrunkCommits commits ago, trunk has advanced by $extraCommits commits since then.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +90,11 @@ String findCommit({
|
||||
}
|
||||
|
||||
String git(String workingDirectory, List<String> arguments, {bool allowFailure = false}) {
|
||||
final ProcessResult result = Process.runSync('git', arguments, workingDirectory: workingDirectory);
|
||||
final ProcessResult result = Process.runSync(
|
||||
'git',
|
||||
arguments,
|
||||
workingDirectory: workingDirectory,
|
||||
);
|
||||
if (!allowFailure && result.exitCode != 0 || '${result.stderr}'.isNotEmpty) {
|
||||
throw ProcessException('git', arguments, '${result.stdout}${result.stderr}', result.exitCode);
|
||||
}
|
||||
@@ -68,24 +102,29 @@ String git(String workingDirectory, List<String> arguments, {bool allowFailure =
|
||||
}
|
||||
|
||||
void main(List<String> arguments) {
|
||||
if (arguments.isEmpty || arguments.length != 4 || arguments.contains('--help') || arguments.contains('-h')) {
|
||||
if (arguments.isEmpty ||
|
||||
arguments.length != 4 ||
|
||||
arguments.contains('--help') ||
|
||||
arguments.contains('-h')) {
|
||||
print(
|
||||
'Usage: dart find_commit.dart <path-to-primary-repo> <primary-trunk> <path-to-secondary-repo> <secondary-branch>\n'
|
||||
'This script will find the commit in the secondary repo that was contemporary\n'
|
||||
'when the commit in the primary repo was created. If that commit is on a\n'
|
||||
"branch, then the date of the branch's last merge is used instead."
|
||||
"branch, then the date of the branch's last merge is used instead.",
|
||||
);
|
||||
} else {
|
||||
final String primaryRepo = arguments.first;
|
||||
final String primaryTrunk = arguments[1];
|
||||
final String secondaryRepo = arguments[2];
|
||||
final String secondaryBranch = arguments.last;
|
||||
print(findCommit(
|
||||
primaryRepoDirectory: primaryRepo,
|
||||
primaryBranch: git(primaryRepo, <String>['rev-parse', '--abbrev-ref', 'HEAD']).trim(),
|
||||
primaryTrunk: primaryTrunk,
|
||||
secondaryRepoDirectory: secondaryRepo,
|
||||
secondaryBranch: secondaryBranch,
|
||||
).trim());
|
||||
print(
|
||||
findCommit(
|
||||
primaryRepoDirectory: primaryRepo,
|
||||
primaryBranch: git(primaryRepo, <String>['rev-parse', '--abbrev-ref', 'HEAD']).trim(),
|
||||
primaryTrunk: primaryTrunk,
|
||||
secondaryRepoDirectory: secondaryRepo,
|
||||
secondaryBranch: secondaryBranch,
|
||||
).trim(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,18 @@ import 'package:process_runner/process_runner.dart';
|
||||
Future<int> main(List<String> arguments) async {
|
||||
final ArgParser parser = ArgParser();
|
||||
parser.addFlag('help', help: 'Print help.', abbr: 'h');
|
||||
parser.addFlag('fix',
|
||||
abbr: 'f',
|
||||
help: 'Instead of just checking for formatting errors, fix them in place.');
|
||||
parser.addFlag('all-files',
|
||||
abbr: 'a',
|
||||
help: 'Instead of just checking for formatting errors in changed files, '
|
||||
'check for them in all files.');
|
||||
parser.addFlag(
|
||||
'fix',
|
||||
abbr: 'f',
|
||||
help: 'Instead of just checking for formatting errors, fix them in place.',
|
||||
);
|
||||
parser.addFlag(
|
||||
'all-files',
|
||||
abbr: 'a',
|
||||
help:
|
||||
'Instead of just checking for formatting errors in changed files, '
|
||||
'check for them in all files.',
|
||||
);
|
||||
|
||||
late final ArgResults options;
|
||||
try {
|
||||
@@ -34,10 +39,12 @@ Future<int> main(List<String> arguments) async {
|
||||
final File script = File.fromUri(Platform.script).absolute;
|
||||
final Directory flutterRoot = script.parent.parent.parent.parent;
|
||||
|
||||
final bool result = (await DartFormatChecker(
|
||||
flutterRoot: flutterRoot,
|
||||
allFiles: options['all-files'] as bool,
|
||||
).check(fix: options['fix'] as bool)) == 0;
|
||||
final bool result =
|
||||
(await DartFormatChecker(
|
||||
flutterRoot: flutterRoot,
|
||||
allFiles: options['all-files'] as bool,
|
||||
).check(fix: options['fix'] as bool)) ==
|
||||
0;
|
||||
|
||||
exit(result ? 0 : 1);
|
||||
}
|
||||
@@ -49,12 +56,8 @@ void _usage(ArgParser parser, {int exitCode = 1}) {
|
||||
}
|
||||
|
||||
class DartFormatChecker {
|
||||
DartFormatChecker({
|
||||
required this.flutterRoot,
|
||||
required this.allFiles,
|
||||
}) : processRunner = ProcessRunner(
|
||||
defaultWorkingDirectory: flutterRoot,
|
||||
);
|
||||
DartFormatChecker({required this.flutterRoot, required this.allFiles})
|
||||
: processRunner = ProcessRunner(defaultWorkingDirectory: flutterRoot);
|
||||
|
||||
final Directory flutterRoot;
|
||||
final bool allFiles;
|
||||
@@ -67,10 +70,7 @@ class DartFormatChecker {
|
||||
allFiles: allFiles,
|
||||
baseGitRef: baseGitRef,
|
||||
);
|
||||
return _checkFormat(
|
||||
filesToCheck: filesToCheck,
|
||||
fix: fix,
|
||||
);
|
||||
return _checkFormat(filesToCheck: filesToCheck, fix: fix);
|
||||
}
|
||||
|
||||
Future<String> _getDiffBaseRevision() async {
|
||||
@@ -89,10 +89,12 @@ class DartFormatChecker {
|
||||
// This is the preferred command to use, but developer checkouts often do
|
||||
// not have a clear fork point, so we fall back to just the regular
|
||||
// merge-base in that case.
|
||||
result = await _runGit(
|
||||
<String>['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'],
|
||||
processRunner,
|
||||
);
|
||||
result = await _runGit(<String>[
|
||||
'merge-base',
|
||||
'--fork-point',
|
||||
'FETCH_HEAD',
|
||||
'HEAD',
|
||||
], processRunner);
|
||||
} on ProcessRunnerException {
|
||||
result = await _runGit(<String>['merge-base', 'FETCH_HEAD', 'HEAD'], processRunner);
|
||||
}
|
||||
@@ -100,14 +102,14 @@ class DartFormatChecker {
|
||||
}
|
||||
|
||||
Future<String> _runGit(
|
||||
List<String> args,
|
||||
ProcessRunner processRunner, {
|
||||
bool failOk = false,
|
||||
}) async {
|
||||
final ProcessRunnerResult result = await processRunner.runProcess(
|
||||
<String>['git', ...args],
|
||||
failOk: failOk,
|
||||
);
|
||||
List<String> args,
|
||||
ProcessRunner processRunner, {
|
||||
bool failOk = false,
|
||||
}) async {
|
||||
final ProcessRunnerResult result = await processRunner.runProcess(<String>[
|
||||
'git',
|
||||
...args,
|
||||
], failOk: failOk);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
@@ -118,11 +120,7 @@ class DartFormatChecker {
|
||||
}) async {
|
||||
String output;
|
||||
if (allFiles) {
|
||||
output = await _runGit(<String>[
|
||||
'ls-files',
|
||||
'--',
|
||||
...types,
|
||||
], processRunner);
|
||||
output = await _runGit(<String>['ls-files', '--', ...types], processRunner);
|
||||
} else {
|
||||
output = await _runGit(<String>[
|
||||
'diff',
|
||||
@@ -135,13 +133,13 @@ class DartFormatChecker {
|
||||
...types,
|
||||
], processRunner);
|
||||
}
|
||||
return output.split('\n').where((String line) => line.isNotEmpty).toList();
|
||||
return output
|
||||
.split('\n')
|
||||
.where((String line) => line.isNotEmpty && !line.startsWith('engine'))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<int> _checkFormat({
|
||||
required List<String> filesToCheck,
|
||||
required bool fix,
|
||||
}) async {
|
||||
Future<int> _checkFormat({required List<String> filesToCheck, required bool fix}) async {
|
||||
final List<String> cmd = <String>[
|
||||
path.join(flutterRoot.path, 'bin', 'dart'),
|
||||
'format',
|
||||
@@ -170,19 +168,16 @@ class DartFormatChecker {
|
||||
errorJobs.add(completedJob);
|
||||
} else if (completedJob.result.exitCode == 1) {
|
||||
diffJobs.add(
|
||||
WorkerJob(
|
||||
<String>[
|
||||
'git',
|
||||
'diff',
|
||||
'--no-index',
|
||||
'--no-color',
|
||||
'--ignore-cr-at-eol',
|
||||
'--',
|
||||
completedJob.command.last,
|
||||
'-',
|
||||
],
|
||||
stdinRaw: _codeUnitsAsStream(completedJob.result.stdoutRaw),
|
||||
),
|
||||
WorkerJob(<String>[
|
||||
'git',
|
||||
'diff',
|
||||
'--no-index',
|
||||
'--no-color',
|
||||
'--ignore-cr-at-eol',
|
||||
'--',
|
||||
completedJob.command.last,
|
||||
'-',
|
||||
], stdinRaw: _codeUnitsAsStream(completedJob.result.stdoutRaw)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -210,23 +205,31 @@ class DartFormatChecker {
|
||||
if (incorrect.isNotEmpty) {
|
||||
final bool plural = incorrect.length > 1;
|
||||
if (fix) {
|
||||
stdout.writeln('Fixing ${incorrect.length} dart file${plural ? 's' : ''}'
|
||||
' which ${plural ? 'were' : 'was'} formatted incorrectly.');
|
||||
stdout.writeln(
|
||||
'Fixing ${incorrect.length} dart file${plural ? 's' : ''}'
|
||||
' which ${plural ? 'were' : 'was'} formatted incorrectly.',
|
||||
);
|
||||
} else {
|
||||
stderr.writeln('Found ${incorrect.length} Dart file${plural ? 's' : ''}'
|
||||
' which ${plural ? 'were' : 'was'} formatted incorrectly.');
|
||||
final String fileList = incorrect.map(
|
||||
(WorkerJob job) => job.command[job.command.length - 2]
|
||||
).join(' ');
|
||||
stderr.writeln(
|
||||
'Found ${incorrect.length} Dart file${plural ? 's' : ''}'
|
||||
' which ${plural ? 'were' : 'was'} formatted incorrectly.',
|
||||
);
|
||||
final String fileList = incorrect
|
||||
.map((WorkerJob job) => job.command[job.command.length - 2])
|
||||
.join(' ');
|
||||
stdout.writeln();
|
||||
stdout.writeln('To fix, run `dart format $fileList` or:');
|
||||
stdout.writeln();
|
||||
stdout.writeln('git apply <<DONE');
|
||||
for (final WorkerJob job in incorrect) {
|
||||
stdout.write(job.result.stdout
|
||||
.replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')
|
||||
.replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')
|
||||
.replaceFirst(RegExp('\\+Formatted \\d+ files? \\(\\d+ changed\\) in \\d+.\\d+ seconds.\n'), '')
|
||||
stdout.write(
|
||||
job.result.stdout
|
||||
.replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')
|
||||
.replaceFirst('b/-', 'b/${job.command[job.command.length - 2]}')
|
||||
.replaceFirst(
|
||||
RegExp('\\+Formatted \\d+ files? \\(\\d+ changed\\) in \\d+.\\d+ seconds.\n'),
|
||||
'',
|
||||
),
|
||||
);
|
||||
}
|
||||
stdout.writeln('DONE');
|
||||
@@ -244,7 +247,9 @@ class DartFormatChecker {
|
||||
void _printErrorJobs(List<WorkerJob> errorJobs) {
|
||||
if (errorJobs.isNotEmpty) {
|
||||
final bool plural = errorJobs.length > 1;
|
||||
stderr.writeln('The formatter failed to run on ${errorJobs.length} Dart file${plural ? 's' : ''}.');
|
||||
stderr.writeln(
|
||||
'The formatter failed to run on ${errorJobs.length} Dart file${plural ? 's' : ''}.',
|
||||
);
|
||||
stdout.writeln();
|
||||
for (final WorkerJob job in errorJobs) {
|
||||
stdout.writeln('--> ${job.command.last} produced the following error:');
|
||||
@@ -257,19 +262,20 @@ class DartFormatChecker {
|
||||
|
||||
ProcessPoolProgressReporter _namedReport(String name) {
|
||||
return (int total, int completed, int inProgress, int pending, int failed) {
|
||||
final String percent =
|
||||
total == 0 ? '100' : ((100 * completed) ~/ total).toString().padLeft(3);
|
||||
final String percent = total == 0 ? '100' : ((100 * completed) ~/ total).toString().padLeft(3);
|
||||
final String completedStr = completed.toString().padLeft(3);
|
||||
final String totalStr = total.toString().padRight(3);
|
||||
final String inProgressStr = inProgress.toString().padLeft(2);
|
||||
final String pendingStr = pending.toString().padLeft(3);
|
||||
final String failedStr = failed.toString().padLeft(3);
|
||||
|
||||
stdout.write('$name Jobs: $percent% done, '
|
||||
'$completedStr/$totalStr completed, '
|
||||
'$inProgressStr in progress, '
|
||||
'$pendingStr pending, '
|
||||
'$failedStr failed.${' ' * 20}\r');
|
||||
stdout.write(
|
||||
'$name Jobs: $percent% done, '
|
||||
'$completedStr/$totalStr completed, '
|
||||
'$inProgressStr in progress, '
|
||||
'$pendingStr pending, '
|
||||
'$failedStr failed.${' ' * 20}\r',
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -18,23 +18,27 @@ import 'package:file/local.dart';
|
||||
import 'package:yaml/yaml.dart';
|
||||
|
||||
void main(List<String> arguments) {
|
||||
const String usageMessage = "If you don't wish to re-generate the "
|
||||
const String usageMessage =
|
||||
"If you don't wish to re-generate the "
|
||||
'settings.gradle, build.gradle, and gradle-wrapper.properties files,\n'
|
||||
'add the flag `--no-gradle-generation`.\n'
|
||||
'This tool automatically excludes a set of android subdirectories, '
|
||||
'defined at dev/tools/bin/config/lockfile_exclusion.yaml.\n'
|
||||
'To disable this behavior, run with `--no-exclusion`.\n';
|
||||
|
||||
final ArgParser argParser = ArgParser()
|
||||
..addFlag(
|
||||
'gradle-generation',
|
||||
help: 'Re-generate gradle files in each processed directory.',
|
||||
defaultsTo: true,
|
||||
)..addFlag(
|
||||
'exclusion',
|
||||
help: 'Run the script using the config file at ./configs/lockfile_exclusion.yaml to skip the specified subdirectories.',
|
||||
defaultsTo: true,
|
||||
);
|
||||
final ArgParser argParser =
|
||||
ArgParser()
|
||||
..addFlag(
|
||||
'gradle-generation',
|
||||
help: 'Re-generate gradle files in each processed directory.',
|
||||
defaultsTo: true,
|
||||
)
|
||||
..addFlag(
|
||||
'exclusion',
|
||||
help:
|
||||
'Run the script using the config file at ./configs/lockfile_exclusion.yaml to skip the specified subdirectories.',
|
||||
defaultsTo: true,
|
||||
);
|
||||
|
||||
ArgResults args;
|
||||
try {
|
||||
@@ -55,17 +59,16 @@ void main(List<String> arguments) {
|
||||
|
||||
const FileSystem fileSystem = LocalFileSystem();
|
||||
|
||||
final Directory repoRoot = (() {
|
||||
final String repoRootPath = exec(
|
||||
'git',
|
||||
const <String>['rev-parse', '--show-toplevel'],
|
||||
).trim();
|
||||
final Directory repoRoot = fileSystem.directory(repoRootPath);
|
||||
if (!repoRoot.existsSync()) {
|
||||
throw StateError("Expected $repoRoot to exist but it didn't!");
|
||||
}
|
||||
return repoRoot;
|
||||
})();
|
||||
final Directory repoRoot =
|
||||
(() {
|
||||
final String repoRootPath =
|
||||
exec('git', const <String>['rev-parse', '--show-toplevel']).trim();
|
||||
final Directory repoRoot = fileSystem.directory(repoRootPath);
|
||||
if (!repoRoot.existsSync()) {
|
||||
throw StateError("Expected $repoRoot to exist but it didn't!");
|
||||
}
|
||||
return repoRoot;
|
||||
})();
|
||||
|
||||
final Iterable<Directory> androidDirectories = discoverAndroidDirectories(repoRoot);
|
||||
|
||||
@@ -80,10 +83,9 @@ void main(List<String> arguments) {
|
||||
final Set<String> exclusionSet;
|
||||
if (useExclusion) {
|
||||
exclusionSet = HashSet<String>.from(
|
||||
(loadYaml(exclusionFile.readAsStringSync()) as YamlList)
|
||||
.toList()
|
||||
.cast<String>()
|
||||
.map((String s) => '${repoRoot.path}/$s')
|
||||
(loadYaml(exclusionFile.readAsStringSync()) as YamlList).toList().cast<String>().map(
|
||||
(String s) => '${repoRoot.path}/$s',
|
||||
),
|
||||
);
|
||||
print('Loaded exclusion file from ${exclusionFile.path}.');
|
||||
} else {
|
||||
@@ -97,7 +99,9 @@ void main(List<String> arguments) {
|
||||
}
|
||||
|
||||
if (exclusionSet.contains(androidDirectory.path)) {
|
||||
print('${androidDirectory.path} is included in the exclusion config file at ${exclusionFile.path} - skipping');
|
||||
print(
|
||||
'${androidDirectory.path} is included in the exclusion config file at ${exclusionFile.path} - skipping',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -117,7 +121,9 @@ void main(List<String> arguments) {
|
||||
} else if (androidDirectory.childFile('settings.gradle.kts').existsSync()) {
|
||||
settingsGradle = androidDirectory.childFile('settings.gradle.kts');
|
||||
} else {
|
||||
print('${androidDirectory.childFile('settings.gradle').path}(.kts) does not exist - skipping');
|
||||
print(
|
||||
'${androidDirectory.childFile('settings.gradle').path}(.kts) does not exist - skipping',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -145,15 +151,15 @@ void main(List<String> arguments) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (androidDirectory.parent.childFile('pubspec.yaml').readAsStringSync().contains('deferred-components')) {
|
||||
if (androidDirectory.parent
|
||||
.childFile('pubspec.yaml')
|
||||
.readAsStringSync()
|
||||
.contains('deferred-components')) {
|
||||
print('${rootBuildGradle.path} uses deferred components - skipping');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!androidDirectory.parent
|
||||
.childDirectory('lib')
|
||||
.childFile('main.dart')
|
||||
.existsSync()) {
|
||||
if (!androidDirectory.parent.childDirectory('lib').childFile('main.dart').existsSync()) {
|
||||
print('${rootBuildGradle.path} no main.dart under lib - skipping');
|
||||
continue;
|
||||
}
|
||||
@@ -180,43 +186,29 @@ void main(List<String> arguments) {
|
||||
final String appDirectory = androidDirectory.parent.absolute.path;
|
||||
|
||||
// Fetch pub dependencies.
|
||||
final String flutterPath = repoRoot
|
||||
.childDirectory('bin')
|
||||
.childFile('flutter')
|
||||
.path;
|
||||
final String flutterPath = repoRoot.childDirectory('bin').childFile('flutter').path;
|
||||
exec(flutterPath, <String>['pub', 'get'], workingDirectory: appDirectory);
|
||||
|
||||
// Verify that the Gradlew wrapper exists.
|
||||
final File gradleWrapper = androidDirectory.childFile('gradlew');
|
||||
// Generate Gradle wrapper if it doesn't exist.
|
||||
if (!gradleWrapper.existsSync()) {
|
||||
exec(
|
||||
flutterPath,
|
||||
<String>['build', 'apk', '--config-only'],
|
||||
workingDirectory: appDirectory,
|
||||
);
|
||||
exec(flutterPath, <String>['build', 'apk', '--config-only'], workingDirectory: appDirectory);
|
||||
}
|
||||
|
||||
// Generate lock files.
|
||||
exec(
|
||||
gradleWrapper.absolute.path,
|
||||
<String>[':generateLockfiles'],
|
||||
workingDirectory: androidDirectory.absolute.path,
|
||||
);
|
||||
exec(gradleWrapper.absolute.path, <String>[
|
||||
':generateLockfiles',
|
||||
], workingDirectory: androidDirectory.absolute.path);
|
||||
|
||||
print('Processed');
|
||||
}
|
||||
}
|
||||
|
||||
String exec(
|
||||
String cmd,
|
||||
List<String> args, {
|
||||
String? workingDirectory,
|
||||
}) {
|
||||
String exec(String cmd, List<String> args, {String? workingDirectory}) {
|
||||
final ProcessResult result = Process.runSync(cmd, args, workingDirectory: workingDirectory);
|
||||
if (result.exitCode != 0) {
|
||||
throw ProcessException(
|
||||
cmd, args, '${result.stdout}${result.stderr}', result.exitCode);
|
||||
throw ProcessException(cmd, args, '${result.stdout}${result.stderr}', result.exitCode);
|
||||
}
|
||||
return result.stdout as String;
|
||||
}
|
||||
@@ -311,7 +303,8 @@ distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
|
||||
''';
|
||||
|
||||
Iterable<Directory> discoverAndroidDirectories(Directory repoRoot) {
|
||||
return repoRoot.listSync(recursive: true)
|
||||
return repoRoot
|
||||
.listSync(recursive: true)
|
||||
.whereType<Directory>()
|
||||
.where((FileSystemEntity entity) => entity.basename == 'android');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user