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

@@ -79,30 +79,32 @@ class Chrome {
/// The [onError] callback is called with an error message when the Chrome
/// process encounters an error. In particular, [onError] is called when the
/// Chrome process exits prematurely, i.e. before [stop] is called.
static Future<Chrome> launch(ChromeOptions options, { String? workingDirectory, required ChromeErrorCallback onError }) async {
static Future<Chrome> launch(
ChromeOptions options, {
String? workingDirectory,
required ChromeErrorCallback onError,
}) async {
if (!io.Platform.isWindows) {
final io.ProcessResult versionResult = io.Process.runSync(_findSystemChromeExecutable(), const <String>['--version']);
final io.ProcessResult versionResult = io.Process.runSync(
_findSystemChromeExecutable(),
const <String>['--version'],
);
print('Launching ${versionResult.stdout}');
} else {
print('Launching Chrome...');
}
final String jsFlags = options.enableWasmGC ? <String>[
'--experimental-wasm-gc',
'--experimental-wasm-type-reflection',
].join(' ') : '';
final String jsFlags =
options.enableWasmGC
? <String>['--experimental-wasm-gc', '--experimental-wasm-type-reflection'].join(' ')
: '';
final bool withDebugging = options.debugPort != null;
final List<String> args = <String>[
if (options.userDataDirectory != null)
'--user-data-dir=${options.userDataDirectory}',
if (options.url != null)
options.url!,
if (io.Platform.environment['CHROME_NO_SANDBOX'] == 'true')
'--no-sandbox',
if (options.headless ?? false)
'--headless',
if (withDebugging)
'--remote-debugging-port=${options.debugPort}',
if (options.userDataDirectory != null) '--user-data-dir=${options.userDataDirectory}',
if (options.url != null) options.url!,
if (io.Platform.environment['CHROME_NO_SANDBOX'] == 'true') '--no-sandbox',
if (options.headless ?? false) '--headless',
if (withDebugging) '--remote-debugging-port=${options.debugPort}',
'--window-size=${options.windowWidth},${options.windowHeight}',
'--disable-extensions',
'--disable-popup-blocking',
@@ -134,7 +136,7 @@ class Chrome {
final WipConnection? _debugConnection;
bool _isStopped = false;
Completer<void> ?_tracingCompleter;
Completer<void>? _tracingCompleter;
StreamSubscription<WipEvent>? _tracingSubscription;
List<Map<String, dynamic>>? _tracingData;
@@ -148,7 +150,7 @@ class Chrome {
if (_tracingCompleter != null) {
throw StateError(
'Cannot start a new performance trace. A tracing session labeled '
'"$label" is already in progress.'
'"$label" is already in progress.',
);
}
_tracingCompleter = Completer<void>();
@@ -167,10 +169,14 @@ class Chrome {
} else if (event.method == 'Tracing.dataCollected') {
final dynamic value = event.params?['value'];
if (value is! List) {
throw FormatException('"Tracing.dataCollected" returned malformed data. '
'Expected a List but got: ${value.runtimeType}');
throw FormatException(
'"Tracing.dataCollected" returned malformed data. '
'Expected a List but got: ${value.runtimeType}',
);
}
_tracingData?.addAll((event.params?['value'] as List<dynamic>).cast<Map<String, dynamic>>());
_tracingData?.addAll(
(event.params?['value'] as List<dynamic>).cast<Map<String, dynamic>>(),
);
}
});
await _debugConnection?.sendCommand('Tracing.start', <String, dynamic>{
@@ -226,8 +232,7 @@ String _findSystemChromeExecutable() {
}
if (io.Platform.isLinux) {
final io.ProcessResult which =
io.Process.runSync('which', <String>['google-chrome']);
final io.ProcessResult which = io.Process.runSync('which', <String>['google-chrome']);
if (which.exitCode != 0) {
throw Exception('Failed to locate system Chrome installation.');
@@ -238,11 +243,12 @@ String _findSystemChromeExecutable() {
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
} else if (io.Platform.isWindows) {
const String kWindowsExecutable = r'Google\Chrome\Application\chrome.exe';
final List<String> kWindowsPrefixes = <String?>[
io.Platform.environment['LOCALAPPDATA'],
io.Platform.environment['PROGRAMFILES'],
io.Platform.environment['PROGRAMFILES(X86)'],
].whereType<String>().toList();
final List<String> kWindowsPrefixes =
<String?>[
io.Platform.environment['LOCALAPPDATA'],
io.Platform.environment['PROGRAMFILES'],
io.Platform.environment['PROGRAMFILES(X86)'],
].whereType<String>().toList();
final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
final String expectedPath = path.join(prefix, kWindowsExecutable);
return io.File(expectedPath).existsSync();
@@ -272,7 +278,8 @@ Future<Uri> _getRemoteDebuggerUrl(Uri base) async {
final io.HttpClient client = io.HttpClient();
final io.HttpClientRequest request = await client.getUrl(base.resolve('/json/list'));
final io.HttpClientResponse response = await request.close();
final List<dynamic>? jsonObject = await json.fuse(utf8).decoder.bind(response).single as List<dynamic>?;
final List<dynamic>? jsonObject =
await json.fuse(utf8).decoder.bind(response).single as List<dynamic>?;
if (jsonObject == null || jsonObject.isEmpty) {
return base;
}
@@ -289,10 +296,9 @@ class BlinkTraceSummary {
static BlinkTraceSummary? fromJson(List<Map<String, dynamic>> traceJson) {
try {
// Convert raw JSON data to BlinkTraceEvent objects sorted by timestamp.
List<BlinkTraceEvent> events = traceJson
.map<BlinkTraceEvent>(BlinkTraceEvent.fromJson)
.toList()
..sort((BlinkTraceEvent a, BlinkTraceEvent b) => a.ts! - b.ts!);
List<BlinkTraceEvent> events =
traceJson.map<BlinkTraceEvent>(BlinkTraceEvent.fromJson).toList()
..sort((BlinkTraceEvent a, BlinkTraceEvent b) => a.ts! - b.ts!);
Exception noMeasuredFramesFound() => Exception(
'No measured frames found in benchmark tracing data. This likely '
@@ -349,12 +355,21 @@ class BlinkTraceSummary {
// Compute averages and summarize.
return BlinkTraceSummary._(
averageBeginFrameTime: _computeAverageDuration(frames.map((BlinkFrame frame) => frame.beginFrame).whereType<BlinkTraceEvent>().toList()),
averageUpdateLifecyclePhasesTime: _computeAverageDuration(frames.map((BlinkFrame frame) => frame.updateAllLifecyclePhases).whereType<BlinkTraceEvent>().toList()),
averageBeginFrameTime: _computeAverageDuration(
frames.map((BlinkFrame frame) => frame.beginFrame).whereType<BlinkTraceEvent>().toList(),
),
averageUpdateLifecyclePhasesTime: _computeAverageDuration(
frames
.map((BlinkFrame frame) => frame.updateAllLifecyclePhases)
.whereType<BlinkTraceEvent>()
.toList(),
),
);
} catch (_) {
final io.File traceFile = io.File('./chrome-trace.json');
io.stderr.writeln('Failed to interpret the Chrome trace contents. The trace was saved in ${traceFile.path}');
io.stderr.writeln(
'Failed to interpret the Chrome trace contents. The trace was saved in ${traceFile.path}',
);
traceFile.writeAsStringSync(const JsonEncoder.withIndent(' ').convert(traceJson));
rethrow;
}
@@ -381,9 +396,10 @@ class BlinkTraceSummary {
final Duration averageTotalUIFrameTime;
@override
String toString() => '$BlinkTraceSummary('
'averageBeginFrameTime: ${averageBeginFrameTime.inMicroseconds / 1000}ms, '
'averageUpdateLifecyclePhasesTime: ${averageUpdateLifecyclePhasesTime.inMicroseconds / 1000}ms)';
String toString() =>
'$BlinkTraceSummary('
'averageBeginFrameTime: ${averageBeginFrameTime.inMicroseconds / 1000}ms, '
'averageUpdateLifecyclePhasesTime: ${averageUpdateLifecyclePhasesTime.inMicroseconds / 1000}ms)';
}
/// Contains events pertaining to a single frame in the Blink trace data.
@@ -405,14 +421,15 @@ class BlinkFrame {
/// their average as a [Duration] value.
Duration _computeAverageDuration(List<BlinkTraceEvent> events) {
// Compute the sum of "tdur" fields of the last _kMeasuredSampleCount events.
final double sum = events
.skip(math.max(events.length - _kMeasuredSampleCount, 0))
.fold(0.0, (double previousValue, BlinkTraceEvent event) {
if (event.tdur == null) {
throw FormatException('Trace event lacks "tdur" field: $event');
}
return previousValue + event.tdur!;
});
final double sum = events.skip(math.max(events.length - _kMeasuredSampleCount, 0)).fold(0.0, (
double previousValue,
BlinkTraceEvent event,
) {
if (event.tdur == null) {
throw FormatException('Trace event lacks "tdur" field: $event');
}
return previousValue + event.tdur!;
});
final int sampleCount = math.min(events.length, _kMeasuredSampleCount);
return Duration(microseconds: sum ~/ sampleCount);
}
@@ -447,15 +464,15 @@ class BlinkTraceEvent {
///
/// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
BlinkTraceEvent.fromJson(Map<String, dynamic> json)
: args = json['args'] as Map<String, dynamic>,
cat = json['cat'] as String,
name = json['name'] as String,
ph = json['ph'] as String,
pid = _readInt(json, 'pid'),
tid = _readInt(json, 'tid'),
ts = _readInt(json, 'ts'),
tts = _readInt(json, 'tts'),
tdur = _readInt(json, 'tdur');
: args = json['args'] as Map<String, dynamic>,
cat = json['cat'] as String,
name = json['name'] as String,
ph = json['ph'] as String,
pid = _readInt(json, 'pid'),
tid = _readInt(json, 'tid'),
ts = _readInt(json, 'ts'),
tts = _readInt(json, 'tts'),
tdur = _readInt(json, 'tdur');
/// Event-specific data.
final Map<String, dynamic> args;
@@ -496,11 +513,10 @@ class BlinkTraceEvent {
///
/// This event is a duration event that has its `tdur` populated.
bool get isBeginFrame {
return ph == 'X' && (
name == 'WebViewImpl::beginFrame' ||
name == 'WebFrameWidgetBase::BeginMainFrame' ||
name == 'WebFrameWidgetImpl::BeginMainFrame'
);
return ph == 'X' &&
(name == 'WebViewImpl::beginFrame' ||
name == 'WebFrameWidgetBase::BeginMainFrame' ||
name == 'WebFrameWidgetImpl::BeginMainFrame');
}
/// An "update all lifecycle phases" event contains UI thread computations
@@ -514,10 +530,9 @@ class BlinkTraceEvent {
///
/// This event is a duration event that has its `tdur` populated.
bool get isUpdateAllLifecyclePhases {
return ph == 'X' && (
name == 'WebViewImpl::updateAllLifecyclePhases' ||
name == 'WebFrameWidgetImpl::UpdateLifecycle'
);
return ph == 'X' &&
(name == 'WebViewImpl::updateAllLifecyclePhases' ||
name == 'WebFrameWidgetImpl::UpdateLifecycle');
}
/// Whether this is the beginning of a "measured_frame" event.
@@ -537,16 +552,17 @@ class BlinkTraceEvent {
bool get isEndMeasuredFrame => ph == 'e' && name == 'measured_frame';
@override
String toString() => '$BlinkTraceEvent('
'args: ${json.encode(args)}, '
'cat: $cat, '
'name: $name, '
'ph: $ph, '
'pid: $pid, '
'tid: $tid, '
'ts: $ts, '
'tts: $tts, '
'tdur: $tdur)';
String toString() =>
'$BlinkTraceEvent('
'args: ${json.encode(args)}, '
'cat: $cat, '
'name: $name, '
'ph: $ph, '
'pid: $pid, '
'tid: $tid, '
'ts: $ts, '
'tts: $tts, '
'tdur: $tdur)';
}
/// Read an integer out of [json] stored under [key].
@@ -572,48 +588,56 @@ int? _readInt(Map<String, dynamic> json, String key) {
/// Inconsistency detected by ld.so: ../elf/dl-tls.c: 493: _dl_allocate_tls_init: Assertion `listp->slotinfo[cnt].gen <= GL(dl_tls_generation)' failed!
const String _kGlibcError = 'Inconsistency detected by ld.so';
Future<io.Process> _spawnChromiumProcess(String executable, List<String> args, { String? workingDirectory }) async {
Future<io.Process> _spawnChromiumProcess(
String executable,
List<String> args, {
String? workingDirectory,
}) async {
// Keep attempting to launch the browser until one of:
// - Chrome launched successfully, in which case we just return from the loop.
// - The tool detected an unretryable Chrome error, in which case we throw ToolExit.
while (true) {
final io.Process process = await io.Process.start(executable, args, workingDirectory: workingDirectory);
final io.Process process = await io.Process.start(
executable,
args,
workingDirectory: workingDirectory,
);
process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String line) {
print('[CHROME STDOUT]: $line');
});
process.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen((String line) {
print('[CHROME STDOUT]: $line');
});
// Wait until the DevTools are listening before trying to connect. This is
// only required for flutter_test --platform=chrome and not flutter run.
bool hitGlibcBug = false;
await process.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.map((String line) {
print('[CHROME STDERR]:$line');
if (line.contains(_kGlibcError)) {
hitGlibcBug = true;
}
return line;
})
.firstWhere((String line) => line.startsWith('DevTools listening'), orElse: () {
if (hitGlibcBug) {
print(
'Encountered glibc bug https://sourceware.org/bugzilla/show_bug.cgi?id=19329. '
'Will try launching browser again.',
);
return '';
}
print('Failed to launch browser. Command used to launch it: ${args.join(' ')}');
throw Exception(
'Failed to launch browser. Make sure you are using an up-to-date '
'Chrome or Edge. Otherwise, consider using -d web-server instead '
'and filing an issue at https://github.com/flutter/flutter/issues.',
.transform(utf8.decoder)
.transform(const LineSplitter())
.map((String line) {
print('[CHROME STDERR]:$line');
if (line.contains(_kGlibcError)) {
hitGlibcBug = true;
}
return line;
})
.firstWhere(
(String line) => line.startsWith('DevTools listening'),
orElse: () {
if (hitGlibcBug) {
print(
'Encountered glibc bug https://sourceware.org/bugzilla/show_bug.cgi?id=19329. '
'Will try launching browser again.',
);
return '';
}
print('Failed to launch browser. Command used to launch it: ${args.join(' ')}');
throw Exception(
'Failed to launch browser. Make sure you are using an up-to-date '
'Chrome or Edge. Otherwise, consider using -d web-server instead '
'and filing an issue at https://github.com/flutter/flutter/issues.',
);
},
);
});
if (!hitGlibcBug) {
return process;
@@ -622,9 +646,14 @@ Future<io.Process> _spawnChromiumProcess(String executable, List<String> args, {
// A precaution that avoids accumulating browser processes, in case the
// glibc bug doesn't cause the browser to quit and we keep looping and
// launching more processes.
unawaited(process.exitCode.timeout(const Duration(seconds: 1), onTimeout: () {
process.kill();
return 0;
}));
unawaited(
process.exitCode.timeout(
const Duration(seconds: 1),
onTimeout: () {
process.kill();
return 0;
},
),
);
}
}