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:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -67,8 +67,7 @@ class ProcessInfo {
command: $command
started: $startTime
pid : ${process.pid}
'''
.trim();
'''.trim();
}
}
@@ -77,8 +76,8 @@ class HealthCheckResult {
HealthCheckResult.success([this.details]) : succeeded = true;
HealthCheckResult.failure(this.details) : succeeded = false;
HealthCheckResult.error(dynamic error, dynamic stackTrace)
: succeeded = false,
details = 'ERROR: $error${stackTrace != null ? '\n$stackTrace' : ''}';
: succeeded = false,
details = 'ERROR: $error${stackTrace != null ? '\n$stackTrace' : ''}';
final bool succeeded;
final String? details;
@@ -111,7 +110,7 @@ void fail(String message) {
}
// Remove the given file or directory.
void rm(FileSystemEntity entity, { bool recursive = false}) {
void rm(FileSystemEntity entity, {bool recursive = false}) {
if (entity.existsSync()) {
// This should not be necessary, but it turns out that
// on Windows it's common for deletions to fail due to
@@ -136,8 +135,7 @@ Directory dir(String path) => Directory(path);
File file(String path) => File(path);
void copy(File sourceFile, Directory targetDirectory, {String? name}) {
final File target = file(
path.join(targetDirectory.path, name ?? path.basename(sourceFile.path)));
final File target = file(path.join(targetDirectory.path, name ?? path.basename(sourceFile.path)));
target.writeAsBytesSync(sourceFile.readAsBytesSync());
}
@@ -162,10 +160,8 @@ void recursiveCopy(Directory source, Directory target) {
}
}
FileSystemEntity move(FileSystemEntity whatToMove,
{required Directory to, String? name}) {
return whatToMove
.renameSync(path.join(to.path, name ?? path.basename(whatToMove.path)));
FileSystemEntity move(FileSystemEntity whatToMove, {required Directory to, String? name}) {
return whatToMove.renameSync(path.join(to.path, name ?? path.basename(whatToMove.path)));
}
/// Equivalent of `chmod a+x file`
@@ -174,11 +170,7 @@ void makeExecutable(File file) {
if (Platform.isWindows) {
return;
}
final ProcessResult result = _processManager.runSync(<String>[
'chmod',
'a+x',
file.path,
]);
final ProcessResult result = _processManager.runSync(<String>['chmod', 'a+x', file.path]);
if (result.exitCode != 0) {
throw FileSystemException(
@@ -250,12 +242,7 @@ Future<String?> getCurrentFlutterRepoCommit() {
Future<DateTime> getFlutterRepoCommitTimestamp(String commit) {
// git show -s --format=%at 4b546df7f0b3858aaaa56c4079e5be1ba91fbb65
return inDirectory<DateTime>(flutterDirectory, () async {
final String unixTimestamp = await eval('git', <String>[
'show',
'-s',
'--format=%at',
commit,
]);
final String unixTimestamp = await eval('git', <String>['show', '-s', '--format=%at', commit]);
final int secondsSinceEpoch = int.parse(unixTimestamp);
return DateTime.fromMillisecondsSinceEpoch(secondsSinceEpoch * 1000);
});
@@ -289,12 +276,15 @@ Future<Process> startProcess(
String executable,
List<String>? arguments, {
Map<String, String>? environment,
bool isBot = true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
bool isBot =
true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
String? workingDirectory,
}) async {
final String command = '$executable ${arguments?.join(" ") ?? ""}';
final String finalWorkingDirectory = workingDirectory ?? cwd;
final Map<String, String> newEnvironment = Map<String, String>.from(environment ?? <String, String>{});
final Map<String, String> newEnvironment = Map<String, String>.from(
environment ?? <String, String>{},
);
newEnvironment['BOT'] = isBot ? 'true' : 'false';
newEnvironment['LANG'] = 'en_US.UTF-8';
print('Executing "$command" in "$finalWorkingDirectory" with environment $newEnvironment');
@@ -307,9 +297,11 @@ Future<Process> startProcess(
final ProcessInfo processInfo = ProcessInfo(command, process);
_runningProcesses.add(processInfo);
unawaited(process.exitCode.then<void>((int exitCode) {
_runningProcesses.remove(processInfo);
}));
unawaited(
process.exitCode.then<void>((int exitCode) {
_runningProcesses.remove(processInfo);
}),
);
return process;
}
@@ -346,7 +338,7 @@ Future<int> exec(
executable,
arguments,
environment: environment,
canFail : canFail,
canFail: canFail,
workingDirectory: workingDirectory,
output: output,
stderr: stderr,
@@ -397,32 +389,39 @@ Future<void> forwardStandardStreams(
StringBuffer? stderr,
bool printStdout = true,
bool printStderr = true,
}) {
}) {
final Completer<void> stdoutDone = Completer<void>();
final Completer<void> stderrDone = Completer<void>();
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (printStdout) {
print('stdout: $line');
}
output?.writeln(line);
}, onDone: () { stdoutDone.complete(); });
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(
(String line) {
if (printStdout) {
print('stdout: $line');
}
output?.writeln(line);
},
onDone: () {
stdoutDone.complete();
},
);
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (printStderr) {
print('stderr: $line');
}
stderr?.writeln(line);
}, onDone: () { stderrDone.complete(); });
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(
(String line) {
if (printStderr) {
print('stderr: $line');
}
stderr?.writeln(line);
},
onDone: () {
stderrDone.complete();
},
);
return Future.wait<void>(<Future<void>>[
stdoutDone.future,
stderrDone.future,
]);
return Future.wait<void>(<Future<void>>[stdoutDone.future, stderrDone.future]);
}
/// Executes a command and returns its standard output as a String.
@@ -476,11 +475,8 @@ List<String> _flutterCommandArgs(
final bool pubOrPackagesCommand = command.startsWith('packages') || command.startsWith('pub');
return <String>[
command,
if (deviceOperatingSystem == DeviceOperatingSystem.ios && supportedDeviceTimeoutCommands.contains(command))
...<String>[
'--device-timeout',
'5',
],
if (deviceOperatingSystem == DeviceOperatingSystem.ios &&
supportedDeviceTimeoutCommands.contains(command)) ...<String>['--device-timeout', '5'],
// DDS should generally be disabled for flutter drive in CI.
// See https://github.com/flutter/flutter/issues/152684.
@@ -500,34 +496,33 @@ List<String> _flutterCommandArgs(
// the same allowed args.
if (!pubOrPackagesCommand) '--ci',
if (!pubOrPackagesCommand && hostAgent.dumpDirectory != null)
'--debug-logs-dir=${hostAgent.dumpDirectory!.path}'
'--debug-logs-dir=${hostAgent.dumpDirectory!.path}',
];
}
/// Runs the flutter `command`, and returns the exit code.
/// If `canFail` is `false`, the future completes with an error.
Future<int> flutter(String command, {
Future<int> flutter(
String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
bool driveWithDds = false, // `flutter drive` tests should generally have dds disabled.
// The exception is tests that also exercise DevTools, such as
// DevToolsMemoryTest in perf_tests.dart.
bool driveWithDds = false, // `flutter drive` tests should generally have dds disabled.
// The exception is tests that also exercise DevTools, such as
// DevToolsMemoryTest in perf_tests.dart.
Map<String, String>? environment,
String? workingDirectory,
StringBuffer? output, // if not null, the stdout will be written here
StringBuffer? stderr, // if not null, the stderr will be written here
}) async {
final List<String> args = _flutterCommandArgs(
command, options, driveWithDds: driveWithDds,
);
final List<String> args = _flutterCommandArgs(command, options, driveWithDds: driveWithDds);
final int exitCode = await exec(
path.join(flutterDirectory.path, 'bin', 'flutter'),
args,
canFail: canFail,
environment: environment,
workingDirectory: workingDirectory,
output: output,
stderr: stderr,
path.join(flutterDirectory.path, 'bin', 'flutter'),
args,
canFail: canFail,
environment: environment,
workingDirectory: workingDirectory,
output: output,
stderr: stderr,
);
if (exitCode != 0 && !canFail) {
@@ -558,10 +553,12 @@ Future<int> flutter(String command, {
///
/// The actual process executes asynchronously. A handle to the subprocess is
/// returned in the form of a [Future] that completes to a [Process] object.
Future<Process> startFlutter(String command, {
Future<Process> startFlutter(
String command, {
List<String> options = const <String>[],
Map<String, String> environment = const <String, String>{},
bool isBot = true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
bool isBot =
true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
String? workingDirectory,
}) async {
final List<String> args = _flutterCommandArgs(command, options);
@@ -573,16 +570,19 @@ Future<Process> startFlutter(String command, {
workingDirectory: workingDirectory,
);
unawaited(process.exitCode.then<void>((int exitCode) async {
if (exitCode != 0) {
await _flutterScreenshot(workingDirectory: workingDirectory);
}
}));
unawaited(
process.exitCode.then<void>((int exitCode) async {
if (exitCode != 0) {
await _flutterScreenshot(workingDirectory: workingDirectory);
}
}),
);
return process;
}
/// Runs a `flutter` command and returns the standard output as a string.
Future<String> evalFlutter(String command, {
Future<String> evalFlutter(
String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
Map<String, String>? environment,
@@ -590,19 +590,26 @@ Future<String> evalFlutter(String command, {
String? workingDirectory,
}) {
final List<String> args = _flutterCommandArgs(command, options);
return eval(path.join(flutterDirectory.path, 'bin', 'flutter'), args,
canFail: canFail, environment: environment, stderr: stderr, workingDirectory: workingDirectory);
return eval(
path.join(flutterDirectory.path, 'bin', 'flutter'),
args,
canFail: canFail,
environment: environment,
stderr: stderr,
workingDirectory: workingDirectory,
);
}
Future<ProcessResult> executeFlutter(String command, {
Future<ProcessResult> executeFlutter(
String command, {
List<String> options = const <String>[],
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
}) async {
final List<String> args = _flutterCommandArgs(command, options);
final ProcessResult processResult = await _processManager.run(
<String>[path.join(flutterDirectory.path, 'bin', 'flutter'), ...args],
workingDirectory: cwd,
);
final ProcessResult processResult = await _processManager.run(<String>[
path.join(flutterDirectory.path, 'bin', 'flutter'),
...args,
], workingDirectory: cwd);
if (processResult.exitCode != 0 && !canFail) {
await _flutterScreenshot();
@@ -610,7 +617,7 @@ Future<ProcessResult> executeFlutter(String command, {
return processResult;
}
Future<void> _flutterScreenshot({ String? workingDirectory }) async {
Future<void> _flutterScreenshot({String? workingDirectory}) async {
try {
final Directory? dumpDirectory = hostAgent.dumpDirectory;
if (dumpDirectory == null) {
@@ -624,18 +631,16 @@ Future<void> _flutterScreenshot({ String? workingDirectory }) async {
final String deviceId = (await devices.workingDevice).deviceId;
print('Taking screenshot of working device $deviceId at $screenshotPath');
final List<String> args = _flutterCommandArgs(
'screenshot',
<String>[
'--out',
screenshotPath,
'-d', deviceId,
],
);
final ProcessResult screenshot = await _processManager.run(
<String>[path.join(flutterDirectory.path, 'bin', 'flutter'), ...args],
workingDirectory: workingDirectory ?? cwd,
);
final List<String> args = _flutterCommandArgs('screenshot', <String>[
'--out',
screenshotPath,
'-d',
deviceId,
]);
final ProcessResult screenshot = await _processManager.run(<String>[
path.join(flutterDirectory.path, 'bin', 'flutter'),
...args,
], workingDirectory: workingDirectory ?? cwd);
if (screenshot.exitCode != 0) {
print('Failed to take screenshot. Continuing.');
@@ -645,11 +650,9 @@ Future<void> _flutterScreenshot({ String? workingDirectory }) async {
}
}
String get dartBin =>
path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'dart');
String get dartBin => path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'dart');
String get pubBin =>
path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'pub');
String get pubBin => path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'pub');
Future<int> dart(List<String> args) => exec(dartBin, args);
@@ -664,14 +667,13 @@ Future<String?> findJavaHome() async {
if (hits.isEmpty) {
return null;
}
final String javaBinary = hits.first
.split(': ')
.last;
final String javaBinary = hits.first.split(': ').last;
// javaBinary == /some/path/to/java/home/bin/java
_javaHome = path.dirname(path.dirname(javaBinary));
}
return _javaHome;
}
String? _javaHome;
Future<T> inDirectory<T>(dynamic directory, Future<T> Function() action) async {
@@ -693,7 +695,10 @@ void cd(dynamic directory) {
cwd = directory.path;
d = directory;
} else {
throw FileSystemException('Unsupported directory type ${directory.runtimeType}', directory.toString());
throw FileSystemException(
'Unsupported directory type ${directory.runtimeType}',
directory.toString(),
);
}
if (!d.existsSync()) {
@@ -758,8 +763,7 @@ Future<void> runAndCaptureAsyncStacks(Future<void> Function() callback) {
bool canRun(String path) => _processManager.canRun(path);
final RegExp _obsRegExp =
RegExp('A Dart VM Service .* is available at: ');
final RegExp _obsRegExp = RegExp('A Dart VM Service .* is available at: ');
final RegExp _obsPortRegExp = RegExp(r'(\S+:(\d+)/\S*)$');
final RegExp _obsUriRegExp = RegExp(r'((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
@@ -767,17 +771,14 @@ final RegExp _obsUriRegExp = RegExp(r'((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
/// `prefix` defaults to the RegExp: `A Dart VM Service .* is available at: `.
int? parseServicePort(String line, {
Pattern? prefix,
}) {
int? parseServicePort(String line, {Pattern? prefix}) {
prefix ??= _obsRegExp;
final Iterable<Match> matchesIter = prefix.allMatches(line);
if (matchesIter.isEmpty) {
return null;
}
final Match prefixMatch = matchesIter.first;
final List<Match> matches =
_obsPortRegExp.allMatches(line, prefixMatch.end).toList();
final List<Match> matches = _obsPortRegExp.allMatches(line, prefixMatch.end).toList();
return matches.isEmpty ? null : int.parse(matches[0].group(2)!);
}
@@ -785,17 +786,14 @@ int? parseServicePort(String line, {
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
/// `prefix` defaults to the RegExp: `A Dart VM Service .* is available at: `.
Uri? parseServiceUri(String line, {
Pattern? prefix,
}) {
Uri? parseServiceUri(String line, {Pattern? prefix}) {
prefix ??= _obsRegExp;
final Iterable<Match> matchesIter = prefix.allMatches(line);
if (matchesIter.isEmpty) {
return null;
}
final Match prefixMatch = matchesIter.first;
final List<Match> matches =
_obsUriRegExp.allMatches(line, prefixMatch.end).toList();
final List<Match> matches = _obsUriRegExp.allMatches(line, prefixMatch.end).toList();
return matches.isEmpty ? null : Uri.parse(matches[0].group(0)!);
}
@@ -860,7 +858,7 @@ void checkFileContains(List<Pattern> patterns, String filePath) {
if (!fileContent.contains(pattern)) {
throw TaskResult.failure(
'Expected to find `$pattern` in `$filePath` '
'instead it found:\n$fileContent'
'instead it found:\n$fileContent',
);
}
}
@@ -875,10 +873,7 @@ Future<int> gitClone({required String path, required String repo}) async {
await Directory(path).create(recursive: true);
return inDirectory<int>(
path,
() => exec('git', <String>['clone', repo]),
);
return inDirectory<int>(path, () => exec('git', <String>['clone', repo]));
}
/// Call [fn] retrying so long as [retryIf] return `true` for the exception
@@ -901,8 +896,7 @@ Future<T> retry<T>(
try {
return await fn();
} on Exception catch (e) {
if (attempt >= maxAttempts ||
(retryIf != null && !(await retryIf(e)))) {
if (attempt >= maxAttempts || (retryIf != null && !(await retryIf(e)))) {
rethrow;
}
}
@@ -924,12 +918,8 @@ Future<void> createFfiPackage(String name, Directory parent) async {
name,
],
);
await _pinDependencies(
File(path.join(parent.path, name, 'pubspec.yaml')),
);
await _pinDependencies(
File(path.join(parent.path, name, 'example', 'pubspec.yaml')),
);
await _pinDependencies(File(path.join(parent.path, name, 'pubspec.yaml')));
await _pinDependencies(File(path.join(parent.path, name, 'example', 'pubspec.yaml')));
});
}