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

@@ -26,18 +26,18 @@ enum FieldJustification { LEFT, RIGHT, CENTER }
/// See [printSummary] for more.
class ABTest {
ABTest({required this.localEngine, required this.localEngineHost, required this.taskName})
: runStart = DateTime.now(),
_aResults = <String, List<double>>{},
_bResults = <String, List<double>>{};
: runStart = DateTime.now(),
_aResults = <String, List<double>>{},
_bResults = <String, List<double>>{};
ABTest.fromJsonMap(Map<String, dynamic> jsonResults)
: localEngine = jsonResults[kLocalEngineKeyName] as String,
localEngineHost = jsonResults[kLocalEngineHostKeyName] as String?,
taskName = jsonResults[kTaskNameKeyName] as String,
runStart = DateTime.parse(jsonResults[kRunStartKeyName] as String),
_runEnd = DateTime.parse(jsonResults[kRunEndKeyName] as String),
_aResults = _convertFrom(jsonResults[kAResultsKeyName] as Map<String, dynamic>),
_bResults = _convertFrom(jsonResults[kBResultsKeyName] as Map<String, dynamic>);
: localEngine = jsonResults[kLocalEngineKeyName] as String,
localEngineHost = jsonResults[kLocalEngineHostKeyName] as String?,
taskName = jsonResults[kTaskNameKeyName] as String,
runStart = DateTime.parse(jsonResults[kRunStartKeyName] as String),
_runEnd = DateTime.parse(jsonResults[kRunEndKeyName] as String),
_aResults = _convertFrom(jsonResults[kAResultsKeyName] as Map<String, dynamic>),
_bResults = _convertFrom(jsonResults[kBResultsKeyName] as Map<String, dynamic>);
final String localEngine;
final String? localEngineHost;
@@ -51,7 +51,7 @@ class ABTest {
static Map<String, List<double>> _convertFrom(dynamic results) {
final Map<String, dynamic> resultMap = results as Map<String, dynamic>;
return <String, List<double>> {
return <String, List<double>>{
for (final String key in resultMap.keys)
key: (resultMap[key] as List<dynamic>).cast<double>(),
};
@@ -86,16 +86,15 @@ class ABTest {
}
Map<String, dynamic> get jsonMap => <String, dynamic>{
kBenchmarkTypeKeyName: kBenchmarkResultsType,
kBenchmarkVersionKeyName: kBenchmarkABVersion,
kLocalEngineKeyName: localEngine,
if (localEngineHost != null)
kLocalEngineHostKeyName: localEngineHost,
kTaskNameKeyName: taskName,
kRunStartKeyName: runStart.toIso8601String(),
kRunEndKeyName: runEnd!.toIso8601String(),
kAResultsKeyName: _aResults,
kBResultsKeyName: _bResults,
kBenchmarkTypeKeyName: kBenchmarkResultsType,
kBenchmarkVersionKeyName: kBenchmarkABVersion,
kLocalEngineKeyName: localEngine,
if (localEngineHost != null) kLocalEngineHostKeyName: localEngineHost,
kTaskNameKeyName: taskName,
kRunStartKeyName: runStart.toIso8601String(),
kRunEndKeyName: runEnd!.toIso8601String(),
kAResultsKeyName: _aResults,
kBResultsKeyName: _bResults,
};
static void updateColumnLengths(List<int> lengths, List<String?> results) {
@@ -106,10 +105,12 @@ class ABTest {
}
}
static void formatResult(StringBuffer buffer,
List<int> lengths,
List<FieldJustification> aligns,
List<String?> values) {
static void formatResult(
StringBuffer buffer,
List<int> lengths,
List<FieldJustification> aligns,
List<String?> values,
) {
for (int column = 0; column < lengths.length; column++) {
final int len = lengths[column];
String? value = values[column];
@@ -117,13 +118,13 @@ class ABTest {
value = ''.padRight(len);
} else {
value = switch (aligns[column]) {
FieldJustification.LEFT => value.padRight(len),
FieldJustification.RIGHT => value.padLeft(len),
FieldJustification.LEFT => value.padRight(len),
FieldJustification.RIGHT => value.padLeft(len),
FieldJustification.CENTER => value.padLeft((len + value.length) ~/ 2).padRight(len),
};
}
if (column > 0) {
value = value.padLeft(len+1);
value = value.padLeft(len + 1);
}
buffer.write(value);
}
@@ -141,22 +142,28 @@ class ABTest {
for (final String scoreKey in <String>{...summariesA.keys, ...summariesB.keys})
<String?>[
scoreKey,
summariesA[scoreKey]?.averageString, summariesA[scoreKey]?.noiseString,
summariesB[scoreKey]?.averageString, summariesB[scoreKey]?.noiseString,
summariesA[scoreKey]?.averageString,
summariesA[scoreKey]?.noiseString,
summariesB[scoreKey]?.averageString,
summariesB[scoreKey]?.noiseString,
summariesA[scoreKey]?.improvementOver(summariesB[scoreKey]),
],
];
final List<String> titles = <String>[
'Score',
'Average A', '(noise)',
'Average B', '(noise)',
'Average A',
'(noise)',
'Average B',
'(noise)',
'Speed-up',
];
final List<FieldJustification> alignments = <FieldJustification>[
FieldJustification.LEFT,
FieldJustification.RIGHT, FieldJustification.LEFT,
FieldJustification.RIGHT, FieldJustification.LEFT,
FieldJustification.RIGHT,
FieldJustification.LEFT,
FieldJustification.RIGHT,
FieldJustification.LEFT,
FieldJustification.CENTER,
];
@@ -167,11 +174,10 @@ class ABTest {
}
final StringBuffer buffer = StringBuffer();
formatResult(buffer, lengths,
<FieldJustification>[
FieldJustification.CENTER,
...alignments.skip(1),
], titles);
formatResult(buffer, lengths, <FieldJustification>[
FieldJustification.CENTER,
...alignments.skip(1),
], titles);
for (final List<String?> row in tableRows) {
formatResult(buffer, lengths, alignments, row);
}
@@ -208,10 +214,7 @@ class ABTest {
return buffer.toString();
}
Set<String> get _allScoreKeys => <String>{
..._aResults.keys,
..._bResults.keys,
};
Set<String> get _allScoreKeys => <String>{..._aResults.keys, ..._bResults.keys};
/// Returns the summary as a tab-separated spreadsheet.
///
@@ -253,10 +256,7 @@ class ABTest {
}
class _ScoreSummary {
_ScoreSummary({
required this.average,
required this.noise,
});
_ScoreSummary({required this.average, required this.noise});
/// Average (arithmetic mean) of a series of values collected by a benchmark.
final double average;
@@ -283,13 +283,14 @@ void _addResult(TaskResult result, Map<String, List<double>> results) {
Map<String, _ScoreSummary> _summarize(Map<String, List<double>> results) {
return results.map<String, _ScoreSummary>((String scoreKey, List<double> values) {
final double average = _computeAverage(values);
return MapEntry<String, _ScoreSummary>(scoreKey, _ScoreSummary(
average: average,
// If the average is zero, the benchmark got the perfect score with no noise.
noise: average > 0
? _computeStandardDeviationForPopulation(values) / average
: 0.0,
));
return MapEntry<String, _ScoreSummary>(
scoreKey,
_ScoreSummary(
average: average,
// If the average is zero, the benchmark got the perfect score with no noise.
noise: average > 0 ? _computeStandardDeviationForPopulation(values) / average : 0.0,
),
);
});
}

View File

@@ -22,14 +22,13 @@ final List<String> debugAssets = <String>[
'assets/flutter_assets/vm_snapshot_data',
];
final List<String> baseApkFiles = <String> [
'classes.dex',
'AndroidManifest.xml',
];
final List<String> baseApkFiles = <String>['classes.dex', 'AndroidManifest.xml'];
/// Runs the given [testFunction] on a freshly generated Flutter project.
Future<void> runProjectTest(Future<void> Function(FlutterProject project) testFunction) async {
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.');
final Directory tempDir = Directory.systemTemp.createTempSync(
'flutter_devicelab_gradle_plugin_test.',
);
final FlutterProject project = await FlutterProject.create(tempDir, 'hello');
try {
@@ -40,8 +39,12 @@ Future<void> runProjectTest(Future<void> Function(FlutterProject project) testFu
}
/// Runs the given [testFunction] on a freshly generated Flutter plugin project.
Future<void> runPluginProjectTest(Future<void> Function(FlutterPluginProject pluginProject) testFunction) async {
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.');
Future<void> runPluginProjectTest(
Future<void> Function(FlutterPluginProject pluginProject) testFunction,
) async {
final Directory tempDir = Directory.systemTemp.createTempSync(
'flutter_devicelab_gradle_plugin_test.',
);
final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tempDir, 'aaa');
try {
@@ -52,9 +55,16 @@ Future<void> runPluginProjectTest(Future<void> Function(FlutterPluginProject plu
}
/// Runs the given [testFunction] on a freshly generated Flutter module project.
Future<void> runModuleProjectTest(Future<void> Function(FlutterModuleProject moduleProject) testFunction) async {
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_module_test.');
final FlutterModuleProject moduleProject = await FlutterModuleProject.create(tempDir, 'hello_module');
Future<void> runModuleProjectTest(
Future<void> Function(FlutterModuleProject moduleProject) testFunction,
) async {
final Directory tempDir = Directory.systemTemp.createTempSync(
'flutter_devicelab_gradle_module_test.',
);
final FlutterModuleProject moduleProject = await FlutterModuleProject.create(
tempDir,
'hello_module',
);
try {
await testFunction(moduleProject);
@@ -66,18 +76,12 @@ Future<void> runModuleProjectTest(Future<void> Function(FlutterModuleProject mod
/// Returns the list of files inside an Android Package Kit.
Future<Iterable<String>> getFilesInApk(String apk) async {
if (!File(apk).existsSync()) {
throw TaskResult.failure(
'Gradle did not produce an output artifact file at: $apk');
throw TaskResult.failure('Gradle did not produce an output artifact file at: $apk');
}
final String files = await _evalApkAnalyzer(
<String>[
'files',
'list',
apk,
]
);
final String files = await _evalApkAnalyzer(<String>['files', 'list', apk]);
return files.split('\n').map((String file) => file.substring(1).trim());
}
/// Returns the list of files inside an Android App Bundle.
Future<Iterable<String>> getFilesInAppBundle(String bundle) {
return getFilesInApk(bundle);
@@ -102,8 +106,8 @@ bool hasMultipleOccurrences(String text, Pattern pattern) {
/// The Android home directory.
String get _androidHome {
final String? androidHome = Platform.environment['ANDROID_HOME'] ??
Platform.environment['ANDROID_SDK_ROOT'];
final String? androidHome =
Platform.environment['ANDROID_HOME'] ?? Platform.environment['ANDROID_SDK_ROOT'];
if (androidHome == null || androidHome.isEmpty) {
throw Exception('Environment variable `ANDROID_HOME` is not set.');
}
@@ -120,19 +124,22 @@ Future<String> _evalApkAnalyzer(
if (javaHome == null || javaHome.isEmpty) {
throw Exception('No JAVA_HOME set.');
}
final String apkAnalyzer = path
.join(_androidHome, 'cmdline-tools', 'latest', 'bin', Platform.isWindows ? 'apkanalyzer.bat' : 'apkanalyzer');
if (canRun(apkAnalyzer)) {
return eval(
apkAnalyzer,
args,
printStdout: printStdout,
workingDirectory: workingDirectory,
environment: <String, String>{
'JAVA_HOME': javaHome,
},
);
}
final String apkAnalyzer = path.join(
_androidHome,
'cmdline-tools',
'latest',
'bin',
Platform.isWindows ? 'apkanalyzer.bat' : 'apkanalyzer',
);
if (canRun(apkAnalyzer)) {
return eval(
apkAnalyzer,
args,
printStdout: printStdout,
workingDirectory: workingDirectory,
environment: <String, String>{'JAVA_HOME': javaHome},
);
}
final String javaBinary = path.join(javaHome, 'bin', 'java');
assert(canRun(javaBinary));
@@ -140,7 +147,7 @@ Future<String> _evalApkAnalyzer(
final String libs = path.join(androidTools, 'lib');
assert(Directory(libs).existsSync());
final String classSeparator = Platform.isWindows ? ';' : ':';
final String classSeparator = Platform.isWindows ? ';' : ':';
return eval(
javaBinary,
<String>[
@@ -171,22 +178,18 @@ class ApkExtractor {
if (_extracted) {
return;
}
final String packages = await _evalApkAnalyzer(
<String>[
'dex',
'packages',
apkFile.path,
],
);
final String packages = await _evalApkAnalyzer(<String>['dex', 'packages', apkFile.path]);
final List<String> lines = packages.split('\n');
_classes = Set<String>.from(
lines.where((String line) => line.startsWith('C'))
.map<String>((String line) => line.split('\t').last),
lines
.where((String line) => line.startsWith('C'))
.map<String>((String line) => line.split('\t').last),
);
assert(_classes.isNotEmpty);
_methods = Set<String>.from(
lines.where((String line) => line.startsWith('M'))
.map<String>((String line) => line.split('\t').last)
lines
.where((String line) => line.startsWith('M'))
.map<String>((String line) => line.split('\t').last),
);
assert(_methods.isNotEmpty);
_extracted = true;
@@ -219,14 +222,7 @@ class ApkExtractor {
/// Gets the content of the `AndroidManifest.xml`.
Future<String> getAndroidManifest(String apk) async {
return _evalApkAnalyzer(
<String>[
'manifest',
'print',
apk,
],
workingDirectory: _androidHome,
);
return _evalApkAnalyzer(<String>['manifest', 'print', apk], workingDirectory: _androidHome);
}
/// Checks that the [apk] includes any classes from a particularly library with
@@ -325,14 +321,16 @@ android {
Future<void> addProductFlavors(Iterable<String> flavors) async {
final File buildScript = appBuildFile;
final String flavorConfig = flavors.map((String name) {
return '''
final String flavorConfig = flavors
.map((String name) {
return '''
create("$name") {
applicationIdSuffix = ".$name"
versionNameSuffix = "-$name"
}
''';
}).join('\n');
})
.join('\n');
buildScript.openWrite(mode: FileMode.append).write('''
android {
@@ -346,21 +344,24 @@ android {
Future<void> introduceError() async {
final File buildScript = appBuildFile;
await buildScript.writeAsString((await buildScript.readAsString()).replaceAll('buildTypes', 'builTypes'));
await buildScript.writeAsString(
(await buildScript.readAsString()).replaceAll('buildTypes', 'builTypes'),
);
}
Future<void> introducePubspecError() async {
final File pubspec = File(
path.join(parent.path, 'hello', 'pubspec.yaml')
);
final File pubspec = File(path.join(parent.path, 'hello', 'pubspec.yaml'));
final String contents = pubspec.readAsStringSync();
final String newContents = contents.replaceFirst('${Platform.lineTerminator}flutter:${Platform.lineTerminator}', '''
final String newContents = contents.replaceFirst(
'${Platform.lineTerminator}flutter:${Platform.lineTerminator}',
'''
flutter:
assets:
- lib/gallery/example_code.dart
''');
''',
);
pubspec.writeAsStringSync(newContents);
}
@@ -387,7 +388,11 @@ class FlutterPluginProject {
final Directory parent;
final String name;
static Future<FlutterPluginProject> create(Directory directory, String name, {List<String> options = const <String>['--platforms=ios,android']}) async {
static Future<FlutterPluginProject> create(
Directory directory,
String name, {
List<String> options = const <String>['--platforms=ios,android'],
}) async {
await inDirectory(directory, () async {
await flutter('create', options: <String>['--template=plugin', ...options, name]);
});
@@ -397,11 +402,22 @@ class FlutterPluginProject {
String get rootPath => path.join(parent.path, name);
String get examplePath => path.join(rootPath, 'example');
String get exampleAndroidPath => path.join(examplePath, 'android');
String get debugApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk');
String get releaseApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-release.apk');
String get releaseArmApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk','app-armeabi-v7a-release.apk');
String get releaseArm64ApkPath => path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-arm64-v8a-release.apk');
String get releaseBundlePath => path.join(examplePath, 'build', 'app', 'outputs', 'bundle', 'release', 'app.aab');
String get debugApkPath =>
path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk');
String get releaseApkPath =>
path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-release.apk');
String get releaseArmApkPath => path.join(
examplePath,
'build',
'app',
'outputs',
'flutter-apk',
'app-armeabi-v7a-release.apk',
);
String get releaseArm64ApkPath =>
path.join(examplePath, 'build', 'app', 'outputs', 'flutter-apk', 'app-arm64-v8a-release.apk');
String get releaseBundlePath =>
path.join(examplePath, 'build', 'app', 'outputs', 'bundle', 'release', 'app.aab');
}
class FlutterModuleProject {
@@ -426,9 +442,10 @@ Future<void> _runGradleTask({
List<String>? options,
}) async {
final ProcessResult result = await _resultOfGradleTask(
workingDirectory: workingDirectory,
task: task,
options: options);
workingDirectory: workingDirectory,
task: task,
options: options,
);
if (result.exitCode != 0) {
print('stdout:');
print(result.stdout);
@@ -454,44 +471,61 @@ Future<ProcessResult> _resultOfGradleTask({
print('\nUsing JAVA_HOME=$javaHome');
final List<String> args = <String>[
'app:$task',
...?options,
];
final String gradle = path.join(workingDirectory, Platform.isWindows ? 'gradlew.bat' : './gradlew');
final List<String> args = <String>['app:$task', ...?options];
final String gradle = path.join(
workingDirectory,
Platform.isWindows ? 'gradlew.bat' : './gradlew',
);
print('┌── $gradle');
print(File(path.join(workingDirectory, gradle)).readAsLinesSync().map((String line) => '| $line').join('\n'));
print(
File(
path.join(workingDirectory, gradle),
).readAsLinesSync().map((String line) => '| $line').join('\n'),
);
print('└─────────────────────────────────────────────────────────────────────────────────────');
print(
'Running Gradle:\n'
' Executable: $gradle\n'
' Arguments: ${args.join(' ')}\n'
' Working directory: $workingDirectory\n'
' JAVA_HOME: $javaHome\n'
' JAVA_HOME: $javaHome\n',
);
return Process.run(
gradle,
args,
workingDirectory: workingDirectory,
environment: <String, String>{ 'JAVA_HOME': javaHome },
environment: <String, String>{'JAVA_HOME': javaHome},
);
}
/// Returns [null] if target matches [expectedTarget], otherwise returns an error message.
String? validateSnapshotDependency(FlutterProject project, String expectedTarget) {
final File snapshotBlob = File(
path.join(project.rootPath, 'build', 'app', 'intermediates',
'flutter', 'debug', 'flutter_build.d'));
path.join(
project.rootPath,
'build',
'app',
'intermediates',
'flutter',
'debug',
'flutter_build.d',
),
);
assert(snapshotBlob.existsSync());
final String contentSnapshot = snapshotBlob.readAsStringSync();
return contentSnapshot.contains('$expectedTarget ')
? null : 'Dependency file should have $expectedTarget as target. Instead found $contentSnapshot';
? null
: 'Dependency file should have $expectedTarget as target. Instead found $contentSnapshot';
}
File getAndroidBuildFile(String androidAppPath, {bool settings = false}) {
final File groovyFile = File(path.join(androidAppPath, settings ? 'settings.gradle' : 'build.gradle'));
final File kotlinFile = File(path.join(androidAppPath, settings ? 'settings.gradle.kts' : 'build.gradle.kts'));
final File groovyFile = File(
path.join(androidAppPath, settings ? 'settings.gradle' : 'build.gradle'),
);
final File kotlinFile = File(
path.join(androidAppPath, settings ? 'settings.gradle.kts' : 'build.gradle.kts'),
);
if (groovyFile.existsSync()) {
return groovyFile;

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;
},
),
);
}
}

View File

@@ -15,16 +15,17 @@ import 'package:meta/meta.dart';
import 'task_result.dart';
import 'utils.dart';
typedef ProcessRunSync = ProcessResult Function(
String,
List<String>, {
Map<String, String>? environment,
bool includeParentEnvironment,
bool runInShell,
Encoding? stderrEncoding,
Encoding? stdoutEncoding,
String? workingDirectory,
});
typedef ProcessRunSync =
ProcessResult Function(
String,
List<String>, {
Map<String, String>? environment,
bool includeParentEnvironment,
bool runInShell,
Encoding? stderrEncoding,
Encoding? stdoutEncoding,
String? workingDirectory,
});
/// Class for test runner to interact with Flutter's infrastructure service, Cocoon.
///
@@ -38,7 +39,11 @@ class Cocoon {
@visibleForTesting this.processRunSync = Process.runSync,
@visibleForTesting this.requestRetryLimit = 5,
@visibleForTesting this.requestTimeoutLimit = 30,
}) : _httpClient = AuthenticatedCocoonClient(serviceAccountTokenPath, httpClient: httpClient, filesystem: fs);
}) : _httpClient = AuthenticatedCocoonClient(
serviceAccountTokenPath,
httpClient: httpClient,
filesystem: fs,
);
/// Client to make http requests to Cocoon.
final AuthenticatedCocoonClient _httpClient;
@@ -105,8 +110,10 @@ class Cocoon {
resultsJson['TestFlaky'] = isTestFlaky ?? false;
if (_shouldUpdateCocoon(resultsJson, builderBucket ?? 'prod')) {
await retry(
() async => _sendUpdateTaskRequest(resultsJson).timeout(Duration(seconds: requestTimeoutLimit)),
retryIf: (Exception e) => e is SocketException || e is TimeoutException || e is ClientException,
() async =>
_sendUpdateTaskRequest(resultsJson).timeout(Duration(seconds: requestTimeoutLimit)),
retryIf:
(Exception e) => e is SocketException || e is TimeoutException || e is ClientException,
maxAttempts: requestRetryLimit,
);
}
@@ -191,7 +198,8 @@ class Cocoon {
/// as version changes to the backend, datastore issues, or latency issues.
final Response response = await retry(
() => _httpClient.post(url, body: json.encode(jsonData)),
retryIf: (Exception e) => e is SocketException || e is TimeoutException || e is ClientException,
retryIf:
(Exception e) => e is SocketException || e is TimeoutException || e is ClientException,
maxAttempts: requestRetryLimit,
);
return json.decode(response.body) as Map<String, dynamic>;
@@ -204,8 +212,8 @@ class AuthenticatedCocoonClient extends BaseClient {
this._serviceAccountTokenPath, {
@visibleForTesting Client? httpClient,
@visibleForTesting FileSystem? filesystem,
}) : _delegate = httpClient ?? Client(),
_fs = filesystem ?? const LocalFileSystem();
}) : _delegate = httpClient ?? Client(),
_fs = filesystem ?? const LocalFileSystem();
/// Authentication token to have the ability to upload and record test results.
///
@@ -234,12 +242,13 @@ class AuthenticatedCocoonClient extends BaseClient {
if (response.statusCode != 200) {
throw ClientException(
'AuthenticatedClientError:\n'
' URI: ${request.url}\n'
' HTTP Status: ${response.statusCode}\n'
' Response body:\n'
'${(await Response.fromStream(response)).body}',
request.url);
'AuthenticatedClientError:\n'
' URI: ${request.url}\n'
' HTTP Status: ${response.statusCode}\n'
' Response body:\n'
'${(await Response.fromStream(response)).body}',
request.url,
);
}
return response;
}

View File

@@ -64,7 +64,6 @@ final RegExp flutterCompileSdkString = RegExp(r'flutter\.compileSdkVersion|flutt
/// A simple class containing a Kotlin, Gradle, and AGP version.
class VersionTuple {
VersionTuple({
required this.agpVersion,
required this.gradleVersion,
@@ -94,7 +93,8 @@ class VersionTuple {
Future<TaskResult> buildFlutterApkWithSpecifiedDependencyVersions({
required List<VersionTuple> versionTuples,
required Directory tempDir,
required LocalFileSystem localFileSystem,}) async {
required LocalFileSystem localFileSystem,
}) async {
for (final VersionTuple versions in versionTuples) {
final Directory innerTempDir = tempDir.createTempSync(versions.gradleVersion);
try {
@@ -102,25 +102,33 @@ Future<TaskResult> buildFlutterApkWithSpecifiedDependencyVersions({
section('Create new app with dependency versions: $versions');
await flutter(
'create',
options: <String>[
'dependency_checker_app',
'--platforms=android',
],
options: <String>['dependency_checker_app', '--platforms=android'],
workingDirectory: innerTempDir.path,
);
final String appPath = '${innerTempDir.absolute.path}/dependency_checker_app';
if (versions.compileSdkVersion != null) {
final File appGradleBuild = getAndroidBuildFile(localFileSystem.path.join(appPath, 'android', 'app'));
final String appBuildContent = appGradleBuild.readAsStringSync()
.replaceFirst(flutterCompileSdkString, versions.compileSdkVersion!);
final File appGradleBuild = getAndroidBuildFile(
localFileSystem.path.join(appPath, 'android', 'app'),
);
final String appBuildContent = appGradleBuild.readAsStringSync().replaceFirst(
flutterCompileSdkString,
versions.compileSdkVersion!,
);
appGradleBuild.writeAsStringSync(appBuildContent);
}
// Modify gradle version to passed in version.
final File gradleWrapperProperties = localFileSystem.file(localFileSystem.path.join(
appPath, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'));
final File gradleWrapperProperties = localFileSystem.file(
localFileSystem.path.join(
appPath,
'android',
'gradle',
'wrapper',
'gradle-wrapper.properties',
),
);
final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst(
gradleReplacementString,
versions.gradleVersion,
@@ -136,20 +144,16 @@ Future<TaskResult> buildFlutterApkWithSpecifiedDependencyVersions({
.replaceFirst(kgpReplacementString, versions.kotlinVersion);
await gradleSettingsFile.writeAsString(settingsContent, flush: true);
// Ensure that gradle files exists from templates.
section("Ensure 'flutter build apk' succeeds with Gradle ${versions.gradleVersion}, AGP ${versions.agpVersion}, and Kotlin ${versions.kotlinVersion}");
await flutter(
'build',
options: <String>[
'apk',
'--debug',
],
workingDirectory: appPath,
section(
"Ensure 'flutter build apk' succeeds with Gradle ${versions.gradleVersion}, AGP ${versions.agpVersion}, and Kotlin ${versions.kotlinVersion}",
);
await flutter('build', options: <String>['apk', '--debug'], workingDirectory: appPath);
} catch (e) {
tempDir.deleteSync(recursive: true);
return TaskResult.failure('Failed to build app with Gradle ${versions.gradleVersion}, AGP ${versions.agpVersion}, and Kotlin ${versions.kotlinVersion}, error was:\n$e');
return TaskResult.failure(
'Failed to build app with Gradle ${versions.gradleVersion}, AGP ${versions.agpVersion}, and Kotlin ${versions.kotlinVersion}, error was:\n$e',
);
}
}
tempDir.deleteSync(recursive: true);

View File

@@ -25,12 +25,7 @@ class DeviceException implements Exception {
/// Gets the artifact path relative to the current directory.
String getArtifactPath() {
return path.normalize(
path.join(
path.current,
'../../bin/cache/artifacts',
)
);
return path.normalize(path.join(path.current, '../../bin/cache/artifacts'));
}
/// Return the item is in idList if find a match, otherwise return null
@@ -201,10 +196,7 @@ abstract class Device {
Future<void> awaitDevice();
Future<void> uninstallApp() async {
await flutter('install', options: <String>[
'--uninstall-only',
'-d',
deviceId]);
await flutter('install', options: <String>['--uninstall-only', '-d', deviceId]);
await Future<void>.delayed(const Duration(seconds: 2));
@@ -217,10 +209,7 @@ abstract class Device {
}
}
enum AndroidCPU {
arm,
arm64,
}
enum AndroidCPU { arm, arm64 }
class AndroidDeviceDiscovery implements DeviceDiscovery {
factory AndroidDeviceDiscovery({AndroidCPU? cpu}) {
@@ -258,7 +247,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
return switch (cpu) {
null => Future<bool>.value(true),
AndroidCPU.arm64 => device.isArm64(),
AndroidCPU.arm => device.isArm(),
AndroidCPU.arm => device.isArm(),
};
}
@@ -266,9 +255,10 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
/// [workingDevice].
@override
Future<void> chooseWorkingDevice() async {
final List<AndroidDevice> allDevices = (await discoverDevices())
.map<AndroidDevice>((String id) => AndroidDevice(deviceId: id))
.toList();
final List<AndroidDevice> allDevices =
(await discoverDevices())
.map<AndroidDevice>((String id) => AndroidDevice(deviceId: id))
.toList();
if (allDevices.isEmpty) {
throw const DeviceException('No Android devices detected');
@@ -281,7 +271,6 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
break;
}
}
} else {
// TODO(yjbanov): filter out and warn about those with low battery level
_workingDevice = allDevices[math.Random().nextInt(allDevices.length)];
@@ -301,7 +290,9 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
_workingDevice = AndroidDevice(deviceId: matchedId);
if (cpu != null) {
if (!await _matchesCPURequirement(_workingDevice!)) {
throw DeviceException('The selected device $matchedId does not match the cpu requirement');
throw DeviceException(
'The selected device $matchedId does not match the cpu requirement',
);
}
}
print('Choose device by ID: $matchedId');
@@ -309,14 +300,13 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
}
throw DeviceException(
'Device with ID $deviceId is not found for operating system: '
'$deviceOperatingSystem'
);
'$deviceOperatingSystem',
);
}
@override
Future<List<String>> discoverDevices() async {
final List<String> output = (await eval(adbPath, <String>['devices', '-l']))
.trim().split('\n');
final List<String> output = (await eval(adbPath, <String>['devices', '-l'])).trim().split('\n');
final List<String> results = <String>[];
for (final String line in output) {
// Skip lines like: * daemon started successfully *
@@ -391,10 +381,10 @@ class LinuxDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> chooseWorkingDevice() async { }
Future<void> chooseWorkingDevice() async {}
@override
Future<void> chooseWorkingDeviceById(String deviceId) async { }
Future<void> chooseWorkingDeviceById(String deviceId) async {}
@override
Future<List<String>> discoverDevices() async {
@@ -402,10 +392,10 @@ class LinuxDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> performPreflightTasks() async { }
Future<void> performPreflightTasks() async {}
@override
Future<Device> get workingDevice async => _device;
Future<Device> get workingDevice async => _device;
}
class MacosDeviceDiscovery implements DeviceDiscovery {
@@ -425,10 +415,10 @@ class MacosDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> chooseWorkingDevice() async { }
Future<void> chooseWorkingDevice() async {}
@override
Future<void> chooseWorkingDeviceById(String deviceId) async { }
Future<void> chooseWorkingDeviceById(String deviceId) async {}
@override
Future<List<String>> discoverDevices() async {
@@ -436,10 +426,10 @@ class MacosDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> performPreflightTasks() async { }
Future<void> performPreflightTasks() async {}
@override
Future<Device> get workingDevice async => _device;
Future<Device> get workingDevice async => _device;
}
class WindowsDeviceDiscovery implements DeviceDiscovery {
@@ -459,10 +449,10 @@ class WindowsDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> chooseWorkingDevice() async { }
Future<void> chooseWorkingDevice() async {}
@override
Future<void> chooseWorkingDeviceById(String deviceId) async { }
Future<void> chooseWorkingDeviceById(String deviceId) async {}
@override
Future<List<String>> discoverDevices() async {
@@ -470,10 +460,10 @@ class WindowsDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> performPreflightTasks() async { }
Future<void> performPreflightTasks() async {}
@override
Future<Device> get workingDevice async => _device;
Future<Device> get workingDevice async => _device;
}
class FuchsiaDeviceDiscovery implements DeviceDiscovery {
@@ -488,7 +478,7 @@ class FuchsiaDeviceDiscovery implements DeviceDiscovery {
FuchsiaDevice? _workingDevice;
String get _ffx {
final String ffx = path.join(getArtifactPath(), 'fuchsia', 'tools','x64', 'ffx');
final String ffx = path.join(getArtifactPath(), 'fuchsia', 'tools', 'x64', 'ffx');
if (!File(ffx).existsSync()) {
throw FileSystemException("Couldn't find ffx at location $ffx");
}
@@ -511,9 +501,10 @@ class FuchsiaDeviceDiscovery implements DeviceDiscovery {
/// Picks the first connected Fuchsia device.
@override
Future<void> chooseWorkingDevice() async {
final List<FuchsiaDevice> allDevices = (await discoverDevices())
.map<FuchsiaDevice>((String id) => FuchsiaDevice(deviceId: id))
.toList();
final List<FuchsiaDevice> allDevices =
(await discoverDevices())
.map<FuchsiaDevice>((String id) => FuchsiaDevice(deviceId: id))
.toList();
if (allDevices.isEmpty) {
throw const DeviceException('No Fuchsia devices detected');
@@ -532,15 +523,18 @@ class FuchsiaDeviceDiscovery implements DeviceDiscovery {
}
throw DeviceException(
'Device with ID $deviceId is not found for operating system: '
'$deviceOperatingSystem'
);
'$deviceOperatingSystem',
);
}
@override
Future<List<String>> discoverDevices() async {
final List<String> output = (await eval(_ffx, <String>['target', 'list', '-f', 's']))
.trim()
.split('\n');
final List<String> output = (await eval(_ffx, <String>[
'target',
'list',
'-f',
's',
])).trim().split('\n');
final List<String> devices = <String>[];
for (final String line in output) {
@@ -556,20 +550,13 @@ class FuchsiaDeviceDiscovery implements DeviceDiscovery {
final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{};
for (final String deviceId in await discoverDevices()) {
try {
final int resolveResult = await exec(
_ffx,
<String>[
'target',
'list',
'-f',
'a',
deviceId,
]
);
final int resolveResult = await exec(_ffx, <String>['target', 'list', '-f', 'a', deviceId]);
if (resolveResult == 0) {
results['fuchsia-device-$deviceId'] = HealthCheckResult.success();
} else {
results['fuchsia-device-$deviceId'] = HealthCheckResult.failure('Cannot resolve device $deviceId');
results['fuchsia-device-$deviceId'] = HealthCheckResult.failure(
'Cannot resolve device $deviceId',
);
}
} on Exception catch (error, stacktrace) {
results['fuchsia-device-$deviceId'] = HealthCheckResult.error(error, stacktrace);
@@ -594,7 +581,11 @@ class AndroidDevice extends Device {
@override
Future<void> toggleFixedPerformanceMode(bool enable) async {
await shellExec('cmd', <String>['power', 'set-fixed-performance-mode-enabled', if (enable) 'true' else 'false']);
await shellExec('cmd', <String>[
'power',
'set-fixed-performance-mode-enabled',
if (enable) 'true' else 'false',
]);
}
/// Whether the device is awake.
@@ -677,15 +668,15 @@ class AndroidDevice extends Device {
Future<void> _updateDeviceInfo() async {
String info;
try {
info = await shellEval(
info = await shellEval('getprop', <String>[
'ro.bootimage.build.fingerprint',
';',
'getprop',
<String>[
'ro.bootimage.build.fingerprint', ';',
'getprop', 'ro.build.version.release', ';',
'getprop', 'ro.build.version.sdk',
],
silent: true,
);
'ro.build.version.release',
';',
'getprop',
'ro.build.version.sdk',
], silent: true);
} on IOException {
info = '';
}
@@ -700,22 +691,32 @@ class AndroidDevice extends Device {
}
/// Executes [command] on `adb shell`.
Future<void> shellExec(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) async {
Future<void> shellExec(
String command,
List<String> arguments, {
Map<String, String>? environment,
bool silent = false,
}) async {
await adb(<String>['shell', command, ...arguments], environment: environment, silent: silent);
}
/// Executes [command] on `adb shell` and returns its standard output as a [String].
Future<String> shellEval(String command, List<String> arguments, { Map<String, String>? environment, bool silent = false }) {
Future<String> shellEval(
String command,
List<String> arguments, {
Map<String, String>? environment,
bool silent = false,
}) {
return adb(<String>['shell', command, ...arguments], environment: environment, silent: silent);
}
/// Runs `adb` with the given [arguments], selecting this device.
Future<String> adb(
List<String> arguments, {
Map<String, String>? environment,
bool silent = false,
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
}) {
List<String> arguments, {
Map<String, String>? environment,
bool silent = false,
bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
}) {
return eval(
adbPath,
<String>['-s', deviceId, ...arguments],
@@ -731,9 +732,7 @@ class AndroidDevice extends Device {
final String meminfo = await shellEval('dumpsys', <String>['meminfo', packageName]);
final Match? match = RegExp(r'TOTAL\s+(\d+)').firstMatch(meminfo);
assert(match != null, 'could not parse dumpsys meminfo output');
return <String, dynamic>{
'total_kb': int.parse(match!.group(1)!),
};
return <String, dynamic>{'total_kb': int.parse(match!.group(1)!)};
}
@override
@@ -752,21 +751,23 @@ class AndroidDevice extends Device {
// Catch the whole log.
<String>['-s', deviceId, 'logcat'],
);
_loggingProcess!.stdout
.transform<String>(const Utf8Decoder(allowMalformed: true))
.listen((String line) {
sink.write(line);
});
_loggingProcess!.stderr
.transform<String>(const Utf8Decoder(allowMalformed: true))
.listen((String line) {
sink.write(line);
});
unawaited(_loggingProcess!.exitCode.then<void>((int exitCode) {
if (!_abortedLogging) {
sink.writeln('adb logcat failed with exit code $exitCode.\n');
}
}));
_loggingProcess!.stdout.transform<String>(const Utf8Decoder(allowMalformed: true)).listen((
String line,
) {
sink.write(line);
});
_loggingProcess!.stderr.transform<String>(const Utf8Decoder(allowMalformed: true)).listen((
String line,
) {
sink.write(line);
});
unawaited(
_loggingProcess!.exitCode.then<void>((int exitCode) {
if (!_abortedLogging) {
sink.writeln('adb logcat failed with exit code $exitCode.\n');
}
}),
);
}
@override
@@ -805,27 +806,39 @@ class AndroidDevice extends Device {
<String>['-s', deviceId, 'logcat', 'ActivityManager:I', 'flutter:V', '*:F'],
);
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
print('adb logcat: $line');
if (!stream.isClosed) {
stream.sink.add(line);
}
}, onDone: () { stdoutDone.complete(); });
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(
(String line) {
print('adb logcat: $line');
if (!stream.isClosed) {
stream.sink.add(line);
}
},
onDone: () {
stdoutDone.complete();
},
);
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
print('adb logcat stderr: $line');
}, onDone: () { stderrDone.complete(); });
unawaited(process.exitCode.then<void>((int exitCode) {
print('adb logcat process terminated with exit code $exitCode');
if (!aborted) {
stream.addError(BuildFailedError('adb logcat failed with exit code $exitCode.\n'));
processDone.complete();
}
}));
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(
(String line) {
print('adb logcat stderr: $line');
},
onDone: () {
stderrDone.complete();
},
);
unawaited(
process.exitCode.then<void>((int exitCode) {
print('adb logcat process terminated with exit code $exitCode');
if (!aborted) {
stream.addError(BuildFailedError('adb logcat failed with exit code $exitCode.\n'));
processDone.complete();
}
}),
);
await Future.any<dynamic>(<Future<dynamic>>[
Future.wait<void>(<Future<void>>[
stdoutDone.future,
@@ -871,7 +884,11 @@ class AndroidDevice extends Device {
print('Waiting for device.');
final String waitOut = await adb(<String>['wait-for-device']);
print(waitOut);
const RetryOptions retryOptions = RetryOptions(delayFactor: Duration(seconds: 1), maxAttempts: 10, maxDelay: Duration(minutes: 1));
const RetryOptions retryOptions = RetryOptions(
delayFactor: Duration(seconds: 1),
maxAttempts: 10,
maxDelay: Duration(minutes: 1),
);
await retryOptions.retry(() async {
final String adbShellOut = await adb(<String>['shell', 'getprop sys.boot_completed']);
if (adbShellOut != '1') {
@@ -913,9 +930,8 @@ class IosDeviceDiscovery implements DeviceDiscovery {
/// [workingDevice].
@override
Future<void> chooseWorkingDevice() async {
final List<IosDevice> allDevices = (await discoverDevices())
.map<IosDevice>((String id) => IosDevice(deviceId: id))
.toList();
final List<IosDevice> allDevices =
(await discoverDevices()).map<IosDevice>((String id) => IosDevice(deviceId: id)).toList();
if (allDevices.isEmpty) {
throw const DeviceException('No iOS devices detected');
@@ -936,16 +952,23 @@ class IosDeviceDiscovery implements DeviceDiscovery {
}
throw DeviceException(
'Device with ID $deviceId is not found for operating system: '
'$deviceOperatingSystem'
);
'$deviceOperatingSystem',
);
}
@override
Future<List<String>> discoverDevices() async {
final List<dynamic> results = json.decode(await eval(
path.join(flutterDirectory.path, 'bin', 'flutter'),
<String>['devices', '--machine', '--suppress-analytics', '--device-timeout', '5'],
)) as List<dynamic>;
final List<dynamic> results =
json.decode(
await eval(path.join(flutterDirectory.path, 'bin', 'flutter'), <String>[
'devices',
'--machine',
'--suppress-analytics',
'--device-timeout',
'5',
]),
)
as List<dynamic>;
// [
// {
@@ -1003,13 +1026,20 @@ class IosDeviceDiscovery implements DeviceDiscovery {
/// iOS device.
class IosDevice extends Device {
IosDevice({ required this.deviceId });
IosDevice({required this.deviceId});
@override
final String deviceId;
String get idevicesyslogPath {
return path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'libimobiledevice', 'idevicesyslog');
return path.join(
flutterDirectory.path,
'bin',
'cache',
'artifacts',
'libimobiledevice',
'idevicesyslog',
);
}
String get dyldLibraryPath {
@@ -1034,25 +1064,25 @@ class IosDevice extends Device {
_loggingProcess = await startProcess(
idevicesyslogPath,
<String>['-u', deviceId, '--quiet'],
environment: <String, String>{
'DYLD_LIBRARY_PATH': dyldLibraryPath,
},
environment: <String, String>{'DYLD_LIBRARY_PATH': dyldLibraryPath},
);
_loggingProcess!.stdout.transform<String>(const Utf8Decoder(allowMalformed: true)).listen((
String line,
) {
sink.write(line);
});
_loggingProcess!.stderr.transform<String>(const Utf8Decoder(allowMalformed: true)).listen((
String line,
) {
sink.write(line);
});
unawaited(
_loggingProcess!.exitCode.then<void>((int exitCode) {
if (!_abortedLogging) {
sink.writeln('idevicesyslog failed with exit code $exitCode.\n');
}
}),
);
_loggingProcess!.stdout
.transform<String>(const Utf8Decoder(allowMalformed: true))
.listen((String line) {
sink.write(line);
});
_loggingProcess!.stderr
.transform<String>(const Utf8Decoder(allowMalformed: true))
.listen((String line) {
sink.write(line);
});
unawaited(_loggingProcess!.exitCode.then<void>((int exitCode) {
if (!_abortedLogging) {
sink.writeln('idevicesyslog failed with exit code $exitCode.\n');
}
}));
}
@override
@@ -1132,7 +1162,7 @@ class LinuxDevice extends Device {
}
@override
Future<void> home() async { }
Future<void> home() async {}
@override
Future<bool> isAsleep() async {
@@ -1151,25 +1181,25 @@ class LinuxDevice extends Device {
Future<void> clearLogs() async {}
@override
Future<void> reboot() async { }
Future<void> reboot() async {}
@override
Future<void> sendToSleep() async { }
Future<void> sendToSleep() async {}
@override
Future<void> stop(String packageName) async { }
Future<void> stop(String packageName) async {}
@override
Future<void> tap(int x, int y) async { }
Future<void> tap(int x, int y) async {}
@override
Future<void> togglePower() async { }
Future<void> togglePower() async {}
@override
Future<void> unlock() async { }
Future<void> unlock() async {}
@override
Future<void> wakeUp() async { }
Future<void> wakeUp() async {}
@override
Future<void> awaitDevice() async {}
@@ -1187,7 +1217,7 @@ class MacosDevice extends Device {
}
@override
Future<void> home() async { }
Future<void> home() async {}
@override
Future<bool> isAsleep() async {
@@ -1206,25 +1236,25 @@ class MacosDevice extends Device {
Future<void> clearLogs() async {}
@override
Future<void> reboot() async { }
Future<void> reboot() async {}
@override
Future<void> sendToSleep() async { }
Future<void> sendToSleep() async {}
@override
Future<void> stop(String packageName) async { }
Future<void> stop(String packageName) async {}
@override
Future<void> tap(int x, int y) async { }
Future<void> tap(int x, int y) async {}
@override
Future<void> togglePower() async { }
Future<void> togglePower() async {}
@override
Future<void> unlock() async { }
Future<void> unlock() async {}
@override
Future<void> wakeUp() async { }
Future<void> wakeUp() async {}
@override
Future<void> awaitDevice() async {}
@@ -1242,7 +1272,7 @@ class WindowsDevice extends Device {
}
@override
Future<void> home() async { }
Future<void> home() async {}
@override
Future<bool> isAsleep() async {
@@ -1261,25 +1291,25 @@ class WindowsDevice extends Device {
Future<void> clearLogs() async {}
@override
Future<void> reboot() async { }
Future<void> reboot() async {}
@override
Future<void> sendToSleep() async { }
Future<void> sendToSleep() async {}
@override
Future<void> stop(String packageName) async { }
Future<void> stop(String packageName) async {}
@override
Future<void> tap(int x, int y) async { }
Future<void> tap(int x, int y) async {}
@override
Future<void> togglePower() async { }
Future<void> togglePower() async {}
@override
Future<void> unlock() async { }
Future<void> unlock() async {}
@override
Future<void> wakeUp() async { }
Future<void> wakeUp() async {}
@override
Future<void> awaitDevice() async {}
@@ -1287,7 +1317,7 @@ class WindowsDevice extends Device {
/// Fuchsia device.
class FuchsiaDevice extends Device {
const FuchsiaDevice({ required this.deviceId });
const FuchsiaDevice({required this.deviceId});
@override
final String deviceId;
@@ -1344,13 +1374,14 @@ class FuchsiaDevice extends Device {
/// Path to the `adb` executable.
String get adbPath {
final String? androidHome = Platform.environment['ANDROID_HOME'] ?? Platform.environment['ANDROID_SDK_ROOT'];
final String? androidHome =
Platform.environment['ANDROID_HOME'] ?? Platform.environment['ANDROID_SDK_ROOT'];
if (androidHome == null) {
throw const DeviceException(
'The ANDROID_HOME environment variable is '
'missing. The variable must point to the Android '
'SDK directory containing platform-tools.'
'SDK directory containing platform-tools.',
);
}
@@ -1364,7 +1395,7 @@ String get adbPath {
}
class FakeDevice extends Device {
const FakeDevice({ required this.deviceId });
const FakeDevice({required this.deviceId});
@override
final String deviceId;
@@ -1461,8 +1492,8 @@ class FakeDeviceDiscovery implements DeviceDiscovery {
}
throw DeviceException(
'Device with ID $deviceId is not found for operating system: '
'$deviceOperatingSystem'
);
'$deviceOperatingSystem',
);
}
@override
@@ -1480,5 +1511,5 @@ class FakeDeviceDiscovery implements DeviceDiscovery {
}
@override
Future<void> performPreflightTasks() async { }
Future<void> performPreflightTasks() async {}
}

View File

@@ -45,7 +45,7 @@ bool _isTaskRegistered = false;
///
/// If no `processManager` is provided, a default [LocalProcessManager] is created
/// for the task.
Future<TaskResult> task(TaskFunction task, { ProcessManager? processManager }) async {
Future<TaskResult> task(TaskFunction task, {ProcessManager? processManager}) async {
if (_isTaskRegistered) {
throw StateError('A task is already registered');
}
@@ -66,18 +66,16 @@ Future<TaskResult> task(TaskFunction task, { ProcessManager? processManager }) a
class _TaskRunner {
_TaskRunner(this.task, this.processManager) {
final String successResponse = json.encode(
const <String, String>{
'result': 'success',
},
);
final String successResponse = json.encode(const <String, String>{'result': 'success'});
registerExtension('ext.cocoonRunTask',
(String method, Map<String, String> parameters) async {
final Duration? taskTimeout = parameters.containsKey('timeoutInMinutes')
? Duration(minutes: int.parse(parameters['timeoutInMinutes']!))
: null;
final bool runFlutterConfig = parameters['runFlutterConfig'] != 'false'; // used by tests to avoid changing the configuration
registerExtension('ext.cocoonRunTask', (String method, Map<String, String> parameters) async {
final Duration? taskTimeout =
parameters.containsKey('timeoutInMinutes')
? Duration(minutes: int.parse(parameters['timeoutInMinutes']!))
: null;
final bool runFlutterConfig =
parameters['runFlutterConfig'] !=
'false'; // used by tests to avoid changing the configuration
final bool runProcessCleanup = parameters['runProcessCleanup'] != 'false';
final String? localEngine = parameters['localEngine'];
final String? localEngineHost = parameters['localEngineHost'];
@@ -89,22 +87,25 @@ class _TaskRunner {
localEngineHost: localEngineHost,
);
const Duration taskResultReceivedTimeout = Duration(seconds: 30);
_taskResultReceivedTimeout = Timer(
taskResultReceivedTimeout,
() {
logger.severe('Task runner did not acknowledge task results in $taskResultReceivedTimeout.');
_closeKeepAlivePort();
exitCode = 1;
}
);
_taskResultReceivedTimeout = Timer(taskResultReceivedTimeout, () {
logger.severe(
'Task runner did not acknowledge task results in $taskResultReceivedTimeout.',
);
_closeKeepAlivePort();
exitCode = 1;
});
return ServiceExtensionResponse.result(json.encode(result.toJson()));
});
registerExtension('ext.cocoonRunnerReady',
(String method, Map<String, String> parameters) async {
registerExtension('ext.cocoonRunnerReady', (
String method,
Map<String, String> parameters,
) async {
return ServiceExtensionResponse.result(successResponse);
});
registerExtension('ext.cocoonTaskResultReceived',
(String method, Map<String, String> parameters) async {
registerExtension('ext.cocoonTaskResultReceived', (
String method,
Map<String, String> parameters,
) async {
_closeKeepAlivePort();
return ServiceExtensionResponse.result(successResponse);
});
@@ -134,7 +135,8 @@ class _TaskRunner {
/// Signals that this task runner finished running the task.
Future<TaskResult> get whenDone => _completer.future;
Future<TaskResult> run(Duration? taskTimeout, {
Future<TaskResult> run(
Duration? taskTimeout, {
bool runFlutterConfig = true,
bool runProcessCleanup = true,
required String? localEngine,
@@ -151,7 +153,9 @@ class _TaskRunner {
processName: 'dart$exe',
processManager: processManager,
);
final Set<RunningProcessInfo> allProcesses = await getRunningProcesses(processManager: processManager);
final Set<RunningProcessInfo> allProcesses = await getRunningProcesses(
processManager: processManager,
);
beforeRunningDartInstances.forEach(print);
for (final RunningProcessInfo info in allProcesses) {
if (info.commandLine.contains('iproxy')) {
@@ -162,14 +166,18 @@ class _TaskRunner {
if (runFlutterConfig) {
print('Enabling configs for macOS and Linux...');
final int configResult = await exec(path.join(flutterDirectory.path, 'bin', 'flutter'), <String>[
'config',
'-v',
'--enable-macos-desktop',
'--enable-linux-desktop',
if (localEngine != null) ...<String>['--local-engine', localEngine],
if (localEngineHost != null) ...<String>['--local-engine-host', localEngineHost],
], canFail: true);
final int configResult = await exec(
path.join(flutterDirectory.path, 'bin', 'flutter'),
<String>[
'config',
'-v',
'--enable-macos-desktop',
'--enable-linux-desktop',
if (localEngine != null) ...<String>['--local-engine', localEngine],
if (localEngineHost != null) ...<String>['--local-engine-host', localEngineHost],
],
canFail: true,
);
if (configResult != 0) {
print('Failed to enable configuration, tasks may not run.');
}
@@ -184,7 +192,8 @@ class _TaskRunner {
IOSink? sink;
try {
if (device != null && device.canStreamLogs && hostAgent.dumpDirectory != null) {
sink = File(path.join(hostAgent.dumpDirectory!.path, '${device.deviceId}.log')).openWrite();
sink =
File(path.join(hostAgent.dumpDirectory!.path, '${device.deviceId}.log')).openWrite();
await device.startLoggingToSink(sink);
}
@@ -295,23 +304,26 @@ class _TaskRunner {
Future<TaskResult> _performTask() {
final Completer<TaskResult> completer = Completer<TaskResult>();
Chain.capture(() async {
completer.complete(await task());
}, onError: (dynamic taskError, Chain taskErrorStack) {
final String message = 'Task failed: $taskError';
stderr
..writeln(message)
..writeln('\nStack trace:')
..writeln(taskErrorStack.terse);
// IMPORTANT: We're completing the future _successfully_ but with a value
// that indicates a task failure. This is intentional. At this point we
// are catching errors coming from arbitrary (and untrustworthy) task
// code. Our goal is to convert the failure into a readable message.
// Propagating it further is not useful.
if (!completer.isCompleted) {
completer.complete(TaskResult.failure(message));
}
});
Chain.capture(
() async {
completer.complete(await task());
},
onError: (dynamic taskError, Chain taskErrorStack) {
final String message = 'Task failed: $taskError';
stderr
..writeln(message)
..writeln('\nStack trace:')
..writeln(taskErrorStack.terse);
// IMPORTANT: We're completing the future _successfully_ but with a value
// that indicates a task failure. This is intentional. At this point we
// are catching errors coming from arbitrary (and untrustworthy) task
// code. Our goal is to convert the failure into a readable message.
// Propagating it further is not useful.
if (!completer.isCompleted) {
completer.complete(TaskResult.failure(message));
}
},
);
return completer.future;
}
}

View File

@@ -8,13 +8,14 @@ import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
/// The current host machine running the tests.
HostAgent get hostAgent => HostAgent(platform: const LocalPlatform(), fileSystem: const LocalFileSystem());
HostAgent get hostAgent =>
HostAgent(platform: const LocalPlatform(), fileSystem: const LocalFileSystem());
/// Host machine running the tests.
class HostAgent {
HostAgent({required Platform platform, required FileSystem fileSystem})
: _platform = platform,
_fileSystem = fileSystem;
: _platform = platform,
_fileSystem = fileSystem;
final Platform _platform;
final FileSystem _fileSystem;

View File

@@ -17,12 +17,7 @@ Future<String> fileType(String pathToBinary) {
}
Future<String?> minPhoneOSVersion(String pathToBinary) async {
final String loadCommands = await eval('otool', <String>[
'-l',
'-arch',
'arm64',
pathToBinary,
]);
final String loadCommands = await eval('otool', <String>['-l', '-arch', 'arm64', pathToBinary]);
if (!loadCommands.contains('LC_VERSION_MIN_IPHONEOS')) {
return null;
}
@@ -37,9 +32,7 @@ Future<String?> minPhoneOSVersion(String pathToBinary) async {
final List<String> lines = LineSplitter.split(loadCommands).toList();
lines.asMap().forEach((int index, String line) {
if (line.contains('LC_VERSION_MIN_IPHONEOS') && lines.length - index - 1 > 3) {
final String versionLine = lines
.skip(index - 1)
.take(4).last;
final String versionLine = lines.skip(index - 1).take(4).last;
final RegExp versionRegex = RegExp(r'\s*version\s*(\S*)');
minVersion = versionRegex.firstMatch(versionLine)?.group(1);
}
@@ -56,35 +49,27 @@ Future<void> testWithNewIOSSimulator(
SimulatorFunction testFunction, {
String deviceTypeId = 'com.apple.CoreSimulator.SimDeviceType.iPhone-11',
}) async {
final String availableRuntimes = await eval(
'xcrun',
<String>[
'simctl',
'list',
'runtimes',
],
workingDirectory: flutterDirectory.path,
);
final String availableRuntimes = await eval('xcrun', <String>[
'simctl',
'list',
'runtimes',
], workingDirectory: flutterDirectory.path);
final String runtimesForSelectedXcode = await eval(
'xcrun',
<String>[
'simctl',
'runtime',
'match',
'list',
'--json',
],
workingDirectory: flutterDirectory.path,
);
final String runtimesForSelectedXcode = await eval('xcrun', <String>[
'simctl',
'runtime',
'match',
'list',
'--json',
], workingDirectory: flutterDirectory.path);
// Get the preferred runtime build for the selected Xcode version. Preferred
// means the runtime was either bundled with Xcode, exactly matched your SDK
// version, or it's indicated a better match for your SDK.
final Map<String, Object?> decodeResult = json.decode(runtimesForSelectedXcode) as Map<String, Object?>;
final String? iosKey = decodeResult.keys
.where((String key) => key.contains('iphoneos'))
.firstOrNull;
final Map<String, Object?> decodeResult =
json.decode(runtimesForSelectedXcode) as Map<String, Object?>;
final String? iosKey =
decodeResult.keys.where((String key) => key.contains('iphoneos')).firstOrNull;
final String? runtimeBuildForSelectedXcode = switch (decodeResult[iosKey]) {
{'preferredBuild': final String build} => build,
_ => null,
@@ -100,8 +85,7 @@ Future<void> testWithNewIOSSimulator(
// For example, iOS 17 (released with Xcode 15) may be available even if the
// selected Xcode version is 14.
for (final String runtime in LineSplitter.split(availableRuntimes)) {
if (runtimeBuildForSelectedXcode != null &&
!runtime.contains(runtimeBuildForSelectedXcode)) {
if (runtimeBuildForSelectedXcode != null && !runtime.contains(runtimeBuildForSelectedXcode)) {
continue;
}
// These seem to be in order, so allow matching multiple lines so it grabs
@@ -120,26 +104,18 @@ Future<void> testWithNewIOSSimulator(
}
}
final String deviceId = await eval(
'xcrun',
<String>[
'simctl',
'create',
deviceName,
deviceTypeId,
iOSSimRuntime,
],
workingDirectory: flutterDirectory.path,
);
await eval(
'xcrun',
<String>[
'simctl',
'boot',
deviceId,
],
workingDirectory: flutterDirectory.path,
);
final String deviceId = await eval('xcrun', <String>[
'simctl',
'create',
deviceName,
deviceTypeId,
iOSSimRuntime,
], workingDirectory: flutterDirectory.path);
await eval('xcrun', <String>[
'simctl',
'boot',
deviceId,
], workingDirectory: flutterDirectory.path);
await testFunction(deviceId);
}
@@ -149,21 +125,13 @@ Future<void> removeIOSSimulator(String? deviceId) async {
if (deviceId != null && deviceId != '') {
await eval(
'xcrun',
<String>[
'simctl',
'shutdown',
deviceId,
],
<String>['simctl', 'shutdown', deviceId],
canFail: true,
workingDirectory: flutterDirectory.path,
);
await eval(
'xcrun',
<String>[
'simctl',
'delete',
deviceId,
],
<String>['simctl', 'delete', deviceId],
canFail: true,
workingDirectory: flutterDirectory.path,
);
@@ -211,12 +179,9 @@ Future<bool> runXcodeTests({
resultBundlePath,
'test',
'COMPILER_INDEX_STORE_ENABLE=NO',
if (developmentTeam != null)
'DEVELOPMENT_TEAM=$developmentTeam',
if (codeSignStyle != null)
'CODE_SIGN_STYLE=$codeSignStyle',
if (provisioningProfile != null)
'PROVISIONING_PROFILE_SPECIFIER=$provisioningProfile',
if (developmentTeam != null) 'DEVELOPMENT_TEAM=$developmentTeam',
if (codeSignStyle != null) 'CODE_SIGN_STYLE=$codeSignStyle',
if (provisioningProfile != null) 'PROVISIONING_PROFILE_SPECIFIER=$provisioningProfile',
if (disabledSandboxEntitlementFile != null)
'CODE_SIGN_ENTITLEMENTS=${disabledSandboxEntitlementFile.path}',
],
@@ -230,17 +195,13 @@ Future<bool> runXcodeTests({
if (dumpDirectory != null) {
if (xcresultBundle.existsSync()) {
// Zip the test results to the artifacts directory for upload.
final String zipPath = path.join(dumpDirectory.path,
'$testName-${DateTime.now().toLocal().toIso8601String()}.zip');
final String zipPath = path.join(
dumpDirectory.path,
'$testName-${DateTime.now().toLocal().toIso8601String()}.zip',
);
await exec(
'zip',
<String>[
'-r',
'-9',
'-q',
zipPath,
path.basename(xcresultBundle.path),
],
<String>['-r', '-9', '-q', zipPath, path.basename(xcresultBundle.path)],
workingDirectory: resultBundleTemp,
canFail: true, // Best effort to get the logs.
);
@@ -260,10 +221,7 @@ Future<bool> runXcodeTests({
/// access to the app. To workaround this in CI, we create and use a entitlements
/// file with sandboxing disabled. See
/// https://developer.apple.com/documentation/security/app_sandbox/accessing_files_from_the_macos_app_sandbox.
File? _createDisabledSandboxEntitlementFile(
String platformDirectory,
String configuration,
) {
File? _createDisabledSandboxEntitlementFile(String platformDirectory, String configuration) {
String entitlementDefaultFileName;
if (configuration == 'Release') {
entitlementDefaultFileName = 'Release';
@@ -283,15 +241,15 @@ File? _createDisabledSandboxEntitlementFile(
return null;
}
final String originalEntitlementFileContents =
entitlementFile.readAsStringSync();
final String tempEntitlementPath = Directory.systemTemp
.createTempSync('flutter_disable_sandbox_entitlement.')
.path;
final File disabledSandboxEntitlementFile = File(path.join(
tempEntitlementPath,
'${entitlementDefaultFileName}WithDisabledSandboxing.entitlements',
));
final String originalEntitlementFileContents = entitlementFile.readAsStringSync();
final String tempEntitlementPath =
Directory.systemTemp.createTempSync('flutter_disable_sandbox_entitlement.').path;
final File disabledSandboxEntitlementFile = File(
path.join(
tempEntitlementPath,
'${entitlementDefaultFileName}WithDisabledSandboxing.entitlements',
),
);
disabledSandboxEntitlementFile.createSync(recursive: true);
disabledSandboxEntitlementFile.writeAsStringSync(
originalEntitlementFileContents.replaceAll(
@@ -307,14 +265,5 @@ File? _createDisabledSandboxEntitlementFile(
/// Returns global (external) symbol table entries, delimited by new lines.
Future<String> dumpSymbolTable(String filePath) {
return eval(
'nm',
<String>[
'--extern-only',
'--just-symbol-name',
filePath,
'-arch',
'arm64',
],
);
return eval('nm', <String>['--extern-only', '--just-symbol-name', filePath, '-arch', 'arm64']);
}

View File

@@ -52,7 +52,11 @@ Future<FlutterDestination> connectFlutterDestination() async {
/// "host_type": "linux",
/// "host_version": "debian-10.11"
/// }
List<MetricPoint> parse(Map<String, dynamic> resultsJson, Map<String, dynamic> benchmarkTags, String taskName) {
List<MetricPoint> parse(
Map<String, dynamic> resultsJson,
Map<String, dynamic> benchmarkTags,
String taskName,
) {
print('Results to upload to skia perf: $resultsJson');
print('Benchmark tags to upload to skia perf: $benchmarkTags');
final List<String> scoreKeys =
@@ -72,13 +76,12 @@ List<MetricPoint> parse(Map<String, dynamic> resultsJson, Map<String, dynamic> b
};
// Append additional benchmark tags, which will surface in Skia Perf dashboards.
tags = mergeMaps<String, String>(
tags, benchmarkTags.map((String key, dynamic value) => MapEntry<String, String>(key, value.toString())));
metricPoints.add(
MetricPoint(
(resultData[scoreKey] as num).toDouble(),
tags,
tags,
benchmarkTags.map(
(String key, dynamic value) => MapEntry<String, String>(key, value.toString()),
),
);
metricPoints.add(MetricPoint((resultData[scoreKey] as num).toDouble(), tags));
}
return metricPoints;
}
@@ -100,10 +103,7 @@ Future<void> upload(
) async {
await metricsDestination.update(
metricPoints,
DateTime.fromMillisecondsSinceEpoch(
commitTimeSinceEpoch,
isUtc: true,
),
DateTime.fromMillisecondsSinceEpoch(commitTimeSinceEpoch, isUtc: true),
taskName,
);
}
@@ -114,7 +114,12 @@ Future<void> upload(
/// 1. Run DeviceLab test, writing results to a known path
/// 2. Request service account token from luci auth (valid for at least 3 minutes)
/// 3. Upload results from (1) to skia perf.
Future<void> uploadToSkiaPerf(String? resultsPath, String? commitTime, String? taskName, String? benchmarkTags) async {
Future<void> uploadToSkiaPerf(
String? resultsPath,
String? commitTime,
String? taskName,
String? benchmarkTags,
) async {
int commitTimeSinceEpoch;
if (resultsPath == null) {
return;
@@ -125,7 +130,8 @@ Future<void> uploadToSkiaPerf(String? resultsPath, String? commitTime, String? t
commitTimeSinceEpoch = DateTime.now().millisecondsSinceEpoch;
}
taskName = taskName ?? 'default';
final Map<String, dynamic> benchmarkTagsMap = jsonDecode(benchmarkTags ?? '{}') as Map<String, dynamic>;
final Map<String, dynamic> benchmarkTagsMap =
jsonDecode(benchmarkTags ?? '{}') as Map<String, dynamic>;
final File resultFile = File(resultsPath);
Map<String, dynamic> resultsJson = <String, dynamic>{};
resultsJson = json.decode(await resultFile.readAsString()) as Map<String, dynamic>;
@@ -150,10 +156,7 @@ Future<void> uploadToSkiaPerf(String? resultsPath, String? commitTime, String? t
/// For example:
/// Old file name: `backdrop_filter_perf__timeline_summary`
/// New file name: `backdrop_filter_perf__timeline_summary_intel_linux_motoG4`
String metricFileName(
String taskName,
Map<String, dynamic> benchmarkTagsMap,
) {
String metricFileName(String taskName, Map<String, dynamic> benchmarkTagsMap) {
final StringBuffer fileName = StringBuffer(taskName);
if (benchmarkTagsMap.containsKey('arch')) {
fileName

View File

@@ -74,7 +74,9 @@ Future<void> runTasks(
} else {
section('Flaky status for "$taskName"');
if (failureCount > 0) {
print('Total ${failureCount+1} executions: $failureCount failures and 1 false positive.');
print(
'Total ${failureCount + 1} executions: $failureCount failures and 1 false positive.',
);
print('flaky: true');
// TODO(ianh): stop ignoring this failure. We should set exitCode=1, and quit
// if exitOnFirstTestFailure is true.
@@ -197,17 +199,16 @@ Future<TaskResult> runTask(
taskExecutable,
...?taskArgs,
],
environment: <String, String>{
if (deviceId != null)
DeviceIdEnvName: deviceId,
},
environment: <String, String>{if (deviceId != null) DeviceIdEnvName: deviceId},
);
bool runnerFinished = false;
unawaited(runner.exitCode.whenComplete(() {
runnerFinished = true;
}));
unawaited(
runner.exitCode.whenComplete(() {
runnerFinished = true;
}),
);
final Completer<Uri> uri = Completer<Uri>();
@@ -215,42 +216,44 @@ Future<TaskResult> runTask(
.transform<String>(const Utf8Decoder())
.transform<String>(const LineSplitter())
.listen((String line) {
if (!uri.isCompleted) {
final Uri? serviceUri = parseServiceUri(line, prefix: RegExp('The Dart VM service is listening on '));
if (serviceUri != null) {
uri.complete(serviceUri);
}
}
if (!silent) {
stdout.writeln('[${DateTime.now()}] [STDOUT] $line');
}
});
if (!uri.isCompleted) {
final Uri? serviceUri = parseServiceUri(
line,
prefix: RegExp('The Dart VM service is listening on '),
);
if (serviceUri != null) {
uri.complete(serviceUri);
}
}
if (!silent) {
stdout.writeln('[${DateTime.now()}] [STDOUT] $line');
}
});
final StreamSubscription<String> stderrSub = runner.stderr
.transform<String>(const Utf8Decoder())
.transform<String>(const LineSplitter())
.listen((String line) {
stderr.writeln('[${DateTime.now()}] [STDERR] $line');
});
stderr.writeln('[${DateTime.now()}] [STDERR] $line');
});
try {
final ConnectionResult result = await _connectToRunnerIsolate(await uri.future);
print('[$taskName] Connected to VM server.');
isolateParams = isolateParams == null ? <String, String>{} : Map<String, String>.of(isolateParams);
isolateParams =
isolateParams == null ? <String, String>{} : Map<String, String>.of(isolateParams);
isolateParams['runProcessCleanup'] = terminateStrayDartProcesses.toString();
final VmService service = result.vmService;
final String isolateId = result.isolate.id!;
final Map<String, dynamic> taskResultJson = (await service.callServiceExtension(
'ext.cocoonRunTask',
args: isolateParams,
isolateId: isolateId,
)).json!;
final Map<String, dynamic> taskResultJson =
(await service.callServiceExtension(
'ext.cocoonRunTask',
args: isolateParams,
isolateId: isolateId,
)).json!;
// Notify the task process that the task result has been received and it
// can proceed to shutdown.
await _acknowledgeTaskResultReceived(
service: service,
isolateId: isolateId,
);
await _acknowledgeTaskResultReceived(service: service, isolateId: isolateId);
final TaskResult taskResult = TaskResult.fromJson(taskResultJson);
final int exitCode = await runner.exitCode;
print('[$taskName] Process terminated with exit code $exitCode.');
@@ -288,7 +291,10 @@ Future<ConnectionResult> _connectToRunnerIsolate(Uri vmServiceUri) async {
}
final IsolateRef isolate = vm.isolates!.first;
// Sanity check to ensure we're talking with the main isolate.
final Response response = await client.callServiceExtension('ext.cocoonRunnerReady', isolateId: isolate.id);
final Response response = await client.callServiceExtension(
'ext.cocoonRunnerReady',
isolateId: isolate.id,
);
if (response.json!['result'] != 'success') {
throw 'not ready yet';
}
@@ -309,14 +315,11 @@ Future<ConnectionResult> _connectToRunnerIsolate(Uri vmServiceUri) async {
}
Future<void> _acknowledgeTaskResultReceived({
required VmService service,
required String isolateId,
}) async {
required VmService service,
required String isolateId,
}) async {
try {
await service.callServiceExtension(
'ext.cocoonTaskResultReceived',
isolateId: isolateId,
);
await service.callServiceExtension('ext.cocoonTaskResultReceived', isolateId: isolateId);
} on RPCError {
// The target VM may shutdown before the response is received.
}

View File

@@ -17,10 +17,10 @@ class RunningProcessInfo {
@override
bool operator ==(Object other) {
return other is RunningProcessInfo
&& other.pid == pid
&& other.commandLine == commandLine
&& other.creationDate == creationDate;
return other is RunningProcessInfo &&
other.pid == pid &&
other.commandLine == commandLine &&
other.creationDate == creationDate;
}
Future<bool> terminate({required ProcessManager processManager}) async {
@@ -30,7 +30,7 @@ class RunningProcessInfo {
// TODO(ianh): Move Windows to killPid once we can.
// - killPid on Windows has not-useful return code: https://github.com/dart-lang/sdk/issues/47675
final ProcessResult result = await processManager.run(<String>[
'taskkill.exe',
'taskkill.exe',
'/pid',
'$pid',
'/f',
@@ -66,15 +66,13 @@ Future<Set<RunningProcessInfo>> windowsRunningProcesses(
) async {
// PowerShell script to get the command line arguments and create time of a process.
// See: https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-process
final String script = processName != null
? '"Get-CimInstance Win32_Process -Filter \\"name=\'$processName\'\\" | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"'
: '"Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"';
final String script =
processName != null
? '"Get-CimInstance Win32_Process -Filter \\"name=\'$processName\'\\" | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"'
: '"Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"';
// TODO(ianh): Unfortunately, there doesn't seem to be a good way to get
// ProcessManager to run this.
final ProcessResult result = await Process.run(
'powershell -command $script',
<String>[],
);
final ProcessResult result = await Process.run('powershell -command $script', <String>[]);
if (result.exitCode != 0) {
print('Could not list processes!');
print(result.stderr);
@@ -115,10 +113,7 @@ Iterable<RunningProcessInfo> processPowershellOutput(String output) sync* {
// 3/11/2019 11:01:54 AM
// 12/11/2019 11:01:54 AM
String rawTime = line.substring(
creationDateHeaderStart,
creationDateHeaderEnd,
).trim();
String rawTime = line.substring(creationDateHeaderStart, creationDateHeaderEnd).trim();
if (rawTime[1] == '/') {
rawTime = '0$rawTime';
@@ -177,10 +172,7 @@ Future<Set<RunningProcessInfo>> posixRunningProcesses(
/// Sat Mar 9 20:12:47 2019 1 /sbin/launchd
/// Sat Mar 9 20:13:00 2019 49 /usr/sbin/syslogd
@visibleForTesting
Iterable<RunningProcessInfo> processPsOutput(
String output,
String? processName,
) sync* {
Iterable<RunningProcessInfo> processPsOutput(String output, String? processName) sync* {
bool inTableBody = false;
for (String line in output.split('\n')) {
if (line.trim().startsWith('STARTED')) {

View File

@@ -8,7 +8,8 @@ import 'package:path/path.dart' as path;
import 'package:pub_semver/pub_semver.dart';
String adbPath() {
final String? androidHome = io.Platform.environment['ANDROID_HOME'] ?? io.Platform.environment['ANDROID_SDK_ROOT'];
final String? androidHome =
io.Platform.environment['ANDROID_HOME'] ?? io.Platform.environment['ANDROID_SDK_ROOT'];
if (androidHome == null) {
return 'adb';
} else {
@@ -24,7 +25,9 @@ Future<Version> getTalkbackVersion() async {
'com.google.android.marvin.talkback',
]);
if (result.exitCode != 0) {
throw Exception('Failed to get TalkBack version: ${result.stdout as String}\n${result.stderr as String}');
throw Exception(
'Failed to get TalkBack version: ${result.stdout as String}\n${result.stderr as String}',
);
}
final List<String> lines = (result.stdout as String).split('\n');
String? version;
@@ -39,7 +42,9 @@ Future<Version> getTalkbackVersion() async {
}
// Android doesn't quite use semver, so convert the version string to semver form.
final RegExp startVersion = RegExp(r'(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(\.(?<build>\d+))?');
final RegExp startVersion = RegExp(
r'(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(\.(?<build>\d+))?',
);
final RegExpMatch? match = startVersion.firstMatch(version);
if (match == null) {
return Version(0, 0, 0);

View File

@@ -8,19 +8,19 @@ import 'dart:io';
/// A result of running a single task.
class TaskResult {
TaskResult.buildOnly()
: succeeded = true,
data = null,
detailFiles = null,
benchmarkScoreKeys = null,
message = 'No tests run';
: succeeded = true,
data = null,
detailFiles = null,
benchmarkScoreKeys = null,
message = 'No tests run';
/// Constructs a successful result.
TaskResult.success(this.data, {
TaskResult.success(
this.data, {
this.benchmarkScoreKeys = const <String>[],
this.detailFiles = const <String>[],
this.message = 'success',
})
: succeeded = true {
}) : succeeded = true {
const JsonEncoder prettyJson = JsonEncoder.withIndent(' ');
if (benchmarkScoreKeys != null) {
for (final String key in benchmarkScoreKeys!) {
@@ -36,7 +36,8 @@ class TaskResult {
}
/// Constructs a successful result using JSON data stored in a file.
factory TaskResult.successFromFile(File file, {
factory TaskResult.successFromFile(
File file, {
List<String> benchmarkScoreKeys = const <String>[],
List<String> detailFiles = const <String>[],
}) {
@@ -51,9 +52,12 @@ class TaskResult {
factory TaskResult.fromJson(Map<String, dynamic> json) {
final bool success = json['success'] as bool;
if (success) {
final List<String> benchmarkScoreKeys = (json['benchmarkScoreKeys'] as List<dynamic>? ?? <String>[]).cast<String>();
final List<String> detailFiles = (json['detailFiles'] as List<dynamic>? ?? <String>[]).cast<String>();
return TaskResult.success(json['data'] as Map<String, dynamic>?,
final List<String> benchmarkScoreKeys =
(json['benchmarkScoreKeys'] as List<dynamic>? ?? <String>[]).cast<String>();
final List<String> detailFiles =
(json['detailFiles'] as List<dynamic>? ?? <String>[]).cast<String>();
return TaskResult.success(
json['data'] as Map<String, dynamic>?,
benchmarkScoreKeys: benchmarkScoreKeys,
detailFiles: detailFiles,
message: json['reason'] as String?,
@@ -65,10 +69,10 @@ class TaskResult {
/// Constructs an unsuccessful result.
TaskResult.failure(this.message)
: succeeded = false,
data = null,
detailFiles = null,
benchmarkScoreKeys = null;
: succeeded = false,
data = null,
detailFiles = null,
benchmarkScoreKeys = null;
/// Whether the task succeeded.
final bool succeeded;
@@ -106,9 +110,7 @@ class TaskResult {
/// "reason": failure reason string valid only for unsuccessful results
/// }
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = <String, dynamic>{
'success': succeeded,
};
final Map<String, dynamic> json = <String, dynamic>{'success': succeeded};
if (succeeded) {
json['data'] = data;

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')));
});
}