diff --git a/flutter/dev/a11y_assessments/README.md b/flutter/dev/a11y_assessments/README.md index 1f8a64cafb98302a69570db869d7e22d23b1ab21..b6400496adc1879849130e62894a4411ec744dec 100644 --- a/flutter/dev/a11y_assessments/README.md +++ b/flutter/dev/a11y_assessments/README.md @@ -1,3 +1,33 @@ # a11y_assessments -An application to conduct accessibility assessments. +This app is used for internal testing. + +## Release a new version for Android + +pre-requisite: This can and should only be done by a googler and you must also +be in the flutter.dev play console account. + +1. Follow https://docs.flutter.dev/deployment/android to create a keystore file if you don't already +have one. + +2. Bump the pubspec.yaml version + +3. Create a key.properties file in `android/` directory following this format. +``` +storePassword= +keyPassword= +keyAlias=upload +storeFile= +``` + +4. Run `flutter build appbundle` and upload the artifact to play console + +## Release a new version for iOS + +pre-requisite: This can and should only be done by a googler and you must also +be in the FLUTTER.IO LLC developer account with iOS distribution permission. + +1. Bump the pubspec.yaml version +2. Run `flutter build ipa` and upload the artifact to app store using transporter or other tools. +For more information, see https://docs.flutter.dev/deployment/ios. +3. Once the app is in TestFlight, add appropriate testers to the app so they can start testing. \ No newline at end of file diff --git a/flutter/dev/a11y_assessments/pubspec.yaml b/flutter/dev/a11y_assessments/pubspec.yaml index 5c89dc332d596a056e5f3947c8b3124a1c3591a6..9ee5a9efc8e866b683bcb1d4b8a310af02c0c031 100644 --- a/flutter/dev/a11y_assessments/pubspec.yaml +++ b/flutter/dev/a11y_assessments/pubspec.yaml @@ -1,41 +1,42 @@ name: a11y_assessments description: A new Flutter project +version: 5.0.0+5 environment: - sdk: '>=3.2.0-22.0.dev <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter - characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - meta: 1.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + characters: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + material_color_utilities: 0.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + meta: 1.16.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: flutter_test: sdk: flutter - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker: 10.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_flutter_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + clock: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + fake_async: 1.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker: 10.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_flutter_testing: 3.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + path: 1.9.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_api: 0.7.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vm_service: 15.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: uses-material-design: true -# PUBSPEC CHECKSUM: 8023 +# PUBSPEC CHECKSUM: 5b23 diff --git a/flutter/dev/automated_tests/pubspec.yaml b/flutter/dev/automated_tests/pubspec.yaml index c935b44f72ce0f0667da1542e1a34973d93d91d6..cf6cb754a77c52ab545c266b121c229e5388b15d 100644 --- a/flutter/dev/automated_tests/pubspec.yaml +++ b/flutter/dev/automated_tests/pubspec.yaml @@ -1,7 +1,7 @@ name: flutter_automated_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -12,67 +12,68 @@ dependencies: sdk: flutter integration_test: sdk: flutter - platform: 3.1.4 - test: 1.24.9 + platform: 3.1.6 + test: 1.25.15 - _fe_analyzer_shared: 65.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - analyzer: 6.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - js: 0.6.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker: 10.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_flutter_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - meta: 1.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - mime: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _fe_analyzer_shared: 80.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + analyzer: 7.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + args: 2.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + characters: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + clock: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + crypto: 3.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + fake_async: 1.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + file: 7.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + frontend_server_client: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + glob: 2.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_multi_server: 3.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_parser: 4.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + io: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + js: 0.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker: 10.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_flutter_testing: 3.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + logging: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + material_color_utilities: 0.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + meta: 1.16.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + mime: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + package_config: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + path: 1.9.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - process: 5.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + process: 5.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf: 1.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_core: 0.5.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_static: 1.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_map_stack_trace: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_maps: 0.10.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_api: 0.7.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + typed_data: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web: 0.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vm_service: 15.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + watcher: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket: 0.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket_channel: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: uses-material-design: true assets: - icon/test.png -# PUBSPEC CHECKSUM: 9de1 +# PUBSPEC CHECKSUM: 0ab4 diff --git a/flutter/dev/bots/README.md b/flutter/dev/bots/README.md index 491a614e2e546e37185acc3f34460d435cf804ed..4743b8894b178f7a94e14c0e631b76a6ab70b934 100644 --- a/flutter/dev/bots/README.md +++ b/flutter/dev/bots/README.md @@ -2,23 +2,21 @@ This directory exists to support building Flutter on our build infrastructure. -Flutter build results are available at: -* https://flutter-dashboard.appspot.com/#/build - - Aggregate dashboard of the separate CI systems used by Flutter. -* https://cirrus-ci.com/github/flutter/flutter/master - - Testing is done on PRs and submitted changes on GitHub. +Flutter build results are available at: . Flutter infra requires special permissions to retrigger builds on the -[build dashboard](https://flutter-dashboard.appspot.com/#/build). File an -[infra ticket](https://github.com/flutter/flutter/wiki/Infra-Ticket-Queue) to -request permission. - -The [Cirrus](https://cirrus-ci.org)-based bots run the [`test.dart`](test.dart) -script for each PR and submission. This does testing for the tools, for the -framework, and (for submitted changes only) rebuilds and updates the main -branch API docs [staging site](https://main-api.flutter.dev/). +[build dashboard](https://flutter-dashboard.appspot.com/#/build). File a `team-infra` +issue to request permission. + +The [LUCI](https://chromium.googlesource.com/infra/luci/luci-py/+/refs/heads/main/README.md)-based +bots run the [`test.dart`](test.dart) script for each PR and submission. This +does testing for the tools, for the framework, and (for submitted changes only) +rebuilds and updates the main branch API docs [staging site](https://main-api.flutter.dev/). For tagged dev and beta builds, it also builds and deploys the gallery app to -the app stores. It is configured by the [.cirrus.yml](/.cirrus.yml). +the app stores. It is configured by two `.ci.yaml` files: + +- framework: [`.ci.yaml`](../../.ci.yaml) +- engine: [`engine/src/flutter/.ci.yaml`](../../engine/src/flutter/.ci.yaml) The build dashboard includes post-commit testing run on physical devices. See [//dev/devicelab](../devicelab/README.md) for more information. @@ -27,8 +25,7 @@ The build dashboard includes post-commit testing run on physical devices. See A [set of infra scripts](https://flutter.googlesource.com/recipes/) run on Windows, Linux, and Mac machines. The configuration for how many -machines and what kind are managed internally by Google. File an -[infra ticket](https://github.com/flutter/flutter/wiki/Infra-Ticket-Queue) +machines and what kind are managed internally by Google. File a `team-infra` issue to request new machine types to be added. Both of these technologies are highly specific to the [LUCI](https://github.com/luci) project, which is the successor to Chromium's infra and the foundation to Flutter's infrastructure. @@ -61,7 +58,7 @@ actions through `recipe_modules`. Searching the builder config in [infra](https: will indicate the recipe used for a test. Recipes are just Python with some limitations on what can be imported. They are -[documented](https://github.com/luci/recipes-py/blob/master/doc/user_guide.md) +[documented](https://github.com/luci/recipes-py/blob/main/doc/user_guide.md) by the [luci/recipes-py GitHub project](https://github.com/luci/recipes-py). The typical cycle for editing a recipe is: @@ -134,7 +131,6 @@ components need to be updated or installed, follow the steps below: `$ cd ../..` `$ dev/bots/upload_android_tools.py -t ndk` - ## Flutter codelabs build test The Flutter codelabs exercise Material Components in the form of a @@ -165,15 +161,15 @@ For example To remove a published package corresponding to the git hash `d444a455de87a2e40b7f576dc12ffd9ab82fd491`, first do a dry run of the script to see what it will do: -``` -$ dart ./unpublish_package.dart --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 +```sh +dart ./unpublish_package.dart --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 ``` And once you've verified the output of the dry run to be sure it is what you want to do, run: -``` -$ dart ./unpublish_package.dart --confirm --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 +```sh +dart ./unpublish_package.dart --confirm --temp_dir=/tmp/foo --revision d444a455de87a2e40b7f576dc12ffd9ab82fd491 ``` and it will perform the actions. You will of course need to have access diff --git a/flutter/dev/bots/analyze.dart b/flutter/dev/bots/analyze.dart index 0527d9b563aac4e38d2146b51c0b3c0218ec9ce4..b46863f43df7c634724f0f79856b15d3f4599327 100644 --- a/flutter/dev/bots/analyze.dart +++ b/flutter/dev/bots/analyze.dart @@ -12,19 +12,21 @@ import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/analysis/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; +import 'package:collection/equality.dart'; import 'package:crypto/crypto.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'allowlist.dart'; import 'custom_rules/analyze.dart'; +import 'custom_rules/avoid_future_catcherror.dart'; import 'custom_rules/no_double_clamp.dart'; import 'custom_rules/no_stop_watches.dart'; +import 'custom_rules/protect_public_state_subtypes.dart'; +import 'custom_rules/render_box_intrinsics.dart'; import 'run_command.dart'; import 'utils.dart'; -final String flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); -final String flutter = path.join(flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'); final String flutterPackages = path.join(flutterRoot, 'packages'); final String flutterExamples = path.join(flutterRoot, 'examples'); @@ -85,7 +87,10 @@ String? _getDartSdkFromArguments(List arguments) { Future run(List arguments) async { bool assertsEnabled = false; - assert(() { assertsEnabled = true; return true; }()); + assert(() { + assertsEnabled = true; + return true; + }()); if (!assertsEnabled) { foundError(['The analyze.dart script must be run with --enable-asserts.']); } @@ -106,14 +111,19 @@ Future run(List arguments) async { printProgress('Debug mode instead of checked mode...'); await verifyNoCheckedMode(flutterRoot); - printProgress('Links for creating GitHub issues'); + printProgress('Links for creating GitHub issues...'); await verifyIssueLinks(flutterRoot); + printProgress('Links to repositories...'); + await verifyRepositoryLinks(flutterRoot); + printProgress('Unexpected binaries...'); await verifyNoBinaries(flutterRoot); printProgress('Trailing spaces...'); - await verifyNoTrailingSpaces(flutterRoot); // assumes no unexpected binaries, so should be after verifyNoBinaries + await verifyNoTrailingSpaces( + flutterRoot, + ); // assumes no unexpected binaries, so should be after verifyNoBinaries printProgress('Spaces after flow control statements...'); await verifySpacesAfterFlowControlStatements(flutterRoot); @@ -142,6 +152,9 @@ Future run(List arguments) async { printProgress('Internationalization...'); await verifyInternationalizations(flutterRoot, dart); + printProgress('Localization files of stocks app...'); + await verifyStockAppLocalizations(flutterRoot); + printProgress('Integration test timeouts...'); await verifyIntegrationTestTimeouts(flutterRoot); @@ -151,11 +164,15 @@ Future run(List arguments) async { printProgress('Taboo words...'); await verifyTabooDocumentation(flutterRoot); + printProgress('Lint Kotlin files...'); + await lintKotlinFiles(flutterRoot); + // Ensure that all package dependencies are in sync. printProgress('Package dependencies...'); - await runCommand(flutter, ['update-packages', '--verify-only'], - workingDirectory: flutterRoot, - ); + await runCommand(flutter, [ + 'update-packages', + '--verify-only', + ], workingDirectory: flutterRoot); /// Ensure that no new dependencies have been accidentally /// added to core packages. @@ -164,30 +181,51 @@ Future run(List arguments) async { // Analyze all the Dart code in the repo. printProgress('Dart analysis...'); - final CommandResult dartAnalyzeResult = await _runFlutterAnalyze(flutterRoot, options: [ - '--flutter-repo', - ...arguments, - ]); + final CommandResult dartAnalyzeResult = await _runFlutterAnalyze( + flutterRoot, + options: ['--flutter-repo', ...arguments], + ); + + printProgress('Check formatting of Dart files...'); + await runCommand(dart, [ + '--enable-asserts', + path.join(flutterRoot, 'dev', 'tools', 'bin', 'format.dart'), + ], workingDirectory: flutterRoot); if (dartAnalyzeResult.exitCode == 0) { // Only run the private lints when the code is free of type errors. The // lints are easier to write when they can assume, for example, there is no // inheritance cycles. - final List rules = [noDoubleClamp, noStopwatches]; + final List rules = [ + noDoubleClamp, + noStopwatches, + renderBoxIntrinsicCalculation, + protectPublicStateSubtypes, + ]; final String ruleNames = rules.map((AnalyzeRule rule) => '\n * $rule').join(); printProgress('Analyzing code in the framework with the following rules:$ruleNames'); - await analyzeWithRules(flutterRoot, rules, - includePaths: ['packages/flutter/lib'], - excludePaths: ['packages/flutter/lib/fix_data'], + await analyzeWithRules( + flutterRoot, + rules, + includePaths: const ['packages/flutter/lib'], + excludePaths: const ['packages/flutter/lib/fix_data'], ); final List testRules = [noStopwatches]; final String testRuleNames = testRules.map((AnalyzeRule rule) => '\n * $rule').join(); printProgress('Analyzing code in the test folder with the following rules:$testRuleNames'); - await analyzeWithRules(flutterRoot, testRules, - includePaths: ['packages/flutter/test'], + await analyzeWithRules(flutterRoot, testRules, includePaths: ['packages/flutter/test']); + final List toolRules = [AvoidFutureCatchError()]; + final String toolRuleNames = toolRules.map((AnalyzeRule rule) => '\n * $rule').join(); + printProgress('Analyzing code in the tool with the following rules:$toolRuleNames'); + await analyzeWithRules( + flutterRoot, + toolRules, + includePaths: const ['packages/flutter_tools/lib', 'packages/flutter_tools/test'], ); } else { - printProgress('Skipped performing further analysis in the framework because "flutter analyze" finished with a non-zero exit code.'); + printProgress( + 'Skipped performing further analysis in the framework because "flutter analyze" finished with a non-zero exit code.', + ); } printProgress('Executable allowlist...'); @@ -197,44 +235,41 @@ Future run(List arguments) async { // The --benchmark argument exits after one run. // We specify a failureMessage so that the actual output is muted in the case where _runFlutterAnalyze above already failed. printProgress('Dart analysis (with --watch)...'); - await _runFlutterAnalyze(flutterRoot, failureMessage: 'Dart analyzer failed when --watch was used.', options: [ - '--flutter-repo', - '--watch', - '--benchmark', - ...arguments, - ]); + await _runFlutterAnalyze( + flutterRoot, + failureMessage: 'Dart analyzer failed when --watch was used.', + options: ['--flutter-repo', '--watch', '--benchmark', ...arguments], + ); // Analyze the code in `{@tool snippet}` sections in the repo. printProgress('Snippet code...'); - await runCommand(dart, - ['--enable-asserts', path.join(flutterRoot, 'dev', 'bots', 'analyze_snippet_code.dart'), '--verbose'], - workingDirectory: flutterRoot, - ); + await runCommand(dart, [ + '--enable-asserts', + path.join(flutterRoot, 'dev', 'bots', 'analyze_snippet_code.dart'), + '--verbose', + ], workingDirectory: flutterRoot); // Make sure that all of the existing samples are linked from at least one API doc comment. printProgress('Code sample link validation...'); - await runCommand(dart, - ['--enable-asserts', path.join(flutterRoot, 'dev', 'bots', 'check_code_samples.dart')], - workingDirectory: flutterRoot, - ); + await runCommand(dart, [ + '--enable-asserts', + path.join(flutterRoot, 'dev', 'bots', 'check_code_samples.dart'), + ], workingDirectory: flutterRoot); // Try analysis against a big version of the gallery; generate into a temporary directory. printProgress('Dart analysis (mega gallery)...'); final Directory outDir = Directory.systemTemp.createTempSync('flutter_mega_gallery.'); try { - await runCommand(dart, - [ - path.join(flutterRoot, 'dev', 'tools', 'mega_gallery.dart'), - '--out', - outDir.path, - ], - workingDirectory: flutterRoot, + await runCommand(dart, [ + path.join(flutterRoot, 'dev', 'tools', 'mega_gallery.dart'), + '--out', + outDir.path, + ], workingDirectory: flutterRoot); + await _runFlutterAnalyze( + outDir.path, + failureMessage: 'Dart analyzer failed on mega_gallery benchmark.', + options: ['--watch', '--benchmark', ...arguments], ); - await _runFlutterAnalyze(outDir.path, failureMessage: 'Dart analyzer failed on mega_gallery benchmark.', options: [ - '--watch', - '--benchmark', - ...arguments, - ]); } finally { outDir.deleteSync(recursive: true); } @@ -243,12 +278,15 @@ Future run(List arguments) async { printProgress('Correct file names in gen_defaults.dart...'); await verifyTokenTemplatesUpdateCorrectFiles(flutterRoot); + // Ensure material library files are up-to-date with the token template files. + printProgress('Material library files are up-to-date with token template files...'); + await verifyMaterialFilesAreUpToDateWithTemplateFiles(flutterRoot, dart); + // Ensure integration test files are up-to-date with the app template. printProgress('Up to date integration test template files...'); await verifyIntegrationTestTemplateFiles(flutterRoot); } - // TESTS FeatureSet _parsingFeatureSet() => FeatureSet.latestLanguageVersion(); @@ -263,7 +301,9 @@ _Line _getLine(ParseStringResult parseResult, int offset) { } Future verifyTargetPlatform(String workingDirectory) async { - final File framework = File('$workingDirectory/packages/flutter/lib/src/foundation/platform.dart'); + final File framework = File( + '$workingDirectory/packages/flutter/lib/src/foundation/platform.dart', + ); final Set frameworkPlatforms = {}; List lines = framework.readAsLinesSync(); int index = 0; @@ -295,7 +335,9 @@ Future verifyTargetPlatform(String workingDirectory) async { if (line.endsWith(',')) { frameworkPlatforms.add(line.substring(0, line.length - 1)); } else { - foundError(['${framework.path}:$index: unparseable line when looking for TargetPlatform values']); + foundError([ + '${framework.path}:$index: unparseable line when looking for TargetPlatform values', + ]); } } index += 1; @@ -326,17 +368,23 @@ Future verifyTargetPlatform(String workingDirectory) async { } else if (line == '];') { break; } else { - foundError(['${tool.path}:$index: unparseable line when looking for nextPlatform values']); + foundError([ + '${tool.path}:$index: unparseable line when looking for nextPlatform values', + ]); } index += 1; } final Set frameworkExtra = frameworkPlatforms.difference(toolPlatforms); if (frameworkExtra.isNotEmpty) { - foundError(['TargetPlatform has some extra values not found in the tool: ${frameworkExtra.join(", ")}']); + foundError([ + 'TargetPlatform has some extra values not found in the tool: ${frameworkExtra.join(", ")}', + ]); } final Set toolExtra = toolPlatforms.difference(frameworkPlatforms); if (toolExtra.isNotEmpty) { - foundError(['The nextPlatform logic in the tool has some extra values not found in TargetPlatform: ${toolExtra.join(", ")}']); + foundError([ + 'The nextPlatform logic in the tool has some extra values not found in TargetPlatform: ${toolExtra.join(", ")}', + ]); } } @@ -353,7 +401,9 @@ Future verifyTokenTemplatesUpdateCorrectFiles(String workingDirectory) asy String getFileName(String line) { const String materialLibString = r"'$materialLib/"; - final String leftClamp = line.substring(line.indexOf(materialLibString) + materialLibString.length); + final String leftClamp = line.substring( + line.indexOf(materialLibString) + materialLibString.length, + ); return leftClamp.substring(0, leftClamp.indexOf("'")); } @@ -376,8 +426,11 @@ Future verifyTokenTemplatesUpdateCorrectFiles(String workingDirectory) asy } } - assert(atLeastOneTargetLineExists, 'No lines exist that this test expects to ' - 'verify. Check if the target file is correct or remove this test'); + assert( + atLeastOneTargetLineExists, + 'No lines exist that this test expects to ' + 'verify. Check if the target file is correct or remove this test', + ); // Fail if any errors if (errors.isNotEmpty) { @@ -390,21 +443,95 @@ Future verifyTokenTemplatesUpdateCorrectFiles(String workingDirectory) asy } } +/// Verify Material library files are up-to-date with the token template files +/// when running /dev/tools/gen_defaults/bin/gen_defaults.dart. +Future verifyMaterialFilesAreUpToDateWithTemplateFiles( + String workingDirectory, + String dartExecutable, +) async { + final List errors = []; + const String beginGeneratedComment = '// BEGIN GENERATED TOKEN PROPERTIES'; + + String getMaterialDirPath(List lines) { + final String line = lines.firstWhere((String line) => line.contains('String materialLib')); + final String relativePath = line.substring(line.indexOf("'") + 1, line.lastIndexOf("'")); + return path.join(workingDirectory, relativePath); + } + + String getFileName(String line) { + const String materialLibString = r"'$materialLib/"; + final String leftClamp = line.substring( + line.indexOf(materialLibString) + materialLibString.length, + ); + return leftClamp.substring(0, leftClamp.indexOf("'")); + } + + // Get the template generated code from the file. + List getGeneratedCode(List lines) { + return lines.skipWhile((String line) => !line.contains(beginGeneratedComment)).toList(); + } + + final String genDefaultsBinDir = '$workingDirectory/dev/tools/gen_defaults/bin'; + final File file = File(path.join(genDefaultsBinDir, 'gen_defaults.dart')); + final List lines = file.readAsLinesSync(); + final String materialDirPath = getMaterialDirPath(lines); + final Map> beforeGeneratedCode = >{}; + final Map> afterGeneratedCode = >{}; + + for (final String line in lines) { + if (line.contains('updateFile();')) { + final String fileName = getFileName(line); + final String filePath = path.join(materialDirPath, fileName); + final File file = File(filePath); + beforeGeneratedCode[fileName] = getGeneratedCode(file.readAsLinesSync()); + } + } + + // Run gen_defaults.dart to generate the token template files. + await runCommand(dartExecutable, [ + '--enable-asserts', + path.join('dev', 'tools', 'gen_defaults', 'bin', 'gen_defaults.dart'), + ], workingDirectory: workingDirectory); + + for (final String line in lines) { + if (line.contains('updateFile();')) { + final String fileName = getFileName(line); + final String filePath = path.join(materialDirPath, fileName); + final File file = File(filePath); + afterGeneratedCode[fileName] = getGeneratedCode(file.readAsLinesSync()); + } + } + + // Compare the generated code before and after running gen_defaults.dart. + for (final String fileName in beforeGeneratedCode.keys) { + final List before = beforeGeneratedCode[fileName]!; + final List after = afterGeneratedCode[fileName]!; + if (!const IterableEquality().equals(before, after)) { + errors.add('$fileName is not up-to-date with the token template file.'); + } + } + + // Fail if any errors. + if (errors.isNotEmpty) { + foundError([ + ...errors, + '${bold}See: https://github.com/flutter/flutter/blob/main/dev/tools/gen_defaults to update the token template files.$reset', + ]); + } +} + /// Verify tool test files end in `_test.dart`. /// /// The test runner will only recognize files ending in `_test.dart` as tests to /// be run: https://github.com/dart-lang/test/tree/master/pkgs/test#running-tests Future verifyToolTestsEndInTestDart(String workingDirectory) async { - final String toolsTestPath = path.join( - workingDirectory, - 'packages', - 'flutter_tools', - 'test', - ); + final String toolsTestPath = path.join(workingDirectory, 'packages', 'flutter_tools', 'test'); final List violations = []; // detect files that contains calls to test(), testUsingContext(), and testWithoutContext() - final RegExp callsTestFunctionPattern = RegExp(r'(test\(.*\)|testUsingContext\(.*\)|testWithoutContext\(.*\))'); + final RegExp callsTestFunctionPattern = RegExp( + r'(test\(.*\)|testUsingContext\(.*\)|testWithoutContext\(.*\))', + ); await for (final File file in _allFiles(toolsTestPath, 'dart', minimumMatches: 300)) { final bool isValidTestFile = file.path.endsWith('_test.dart'); @@ -437,12 +564,16 @@ Future verifyToolTestsEndInTestDart(String workingDirectory) async { } } -Future verifyNoSyncAsyncStar(String workingDirectory, {int minimumMatches = 2000 }) async { +Future verifyNoSyncAsyncStar(String workingDirectory, {int minimumMatches = 2000}) async { final RegExp syncPattern = RegExp(r'\s*?a?sync\*\s*?{'); final RegExp ignorePattern = RegExp(r'^\s*?// The following uses a?sync\* because:? '); final RegExp commentPattern = RegExp(r'^\s*?//'); final List errors = []; - await for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { + await for (final File file in _allFiles( + workingDirectory, + 'dart', + minimumMatches: minimumMatches, + )) { if (file.path.contains('test')) { continue; } @@ -470,7 +601,7 @@ Future verifyNoSyncAsyncStar(String workingDirectory, {int minimumMatches } if (errors.isNotEmpty) { foundError([ - '${bold}Do not use sync*/async* methods. See https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#avoid-syncasync for details.$reset', + '${bold}Do not use sync*/async* methods. See https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#avoid-syncasync for details.$reset', ...errors, ]); } @@ -488,9 +619,13 @@ final RegExp _goldenTagPattern2 = RegExp(r"'reduced-test-set'"); const String _ignoreGoldenTag = '// flutter_ignore: golden_tag (see analyze.dart)'; const String _ignoreGoldenTagForFile = '// flutter_ignore_for_file: golden_tag (see analyze.dart)'; -Future verifyGoldenTags(String workingDirectory, { int minimumMatches = 2000 }) async { +Future verifyGoldenTags(String workingDirectory, {int minimumMatches = 2000}) async { final List errors = []; - await for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { + await for (final File file in _allFiles( + workingDirectory, + 'dart', + minimumMatches: minimumMatches, + )) { bool needsTag = false; bool hasTagNotation = false; bool hasReducedTag = false; @@ -503,10 +638,10 @@ Future verifyGoldenTags(String workingDirectory, { int minimumMatches = 20 if (line.contains(_goldenTagPattern2)) { hasReducedTag = true; } - if (line.contains(_findGoldenTestPattern) - && !line.contains(_findGoldenDefinitionPattern) - && !line.contains(_leadingComment) - && !line.contains(_ignoreGoldenTag)) { + if (line.contains(_findGoldenTestPattern) && + !line.contains(_findGoldenDefinitionPattern) && + !line.contains(_leadingComment) && + !line.contains(_ignoreGoldenTag)) { needsTag = true; } if (line.contains(_ignoreGoldenTagForFile)) { @@ -526,164 +661,298 @@ Future verifyGoldenTags(String workingDirectory, { int minimumMatches = 20 // test environments. if (needsTag) { if (!hasTagNotation) { - errors.add('${file.path}: Files containing golden tests must be tagged using ' - "@Tags(['reduced-test-set']) at the top of the file before import statements."); + errors.add( + '${file.path}: Files containing golden tests must be tagged using ' + "@Tags(['reduced-test-set']) at the top of the file before import statements.", + ); } else if (!hasReducedTag) { - errors.add('${file.path}: Files containing golden tests must be tagged with ' - "'reduced-test-set'."); + errors.add( + '${file.path}: Files containing golden tests must be tagged with ' + "'reduced-test-set'.", + ); } } } if (errors.isNotEmpty) { foundError([ ...errors, - '${bold}See: https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter$reset', + '${bold}See: https://github.com/flutter/flutter/blob/main/docs/contributing/testing/Writing-a-golden-file-test-for-package-flutter.md$reset', ]); } } -final RegExp _findDeprecationPattern = RegExp(r'@[Dd]eprecated'); -final RegExp _deprecationStartPattern = RegExp(r'^(? *)@Deprecated\($'); // flutter_ignore: deprecation_syntax (see analyze.dart) -final RegExp _deprecationMessagePattern = RegExp(r"^ *'(?.+) '$"); -final RegExp _deprecationVersionPattern = RegExp(r"^ *'This feature was deprecated after v(?\d+)\.(?\d+)\.(?\d+)(?-\d+\.\d+\.pre)?\.',?$"); -final RegExp _deprecationEndPattern = RegExp(r'^ *\)$'); +class _DeprecationMessagesVisitor extends RecursiveAstVisitor { + _DeprecationMessagesVisitor(this.parseResult, this.filePath); -/// Some deprecation notices are special, for example they're used to annotate members that -/// will never go away and were never allowed but which we are trying to show messages for. -/// (One example would be a library that intentionally conflicts with a member in another -/// library to indicate that it is incompatible with that other library. Another would be -/// the regexp just above...) -const String _ignoreDeprecation = ' // flutter_ignore: deprecation_syntax (see analyze.dart)'; + final ParseStringResult parseResult; + final String filePath; + final List errors = []; -/// Some deprecation notices are exempt for historical reasons. They must have an issue listed. -final RegExp _legacyDeprecation = RegExp(r' // flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/\d+$'); + /// Some deprecation notices are special, for example they're used to annotate members that + /// will never go away and were never allowed but which we are trying to show messages for. + /// (One example would be a library that intentionally conflicts with a member in another + /// library to indicate that it is incompatible with that other library. Another would be + /// the regexp just above...) + static const Pattern ignoreDeprecration = + '// flutter_ignore: deprecation_syntax (see analyze.dart)'; + + /// Some deprecation notices are exempt for historical reasons. They must have an issue listed. + static final RegExp legacyDeprecation = RegExp( + r'// flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/\d+', + ); -Future verifyDeprecations(String workingDirectory, { int minimumMatches = 2000 }) async { - final List errors = []; - await for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { - int lineNumber = 0; - final List lines = file.readAsLinesSync(); - final List linesWithDeprecations = []; - for (final String line in lines) { - if (line.contains(_findDeprecationPattern) && - !line.endsWith(_ignoreDeprecation) && - !line.contains(_legacyDeprecation)) { - linesWithDeprecations.add(lineNumber); + static final RegExp deprecationVersionPattern = RegExp( + r'This feature was deprecated after v(?\d+)\.(?\d+)\.(?\d+)(?-\d+\.\d+\.pre)?\.$', + ); + + void _addErrorWithLineInfo(AstNode node, {required String error}) { + final int lineNumber = parseResult.lineInfo.getLocation(node.offset).lineNumber; + errors.add('$filePath:$lineNumber: $error'); + } + + @override + void visitAnnotation(Annotation node) { + super.visitAnnotation(node); + final bool shouldCheckAnnotation = + node.name.name == 'Deprecated' && + !hasInlineIgnore(node, parseResult, ignoreDeprecration) && + !hasInlineIgnore(node, parseResult, legacyDeprecation); + if (!shouldCheckAnnotation) { + return; + } + final NodeList? arguments = node.arguments?.arguments; + if (arguments == null || arguments.length != 1) { + _addErrorWithLineInfo( + node, + error: 'A @Deprecation annotation must have exactly one deprecation notice String.', + ); + return; + } + final Expression deprecationNotice = arguments.first; + if (deprecationNotice is! AdjacentStrings) { + _addErrorWithLineInfo(node, error: 'Deprecation notice must be an adjacent string.'); + return; + } + final List strings = deprecationNotice.strings; + final Iterator deprecationMessageIterator = strings.iterator; + final bool isNotEmpty = deprecationMessageIterator.moveNext(); + assert(isNotEmpty); // An AdjacentString always has 2 or more string literals. + + final [...List messageLiterals, StringLiteral versionLiteral] = strings; + + // Verify the version literal has the correct pattern. + final RegExpMatch? versionMatch = + versionLiteral is SimpleStringLiteral + ? deprecationVersionPattern.firstMatch(versionLiteral.value) + : null; + if (versionMatch == null) { + _addErrorWithLineInfo( + versionLiteral, + error: + 'Deprecation notice must end with a line saying "This feature was deprecated after...".', + ); + return; + } + + final int major = int.parse(versionMatch.namedGroup('major')!); + final int minor = int.parse(versionMatch.namedGroup('minor')!); + final int patch = int.parse(versionMatch.namedGroup('patch')!); + final bool hasBuild = versionMatch.namedGroup('build') != null; + // There was a beta release that was mistakenly labeled 3.1.0 without a build. + final bool specialBeta = major == 3 && minor == 1 && patch == 0; + if (!specialBeta && (major > 1 || (major == 1 && minor >= 20))) { + if (!hasBuild) { + _addErrorWithLineInfo( + versionLiteral, + error: + 'Deprecation notice does not accurately indicate a beta branch version number; please see https://flutter.dev/docs/development/tools/sdk/releases to find the latest beta build version number.', + ); + return; } - lineNumber += 1; } - for (int lineNumber in linesWithDeprecations) { - try { - final RegExpMatch? startMatch = _deprecationStartPattern.firstMatch(lines[lineNumber]); - if (startMatch == null) { - throw 'Deprecation notice does not match required pattern.'; - } - final String indent = startMatch.namedGroup('indent')!; - lineNumber += 1; - if (lineNumber >= lines.length) { - throw 'Incomplete deprecation notice.'; - } - RegExpMatch? versionMatch; - String? message; - do { - final RegExpMatch? messageMatch = _deprecationMessagePattern.firstMatch(lines[lineNumber]); - if (messageMatch == null) { - String possibleReason = ''; - if (lines[lineNumber].trimLeft().startsWith('"')) { - possibleReason = ' You might have used double quotes (") for the string instead of single quotes (\').'; - } else if (!lines[lineNumber].contains("'")) { - possibleReason = ' It might be missing the line saying "This feature was deprecated after...".'; - } else if (!lines[lineNumber].trimRight().endsWith(" '")) { - if (lines[lineNumber].contains('This feature was deprecated')) { - possibleReason = ' There might not be an explanatory message.'; - } else { - possibleReason = ' There might be a missing space character at the end of the line.'; - } - } - throw 'Deprecation notice does not match required pattern.$possibleReason'; - } - if (!lines[lineNumber].startsWith("$indent '")) { - throw 'Unexpected deprecation notice indent.'; - } - if (message == null) { - message = messageMatch.namedGroup('message'); - final String firstChar = String.fromCharCode(message!.runes.first); - if (firstChar.toUpperCase() != firstChar) { - throw 'Deprecation notice should be a grammatically correct sentence and start with a capital letter; see style guide: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo'; - } - } else { - message += messageMatch.namedGroup('message')!; - } - lineNumber += 1; - if (lineNumber >= lines.length) { - throw 'Incomplete deprecation notice.'; - } - versionMatch = _deprecationVersionPattern.firstMatch(lines[lineNumber]); - } while (versionMatch == null); - final int major = int.parse(versionMatch.namedGroup('major')!); - final int minor = int.parse(versionMatch.namedGroup('minor')!); - final int patch = int.parse(versionMatch.namedGroup('patch')!); - final bool hasBuild = versionMatch.namedGroup('build') != null; - // There was a beta release that was mistakenly labeled 3.1.0 without a build. - final bool specialBeta = major == 3 && minor == 1 && patch == 0; - if (!specialBeta && (major > 1 || (major == 1 && minor >= 20))) { - if (!hasBuild) { - throw 'Deprecation notice does not accurately indicate a beta branch version number; please see https://flutter.dev/docs/development/tools/sdk/releases to find the latest beta build version number.'; - } - } - if (!message.endsWith('.') && !message.endsWith('!') && !message.endsWith('?')) { - throw 'Deprecation notice should be a grammatically correct sentence and end with a period; notice appears to be "$message".'; - } - if (!lines[lineNumber].startsWith("$indent '")) { - throw 'Unexpected deprecation notice indent.'; - } - lineNumber += 1; - if (lineNumber >= lines.length) { - throw 'Incomplete deprecation notice.'; - } - if (!lines[lineNumber].contains(_deprecationEndPattern)) { - throw 'End of deprecation notice does not match required pattern.'; - } - if (!lines[lineNumber].startsWith('$indent)')) { - throw 'Unexpected deprecation notice indent.'; - } - } catch (error) { - errors.add('${file.path}:${lineNumber + 1}: $error'); + + // Verify the version literal has the correct pattern. + assert(messageLiterals.isNotEmpty); // An AdjacentString always has 2 or more string literals. + for (final StringLiteral message in messageLiterals) { + if (message is! SingleStringLiteral) { + _addErrorWithLineInfo( + message, + error: 'Deprecation notice does not match required pattern.', + ); + return; + } + if (!message.isSingleQuoted) { + _addErrorWithLineInfo( + message, + error: + 'Deprecation notice does not match required pattern. You might have used double quotes (") for the string instead of single quotes (\').', + ); + return; } } + final String fullExplanation = + messageLiterals + .map((StringLiteral message) => message.stringValue ?? '') + .join() + .trimRight(); + if (fullExplanation.isEmpty) { + _addErrorWithLineInfo( + messageLiterals.last, + error: + 'Deprecation notice should be a grammatically correct sentence and end with a period; There might not be an explanatory message.', + ); + return; + } + final String firstChar = String.fromCharCode(fullExplanation.runes.first); + if (firstChar.toUpperCase() != firstChar) { + _addErrorWithLineInfo( + messageLiterals.first, + error: + 'Deprecation notice should be a grammatically correct sentence and start with a capital letter; see style guide: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md', + ); + return; + } + if (!fullExplanation.endsWith('.') && + !fullExplanation.endsWith('?') && + !fullExplanation.endsWith('!')) { + _addErrorWithLineInfo( + messageLiterals.last, + error: + 'Deprecation notice should be a grammatically correct sentence and end with a period; notice appears to be "$fullExplanation".', + ); + return; + } + } +} + +Future verifyDeprecations(String workingDirectory, {int minimumMatches = 2000}) async { + final List errors = []; + await for (final File file in _allFiles( + workingDirectory, + 'dart', + minimumMatches: minimumMatches, + )) { + final ParseStringResult parseResult = parseFile( + featureSet: _parsingFeatureSet(), + path: file.absolute.path, + ); + final _DeprecationMessagesVisitor visitor = _DeprecationMessagesVisitor(parseResult, file.path); + visitor.visitCompilationUnit(parseResult.unit); + errors.addAll(visitor.errors); } // Fail if any errors if (errors.isNotEmpty) { foundError([ ...errors, - '${bold}See: https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes$reset', + '${bold}See: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes$reset', ]); } } String _generateLicense(String prefix) { return '${prefix}Copyright 2014 The Flutter Authors. All rights reserved.\n' - '${prefix}Use of this source code is governed by a BSD-style license that can be\n' - '${prefix}found in the LICENSE file.'; + '${prefix}Use of this source code is governed by a BSD-style license that can be\n' + '${prefix}found in the LICENSE file.'; } -Future verifyNoMissingLicense(String workingDirectory, { bool checkMinimums = true }) async { +Future verifyNoMissingLicense(String workingDirectory, {bool checkMinimums = true}) async { final int? overrideMinimumMatches = checkMinimums ? null : 0; - await _verifyNoMissingLicenseForExtension(workingDirectory, 'dart', overrideMinimumMatches ?? 2000, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'java', overrideMinimumMatches ?? 39, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'h', overrideMinimumMatches ?? 30, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'm', overrideMinimumMatches ?? 30, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'cc', overrideMinimumMatches ?? 10, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'cpp', overrideMinimumMatches ?? 0, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'swift', overrideMinimumMatches ?? 10, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'gradle', overrideMinimumMatches ?? 80, _generateLicense('// ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'gn', overrideMinimumMatches ?? 0, _generateLicense('# ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'sh', overrideMinimumMatches ?? 1, _generateLicense('# '), header: r'#!/usr/bin/env bash\n',); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'bat', overrideMinimumMatches ?? 1, _generateLicense('REM '), header: r'@ECHO off\n'); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'ps1', overrideMinimumMatches ?? 1, _generateLicense('# ')); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'html', overrideMinimumMatches ?? 1, '', trailingBlank: false, header: r'\n'); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'xml', overrideMinimumMatches ?? 1, '', header: r'(<\?xml version="1.0" encoding="utf-8"\?>\n)?'); - await _verifyNoMissingLicenseForExtension(workingDirectory, 'frag', overrideMinimumMatches ?? 1, _generateLicense('// '), header: r'#version 320 es(\n)+'); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'dart', + overrideMinimumMatches ?? 2000, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'java', + overrideMinimumMatches ?? 1, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'h', + overrideMinimumMatches ?? 30, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'm', + overrideMinimumMatches ?? 30, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'cc', + overrideMinimumMatches ?? 10, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'cpp', + overrideMinimumMatches ?? 0, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'swift', + overrideMinimumMatches ?? 10, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'gradle', + overrideMinimumMatches ?? 80, + _generateLicense('// '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'gn', + overrideMinimumMatches ?? 0, + _generateLicense('# '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'sh', + overrideMinimumMatches ?? 1, + _generateLicense('# '), + header: r'#!/usr/bin/env bash\n', + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'bat', + overrideMinimumMatches ?? 1, + _generateLicense('REM '), + header: r'@ECHO off\n', + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'ps1', + overrideMinimumMatches ?? 1, + _generateLicense('# '), + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'html', + overrideMinimumMatches ?? 1, + '', + trailingBlank: false, + header: r'\n', + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'xml', + overrideMinimumMatches ?? 1, + '', + header: r'(<\?xml version="1.0" encoding="utf-8"\?>\n)?', + ); + await _verifyNoMissingLicenseForExtension( + workingDirectory, + 'frag', + overrideMinimumMatches ?? 1, + _generateLicense('// '), + header: r'#version 320 es(\n)+', + ); } Future _verifyNoMissingLicenseForExtension( @@ -699,11 +968,18 @@ Future _verifyNoMissingLicenseForExtension( assert(!license.endsWith('\n')); final String licensePattern = RegExp.escape('$license\n${trailingBlank ? '\n' : ''}'); final List errors = []; - await for (final File file in _allFiles(workingDirectory, extension, minimumMatches: minimumMatches)) { + await for (final File file in _allFiles( + workingDirectory, + extension, + minimumMatches: minimumMatches, + )) { final String contents = file.readAsStringSync().replaceAll('\r\n', '\n'); if (contents.isEmpty) { continue; // let's not go down the /bin/true rabbit hole } + if (path.basename(file.path) == 'Package.swift') { + continue; + } if (!contents.startsWith(RegExp(header + licensePattern))) { errors.add(file.path); } @@ -735,7 +1011,9 @@ Iterable<_Line> _getTestSkips(File file) { featureSet: _parsingFeatureSet(), path: file.absolute.path, ); - final _TestSkipLinesVisitor visitor = _TestSkipLinesVisitor(parseResult); + final _TestSkipLinesVisitor visitor = _TestSkipLinesVisitor( + parseResult, + ); visitor.visitCompilationUnit(parseResult.unit); return visitor.skips; } @@ -750,11 +1028,22 @@ class _TestSkipLinesVisitor extends RecursiveAstVisitor { return name.startsWith('test') || name == 'group' || name == 'expect'; } + static final Pattern _skipTestIntentionalPattern = RegExp(r'// .*[intended]'); + static final Pattern _skipTestTrackingBugPattern = RegExp( + r'// .*https+?://github.com/.*/issues/\d+', + ); + bool _hasValidJustificationComment(Label skipLabel) { + return hasInlineIgnore(skipLabel, parseResult, _skipTestIntentionalPattern) || + hasInlineIgnore(skipLabel, parseResult, _skipTestTrackingBugPattern); + } + @override T? visitMethodInvocation(MethodInvocation node) { if (isTestMethod(node.methodName.toString())) { for (final Expression argument in node.argumentList.arguments) { - if (argument is NamedExpression && argument.name.label.name == 'skip') { + if (argument is NamedExpression && + argument.name.label.name == 'skip' && + !_hasValidJustificationComment(argument.name)) { skips.add(_getLine(parseResult, argument.beginToken.charOffset)); } } @@ -763,24 +1052,17 @@ class _TestSkipLinesVisitor extends RecursiveAstVisitor { } } -final RegExp _skipTestCommentPattern = RegExp(r'//(.*)$'); -const Pattern _skipTestIntentionalPattern = '[intended]'; -final Pattern _skipTestTrackingBugPattern = RegExp(r'https+?://github.com/.*/issues/\d+'); - Future verifySkipTestComments(String workingDirectory) async { final List errors = []; - final Stream testFiles =_allFiles(workingDirectory, 'dart', minimumMatches: 1500) - .where((File f) => f.path.endsWith('_test.dart')); + final Stream testFiles = _allFiles( + workingDirectory, + 'dart', + minimumMatches: 1500, + ).where((File f) => f.path.endsWith('_test.dart')); await for (final File file in testFiles) { for (final _Line skip in _getTestSkips(file)) { - final Match? match = _skipTestCommentPattern.firstMatch(skip.content); - final String? skipComment = match?.group(1); - if (skipComment == null || - !(skipComment.contains(_skipTestIntentionalPattern) || - skipComment.contains(_skipTestTrackingBugPattern))) { - errors.add('${file.path}:${skip.line}: skip test without a justification comment.'); - } + errors.add('${file.path}:${skip.line}: skip test without a justification comment.'); } } @@ -788,7 +1070,7 @@ Future verifySkipTestComments(String workingDirectory) async { if (errors.isNotEmpty) { foundError([ ...errors, - '\n${bold}See: https://github.com/flutter/flutter/wiki/Tree-hygiene#skipped-tests$reset', + '\n${bold}See: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#skipped-tests$reset', ]); } } @@ -804,7 +1086,12 @@ const Set _exemptTestImports = { Future verifyNoTestImports(String workingDirectory) async { final List errors = []; assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern)); - final List dartFiles = await _allFiles(path.join(workingDirectory, 'packages'), 'dart', minimumMatches: 1500).toList(); + final List dartFiles = + await _allFiles( + path.join(workingDirectory, 'packages'), + 'dart', + minimumMatches: 1500, + ).toList(); for (final File file in dartFiles) { for (final String line in file.readAsLinesSync()) { final Match? match = _testImportPattern.firstMatch(line); @@ -815,9 +1102,8 @@ Future verifyNoTestImports(String workingDirectory) async { } // Fail if any errors if (errors.isNotEmpty) { - final String s = errors.length == 1 ? '' : 's'; foundError([ - '${bold}The following file$s import a test directly. Test utilities should be in their own file.$reset', + '${bold}The following file(s) import a test directly. Test utilities should be in their own file.$reset', ...errors, ]); } @@ -828,35 +1114,51 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { final String libPath = path.join(workingDirectory, 'packages', 'flutter', 'lib'); final String srcPath = path.join(workingDirectory, 'packages', 'flutter', 'lib', 'src'); // Verify there's one libPath/*.dart for each srcPath/*/. - final List packages = Directory(libPath).listSync() - .where((FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart') - .map((FileSystemEntity entity) => path.basenameWithoutExtension(entity.path)) - .toList()..sort(); - final List directories = Directory(srcPath).listSync() - .whereType() - .map((Directory entity) => path.basename(entity.path)) - .toList()..sort(); + final List packages = + Directory(libPath) + .listSync() + .where( + (FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart', + ) + .map((FileSystemEntity entity) => path.basenameWithoutExtension(entity.path)) + .toList() + ..sort(); + final List directories = + Directory(srcPath) + .listSync() + .whereType() + .map((Directory entity) => path.basename(entity.path)) + .toList() + ..sort(); if (!_listEquals(packages, directories)) { - errors.add([ - 'flutter/lib/*.dart does not match flutter/lib/src/*/:', - 'These are the exported packages:', - ...packages.map((String path) => ' lib/$path.dart'), - 'These are the directories:', - ...directories.map((String path) => ' lib/src/$path/'), - ].join('\n')); + errors.add( + [ + 'flutter/lib/*.dart does not match flutter/lib/src/*/:', + 'These are the exported packages:', + ...packages.map((String path) => ' lib/$path.dart'), + 'These are the directories:', + ...directories.map((String path) => ' lib/src/$path/'), + ].join('\n'), + ); } // Verify that the imports are well-ordered. final Map> dependencyMap = >{}; for (final String directory in directories) { - dependencyMap[directory] = await _findFlutterDependencies(path.join(srcPath, directory), errors, checkForMeta: directory != 'foundation'); + dependencyMap[directory] = await _findFlutterDependencies( + path.join(srcPath, directory), + errors, + checkForMeta: directory != 'foundation', + ); } - assert(dependencyMap['material']!.contains('widgets') && - dependencyMap['widgets']!.contains('rendering') && - dependencyMap['rendering']!.contains('painting')); // to make sure we're convinced _findFlutterDependencies is finding some + assert( + dependencyMap['material']!.contains('widgets') && + dependencyMap['widgets']!.contains('rendering') && + dependencyMap['rendering']!.contains('painting'), + ); // to make sure we're convinced _findFlutterDependencies is finding some for (final String package in dependencyMap.keys) { if (dependencyMap[package]!.contains(package)) { errors.add( - 'One of the files in the $yellow$package$reset package imports that package recursively.' + 'One of the files in the $yellow$package$reset package imports that package recursively.', ); } } @@ -868,11 +1170,13 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { } // Sanity check before performing _deepSearch, to ensure there's no rogue // dependencies. - final String validFilenames = dependencyMap.keys.map((String name) => '$name.dart').join(', '); + final String validFilenames = dependencyMap.keys + .map((String name) => '$name.dart') + .join(', '); errors.add( '$key imported package:flutter/$dependency.dart ' 'which is not one of the valid exports { $validFilenames }.\n' - 'Consider changing $dependency.dart to one of them.' + 'Consider changing $dependency.dart to one of them.', ); } } @@ -897,7 +1201,12 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { Future verifyNoBadImportsInFlutterTools(String workingDirectory) async { final List errors = []; - final List files = await _allFiles(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'), 'dart', minimumMatches: 200).toList(); + final List files = + await _allFiles( + path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'), + 'dart', + minimumMatches: 200, + ).toList(); for (final File file in files) { if (file.readAsStringSync().contains('package:flutter_tools/')) { errors.add('$yellow${file.path}$reset imports flutter_tools.'); @@ -918,15 +1227,22 @@ Future verifyNoBadImportsInFlutterTools(String workingDirectory) async { Future verifyIntegrationTestTimeouts(String workingDirectory) async { final List errors = []; final String dev = path.join(workingDirectory, 'dev'); - final List files = await _allFiles(dev, 'dart', minimumMatches: 1) - .where((File file) => file.path.contains('test_driver') && (file.path.endsWith('_test.dart') || file.path.endsWith('util.dart'))) - .toList(); + final List files = + await _allFiles(dev, 'dart', minimumMatches: 1) + .where( + (File file) => + file.path.contains('test_driver') && + (file.path.endsWith('_test.dart') || file.path.endsWith('util.dart')), + ) + .toList(); for (final File file in files) { final String contents = file.readAsStringSync(); final int testCount = ' test('.allMatches(contents).length; final int timeoutNoneCount = 'timeout: Timeout.none'.allMatches(contents).length; if (testCount != timeoutNoneCount) { - errors.add('$yellow${file.path}$reset has at least $testCount test(s) but only $timeoutNoneCount `Timeout.none`(s).'); + errors.add( + '$yellow${file.path}$reset has at least $testCount test(s) but only $timeoutNoneCount `Timeout.none`(s).', + ); } } if (errors.isNotEmpty) { @@ -941,27 +1257,35 @@ Future verifyIntegrationTestTimeouts(String workingDirectory) async { } Future verifyInternationalizations(String workingDirectory, String dartExecutable) async { - final EvalResult materialGenResult = await _evalCommand( - dartExecutable, - [ - path.join('dev', 'tools', 'localization', 'bin', 'gen_localizations.dart'), - '--material', - '--remove-undefined', - ], - workingDirectory: workingDirectory, + final EvalResult materialGenResult = await _evalCommand(dartExecutable, [ + path.join('dev', 'tools', 'localization', 'bin', 'gen_localizations.dart'), + '--material', + '--remove-undefined', + ], workingDirectory: workingDirectory); + final EvalResult cupertinoGenResult = await _evalCommand(dartExecutable, [ + path.join('dev', 'tools', 'localization', 'bin', 'gen_localizations.dart'), + '--cupertino', + '--remove-undefined', + ], workingDirectory: workingDirectory); + + final String materialLocalizationsFile = path.join( + workingDirectory, + 'packages', + 'flutter_localizations', + 'lib', + 'src', + 'l10n', + 'generated_material_localizations.dart', ); - final EvalResult cupertinoGenResult = await _evalCommand( - dartExecutable, - [ - path.join('dev', 'tools', 'localization', 'bin', 'gen_localizations.dart'), - '--cupertino', - '--remove-undefined', - ], - workingDirectory: workingDirectory, + final String cupertinoLocalizationsFile = path.join( + workingDirectory, + 'packages', + 'flutter_localizations', + 'lib', + 'src', + 'l10n', + 'generated_cupertino_localizations.dart', ); - - final String materialLocalizationsFile = path.join(workingDirectory, 'packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'generated_material_localizations.dart'); - final String cupertinoLocalizationsFile = path.join(workingDirectory, 'packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'generated_cupertino_localizations.dart'); final String expectedMaterialResult = await File(materialLocalizationsFile).readAsString(); final String expectedCupertinoResult = await File(cupertinoLocalizationsFile).readAsString(); @@ -991,19 +1315,66 @@ Future verifyInternationalizations(String workingDirectory, String dartExe } } +Future verifyStockAppLocalizations(String workingDirectory) async { + final Directory appRoot = Directory( + path.join(workingDirectory, 'dev', 'benchmarks', 'test_apps', 'stocks'), + ); + if (!appRoot.existsSync()) { + foundError(['Stocks app does not exist at expected location: ${appRoot.path}']); + } + + // Regenerate the localizations. + final String flutterExecutable = path.join( + workingDirectory, + 'bin', + 'flutter${Platform.isWindows ? '.bat' : ''}', + ); + await _evalCommand(flutterExecutable, const ['gen-l10n'], workingDirectory: appRoot.path); + final Directory i10nDirectory = Directory(path.join(appRoot.path, 'lib', 'i18n')); + if (!i10nDirectory.existsSync()) { + foundError([ + 'Localization files for stocks app not found at expected location: ${i10nDirectory.path}', + ]); + } + + // Check that regeneration did not dirty the tree. + final EvalResult result = await _evalCommand('git', [ + 'diff', + '--name-only', + '--exit-code', + i10nDirectory.path, + ], workingDirectory: workingDirectory); + if (result.exitCode == 1) { + foundError([ + 'The following localization files for the stocks app appear to be out of date:', + ...(const LineSplitter().convert(result.stdout).map((String line) => ' * $line')), + 'Run "flutter gen-l10n" in "${path.relative(appRoot.path, from: workingDirectory)}" to regenerate.', + ]); + } else if (result.exitCode != 0) { + foundError([ + 'Failed to run "git diff" on localization files of stocks app:', + result.stderr, + ]); + } +} /// Verifies that all instances of "checked mode" have been migrated to "debug mode". Future verifyNoCheckedMode(String workingDirectory) async { final String flutterPackages = path.join(workingDirectory, 'packages'); - final List files = await _allFiles(flutterPackages, 'dart', minimumMatches: 400) - .where((File file) => path.extension(file.path) == '.dart') - .toList(); + final List files = + await _allFiles( + flutterPackages, + 'dart', + minimumMatches: 400, + ).where((File file) => path.extension(file.path) == '.dart').toList(); final List problems = []; for (final File file in files) { int lineCount = 0; for (final String line in file.readAsLinesSync()) { if (line.toLowerCase().contains('checked mode')) { - problems.add('${file.path}:$lineCount uses deprecated "checked mode" instead of "debug mode".'); + problems.add( + '${file.path}:$lineCount uses deprecated "checked mode" instead of "debug mode".', + ); } lineCount += 1; } @@ -1013,15 +1384,17 @@ Future verifyNoCheckedMode(String workingDirectory) async { } } - Future verifyNoRuntimeTypeInToString(String workingDirectory) async { final String flutterLib = path.join(workingDirectory, 'packages', 'flutter', 'lib'); final Set excludedFiles = { path.join(flutterLib, 'src', 'foundation', 'object.dart'), // Calls this from within an assert. }; - final List files = await _allFiles(flutterLib, 'dart', minimumMatches: 400) - .where((File file) => !excludedFiles.contains(file.path)) - .toList(); + final List files = + await _allFiles( + flutterLib, + 'dart', + minimumMatches: 400, + ).where((File file) => !excludedFiles.contains(file.path)).toList(); final RegExp toStringRegExp = RegExp(r'^\s+String\s+to(.+?)?String(.+?)?\(\)\s+(\{|=>)'); final List problems = []; for (final File file in files) { @@ -1036,6 +1409,7 @@ Future verifyNoRuntimeTypeInToString(String workingDirectory) async { } return false; } + if (checkForRuntimeType(lines[index])) { continue; } @@ -1048,10 +1422,14 @@ Future verifyNoRuntimeTypeInToString(String workingDirectory) async { } } } else { - int openBraceCount = '{'.allMatches(lines[index]).length - '}'.allMatches(lines[index]).length; + int openBraceCount = + '{'.allMatches(lines[index]).length - '}'.allMatches(lines[index]).length; while (!lines[index].contains('}') && openBraceCount > 0) { index++; - assert(index < lines.length, 'Source file $file has unbalanced braces in a toString method.'); + assert( + index < lines.length, + 'Source file $file has unbalanced braces in a toString method.', + ); if (checkForRuntimeType(lines[index])) { break; } @@ -1067,17 +1445,18 @@ Future verifyNoRuntimeTypeInToString(String workingDirectory) async { } } -Future verifyNoTrailingSpaces(String workingDirectory, { int minimumMatches = 4000 }) async { - final List files = await _allFiles(workingDirectory, null, minimumMatches: minimumMatches) - .where((File file) => path.basename(file.path) != 'serviceaccount.enc') - .where((File file) => path.basename(file.path) != 'Ahem.ttf') - .where((File file) => path.extension(file.path) != '.snapshot') - .where((File file) => path.extension(file.path) != '.png') - .where((File file) => path.extension(file.path) != '.jpg') - .where((File file) => path.extension(file.path) != '.ico') - .where((File file) => path.extension(file.path) != '.jar') - .where((File file) => path.extension(file.path) != '.swp') - .toList(); +Future verifyNoTrailingSpaces(String workingDirectory, {int minimumMatches = 4000}) async { + final List files = + await _allFiles(workingDirectory, null, minimumMatches: minimumMatches) + .where((File file) => path.basename(file.path) != 'serviceaccount.enc') + .where((File file) => path.basename(file.path) != 'Ahem.ttf') + .where((File file) => path.extension(file.path) != '.snapshot') + .where((File file) => path.extension(file.path) != '.png') + .where((File file) => path.extension(file.path) != '.jpg') + .where((File file) => path.extension(file.path) != '.ico') + .where((File file) => path.extension(file.path) != '.jar') + .where((File file) => path.extension(file.path) != '.swp') + .toList(); final List problems = []; for (final File file in files) { final List lines = file.readAsLinesSync(); @@ -1097,11 +1476,18 @@ Future verifyNoTrailingSpaces(String workingDirectory, { int minimumMatche } } -final RegExp _flowControlStatementWithoutSpace = RegExp(r'(^|[ \t])(if|switch|for|do|while|catch)\(', multiLine: true); +final RegExp _flowControlStatementWithoutSpace = RegExp( + r'(^|[ \t])(if|switch|for|do|while|catch)\(', + multiLine: true, +); -Future verifySpacesAfterFlowControlStatements(String workingDirectory, { int minimumMatches = 4000 }) async { +Future verifySpacesAfterFlowControlStatements( + String workingDirectory, { + int minimumMatches = 4000, +}) async { const Set extensions = { - '.dart', + // .dart omitted from this list because the Dart auto formatter ensures + // spaces after flow control statements. '.java', '.js', '.kt', @@ -1112,9 +1498,12 @@ Future verifySpacesAfterFlowControlStatements(String workingDirectory, { i '.h', '.m', }; - final List files = await _allFiles(workingDirectory, null, minimumMatches: minimumMatches) - .where((File file) => extensions.contains(path.extension(file.path))) - .toList(); + final List files = + await _allFiles( + workingDirectory, + null, + minimumMatches: minimumMatches, + ).where((File file) => extensions.contains(path.extension(file.path))).toList(); final List problems = []; for (final File file in files) { final List lines = file.readAsLinesSync(); @@ -1133,24 +1522,31 @@ String _bullets(String value) => ' * $value'; Future verifyIssueLinks(String workingDirectory) async { const String issueLinkPrefix = 'https://github.com/flutter/flutter/issues/new'; - const Set stops = { '\n', ' ', "'", '"', r'\', ')', '>' }; - assert(!stops.contains('.')); // instead of "visit https://foo." say "visit: https://", it copy-pastes better + const Set stops = {'\n', ' ', "'", '"', r'\', ')', '>'}; + assert( + !stops.contains('.'), + ); // instead of "visit https://foo." say "visit: https://foo", it copy-pastes better const String kGiveTemplates = - 'Prefer to provide a link either to $issueLinkPrefix/choose (the list of issue ' - 'templates) or to a specific template directly ($issueLinkPrefix?template=...).\n'; + 'Prefer to provide a link either to $issueLinkPrefix/choose (the list of issue ' + 'templates) or to a specific template directly ($issueLinkPrefix?template=...).\n'; final Set templateNames = - Directory(path.join(workingDirectory, '.github', 'ISSUE_TEMPLATE')) - .listSync() - .whereType() - .where((File file) => path.extension(file.path) == '.md' || path.extension(file.path) == '.yml') - .map((File file) => path.basename(file.path)) - .toSet(); - final String kTemplates = 'The available templates are:\n${templateNames.map(_bullets).join("\n")}'; + Directory(path.join(workingDirectory, '.github', 'ISSUE_TEMPLATE')) + .listSync() + .whereType() + .where( + (File file) => + path.extension(file.path) == '.md' || path.extension(file.path) == '.yml', + ) + .map((File file) => path.basename(file.path)) + .toSet(); + final String kTemplates = + 'The available templates are:\n${templateNames.map(_bullets).join("\n")}'; final List problems = []; final Set suggestions = {}; final List files = await _gitFiles(workingDirectory); for (final File file in files) { - if (path.basename(file.path).endsWith('_test.dart') || path.basename(file.path) == 'analyze.dart') { + if (path.basename(file.path).endsWith('_test.dart') || + path.basename(file.path) == 'analyze.dart') { continue; // Skip tests, they're not public-facing. } final Uint8List bytes = file.readAsBytesSync(); @@ -1179,29 +1575,108 @@ Future verifyIssueLinks(String workingDirectory) async { suggestions.add(kGiveTemplates); suggestions.add(kTemplates); } else if (templates.length != 1) { - problems.add('${file.path} contains $url, which has ${templates.length} templates specified.'); + problems.add( + '${file.path} contains $url, which has ${templates.length} templates specified.', + ); suggestions.add(kGiveTemplates); suggestions.add(kTemplates); } else if (!templateNames.contains(templates.single)) { - problems.add('${file.path} contains $url, which specifies a non-existent template ("${templates.single}").'); + problems.add( + '${file.path} contains $url, which specifies a non-existent template ("${templates.single}").', + ); suggestions.add(kTemplates); } else if (parsedUrl.queryParametersAll.keys.length > 1) { - problems.add('${file.path} contains $url, which the analyze.dart script is not sure how to handle.'); - suggestions.add('Update analyze.dart to handle the URLs above, or change them to the expected pattern.'); + problems.add( + '${file.path} contains $url, which the analyze.dart script is not sure how to handle.', + ); + suggestions.add( + 'Update analyze.dart to handle the URLs above, or change them to the expected pattern.', + ); } } else if (url != '$issueLinkPrefix/choose') { - problems.add('${file.path} contains $url, which the analyze.dart script is not sure how to handle.'); - suggestions.add('Update analyze.dart to handle the URLs above, or change them to the expected pattern.'); + problems.add( + '${file.path} contains $url, which the analyze.dart script is not sure how to handle.', + ); + suggestions.add( + 'Update analyze.dart to handle the URLs above, or change them to the expected pattern.', + ); } start = end; } } assert(problems.isEmpty == suggestions.isEmpty); if (problems.isNotEmpty) { - foundError([ - ...problems, - ...suggestions, - ]); + foundError([...problems, ...suggestions]); + } +} + +Future verifyRepositoryLinks(String workingDirectory) async { + const Set stops = {'\n', ' ', "'", '"', r'\', ')', '>'}; + assert( + !stops.contains('.'), + ); // instead of "visit https://foo." say "visit: https://foo", it copy-pastes better + + // Repos whose default branch is still 'master' + const Set repoExceptions = { + 'bdero/flutter-gpu-examples', + 'chromium/chromium', + 'clojure/clojure', + 'dart-lang/test', // TODO(guidezpl): remove when https://github.com/dart-lang/test/issues/2209 is closed + 'dart-lang/webdev', + 'eseidelGoogle/bezier_perf', + 'flutter/devtools', // TODO(guidezpl): remove when https://github.com/flutter/devtools/issues/7551 is closed + 'flutter/flutter_gallery_assets', // TODO(guidezpl): remove when subtask in https://github.com/flutter/flutter/issues/121564 is complete + 'flutter/flutter-intellij', // TODO(guidezpl): remove when https://github.com/flutter/flutter-intellij/issues/7342 is closed + 'flutter/platform_tests', // TODO(guidezpl): remove when subtask in https://github.com/flutter/flutter/issues/121564 is complete + 'flutter/web_installers', + 'glfw/glfw', + 'GoogleCloudPlatform/artifact-registry-maven-tools', + 'material-components/material-components-android', // TODO(guidezpl): remove when https://github.com/material-components/material-components-android/issues/4144 is closed + 'ninja-build/ninja', + 'torvalds/linux', + 'tpn/winsdk-10', + }; + + // See dev/bots/test/analyze-test-input/root/packages/foo/bad_repository_links.dart + // for examples of repository links that are not allowed. + final RegExp pattern = RegExp( + r'^(https:\/\/(?:cs\.opensource\.google|github|raw\.githubusercontent|source\.chromium|([a-z0-9\-]+)\.googlesource)\.)', + ); + + final List problems = []; + final Set suggestions = {}; + final List files = await _allFiles(workingDirectory, null, minimumMatches: 10).toList(); + for (final File file in files) { + final Uint8List bytes = file.readAsBytesSync(); + // We allow invalid UTF-8 here so that binaries don't trip us up. + // There's a separate test in this file that verifies that all text + // files are actually valid UTF-8 (see verifyNoBinaries below). + final String contents = utf8.decode(bytes, allowMalformed: true); + int start = 0; + while ((start = contents.indexOf('https://', start)) >= 0) { + // Find all 'https://' links + int end = start + 8; // Length of 'https://' + while (end < contents.length && !stops.contains(contents[end])) { + end += 1; + } + final String url = contents.substring(start, end).replaceAll('\r', ''); + + if (pattern.hasMatch(url) && !repoExceptions.any(url.contains)) { + if (url.contains('master')) { + problems.add('${file.path} contains $url, which uses the banned "master" branch.'); + suggestions.add( + 'Change the URLs above to the expected pattern by ' + 'using the "main" branch if it exists, otherwise adding the ' + 'repository to the list of exceptions in analyze.dart.', + ); + } + } + start = end; + } + } + assert(problems.isEmpty == suggestions.isEmpty); + if (problems.isNotEmpty) { + foundError([...problems, ...suggestions]); } } @@ -1212,38 +1687,38 @@ class Hash256 { factory Hash256.fromDigest(Digest digest) { assert(digest.bytes.length == 32); return Hash256( - digest.bytes[ 0] << 56 | - digest.bytes[ 1] << 48 | - digest.bytes[ 2] << 40 | - digest.bytes[ 3] << 32 | - digest.bytes[ 4] << 24 | - digest.bytes[ 5] << 16 | - digest.bytes[ 6] << 8 | - digest.bytes[ 7] << 0, - digest.bytes[ 8] << 56 | - digest.bytes[ 9] << 48 | - digest.bytes[10] << 40 | - digest.bytes[11] << 32 | - digest.bytes[12] << 24 | - digest.bytes[13] << 16 | - digest.bytes[14] << 8 | - digest.bytes[15] << 0, + digest.bytes[0] << 56 | + digest.bytes[1] << 48 | + digest.bytes[2] << 40 | + digest.bytes[3] << 32 | + digest.bytes[4] << 24 | + digest.bytes[5] << 16 | + digest.bytes[6] << 8 | + digest.bytes[7] << 0, + digest.bytes[8] << 56 | + digest.bytes[9] << 48 | + digest.bytes[10] << 40 | + digest.bytes[11] << 32 | + digest.bytes[12] << 24 | + digest.bytes[13] << 16 | + digest.bytes[14] << 8 | + digest.bytes[15] << 0, digest.bytes[16] << 56 | - digest.bytes[17] << 48 | - digest.bytes[18] << 40 | - digest.bytes[19] << 32 | - digest.bytes[20] << 24 | - digest.bytes[21] << 16 | - digest.bytes[22] << 8 | - digest.bytes[23] << 0, + digest.bytes[17] << 48 | + digest.bytes[18] << 40 | + digest.bytes[19] << 32 | + digest.bytes[20] << 24 | + digest.bytes[21] << 16 | + digest.bytes[22] << 8 | + digest.bytes[23] << 0, digest.bytes[24] << 56 | - digest.bytes[25] << 48 | - digest.bytes[26] << 40 | - digest.bytes[27] << 32 | - digest.bytes[28] << 24 | - digest.bytes[29] << 16 | - digest.bytes[30] << 8 | - digest.bytes[31] << 0, + digest.bytes[25] << 48 | + digest.bytes[26] << 40 | + digest.bytes[27] << 32 | + digest.bytes[28] << 24 | + digest.bytes[29] << 16 | + digest.bytes[30] << 8 | + digest.bytes[31] << 0, ); } @@ -1257,11 +1732,7 @@ class Hash256 { if (other.runtimeType != runtimeType) { return false; } - return other is Hash256 - && other.a == a - && other.b == b - && other.c == c - && other.d == d; + return other is Hash256 && other.a == a && other.b == b && other.c == c && other.d == d; } @override @@ -1272,7 +1743,7 @@ class Hash256 { // We have a policy of not checking in binaries into this repository. // If you are adding/changing template images, use the flutter_template_images // package and a .img.tmpl placeholder instead. -// If you have other binaries to add, please consult Hixie for advice. +// If you have other binaries to add, please consult johnmccutchan for advice. final Set _legacyBinaries = { // DEFAULT ICON IMAGES @@ -1492,7 +1963,6 @@ final Set _legacyBinaries = { // dev/integration_tests/flutter_gallery/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-87.png const Hash256(0xC17BAE6DF6BB234A, 0xE0AF4BEB0B805F12, 0x14E74EB7AA9A30F1, 0x5763689165DA7DDF), - // STOCKS ICONS // dev/benchmarks/test_apps/stocks/android/app/src/main/res/mipmap-hdpi/ic_launcher.png @@ -1548,7 +2018,6 @@ final Set _legacyBinaries = { // dev/benchmarks/test_apps/stocks/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-Small@3x.png const Hash256(0x4D9F5E81F668DA44, 0xB20A77F8BF7BA2E1, 0xF384533B5AD58F07, 0xB3A2F93F8635CD96), - // LEGACY ICONS // dev/benchmarks/complex_layout/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@3x.png @@ -1573,7 +2042,6 @@ final Set _legacyBinaries = { // examples/image_list/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png const Hash256(0xB5792CA06F48A431, 0xD4379ABA2160BD5D, 0xE92339FC64C6A0D3, 0x417AA359634CD905), - // TEST ASSETS // dev/benchmarks/macrobenchmarks/assets/999x1000.png @@ -1609,7 +2077,6 @@ final Set _legacyBinaries = { // packages/flutter_tools/test/data/intellij/plugins/flutter-intellij.jar const Hash256(0x4C67221E25626CB2, 0x3F94E1F49D34E4CF, 0x3A9787A514924FC5, 0x9EF1E143E5BC5690), - // MISCELLANEOUS // dev/bots/serviceaccount.enc @@ -1628,19 +2095,21 @@ final Set _legacyBinaries = { const Hash256(0x63D2ABD0041C3E3B, 0x4B52AD8D382353B5, 0x3C51C6785E76CE56, 0xED9DACAD2D2E31C4), }; -Future verifyNoBinaries(String workingDirectory, { Set? legacyBinaries }) async { +Future verifyNoBinaries(String workingDirectory, {Set? legacyBinaries}) async { // Please do not add anything to the _legacyBinaries set above. // We have a policy of not checking in binaries into this repository. // If you are adding/changing template images, use the flutter_template_images // package and a .img.tmpl placeholder instead. - // If you have other binaries to add, please consult Hixie for advice. + // If you have other binaries to add, please consult johnmccutchan for advice. assert( _legacyBinaries - .expand((Hash256 hash) => [hash.a, hash.b, hash.c, hash.d]) - .reduce((int value, int element) => value ^ element) == 0x606B51C908B40BFA // Please do not modify this line. + .expand((Hash256 hash) => [hash.a, hash.b, hash.c, hash.d]) + .reduce((int value, int element) => value ^ element) == + 0x606B51C908B40BFA, // Please do not modify this line. ); legacyBinaries ??= _legacyBinaries; - if (!Platform.isWindows) { // TODO(ianh): Port this to Windows + if (!Platform.isWindows) { + // TODO(ianh): Port this to Windows final List files = await _gitFiles(workingDirectory); final List problems = []; for (final File file in files) { @@ -1663,13 +2132,12 @@ Future verifyNoBinaries(String workingDirectory, { Set? legacyBin 'to which you need access, you should consider how to fetch it from another repository;', 'for example, the "assets-for-api-docs" repository is used for images in API docs.', 'To add assets to flutter_tools templates, see the instructions in the wiki:', - 'https://github.com/flutter/flutter/wiki/Managing-template-image-assets', + 'https://github.com/flutter/flutter/blob/main/docs/tool/Managing-template-image-assets.md', ]); } } } - // UTILITY FUNCTIONS bool _listEquals(List a, List b) { @@ -1686,7 +2154,8 @@ bool _listEquals(List a, List b) { Future> _gitFiles(String workingDirectory, {bool runSilently = true}) async { final EvalResult evalResult = await _evalCommand( - 'git', ['ls-files', '-z'], + 'git', + ['ls-files', '-z'], workingDirectory: workingDirectory, runSilently: runSilently, ); @@ -1699,22 +2168,30 @@ Future> _gitFiles(String workingDirectory, {bool runSilently = true}) evalResult.stderr, ]); } - final List filenames = evalResult - .stdout - .split('\x00'); + final List filenames = evalResult.stdout.split('\x00'); assert(filenames.last.isEmpty); // git ls-files gives a trailing blank 0x00 filenames.removeLast(); return filenames + .where((String filename) => !filename.startsWith('engine/')) .map((String filename) => File(path.join(workingDirectory, filename))) .toList(); } -Stream _allFiles(String workingDirectory, String? extension, { required int minimumMatches }) async* { +Stream _allFiles( + String workingDirectory, + String? extension, { + required int minimumMatches, +}) async* { final Set gitFileNamesSet = {}; - gitFileNamesSet.addAll((await _gitFiles(workingDirectory)).map((File f) => path.canonicalize(f.absolute.path))); + gitFileNamesSet.addAll( + (await _gitFiles(workingDirectory)).map((File f) => path.canonicalize(f.absolute.path)), + ); - assert(extension == null || !extension.startsWith('.'), 'Extension argument should not start with a period.'); - final Set pending = { Directory(workingDirectory) }; + assert( + extension == null || !extension.startsWith('.'), + 'Extension argument should not start with a period.', + ); + final Set pending = {Directory(workingDirectory)}; int matches = 0; while (pending.isNotEmpty) { final FileSystemEntity entity = pending.first; @@ -1729,14 +2206,9 @@ Stream _allFiles(String workingDirectory, String? extension, { required in if (_isGeneratedPluginRegistrant(entity)) { continue; } - if (path.basename(entity.path) == 'flutter_export_environment.sh') { - continue; - } - if (path.basename(entity.path) == 'gradlew.bat') { - continue; - } - if (path.basename(entity.path) == '.DS_Store') { - continue; + switch (path.basename(entity.path)) { + case 'flutter_export_environment.sh' || 'gradlew.bat' || '.DS_Store': + continue; } if (extension == null || path.extension(entity.path) == '.$extension') { matches += 1; @@ -1746,36 +2218,21 @@ Stream _allFiles(String workingDirectory, String? extension, { required in if (File(path.join(entity.path, '.dartignore')).existsSync()) { continue; } - if (path.basename(entity.path) == '.git') { - continue; - } - if (path.basename(entity.path) == '.idea') { - continue; - } - if (path.basename(entity.path) == '.gradle') { - continue; - } - if (path.basename(entity.path) == '.dart_tool') { - continue; - } - if (path.basename(entity.path) == '.idea') { - continue; - } - if (path.basename(entity.path) == 'build') { - continue; + switch (path.basename(entity.path)) { + case '.git' || '.idea' || '.gradle' || '.dart_tool' || 'build': + continue; } pending.addAll(entity.listSync()); } } - assert(matches >= minimumMatches, 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.'); + assert( + matches >= minimumMatches, + 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.', + ); } class EvalResult { - EvalResult({ - required this.stdout, - required this.stderr, - this.exitCode = 0, - }); + EvalResult({required this.stdout, required this.stderr, this.exitCode = 0}); final String stdout; final String stderr; @@ -1783,13 +2240,16 @@ class EvalResult { } // TODO(ianh): Refactor this to reuse the code in run_command.dart -Future _evalCommand(String executable, List arguments, { +Future _evalCommand( + String executable, + List arguments, { required String workingDirectory, Map? environment, bool allowNonZeroExit = false, bool runSilently = false, }) async { - final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; + final String commandDescription = + '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; final String relativeWorkingDir = path.relative(workingDirectory); if (!runSilently) { @@ -1797,7 +2257,9 @@ Future _evalCommand(String executable, List arguments, { } final Stopwatch time = Stopwatch()..start(); - final Process process = await Process.start(executable, arguments, + final Process process = await Process.start( + executable, + arguments, workingDirectory: workingDirectory, environment: environment, ); @@ -1812,7 +2274,9 @@ Future _evalCommand(String executable, List arguments, { ); if (!runSilently) { - print('ELAPSED TIME: $bold${prettyPrintDuration(time.elapsed)}$reset for $commandDescription in $relativeWorkingDir'); + print( + 'ELAPSED TIME: $bold${prettyPrintDuration(time.elapsed)}$reset for $commandDescription in $relativeWorkingDir', + ); } if (exitCode != 0 && !allowNonZeroExit) { @@ -1848,16 +2312,15 @@ Future _checkConsumerDependencies() async { '--directory=${path.join(flutterRoot, 'packages', package)}', ]); if (result.exitCode != 0) { - foundError([ - result.stdout.toString(), - result.stderr.toString(), - ]); + foundError([result.stdout.toString(), result.stderr.toString()]); return; } - final Map rawJson = json.decode(result.stdout as String) as Map; + final Map rawJson = + json.decode(result.stdout as String) as Map; final Map> dependencyTree = >{ - for (final Map package in (rawJson['packages']! as List).cast>()) - package['name']! as String : package, + for (final Map package + in (rawJson['packages']! as List).cast>()) + package['name']! as String: package, }; final List> workset = >[]; workset.add(dependencyTree[package]!); @@ -1869,7 +2332,8 @@ Future _checkConsumerDependencies() async { } dependencies.add(currentPackage['name']! as String); - final List currentDependencies = (currentPackage['dependencies']! as List).cast(); + final List currentDependencies = + (currentPackage['dependencies']! as List).cast(); for (final String dependency in currentDependencies) { // Don't add dependencies we've already seen or we will get stuck // forever if there are any circular references. @@ -1910,73 +2374,133 @@ Future _checkConsumerDependencies() async { } } -const String _kDebugOnlyAnnotation = '@_debugOnly'; -final RegExp _nullInitializedField = RegExp(r'kDebugMode \? [\w<> ,{}()]+ : null;'); +class _DebugOnlyFieldVisitor extends RecursiveAstVisitor { + _DebugOnlyFieldVisitor(this.parseResult); + + final ParseStringResult parseResult; + final List errors = []; + + static const String _kDebugOnlyAnnotation = '_debugOnly'; + static final RegExp _nullInitializedField = RegExp(r'kDebugMode \? [\w<> ,{}()]+ : null;'); + + @override + void visitFieldDeclaration(FieldDeclaration node) { + super.visitFieldDeclaration(node); + if (node.metadata.any( + (Annotation annotation) => annotation.name.name == _kDebugOnlyAnnotation, + )) { + if (!node.toSource().contains(_nullInitializedField)) { + errors.add(node.fields); // Use the fields node for line number. + } + } + } +} -Future verifyNullInitializedDebugExpensiveFields(String workingDirectory, {int minimumMatches = 400}) async { +Future verifyNullInitializedDebugExpensiveFields( + String workingDirectory, { + int minimumMatches = 400, +}) async { final String flutterLib = path.join(workingDirectory, 'packages', 'flutter', 'lib'); - final List files = await _allFiles(flutterLib, 'dart', minimumMatches: minimumMatches) - .toList(); + final List files = + await _allFiles(flutterLib, 'dart', minimumMatches: minimumMatches).toList(); final List errors = []; for (final File file in files) { - final List lines = file.readAsLinesSync(); - for (int index = 0; index < lines.length; index += 1) { - final String line = lines[index]; - if (!line.contains(_kDebugOnlyAnnotation)) { - continue; - } - final String nextLine = lines[index + 1]; - if (_nullInitializedField.firstMatch(nextLine) == null) { - errors.add('${file.path}:$index'); - } + final ParseStringResult parsedFile = parseFile( + featureSet: _parsingFeatureSet(), + path: file.absolute.path, + ); + final _DebugOnlyFieldVisitor visitor = _DebugOnlyFieldVisitor(parsedFile); + visitor.visitCompilationUnit(parsedFile.unit); + for (final AstNode badNode in visitor.errors) { + errors.add( + '${file.path}:${parsedFile.lineInfo.getLocation(badNode.offset).lineNumber}: fields annotated with @_debugOnly must null initialize.', + ); } } if (errors.isNotEmpty) { foundError([ - '${bold}ERROR: ${red}fields annotated with @_debugOnly must null initialize.$reset', - 'to ensure both the field and initializer are removed from profile/release mode.', - 'These fields should be written as:\n', - 'field = kDebugMode ? : null;\n', - 'Errors were found in the following files:', ...errors, + '', + '$bold${red}Fields annotated with @_debugOnly must null initialize,$reset', + 'to ensure both the field and initializer are removed from profile/release mode.', + 'These fields should be written as:', + 'field = kDebugMode ? : null;', ]); } } final RegExp tabooPattern = RegExp(r'^ *///.*\b(simply|note:|note that)\b', caseSensitive: false); -Future verifyTabooDocumentation(String workingDirectory, { int minimumMatches = 100 }) async { +Future verifyTabooDocumentation(String workingDirectory, {int minimumMatches = 100}) async { final List errors = []; - await for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { + await for (final File file in _allFiles( + workingDirectory, + 'dart', + minimumMatches: minimumMatches, + )) { final List lines = file.readAsLinesSync(); for (int index = 0; index < lines.length; index += 1) { final String line = lines[index]; final Match? match = tabooPattern.firstMatch(line); if (match != null) { - errors.add('${file.path}:${index + 1}: Found use of the taboo word "${match.group(1)}" in documentation string.'); + errors.add( + '${file.path}:${index + 1}: Found use of the taboo word "${match.group(1)}" in documentation string.', + ); } } } if (errors.isNotEmpty) { foundError([ - '${bold}Avoid the word "simply" in documentation. See https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#use-the-passive-voice-recommend-do-not-require-never-say-things-are-simple for details.$reset', - '${bold}In many cases these words can be omitted without loss of generality; in other cases it may require a bit of rewording to avoid implying that the task is simple.$reset', - '${bold}Similarly, avoid using "note:" or the phrase "note that". See https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#avoid-empty-prose for details.$reset', ...errors, + '', + '${bold}Avoid the word "simply" in documentation. See https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#use-the-passive-voice-recommend-do-not-require-never-say-things-are-simple for details.$reset', + '${bold}In many cases these words can be omitted without loss of generality; in other cases it may require a bit of rewording to avoid implying that the task is simple.$reset', + '${bold}Similarly, avoid using "note:" or the phrase "note that". See https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#avoid-empty-prose for details.$reset', ]); } } -const List _kIgnoreList = [ - 'Runner.rc.tmpl', - 'flutter_window.cpp', -]; +Future lintKotlinFiles(String workingDirectory) async { + const String baselineRelativePath = 'dev/bots/test/analyze-test-input/ktlint-baseline.xml'; + const String editorConfigRelativePath = 'dev/bots/test/analyze-test-input/.editorconfig'; + final EvalResult lintResult = await _evalCommand('ktlint', [ + '--baseline=$flutterRoot/$baselineRelativePath', + '--editorconfig=$flutterRoot/$editorConfigRelativePath', + ], workingDirectory: workingDirectory); + if (lintResult.exitCode != 0) { + final String errorMessage = + 'Found lint violations in Kotlin files:\n ${lintResult.stdout}\n\n' + 'To reproduce this lint locally:\n' + '1. Identify the CIPD version tag used to resolve this particular version of ktlint (check the dependencies section of this shard in the ci.yaml). \n' + '2. Download that version from https://chrome-infra-packages.appspot.com/p/flutter/ktlint/linux-amd64/+/\n' + '3. From the repository root, run `/ktlint --editorconfig=$editorConfigRelativePath --baseline=$baselineRelativePath`\n' + 'Alternatively, if you use Android Studio, follow the docs at docs/platforms/android/Kotlin-android-studio-formatting.md to enable auto formatting.'; + foundError([errorMessage]); + } +} + +const List _kIgnoreList = ['Runner.rc.tmpl', 'flutter_window.cpp']; final String _kIntegrationTestsRelativePath = path.join('dev', 'integration_tests'); -final String _kTemplateRelativePath = path.join('packages', 'flutter_tools', 'templates', 'app_shared', 'windows.tmpl', 'runner'); +final String _kTemplateRelativePath = path.join( + 'packages', + 'flutter_tools', + 'templates', + 'app', + 'windows.tmpl', + 'runner', +); final String _kWindowsRunnerSubPath = path.join('windows', 'runner'); const String _kProjectNameKey = '{{projectName}}'; const String _kTmplExt = '.tmpl'; -final String _kLicensePath = path.join('dev', 'conductor', 'core', 'lib', 'src', 'proto', 'license_header.txt'); +final String _kLicensePath = path.join( + 'dev', + 'conductor', + 'core', + 'lib', + 'src', + 'proto', + 'license_header.txt', +); String _getFlutterLicense(String flutterRoot) { return '${File(path.join(flutterRoot, _kLicensePath)).readAsLinesSync().join("\n")}\n\n'; @@ -1994,7 +2518,8 @@ Future verifyIntegrationTestTemplateFiles(String flutterRoot) async { final String license = _getFlutterLicense(flutterRoot); final String integrationTestsPath = path.join(flutterRoot, _kIntegrationTestsRelativePath); final String templatePath = path.join(flutterRoot, _kTemplateRelativePath); - final IterablesubDirs = Directory(integrationTestsPath).listSync().toList().whereType(); + final Iterable subDirs = + Directory(integrationTestsPath).listSync().toList().whereType(); for (final Directory testPath in subDirs) { final String projectName = path.basename(testPath.path); final String runnerPath = path.join(testPath.path, _kWindowsRunnerSubPath); @@ -2011,15 +2536,27 @@ Future verifyIntegrationTestTemplateFiles(String flutterRoot) async { String templateFileContents = templateFile.readAsLinesSync().join('\n'); String appFilePath = path.join(runnerPath, fileName); if (fileName.endsWith(_kTmplExt)) { - appFilePath = appFilePath.substring(0, appFilePath.length - _kTmplExt.length); // Remove '.tmpl' from app file path - templateFileContents = templateFileContents.replaceAll(_kProjectNameKey, projectName); // Substitute template project name + appFilePath = appFilePath.substring( + 0, + appFilePath.length - _kTmplExt.length, + ); // Remove '.tmpl' from app file path + templateFileContents = templateFileContents.replaceAll( + _kProjectNameKey, + projectName, + ); // Substitute template project name } String appFileContents = File(appFilePath).readAsLinesSync().join('\n'); appFileContents = _removeLicenseIfPresent(appFileContents, license); if (appFileContents != templateFileContents) { int indexOfDifference; - for (indexOfDifference = 0; indexOfDifference < appFileContents.length; indexOfDifference++) { - if (indexOfDifference >= templateFileContents.length || templateFileContents.codeUnitAt(indexOfDifference) != appFileContents.codeUnitAt(indexOfDifference)) { + for ( + indexOfDifference = 0; + indexOfDifference < appFileContents.length; + indexOfDifference++ + ) { + if (indexOfDifference >= templateFileContents.length || + templateFileContents.codeUnitAt(indexOfDifference) != + appFileContents.codeUnitAt(indexOfDifference)) { break; } } @@ -2042,7 +2579,8 @@ Diff at character #$indexOfDifference } } -Future _runFlutterAnalyze(String workingDirectory, { +Future _runFlutterAnalyze( + String workingDirectory, { List options = const [], String? failureMessage, }) async { @@ -2058,9 +2596,10 @@ Future _runFlutterAnalyze(String workingDirectory, { const Set kExecutableAllowlist = { 'bin/dart', 'bin/flutter', + 'bin/flutter-dev', 'bin/internal/update_dart_sdk.sh', + 'bin/internal/update_engine_version.sh', - 'dev/bots/accept_android_sdk_licenses.sh', 'dev/bots/codelabs_build_test.sh', 'dev/bots/docs.sh', @@ -2079,6 +2618,9 @@ const Set kExecutableAllowlist = { 'dev/tools/gen_keycodes/bin/gen_keycodes', 'dev/tools/repackage_gradle_wrapper.sh', + 'dev/tools/bin/engine_hash.sh', + 'dev/tools/format.sh', + 'dev/tools/test/mock_git.sh', 'packages/flutter_tools/bin/macos_assemble.sh', 'packages/flutter_tools/bin/tool_backend.sh', @@ -2091,10 +2633,7 @@ Future _checkForNewExecutables() async { final List files = await _gitFiles(flutterRoot); final List errors = []; for (final File file in files) { - final String relativePath = path.relative( - file.path, - from: flutterRoot, - ); + final String relativePath = path.relative(file.path, from: flutterRoot); final FileStat stat = file.statSync(); final bool isExecutable = stat.mode & executableBitMask != 0x0; if (isExecutable && !kExecutableAllowlist.contains(relativePath)) { @@ -2114,35 +2653,39 @@ Future _checkForNewExecutables() async { final RegExp _importPattern = RegExp(r'''^\s*import (['"])package:flutter/([^.]+)\.dart\1'''); final RegExp _importMetaPattern = RegExp(r'''^\s*import (['"])package:meta/meta\.dart\1'''); -Future> _findFlutterDependencies(String srcPath, List errors, { bool checkForMeta = false }) async { +Future> _findFlutterDependencies( + String srcPath, + List errors, { + bool checkForMeta = false, +}) async { return _allFiles(srcPath, 'dart', minimumMatches: 1) - .map>((File file) { - final Set result = {}; - for (final String line in file.readAsLinesSync()) { - Match? match = _importPattern.firstMatch(line); - if (match != null) { - result.add(match.group(2)!); - } - if (checkForMeta) { - match = _importMetaPattern.firstMatch(line); + .map>((File file) { + final Set result = {}; + for (final String line in file.readAsLinesSync()) { + Match? match = _importPattern.firstMatch(line); if (match != null) { - errors.add( - '${file.path}\nThis package imports the ${yellow}meta$reset package.\n' - 'You should instead import the "foundation.dart" library.' - ); + result.add(match.group(2)!); + } + if (checkForMeta) { + match = _importMetaPattern.firstMatch(line); + if (match != null) { + errors.add( + '${file.path}\nThis package imports the ${yellow}meta$reset package.\n' + 'You should instead import the "foundation.dart" library.', + ); + } } } - } - return result; - }) - .reduce((Set? value, Set element) { - value ??= {}; - value.addAll(element); - return value; - }); + return result; + }) + .reduce((Set? value, Set element) { + value ??= {}; + value.addAll(element); + return value; + }); } -List? _deepSearch(Map> map, T start, [ Set? seen ]) { +List? _deepSearch(Map> map, T start, [Set? seen]) { if (map[start] == null) { return null; // We catch these separately. } @@ -2154,14 +2697,10 @@ List? _deepSearch(Map> map, T start, [ Set? seen ]) { if (seen != null && seen.contains(key)) { return [start, key]; } - final List? result = _deepSearch( - map, + final List? result = _deepSearch(map, key, { + if (seen == null) start else ...seen, key, - { - if (seen == null) start else ...seen, - key, - }, - ); + }); if (result != null) { result.insert(0, start); // Only report the shortest chains. @@ -2178,8 +2717,8 @@ List? _deepSearch(Map> map, T start, [ Set? seen ]) { bool _isGeneratedPluginRegistrant(File file) { final String filename = path.basename(file.path); - return !file.path.contains('.pub-cache') - && (filename == 'GeneratedPluginRegistrant.java' || + return !file.path.contains('.pub-cache') && + (filename == 'GeneratedPluginRegistrant.java' || filename == 'GeneratedPluginRegistrant.swift' || filename == 'GeneratedPluginRegistrant.h' || filename == 'GeneratedPluginRegistrant.m' || diff --git a/flutter/dev/bots/analyze_snippet_code.dart b/flutter/dev/bots/analyze_snippet_code.dart index 924ae2a03efb5556998a02ec550bd6cbbd083a3d..af8b18614462128a6a952210713a851953585901 100644 --- a/flutter/dev/bots/analyze_snippet_code.dart +++ b/flutter/dev/bots/analyze_snippet_code.dart @@ -9,7 +9,7 @@ // // For documentation on creating sample code, see ../../examples/api/README.md // See also our style guide's discussion on documentation and sample code: -// https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#documentation-dartdocs-javadocs-etc +// https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md // // This tool is used to analyze smaller snippets of code in the API docs. // Such snippets are wrapped in ```dart ... ``` blocks, which may themselves @@ -78,12 +78,27 @@ import 'package:watcher/watcher.dart'; final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); final String _packageFlutter = path.join(_flutterRoot, 'packages', 'flutter', 'lib'); -final String _defaultDartUiLocation = path.join(_flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui'); -final String _flutter = path.join(_flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'); +final String _defaultDartUiLocation = path.join( + _flutterRoot, + 'bin', + 'cache', + 'pkg', + 'sky_engine', + 'lib', + 'ui', +); +final String _flutter = path.join( + _flutterRoot, + 'bin', + Platform.isWindows ? 'flutter.bat' : 'flutter', +); Future main(List arguments) async { bool asserts = false; - assert(() { asserts = true; return true; }()); + assert(() { + asserts = true; + return true; + }()); if (!asserts) { print('You must run this script with asserts enabled.'); exit(1); @@ -98,9 +113,10 @@ Future main(List arguments) async { argParser.addOption( 'temp', valueHelp: 'path', - help: 'A location where temporary files may be written. Defaults to a ' - 'directory in the system temp folder. If specified, will not be ' - 'automatically removed at the end of execution.', + help: + 'A location where temporary files may be written. Defaults to a ' + 'directory in the system temp folder. If specified, will not be ' + 'automatically removed at the end of execution.', ); argParser.addFlag( 'verbose', @@ -111,21 +127,18 @@ Future main(List arguments) async { 'dart-ui-location', defaultsTo: _defaultDartUiLocation, valueHelp: 'path', - help: 'A location where the dart:ui dart files are to be found. Defaults to ' - 'the sky_engine directory installed in this flutter repo. This ' - 'is typically the engine/src/flutter/lib/ui directory in an engine dev setup. ' - 'Implies --include-dart-ui.', + help: + 'A location where the dart:ui dart files are to be found. Defaults to ' + 'the sky_engine directory installed in this flutter repo. This ' + 'is typically the engine/src/flutter/lib/ui directory in an engine dev setup. ' + 'Implies --include-dart-ui.', ); argParser.addFlag( 'include-dart-ui', defaultsTo: true, help: 'Includes the dart:ui code supplied by the engine in the analysis.', ); - argParser.addFlag( - 'help', - negatable: false, - help: 'Print help for this command.', - ); + argParser.addFlag('help', negatable: false, help: 'Print help for this command.'); argParser.addOption( 'interactive', abbr: 'i', @@ -173,11 +186,11 @@ Future main(List arguments) async { assert(flutterPackages.length >= 4); } - final bool includeDartUi = parsedArguments.wasParsed('dart-ui-location') || parsedArguments['include-dart-ui'] as bool; + final bool includeDartUi = + parsedArguments.wasParsed('dart-ui-location') || parsedArguments['include-dart-ui'] as bool; late Directory dartUiLocation; if (((parsedArguments['dart-ui-location'] ?? '') as String).isNotEmpty) { - dartUiLocation = Directory( - path.absolute(parsedArguments['dart-ui-location'] as String)); + dartUiLocation = Directory(path.absolute(parsedArguments['dart-ui-location'] as String)); } else { dartUiLocation = Directory(_defaultDartUiLocation); } @@ -195,12 +208,14 @@ Future main(List arguments) async { ); } else { if (await _SnippetChecker( - flutterPackages, - tempDirectory: parsedArguments['temp'] as String?, - verbose: parsedArguments['verbose'] as bool, - dartUiLocation: includeDartUi ? dartUiLocation : null, - ).checkSnippets()) { - stderr.writeln('See the documentation at the top of dev/bots/analyze_snippet_code.dart for details.'); + flutterPackages, + tempDirectory: parsedArguments['temp'] as String?, + verbose: parsedArguments['verbose'] as bool, + dartUiLocation: includeDartUi ? dartUiLocation : null, + ).checkSnippets()) { + stderr.writeln( + 'See the documentation at the top of dev/bots/analyze_snippet_code.dart for details.', + ); exit(1); } } @@ -209,12 +224,8 @@ Future main(List arguments) async { /// A class to represent a line of input code. @immutable class _Line { - const _Line({this.code = '', this.line = -1, this.indent = 0}) - : generated = false; - const _Line.generated({this.code = ''}) - : line = -1, - indent = 0, - generated = true; + const _Line({this.code = '', this.line = -1, this.indent = 0}) : generated = false; + const _Line.generated({this.code = ''}) : line = -1, indent = 0, generated = true; final int line; final int indent; @@ -233,11 +244,11 @@ class _Line { if (other.runtimeType != runtimeType) { return false; } - return other is _Line - && other.line == line - && other.indent == indent - && other.code == code - && other.generated == generated; + return other is _Line && + other.line == line && + other.indent == indent && + other.code == code && + other.generated == generated; } @override @@ -307,10 +318,10 @@ class _SnippetCheckerException extends _ErrorBase implements Exception { if (other.runtimeType != runtimeType) { return false; } - return other is _SnippetCheckerException - && other.message == message - && other.file == file - && other.line == line; + return other is _SnippetCheckerException && + other.message == message && + other.file == file && + other.line == line; } @override @@ -322,14 +333,8 @@ class _SnippetCheckerException extends _ErrorBase implements Exception { /// Changes how it converts to a string based on the source of the error. @immutable class _AnalysisError extends _ErrorBase { - const _AnalysisError( - String file, - int line, - int column, - this.message, - this.errorCode, - this.source, - ) : super(file: file, line: line, column: column); + const _AnalysisError(String file, int line, int column, this.message, this.errorCode, this.source) + : super(file: file, line: line, column: column); final String message; final String errorCode; @@ -345,13 +350,13 @@ class _AnalysisError extends _ErrorBase { if (other.runtimeType != runtimeType) { return false; } - return other is _AnalysisError - && other.file == file - && other.line == line - && other.column == column - && other.message == message - && other.errorCode == errorCode - && other.source == source; + return other is _AnalysisError && + other.file == file && + other.line == line && + other.column == column && + other.message == message && + other.errorCode == errorCode && + other.source == source; } @override @@ -419,16 +424,22 @@ class _SnippetChecker { static final RegExp _nonCodeRegExp = RegExp(r'^ *(//|@)'); /// A RegExp that matches things that look like a function declaration. - static final RegExp _maybeFunctionDeclarationRegExp = RegExp(r'^([A-Z][A-Za-z0-9_<>, ?]*|int|double|num|bool|void)\?? (_?[a-z][A-Za-z0-9_<>]*)\(.*'); + static final RegExp _maybeFunctionDeclarationRegExp = RegExp( + r'^([A-Z][A-Za-z0-9_<>, ?]*|int|double|num|bool|void)\?? (_?[a-z][A-Za-z0-9_<>]*)\(.*', + ); /// A RegExp that matches things that look like a getter. - static final RegExp _maybeGetterDeclarationRegExp = RegExp(r'^([A-Z][A-Za-z0-9_<>?]*|int|double|num|bool)\?? get (_?[a-z][A-Za-z0-9_<>]*) (?:=>|{).*'); + static final RegExp _maybeGetterDeclarationRegExp = RegExp( + r'^([A-Z][A-Za-z0-9_<>?]*|int|double|num|bool)\?? get (_?[a-z][A-Za-z0-9_<>]*) (?:=>|{).*', + ); /// A RegExp that matches an identifier followed by a colon, potentially with two spaces of indent. static final RegExp _namedArgumentRegExp = RegExp(r'^(?: )?([a-zA-Z0-9_]+): '); /// A RegExp that matches things that look unambiguously like top-level declarations. - static final RegExp _topLevelDeclarationRegExp = RegExp(r'^(abstract|class|mixin|enum|typedef|final|extension) '); + static final RegExp _topLevelDeclarationRegExp = RegExp( + r'^(abstract|class|mixin|enum|typedef|final|extension) ', + ); /// A RegExp that matches things that look unambiguously like statements. static final RegExp _statementRegExp = RegExp(r'^(if|while|for|try) '); @@ -472,7 +483,11 @@ class _SnippetChecker { final Directory? _dartUiLocation; static List _listDartFiles(Directory directory, {bool recursive = false}) { - return directory.listSync(recursive: recursive, followLinks: false).whereType().where((File file) => path.extension(file.path) == '.dart').toList(); + return directory + .listSync(recursive: recursive, followLinks: false) + .whereType() + .where((File file) => path.extension(file.path) == '.dart') + .toList(); } static const List ignoresDirectives = [ @@ -489,26 +504,30 @@ class _SnippetChecker { /// Computes the headers needed for each snippet file. List<_Line> get headersWithoutImports { - return _headersWithoutImports ??= ignoresDirectives.map<_Line>((String code) => _Line.generated(code: code)).toList(); + return _headersWithoutImports ??= + ignoresDirectives.map<_Line>((String code) => _Line.generated(code: code)).toList(); } + List<_Line>? _headersWithoutImports; /// Computes the headers needed for each snippet file. List<_Line> get headersWithImports { - return _headersWithImports ??= [ - ...ignoresDirectives, - '// ignore_for_file: unused_import', - "import 'dart:async';", - "import 'dart:convert';", - "import 'dart:io';", - "import 'dart:math' as math;", - "import 'dart:typed_data';", - "import 'dart:ui' as ui;", - "import 'package:flutter_test/flutter_test.dart';", - for (final File file in _listDartFiles(Directory(_packageFlutter))) - "import 'package:flutter/${path.basename(file.path)}';", - ].map<_Line>((String code) => _Line.generated(code: code)).toList(); + return _headersWithImports ??= + [ + ...ignoresDirectives, + '// ignore_for_file: unused_import', + "import 'dart:async';", + "import 'dart:convert';", + "import 'dart:io';", + "import 'dart:math' as math;", + "import 'dart:typed_data';", + "import 'dart:ui' as ui;", + "import 'package:flutter_test/flutter_test.dart';", + for (final File file in _listDartFiles(Directory(_packageFlutter))) + "import 'package:flutter/${path.basename(file.path)}';", + ].map<_Line>((String code) => _Line.generated(code: code)).toList(); } + List<_Line>? _headersWithImports; /// Checks all the snippets in the Dart files in [_flutterPackage] for errors. @@ -535,9 +554,13 @@ class _SnippetChecker { static Directory _createTempDirectory(String? tempArg) { if (tempArg != null) { - final Directory tempDirectory = Directory(path.join(Directory.systemTemp.absolute.path, path.basename(tempArg))); + final Directory tempDirectory = Directory( + path.join(Directory.systemTemp.absolute.path, path.basename(tempArg)), + ); if (path.basename(tempArg) != tempArg) { - stderr.writeln('Supplied temporary directory name should be a name, not a path. Using ${tempDirectory.absolute.path} instead.'); + stderr.writeln( + 'Supplied temporary directory name should be a name, not a path. Using ${tempDirectory.absolute.path} instead.', + ); } print('Leaving temporary output in ${tempDirectory.absolute.path}.'); // Make sure that any directory left around from a previous run is cleared out. @@ -591,7 +614,8 @@ class _SnippetChecker { final List<_Line> ignorePreambleLinesOnly = <_Line>[]; final List<_Line> preambleLines = <_Line>[]; final List<_Line> customImports = <_Line>[]; - bool inExamplesCanAssumePreamble = false; // Whether or not we're in the file-wide preamble section ("Examples can assume"). + bool inExamplesCanAssumePreamble = + false; // Whether or not we're in the file-wide preamble section ("Examples can assume"). bool inToolSection = false; // Whether or not we're in a code snippet bool inDartSection = false; // Whether or not we're in a '```dart' segment. bool inOtherBlock = false; // Whether we're in some other '```' segment. @@ -606,11 +630,15 @@ class _SnippetChecker { // end of preamble inExamplesCanAssumePreamble = false; } else if (!line.startsWith('// ')) { - throw _SnippetCheckerException('Unexpected content in snippet code preamble.', file: relativeFilePath, line: lineNumber); + throw _SnippetCheckerException( + 'Unexpected content in snippet code preamble.', + file: relativeFilePath, + line: lineNumber, + ); } else { final _Line newLine = _Line(line: lineNumber, indent: 3, code: line.substring(3)); if (newLine.code.startsWith('import ')) { - customImports.add(newLine); + customImports.add(newLine); } else { preambleLines.add(newLine); } @@ -620,20 +648,40 @@ class _SnippetChecker { } } else if (trimmedLine.startsWith(_dartDocSnippetEndRegex)) { if (!inToolSection) { - throw _SnippetCheckerException('{@tool-end} marker detected without matching {@tool}.', file: relativeFilePath, line: lineNumber); + throw _SnippetCheckerException( + '{@tool-end} marker detected without matching {@tool}.', + file: relativeFilePath, + line: lineNumber, + ); } if (inDartSection) { - throw _SnippetCheckerException("Dart section didn't terminate before end of snippet", file: relativeFilePath, line: lineNumber); + throw _SnippetCheckerException( + "Dart section didn't terminate before end of snippet", + file: relativeFilePath, + line: lineNumber, + ); } inToolSection = false; } else if (inDartSection) { final RegExpMatch? snippetMatch = _dartDocSnippetBeginRegex.firstMatch(trimmedLine); if (snippetMatch != null) { - throw _SnippetCheckerException('{@tool} found inside Dart section', file: relativeFilePath, line: lineNumber); + throw _SnippetCheckerException( + '{@tool} found inside Dart section', + file: relativeFilePath, + line: lineNumber, + ); } if (trimmedLine.startsWith(_codeBlockEndRegex)) { inDartSection = false; - final _SnippetFile snippet = _processBlock(startLine, block, preambleLines, ignorePreambleLinesOnly, relativeFilePath, lastExample, customImports); + final _SnippetFile snippet = _processBlock( + startLine, + block, + preambleLines, + ignorePreambleLinesOnly, + relativeFilePath, + lastExample, + customImports, + ); final String path = _writeSnippetFile(snippet).path; assert(!snippetMap.containsKey(path)); snippetMap[path] = snippet; @@ -670,14 +718,15 @@ class _SnippetChecker { if (inOtherBlock) { inOtherBlock = false; } else if (line.contains('```yaml') || - line.contains('```ascii') || - line.contains('```java') || - line.contains('```objectivec') || - line.contains('```kotlin') || - line.contains('```swift') || - line.contains('```glsl') || - line.contains('```json') || - line.contains('```csv')) { + line.contains('```ascii') || + line.contains('```java') || + line.contains('```objectivec') || + line.contains('```kotlin') || + line.contains('```swift') || + line.contains('```glsl') || + line.contains('```json') || + line.contains('```csv') || + line.contains('```sh')) { inOtherBlock = true; } else if (line.startsWith(_uncheckedCodeBlockStartRegex)) { // this is an intentionally-unchecked block that doesn't appear in the API docs. @@ -716,15 +765,26 @@ class _SnippetChecker { /// a primitive heuristic to make snippet blocks into valid Dart code. /// /// `block` argument will get mutated, but is copied before this function returns. - _SnippetFile _processBlock(_Line startingLine, List block, List<_Line> assumptions, List<_Line> ignoreAssumptionsOnly, String filename, _SnippetFile? lastExample, List<_Line> customImports) { + _SnippetFile _processBlock( + _Line startingLine, + List block, + List<_Line> assumptions, + List<_Line> ignoreAssumptionsOnly, + String filename, + _SnippetFile? lastExample, + List<_Line> customImports, + ) { if (block.isEmpty) { - throw _SnippetCheckerException('${startingLine.asLocation(filename, 0)}: Empty ```dart block in snippet code.'); + throw _SnippetCheckerException( + '${startingLine.asLocation(filename, 0)}: Empty ```dart block in snippet code.', + ); } bool hasEllipsis = false; for (int index = 0; index < block.length; index += 1) { final Match? match = _ellipsisRegExp.matchAsPrefix(block[index]); if (match != null) { - hasEllipsis = true; // in case the "..." is implying some overridden members, add an ignore to silence relevant warnings + hasEllipsis = + true; // in case the "..." is implying some overridden members, add an ignore to silence relevant warnings break; } } @@ -734,15 +794,27 @@ class _SnippetChecker { for (final String line in block) { if (line == '// (e.g. in a stateful widget)') { if (hasStatefulWidgetComment) { - throw _SnippetCheckerException('Example says it is in a stateful widget twice.', file: filename, line: index); + throw _SnippetCheckerException( + 'Example says it is in a stateful widget twice.', + file: filename, + line: index, + ); } hasStatefulWidgetComment = true; } else if (line == '// continuing from previous example...') { if (importPreviousExample) { - throw _SnippetCheckerException('Example says it continues from the previous example twice.', file: filename, line: index); + throw _SnippetCheckerException( + 'Example says it continues from the previous example twice.', + file: filename, + line: index, + ); } if (lastExample == null) { - throw _SnippetCheckerException('Example says it continues from the previous example but it is the first example in the file.', file: filename, line: index); + throw _SnippetCheckerException( + 'Example says it continues from the previous example but it is the first example in the file.', + file: filename, + line: index, + ); } importPreviousExample = true; } else { @@ -755,24 +827,38 @@ class _SnippetChecker { preamble = <_Line>[ ...lastExample!.code, // includes assumptions if (hasEllipsis || hasStatefulWidgetComment) - const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), + const _Line.generated( + code: '// ignore_for_file: non_abstract_class_inherits_abstract_member', + ), ]; } else { preamble = <_Line>[ if (hasEllipsis || hasStatefulWidgetComment) - const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), + const _Line.generated( + code: '// ignore_for_file: non_abstract_class_inherits_abstract_member', + ), ...assumptions, ]; } - final String firstCodeLine = block.firstWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); - final String lastCodeLine = block.lastWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); + final String firstCodeLine = + block.firstWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); + final String lastCodeLine = + block.lastWhere((String line) => !line.startsWith(_nonCodeRegExp)).trim(); if (firstCodeLine.startsWith('import ')) { // probably an entire program if (importPreviousExample) { - throw _SnippetCheckerException('An example cannot both be self-contained (with its own imports) and say it wants to import the previous example.', file: filename, line: startingLine.line); + throw _SnippetCheckerException( + 'An example cannot both be self-contained (with its own imports) and say it wants to import the previous example.', + file: filename, + line: startingLine.line, + ); } if (hasStatefulWidgetComment) { - throw _SnippetCheckerException('An example cannot both be self-contained (with its own imports) and say it is in a stateful widget.', file: filename, line: startingLine.line); + throw _SnippetCheckerException( + 'An example cannot both be self-contained (with its own imports) and say it is in a stateful widget.', + file: filename, + line: startingLine.line, + ); } return _SnippetFile.fromStrings( startingLine, @@ -781,7 +867,9 @@ class _SnippetChecker { <_Line>[ ...ignoreAssumptionsOnly, if (hasEllipsis) - const _Line.generated(code: '// ignore_for_file: non_abstract_class_inherits_abstract_member'), + const _Line.generated( + code: '// ignore_for_file: non_abstract_class_inherits_abstract_member', + ), ], 'self-contained program', filename, @@ -795,7 +883,7 @@ class _SnippetChecker { ...headersWithoutImports, const _Line.generated(code: '// ignore_for_file: unused_import'), ...customImports, - ] + ], }; if (hasStatefulWidgetComment) { return _SnippetFile.fromStrings( @@ -809,8 +897,9 @@ class _SnippetChecker { filename, ); } else if (firstCodeLine.startsWith(_maybeGetterDeclarationRegExp) || - (firstCodeLine.startsWith(_maybeFunctionDeclarationRegExp) && lastCodeLine.startsWith(_trailingCloseBraceRegExp)) || - block.any((String line) => line.startsWith(_topLevelDeclarationRegExp))) { + (firstCodeLine.startsWith(_maybeFunctionDeclarationRegExp) && + lastCodeLine.startsWith(_trailingCloseBraceRegExp)) || + block.any((String line) => line.startsWith(_topLevelDeclarationRegExp))) { // probably a top-level declaration return _SnippetFile.fromStrings( startingLine, @@ -821,7 +910,7 @@ class _SnippetChecker { filename, ); } else if (lastCodeLine.startsWith(_trailingSemicolonRegExp) || - block.any((String line) => line.startsWith(_statementRegExp))) { + block.any((String line) => line.startsWith(_statementRegExp))) { // probably a statement return _SnippetFile.fromStrings( startingLine, @@ -902,10 +991,14 @@ class _SnippetChecker { } sourcePubSpec.copySync(targetPubSpec.path); } - final File targetAnalysisOptions = File(path.join(_tempDirectory.path, 'analysis_options.yaml')); + final File targetAnalysisOptions = File( + path.join(_tempDirectory.path, 'analysis_options.yaml'), + ); if (!targetAnalysisOptions.existsSync()) { // Use the same analysis_options.yaml configuration that's used for examples/api. - final File sourceAnalysisOptions = File(path.join(_flutterRoot, 'examples', 'api', 'analysis_options.yaml')); + final File sourceAnalysisOptions = File( + path.join(_flutterRoot, 'examples', 'api', 'analysis_options.yaml'), + ); if (!sourceAnalysisOptions.existsSync()) { throw 'Cannot find analysis_options.yaml at ${sourceAnalysisOptions.path}, which is also used to analyze code snippets.'; } @@ -917,9 +1010,15 @@ class _SnippetChecker { /// Writes out a snippet section to the disk and returns the file. File _writeSnippetFile(_SnippetFile snippetFile) { - final String snippetFileId = _createNameFromSource('snippet', snippetFile.filename, snippetFile.indexLine); - final File outputFile = File(path.join(_tempDirectory.path, '$snippetFileId.dart'))..createSync(recursive: true); - final String contents = snippetFile.code.map((_Line line) => line.code).join('\n').trimRight(); + final String snippetFileId = _createNameFromSource( + 'snippet', + snippetFile.filename, + snippetFile.indexLine, + ); + final File outputFile = File(path.join(_tempDirectory.path, '$snippetFileId.dart')) + ..createSync(recursive: true); + final String contents = + snippetFile.code.map((_Line line) => line.code).join('\n').trimRight(); outputFile.writeAsStringSync('$contents\n'); return outputFile; } @@ -955,33 +1054,45 @@ class _SnippetChecker { final int columnNumber = int.parse(columnString, radix: 10); if (lineNumber < 1 || lineNumber > fileContents.length + 1) { - errors.add(_AnalysisError( - file.path, - lineNumber, - columnNumber, - message, - errorCode, - _Line(line: lineNumber), - )); - errors.add(_SnippetCheckerException('Error message points to non-existent line number: $error', file: file.path, line: lineNumber)); + errors.add( + _AnalysisError( + file.path, + lineNumber, + columnNumber, + message, + errorCode, + _Line(line: lineNumber), + ), + ); + errors.add( + _SnippetCheckerException( + 'Error message points to non-existent line number: $error', + file: file.path, + line: lineNumber, + ), + ); continue; } final _SnippetFile? snippet = snippets[file.path]; if (snippet == null) { - errors.add(_SnippetCheckerException( - "Unknown section for ${file.path}. Maybe the temporary directory wasn't empty?", - file: file.path, - line: lineNumber, - )); + errors.add( + _SnippetCheckerException( + "Unknown section for ${file.path}. Maybe the temporary directory wasn't empty?", + file: file.path, + line: lineNumber, + ), + ); continue; } if (fileContents.length != snippet.code.length) { - errors.add(_SnippetCheckerException( - 'Unexpected file contents for ${file.path}. File has ${fileContents.length} lines but we generated ${snippet.code.length} lines:\n${snippet.code.join("\n")}', - file: file.path, - line: lineNumber, - )); + errors.add( + _SnippetCheckerException( + 'Unexpected file contents for ${file.path}. File has ${fileContents.length} lines but we generated ${snippet.code.length} lines:\n${snippet.code.join("\n")}', + file: file.path, + line: lineNumber, + ), + ); continue; } @@ -992,14 +1103,18 @@ class _SnippetChecker { int delta = 0; while (true) { // find the nearest non-generated line to the error - if ((lineNumber - delta > 0) && (lineNumber - delta <= snippet.code.length) && !snippet.code[lineNumber - delta - 1].generated) { + if ((lineNumber - delta > 0) && + (lineNumber - delta <= snippet.code.length) && + !snippet.code[lineNumber - delta - 1].generated) { actualSource = snippet.code[lineNumber - delta - 1]; actualLine = actualSource.line; actualColumn = delta == 0 ? columnNumber : actualSource.code.length + 1; actualMessage = delta == 0 ? message : '$message -- in later generated code'; break; } - if ((lineNumber + delta < snippet.code.length) && (lineNumber + delta >= 0) && !snippet.code[lineNumber + delta].generated) { + if ((lineNumber + delta < snippet.code.length) && + (lineNumber + delta >= 0) && + !snippet.code[lineNumber + delta].generated) { actualSource = snippet.code[lineNumber + delta]; actualLine = actualSource.line; actualColumn = 1; @@ -1009,14 +1124,16 @@ class _SnippetChecker { delta += 1; assert((lineNumber - delta > 0) || (lineNumber + delta < snippet.code.length)); } - errors.add(_AnalysisError( - snippet.filename, - actualLine, - actualColumn, - '$actualMessage (${snippet.generatorComment})', - errorCode, - actualSource, - )); + errors.add( + _AnalysisError( + snippet.filename, + actualLine, + actualColumn, + '$actualMessage (${snippet.generatorComment})', + errorCode, + actualSource, + ), + ); } return errors; } @@ -1026,23 +1143,24 @@ class _SnippetChecker { _createConfigurationFiles(); // Run pub get to avoid output from getting dependencies in the analyzer // output. - Process.runSync( - _flutter, - ['pub', 'get'], - workingDirectory: _tempDirectory.absolute.path, - ); - final ProcessResult result = Process.runSync( - _flutter, - ['--no-wrap', 'analyze', '--no-preamble', '--no-congratulate', '.'], - workingDirectory: _tempDirectory.absolute.path, - ); + Process.runSync(_flutter, [ + 'pub', + 'get', + ], workingDirectory: _tempDirectory.absolute.path); + final ProcessResult result = Process.runSync(_flutter, [ + '--no-wrap', + 'analyze', + '--no-preamble', + '--no-congratulate', + '.', + ], workingDirectory: _tempDirectory.absolute.path); final List stderr = result.stderr.toString().trim().split('\n'); final List stdout = result.stdout.toString().trim().split('\n'); // Remove output from building the flutter tool. stderr.removeWhere((String line) { - return line.startsWith('Building flutter tool...') - || line.startsWith('Waiting for another flutter command to release the startup lock...') - || line.startsWith('Flutter assets will be downloaded from '); + return line.startsWith('Building flutter tool...') || + line.startsWith('Waiting for another flutter command to release the startup lock...') || + line.startsWith('Flutter assets will be downloaded from '); }); // Check out the stderr to see if the analyzer had it's own issues. if (stderr.isNotEmpty && stderr.first.contains(RegExp(r' issues? found\. \(ran in '))) { @@ -1085,10 +1203,8 @@ class _SnippetFile { <_Line>[ ...headers, const _Line.generated(), // blank line - if (preamble.isNotEmpty) - ...preamble, - if (preamble.isNotEmpty) - const _Line.generated(), // blank line + if (preamble.isNotEmpty) ...preamble, + if (preamble.isNotEmpty) const _Line.generated(), // blank line _Line.generated(code: '// From: $filename:${firstLine.line}'), ...code, ], @@ -1105,15 +1221,14 @@ class _SnippetFile { List<_Line> preamble, String generatorComment, String filename, { - String? prefix, String? postfix, + String? prefix, + String? postfix, }) { final List<_Line> codeLines = <_Line>[ - if (prefix != null) - _Line.generated(code: prefix), + if (prefix != null) _Line.generated(code: prefix), for (int i = 0; i < code.length; i += 1) _Line(code: code[i], line: firstLine.line + i, indent: firstLine.indent), - if (postfix != null) - _Line.generated(code: postfix), + if (postfix != null) _Line.generated(code: postfix), ]; return _SnippetFile.fromLines(codeLines, headers, preamble, generatorComment, filename); } @@ -1140,7 +1255,7 @@ Future _runInteractive({ (dartUiLocation == null || !path.isWithin(dartUiLocation.path, file.absolute.path))) { stderr.writeln( 'Specified file ${file.absolute.path} is not within the flutter root: ' - "$_flutterRoot${dartUiLocation != null ? ' or the dart:ui location: $dartUiLocation' : ''}" + "$_flutterRoot${dartUiLocation != null ? ' or the dart:ui location: $dartUiLocation' : ''}", ); exit(1); } @@ -1178,6 +1293,7 @@ Future _runInteractive({ busy = false; } } + await rerun(); stdin.lineMode = false; @@ -1187,10 +1303,8 @@ Future _runInteractive({ case 'q': checker.cleanupTempDirectory(); exit(0); - case 'r': - if (!busy) { - rerun(); - } + case 'r' when !busy: + rerun(); } }); Watcher(file.absolute.path).events.listen((_) => rerun()); diff --git a/flutter/dev/bots/browser.dart b/flutter/dev/bots/browser.dart index b650d8153c5d76e5e3850a30a71def1114a6a207..7484b56da32017456c3691b1516522430500a780 100644 --- a/flutter/dev/bots/browser.dart +++ b/flutter/dev/bots/browser.dart @@ -31,24 +31,29 @@ Future evalTestAppInChrome({ final Completer resultCompleter = Completer(); server = await io.HttpServer.bind('localhost', serverPort); final Cascade cascade = Cascade() - .add((Request request) async { - if (request.requestedUri.path.endsWith('/test-result')) { - resultCompleter.complete(await request.readAsString()); - return Response.ok('Test results received'); - } - return Response.notFound(''); - }) - .add(createStaticHandler(appDirectory)); + .add((Request request) async { + if (request.requestedUri.path.endsWith('/test-result')) { + resultCompleter.complete(await request.readAsString()); + return Response.ok('Test results received'); + } + return Response.notFound(''); + }) + .add(createStaticHandler(appDirectory)); shelf_io.serveRequests(server, cascade.handler); - final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync('flutter_chrome_user_data.'); - chrome = await Chrome.launch(ChromeOptions( - headless: true, - debugPort: browserDebugPort, - url: appUrl, - userDataDirectory: userDataDirectory.path, - windowHeight: 500, - windowWidth: 500, - ), onError: resultCompleter.completeError); + final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync( + 'flutter_chrome_user_data.', + ); + chrome = await Chrome.launch( + ChromeOptions( + headless: true, + debugPort: browserDebugPort, + url: appUrl, + userDataDirectory: userDataDirectory.path, + windowHeight: 500, + windowWidth: 500, + ), + onError: resultCompleter.completeError, + ); return await resultCompleter.future; } finally { chrome?.stop(); @@ -82,19 +87,22 @@ class AppServer { } cascade = cascade.add((Request request) async { final Response response = await staticHandler(request); - return response.change(headers: { - 'cache-control': cacheControl, - }); + return response.change(headers: {'cache-control': cacheControl}); }); shelf_io.serveRequests(server, cascade.handler); - final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync('flutter_chrome_user_data.'); + final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync( + 'flutter_chrome_user_data.', + ); final Completer chromeErrorCompleter = Completer(); - chrome = await Chrome.launch(ChromeOptions( - headless: headless, - debugPort: browserDebugPort, - url: appUrl, - userDataDirectory: userDataDirectory.path, - ), onError: chromeErrorCompleter.complete); + chrome = await Chrome.launch( + ChromeOptions( + headless: headless, + debugPort: browserDebugPort, + url: appUrl, + userDataDirectory: userDataDirectory.path, + ), + onError: chromeErrorCompleter.complete, + ); return AppServer._(server, chrome, chromeErrorCompleter.future); } diff --git a/flutter/dev/bots/check_code_samples.dart b/flutter/dev/bots/check_code_samples.dart index 266ba631a13b68c70a8e535b0e42e12e0656f27b..17bec14ded9dd76da6359182bc88b4c715874d56 100644 --- a/flutter/dev/bots/check_code_samples.dart +++ b/flutter/dev/bots/check_code_samples.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. // To run this, from the root of the Flutter repository: -// bin/cache/dart-sdk/bin/dart --enable-asserts dev/bots/check_code_sample_links.dart +// bin/cache/dart-sdk/bin/dart --enable-asserts dev/bots/check_code_samples.dart import 'dart:io'; @@ -18,7 +18,14 @@ final String _scriptLocation = path.fromUri(Platform.script); final String _flutterRoot = path.dirname(path.dirname(path.dirname(_scriptLocation))); final String _exampleDirectoryPath = path.join(_flutterRoot, 'examples', 'api'); final String _packageDirectoryPath = path.join(_flutterRoot, 'packages'); -final String _dartUIDirectoryPath = path.join(_flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib'); +final String _dartUIDirectoryPath = path.join( + _flutterRoot, + 'bin', + 'cache', + 'pkg', + 'sky_engine', + 'lib', +); final List _knownUnlinkedExamples = [ // These are template files that aren't expected to be linked. @@ -29,11 +36,7 @@ final List _knownUnlinkedExamples = [ void main(List args) { final ArgParser argParser = ArgParser(); - argParser.addFlag( - 'help', - negatable: false, - help: 'Print help for this command.', - ); + argParser.addFlag('help', negatable: false, help: 'Print help for this command.'); argParser.addOption( 'examples', valueHelp: 'path', @@ -134,7 +137,9 @@ class SampleChecker { // Get a list of all the example link paths that appear in the source files. final (Set exampleLinks, Set malformedLinks) = getExampleLinks(packages); // Also add in any that might be found in the dart:ui directory. - final (Set uiExampleLinks, Set uiMalformedLinks) = getExampleLinks(dartUIPath); + final (Set uiExampleLinks, Set uiMalformedLinks) = getExampleLinks( + dartUIPath, + ); exampleLinks.addAll(uiExampleLinks); malformedLinks.addAll(uiMalformedLinks); @@ -142,29 +147,18 @@ class SampleChecker { // Get a list of the filenames that were not found in the source files. final List missingFilenames = checkForMissingLinks(exampleFilenames, exampleLinks); - // Get a list of any tests that are missing, as well as any that used to be - // missing, but have been implemented. - final (List missingTests, List noLongerMissing) = checkForMissingTests(exampleFilenames); + // Get a list of any tests that are missing. + final List missingTests = checkForMissingTests(exampleFilenames); // Remove any that we know are exceptions (examples that aren't expected to be // linked into any source files). These are typically template files used to // generate new examples. missingFilenames.removeWhere((String file) => _knownUnlinkedExamples.contains(file)); - if (missingFilenames.isEmpty && missingTests.isEmpty && noLongerMissing.isEmpty && malformedLinks.isEmpty) { + if (missingFilenames.isEmpty && missingTests.isEmpty && malformedLinks.isEmpty) { return true; } - if (noLongerMissing.isNotEmpty) { - final StringBuffer buffer = StringBuffer('The following tests have been implemented! Huzzah!:\n'); - for (final File name in noLongerMissing) { - buffer.writeln(' ${getRelativePath(name)}'); - } - buffer.writeln('However, they now need to be removed from the _knownMissingTests'); - buffer.write('list in the script $_scriptLocation.'); - foundError(buffer.toString().split('\n')); - } - if (missingTests.isNotEmpty) { final StringBuffer buffer = StringBuffer('The following example test files are missing:\n'); for (final File name in missingTests) { @@ -174,8 +168,9 @@ class SampleChecker { } if (missingFilenames.isNotEmpty) { - final StringBuffer buffer = - StringBuffer('The following examples are not linked from any source file API doc comments:\n'); + final StringBuffer buffer = StringBuffer( + 'The following examples are not linked from any source file API doc comments:\n', + ); for (final String name in missingFilenames) { buffer.writeln(' $name'); } @@ -184,14 +179,15 @@ class SampleChecker { } if (malformedLinks.isNotEmpty) { - final StringBuffer buffer = - StringBuffer('The following malformed links were found in API doc comments:\n'); + final StringBuffer buffer = StringBuffer( + 'The following malformed links were found in API doc comments:\n', + ); for (final LinkInfo link in malformedLinks) { buffer.writeln(' $link'); } buffer.write( 'Correct the formatting of these links so that they match the exact pattern:\n' - r" r'\*\* See code in (?.+) \*\*'" + r" r'\*\* See code in (?.+) \*\*'", ); foundError(buffer.toString().split('\n')); } @@ -204,27 +200,28 @@ class SampleChecker { } List getFiles(Directory directory, [Pattern? filenamePattern]) { - final List filenames = directory - .listSync(recursive: true) - .map((FileSystemEntity entity) { - if (entity is File) { - return entity; - } else { - return null; - } - }) - .where((File? filename) => - filename != null && (filenamePattern == null || filename.absolute.path.contains(filenamePattern))) - .map((File? s) => s!) - .toList(); + final List filenames = + directory + .listSync(recursive: true) + .map((FileSystemEntity entity) { + if (entity is File) { + return entity; + } else { + return null; + } + }) + .where( + (File? filename) => + filename != null && + (filenamePattern == null || filename.absolute.path.contains(filenamePattern)), + ) + .map((File? s) => s!) + .toList(); return filenames; } List getExampleFilenames(Directory directory) { - return getFiles( - directory.childDirectory('lib'), - RegExp(r'\d+\.dart$'), - ); + return getFiles(directory.childDirectory('lib'), RegExp(r'\d+\.dart$')); } (Set, Set) getExampleLinks(Directory searchDirectory) { @@ -234,9 +231,11 @@ class SampleChecker { final RegExp validExampleRe = RegExp(r'\*\* See code in (?.+) \*\*'); // Looks for some common broken versions of example links. This looks for // something that is at minimum "///*seecode*" to indicate that it - // looks like an example link. It should be narrowed if we start gettting false + // looks like an example link. It should be narrowed if we start getting false // positives. - final RegExp malformedLinkRe = RegExp(r'^(?\s*///\s*\*\*?\s*[sS][eE][eE]\s*[Cc][Oo][Dd][Ee].+\*\*?)'); + final RegExp malformedLinkRe = RegExp( + r'^(?\s*///\s*\*\*?\s*[sS][eE][eE]\s*[Cc][Oo][Dd][Ee].+\*\*?)', + ); for (final File file in files) { final String contents = file.readAsStringSync(); final List lines = contents.split('\n'); @@ -279,216 +278,14 @@ class SampleChecker { return '${path.join(testPath, path.basenameWithoutExtension(example.path))}_test.dart'; } - (List, List) checkForMissingTests(List exampleFilenames) { + List checkForMissingTests(List exampleFilenames) { final List missingTests = []; - final List noLongerMissingTests = []; for (final File example in exampleFilenames) { final File testFile = filesystem.file(getTestNameForExample(example, examples)); - final String name = path.relative(testFile.absolute.path, from: flutterRoot.absolute.path); if (!testFile.existsSync()) { missingTests.add(testFile); - } else if (_knownMissingTests.contains(name.replaceAll(r'\', '/'))) { - noLongerMissingTests.add(testFile); } } - // Skip any that we know are missing. - missingTests.removeWhere( - (File test) { - final String name = path.relative(test.absolute.path, from: flutterRoot.absolute.path).replaceAll(r'\', '/'); - return _knownMissingTests.contains(name); - }, - ); - return (missingTests, noLongerMissingTests); + return missingTests; } } - -// These tests are known to be missing. They should all eventually be -// implemented, but until they are we allow them, so that we can catch any new -// examples that are added without tests. -// -// TODO(gspencergoog): implement the missing tests. -// See https://github.com/flutter/flutter/issues/130459 -final Set _knownMissingTests = { - 'examples/api/test/material/bottom_app_bar/bottom_app_bar.2_test.dart', - 'examples/api/test/material/bottom_app_bar/bottom_app_bar.1_test.dart', - 'examples/api/test/material/theme/theme_extension.1_test.dart', - 'examples/api/test/material/material_state/material_state_border_side.0_test.dart', - 'examples/api/test/material/material_state/material_state_mouse_cursor.0_test.dart', - 'examples/api/test/material/material_state/material_state_outlined_border.0_test.dart', - 'examples/api/test/material/material_state/material_state_property.0_test.dart', - 'examples/api/test/material/selectable_region/selectable_region.0_test.dart', - 'examples/api/test/material/text_field/text_field.2_test.dart', - 'examples/api/test/material/text_field/text_field.1_test.dart', - 'examples/api/test/material/button_style/button_style.0_test.dart', - 'examples/api/test/material/range_slider/range_slider.0_test.dart', - 'examples/api/test/material/selection_container/selection_container_disabled.0_test.dart', - 'examples/api/test/material/selection_container/selection_container.0_test.dart', - 'examples/api/test/material/color_scheme/dynamic_content_color.0_test.dart', - 'examples/api/test/material/platform_menu_bar/platform_menu_bar.0_test.dart', - 'examples/api/test/material/menu_anchor/menu_anchor.2_test.dart', - 'examples/api/test/material/stepper/stepper.controls_builder.0_test.dart', - 'examples/api/test/material/flexible_space_bar/flexible_space_bar.0_test.dart', - 'examples/api/test/material/floating_action_button_location/standard_fab_location.0_test.dart', - 'examples/api/test/material/chip/deletable_chip_attributes.on_deleted.0_test.dart', - 'examples/api/test/material/snack_bar/snack_bar.2_test.dart', - 'examples/api/test/material/snack_bar/snack_bar.1_test.dart', - 'examples/api/test/material/icon_button/icon_button.3_test.dart', - 'examples/api/test/material/expansion_panel/expansion_panel_list.expansion_panel_list_radio.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.1_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.prefix_icon_constraints.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.material_state.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.2_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.label.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.suffix_icon_constraints.0_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.3_test.dart', - 'examples/api/test/material/input_decorator/input_decoration.material_state.1_test.dart', - 'examples/api/test/material/text_form_field/text_form_field.1_test.dart', - 'examples/api/test/material/scrollbar/scrollbar.1_test.dart', - 'examples/api/test/material/dropdown_menu/dropdown_menu.1_test.dart', - 'examples/api/test/material/radio/radio.toggleable.0_test.dart', - 'examples/api/test/material/search_anchor/search_anchor.0_test.dart', - 'examples/api/test/material/search_anchor/search_anchor.1_test.dart', - 'examples/api/test/material/search_anchor/search_anchor.2_test.dart', - 'examples/api/test/material/about/about_list_tile.0_test.dart', - 'examples/api/test/material/tab_controller/tab_controller.1_test.dart', - 'examples/api/test/material/selection_area/selection_area.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.end_drawer.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.drawer.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.1_test.dart', - 'examples/api/test/material/scaffold/scaffold.of.0_test.dart', - 'examples/api/test/material/scaffold/scaffold_messenger.of.0_test.dart', - 'examples/api/test/material/scaffold/scaffold_messenger.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.0_test.dart', - 'examples/api/test/material/scaffold/scaffold_state.show_bottom_sheet.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.2_test.dart', - 'examples/api/test/material/scaffold/scaffold_messenger_state.show_material_banner.0_test.dart', - 'examples/api/test/material/scaffold/scaffold.of.1_test.dart', - 'examples/api/test/material/scaffold/scaffold_messenger.of.1_test.dart', - 'examples/api/test/material/scaffold/scaffold_messenger_state.show_snack_bar.0_test.dart', - 'examples/api/test/material/segmented_button/segmented_button.0_test.dart', - 'examples/api/test/material/app_bar/sliver_app_bar.2_test.dart', - 'examples/api/test/material/app_bar/sliver_app_bar.3_test.dart', - 'examples/api/test/material/banner/material_banner.1_test.dart', - 'examples/api/test/material/banner/material_banner.0_test.dart', - 'examples/api/test/material/checkbox/checkbox.1_test.dart', - 'examples/api/test/material/checkbox/checkbox.0_test.dart', - 'examples/api/test/material/navigation_rail/navigation_rail.extended_animation.0_test.dart', - 'examples/api/test/material/text_button/text_button.0_test.dart', - 'examples/api/test/rendering/growth_direction/growth_direction.0_test.dart', - 'examples/api/test/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.0_test.dart', - 'examples/api/test/rendering/sliver_grid/sliver_grid_delegate_with_fixed_cross_axis_count.1_test.dart', - 'examples/api/test/rendering/scroll_direction/scroll_direction.0_test.dart', - 'examples/api/test/painting/axis_direction/axis_direction.0_test.dart', - 'examples/api/test/painting/linear_border/linear_border.0_test.dart', - 'examples/api/test/painting/gradient/linear_gradient.0_test.dart', - 'examples/api/test/painting/star_border/star_border.0_test.dart', - 'examples/api/test/painting/borders/border_side.stroke_align.0_test.dart', - 'examples/api/test/widgets/autocomplete/raw_autocomplete.focus_node.0_test.dart', - 'examples/api/test/widgets/autocomplete/raw_autocomplete.2_test.dart', - 'examples/api/test/widgets/autocomplete/raw_autocomplete.1_test.dart', - 'examples/api/test/widgets/autocomplete/raw_autocomplete.0_test.dart', - 'examples/api/test/widgets/navigator/navigator.restorable_push_and_remove_until.0_test.dart', - 'examples/api/test/widgets/navigator/navigator.0_test.dart', - 'examples/api/test/widgets/navigator/navigator.restorable_push.0_test.dart', - 'examples/api/test/widgets/navigator/navigator_state.restorable_push_replacement.0_test.dart', - 'examples/api/test/widgets/navigator/navigator_state.restorable_push_and_remove_until.0_test.dart', - 'examples/api/test/widgets/navigator/navigator.restorable_push_replacement.0_test.dart', - 'examples/api/test/widgets/navigator/restorable_route_future.0_test.dart', - 'examples/api/test/widgets/navigator/navigator_state.restorable_push.0_test.dart', - 'examples/api/test/widgets/focus_manager/focus_node.unfocus.0_test.dart', - 'examples/api/test/widgets/focus_manager/focus_node.0_test.dart', - 'examples/api/test/widgets/framework/build_owner.0_test.dart', - 'examples/api/test/widgets/framework/error_widget.0_test.dart', - 'examples/api/test/widgets/inherited_theme/inherited_theme.0_test.dart', - 'examples/api/test/widgets/sliver/decorated_sliver.0_test.dart', - 'examples/api/test/widgets/autofill/autofill_group.0_test.dart', - 'examples/api/test/widgets/drag_target/draggable.0_test.dart', - 'examples/api/test/widgets/shared_app_data/shared_app_data.1_test.dart', - 'examples/api/test/widgets/shared_app_data/shared_app_data.0_test.dart', - 'examples/api/test/widgets/form/form.0_test.dart', - 'examples/api/test/widgets/nested_scroll_view/nested_scroll_view_state.0_test.dart', - 'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.2_test.dart', - 'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.1_test.dart', - 'examples/api/test/widgets/nested_scroll_view/nested_scroll_view.0_test.dart', - 'examples/api/test/widgets/scroll_position/scroll_metrics_notification.0_test.dart', - 'examples/api/test/widgets/media_query/media_query_data.system_gesture_insets.0_test.dart', - 'examples/api/test/widgets/async/stream_builder.0_test.dart', - 'examples/api/test/widgets/async/future_builder.0_test.dart', - 'examples/api/test/widgets/restoration_properties/restorable_value.0_test.dart', - 'examples/api/test/widgets/animated_size/animated_size.0_test.dart', - 'examples/api/test/widgets/table/table.0_test.dart', - 'examples/api/test/widgets/animated_switcher/animated_switcher.0_test.dart', - 'examples/api/test/widgets/transitions/relative_positioned_transition.0_test.dart', - 'examples/api/test/widgets/transitions/positioned_transition.0_test.dart', - 'examples/api/test/widgets/transitions/sliver_fade_transition.0_test.dart', - 'examples/api/test/widgets/transitions/align_transition.0_test.dart', - 'examples/api/test/widgets/transitions/fade_transition.0_test.dart', - 'examples/api/test/widgets/transitions/animated_builder.0_test.dart', - 'examples/api/test/widgets/transitions/rotation_transition.0_test.dart', - 'examples/api/test/widgets/transitions/animated_widget.0_test.dart', - 'examples/api/test/widgets/transitions/slide_transition.0_test.dart', - 'examples/api/test/widgets/transitions/listenable_builder.2_test.dart', - 'examples/api/test/widgets/transitions/scale_transition.0_test.dart', - 'examples/api/test/widgets/transitions/default_text_style_transition.0_test.dart', - 'examples/api/test/widgets/transitions/decorated_box_transition.0_test.dart', - 'examples/api/test/widgets/transitions/size_transition.0_test.dart', - 'examples/api/test/widgets/animated_list/animated_list.0_test.dart', - 'examples/api/test/widgets/focus_traversal/focus_traversal_group.0_test.dart', - 'examples/api/test/widgets/focus_traversal/ordered_traversal_policy.0_test.dart', - 'examples/api/test/widgets/image/image.error_builder.0_test.dart', - 'examples/api/test/widgets/image/image.frame_builder.0_test.dart', - 'examples/api/test/widgets/image/image.loading_builder.0_test.dart', - 'examples/api/test/widgets/shortcuts/logical_key_set.0_test.dart', - 'examples/api/test/widgets/shortcuts/shortcuts.0_test.dart', - 'examples/api/test/widgets/shortcuts/single_activator.single_activator.0_test.dart', - 'examples/api/test/widgets/shortcuts/shortcuts.1_test.dart', - 'examples/api/test/widgets/shortcuts/character_activator.0_test.dart', - 'examples/api/test/widgets/shortcuts/callback_shortcuts.0_test.dart', - 'examples/api/test/widgets/page_storage/page_storage.0_test.dart', - 'examples/api/test/widgets/scrollbar/raw_scrollbar.1_test.dart', - 'examples/api/test/widgets/scrollbar/raw_scrollbar.2_test.dart', - 'examples/api/test/widgets/scrollbar/raw_scrollbar.desktop.0_test.dart', - 'examples/api/test/widgets/scrollbar/raw_scrollbar.shape.0_test.dart', - 'examples/api/test/widgets/scrollbar/raw_scrollbar.0_test.dart', - 'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.2_test.dart', - 'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.1_test.dart', - 'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.3_test.dart', - 'examples/api/test/widgets/sliver_fill/sliver_fill_remaining.0_test.dart', - 'examples/api/test/widgets/interactive_viewer/interactive_viewer.constrained.0_test.dart', - 'examples/api/test/widgets/interactive_viewer/interactive_viewer.transformation_controller.0_test.dart', - 'examples/api/test/widgets/interactive_viewer/interactive_viewer.0_test.dart', - 'examples/api/test/widgets/notification_listener/notification.0_test.dart', - 'examples/api/test/widgets/gesture_detector/gesture_detector.1_test.dart', - 'examples/api/test/widgets/gesture_detector/gesture_detector.0_test.dart', - 'examples/api/test/widgets/editable_text/text_editing_controller.0_test.dart', - 'examples/api/test/widgets/editable_text/editable_text.on_changed.0_test.dart', - 'examples/api/test/widgets/undo_history/undo_history_controller.0_test.dart', - 'examples/api/test/widgets/overscroll_indicator/glowing_overscroll_indicator.1_test.dart', - 'examples/api/test/widgets/overscroll_indicator/glowing_overscroll_indicator.0_test.dart', - 'examples/api/test/widgets/tween_animation_builder/tween_animation_builder.0_test.dart', - 'examples/api/test/widgets/single_child_scroll_view/single_child_scroll_view.1_test.dart', - 'examples/api/test/widgets/single_child_scroll_view/single_child_scroll_view.0_test.dart', - 'examples/api/test/widgets/overflow_bar/overflow_bar.0_test.dart', - 'examples/api/test/widgets/restoration/restoration_mixin.0_test.dart', - 'examples/api/test/widgets/actions/actions.0_test.dart', - 'examples/api/test/widgets/actions/action_listener.0_test.dart', - 'examples/api/test/widgets/actions/focusable_action_detector.0_test.dart', - 'examples/api/test/widgets/color_filter/color_filtered.0_test.dart', - 'examples/api/test/widgets/focus_scope/focus.2_test.dart', - 'examples/api/test/widgets/focus_scope/focus.0_test.dart', - 'examples/api/test/widgets/focus_scope/focus.1_test.dart', - 'examples/api/test/widgets/focus_scope/focus_scope.0_test.dart', - 'examples/api/test/widgets/implicit_animations/animated_fractionally_sized_box.0_test.dart', - 'examples/api/test/widgets/implicit_animations/animated_align.0_test.dart', - 'examples/api/test/widgets/implicit_animations/animated_positioned.0_test.dart', - 'examples/api/test/widgets/implicit_animations/animated_padding.0_test.dart', - 'examples/api/test/widgets/implicit_animations/sliver_animated_opacity.0_test.dart', - 'examples/api/test/widgets/implicit_animations/animated_container.0_test.dart', - 'examples/api/test/widgets/dismissible/dismissible.0_test.dart', - 'examples/api/test/widgets/scroll_view/custom_scroll_view.1_test.dart', - 'examples/api/test/widgets/preferred_size/preferred_size.0_test.dart', - 'examples/api/test/widgets/inherited_notifier/inherited_notifier.0_test.dart', - 'examples/api/test/animation/curves/curve2_d.0_test.dart', - 'examples/api/test/gestures/pointer_signal_resolver/pointer_signal_resolver.0_test.dart', -}; diff --git a/flutter/dev/bots/codelabs_build_test.sh b/flutter/dev/bots/codelabs_build_test.sh index ef594a9d728407b230903e8fa089c9dc48fb96c2..e5f70c1f69177be0441190ab5f8bc1162f2c000a 100644 --- a/flutter/dev/bots/codelabs_build_test.sh +++ b/flutter/dev/bots/codelabs_build_test.sh @@ -29,7 +29,7 @@ if [ ${PIPESTATUS[0]} -eq 0 ] || is_expected_failure "$log_file"; then rm "$log_file" else all_builds_ok=0 - echo "View https://github.com/flutter/flutter/blob/master/dev/bots/README.md for steps to resolve this failed build test." >> ${log_file} + echo "View https://github.com/flutter/flutter/blob/main/dev/bots/README.md for steps to resolve this failed build test." >> ${log_file} echo echo "Log left in $log_file." echo diff --git a/flutter/dev/bots/docs.sh b/flutter/dev/bots/docs.sh index d6837fd361bc5aa438c8d6395e760f5575ea1699..9a9dae07b7a9f6ddbdfb68d4af835fa06575ea84 100644 --- a/flutter/dev/bots/docs.sh +++ b/flutter/dev/bots/docs.sh @@ -107,23 +107,32 @@ function parse_args() { fi } +function build_snippets_tool() ( + local snippets_dir="$FLUTTER_ROOT/dev/snippets" + local output_dir="$FLUTTER_BIN/cache/artifacts/snippets" + echo "Building snippets tool executable." + command cd "$snippets_dir" + mkdir -p "$output_dir" + dart pub get + dart compile exe -o "$output_dir/snippets" bin/snippets.dart +) + function generate_docs() { # Install and activate dartdoc. # When updating to a new dartdoc version, please also update # `dartdoc_options.yaml` to include newly introduced error and warning types. - "$DART" pub global activate dartdoc 8.0.2 + "$DART" pub global activate dartdoc 8.3.0 - # Install and activate the snippets tool, which resides in the - # assets-for-api-docs repo: - # https://github.com/flutter/assets-for-api-docs/tree/master/packages/snippets - "$DART" pub global activate snippets 0.4.0 + # Build and install the snippets tool, which resides in + # the dev/docs/snippets directory. + build_snippets_tool # This script generates a unified doc set, and creates # a custom index.html, placing everything into DOC_DIR. # Make sure that create_api_docs.dart has all the dependencies it needs. (cd "$FLUTTER_ROOT/dev/tools" && "$FLUTTER" pub get) - (cd "$FLUTTER_ROOT" && "$DART" --disable-dart-dev --enable-asserts "$FLUTTER_ROOT/dev/tools/create_api_docs.dart" --output-dir="$DOC_DIR") + (cd "$FLUTTER_ROOT" && "$DART" --enable-asserts "$FLUTTER_ROOT/dev/tools/create_api_docs.dart" --output-dir="$DOC_DIR") } function main() { diff --git a/flutter/dev/bots/post_process_docs.dart b/flutter/dev/bots/post_process_docs.dart index 91bdb7086a5ac12b530554bf275e9f9da7555581..89864a91d98069cd83be7a9cc8b46a8028f5256f 100644 --- a/flutter/dev/bots/post_process_docs.dart +++ b/flutter/dev/bots/post_process_docs.dart @@ -32,33 +32,20 @@ Future postProcess() async { } final String checkoutPath = Platform.environment['SDK_CHECKOUT_PATH']!; final String docsPath = path.join(checkoutPath, 'dev', 'docs'); - await runProcessWithValidations( - [ - 'curl', - '-L', - 'https://storage.googleapis.com/flutter_infra_release/flutter/$revision/api_docs.zip', - '--output', - zipDestination, - '--fail', - ], - docsPath, - ); + await runProcessWithValidations([ + 'curl', + '-L', + 'https://storage.googleapis.com/flutter_infra_release/flutter/$revision/api_docs.zip', + '--output', + zipDestination, + '--fail', + ], docsPath); // Unzip to docs folder. - await runProcessWithValidations( - [ - 'unzip', - '-o', - zipDestination, - ], - docsPath, - ); + await runProcessWithValidations(['unzip', '-o', zipDestination], docsPath); // Generate versions file. - await runProcessWithValidations( - ['flutter', '--version'], - docsPath, - ); + await runProcessWithValidations(['flutter', '--version'], docsPath); final File versionFile = File('version'); final String version = versionFile.readAsStringSync(); // Recreate footer @@ -84,7 +71,9 @@ Future gitRevision({ if (fullLength) { return gitRevision; } - return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision; + return gitRevision.length > kGitRevisionLength + ? gitRevision.substring(0, kGitRevisionLength) + : gitRevision; } /// Wrapper function to run a subprocess checking exit code and printing stderr and stdout. @@ -96,8 +85,11 @@ Future runProcessWithValidations( @visibleForTesting ProcessManager processManager = const LocalProcessManager(), bool verbose = true, }) async { - final ProcessResult result = - processManager.runSync(command, stdoutEncoding: utf8, workingDirectory: workingDirectory); + final ProcessResult result = processManager.runSync( + command, + stdoutEncoding: utf8, + workingDirectory: workingDirectory, + ); if (result.exitCode == 0) { if (verbose) { print('stdout: ${result.stdout}'); @@ -123,21 +115,31 @@ Future getBranchName({ if (luciBranch != null && luciBranch.trim().isNotEmpty) { return luciBranch.trim(); } - final ProcessResult gitResult = processManager.runSync(['git', 'status', '-b', '--porcelain']); + final ProcessResult gitResult = processManager.runSync([ + 'git', + 'status', + '-b', + '--porcelain', + ]); if (gitResult.exitCode != 0) { throw 'git status exit with non-zero exit code: ${gitResult.exitCode}'; } - final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch((gitResult.stdout as String).trim().split('\n').first); + final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch( + (gitResult.stdout as String).trim().split('\n').first, + ); return gitBranchMatch == null ? '' : gitBranchMatch.group(1)!.split('...').first; } /// Updates the footer of the api documentation with the correct branch and versions. /// [footerPath] is the path to the location of the footer js file and [version] is a /// string with the version calculated by the flutter tool. -Future createFooter(File footerFile, String version, - {@visibleForTesting String? timestampParam, - @visibleForTesting String? branchParam, - @visibleForTesting String? revisionParam}) async { +Future createFooter( + File footerFile, + String version, { + @visibleForTesting String? timestampParam, + @visibleForTesting String? branchParam, + @visibleForTesting String? revisionParam, +}) async { final String timestamp = timestampParam ?? DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now()); final String gitBranch = branchParam ?? await getBranchName(); final String revision = revisionParam ?? await gitRevision(); diff --git a/flutter/dev/bots/prepare_package.dart b/flutter/dev/bots/prepare_package.dart index 3bd37b3d65d1ad596dc7e10fcedc792150ad6bbb..853fd70dd5695ba2376b64a83d35f40174a04e3f 100644 --- a/flutter/dev/bots/prepare_package.dart +++ b/flutter/dev/bots/prepare_package.dart @@ -26,15 +26,19 @@ Future main(List rawArguments) async { final ArgParser argParser = ArgParser(); argParser.addOption( 'temp_dir', - help: 'A location where temporary files may be written. Defaults to a ' + help: + 'A location where temporary files may be written. Defaults to a ' 'directory in the system temp folder. Will write a few GiB of data, ' 'so it should have sufficient free space. If a temp_dir is not ' 'specified, then the default temp_dir will be created, used, and ' 'removed automatically.', ); - argParser.addOption('revision', - help: 'The Flutter git repo revision to build the ' - 'archive with. Must be the full 40-character hash. Required.'); + argParser.addOption( + 'revision', + help: + 'The Flutter git repo revision to build the ' + 'archive with. Must be the full 40-character hash. Required.', + ); argParser.addOption( 'branch', allowed: Branch.values.map((Branch branch) => branch.name), @@ -42,32 +46,26 @@ Future main(List rawArguments) async { ); argParser.addOption( 'output', - help: 'The path to the directory where the output archive should be ' + help: + 'The path to the directory where the output archive should be ' 'written. If --output is not specified, the archive will be written to ' "the current directory. If the output directory doesn't exist, it, and " 'the path to it, will be created.', ); argParser.addFlag( 'publish', - help: 'If set, will publish the archive to Google Cloud Storage upon ' + help: + 'If set, will publish the archive to Google Cloud Storage upon ' 'successful creation of the archive. Will publish under this ' 'directory: $baseUrl$releaseFolder', ); - argParser.addFlag( - 'force', - abbr: 'f', - help: 'Overwrite a previously uploaded package.', - ); + argParser.addFlag('force', abbr: 'f', help: 'Overwrite a previously uploaded package.'); argParser.addFlag( 'dry_run', negatable: false, help: 'Prints gsutil commands instead of executing them.', ); - argParser.addFlag( - 'help', - negatable: false, - help: 'Print help for this command.', - ); + argParser.addFlag('help', negatable: false, help: 'Print help for this command.'); final ArgResults parsedArguments = argParser.parse(rawArguments); diff --git a/flutter/dev/bots/pubspec.yaml b/flutter/dev/bots/pubspec.yaml index 1587f9114d8aa437b32f893530ceedc110192f48..b36bba62c72eb373e71ca8ad853c9842a3a78dc4 100644 --- a/flutter/dev/bots/pubspec.yaml +++ b/flutter/dev/bots/pubspec.yaml @@ -2,77 +2,79 @@ name: tests_on_bots description: Scripts which run on bots. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: - analyzer: 6.3.0 - args: 2.4.2 - crypto: 3.0.3 - intl: 0.18.1 - file: 7.0.0 + analyzer: 7.3.0 + args: 2.7.0 + crypto: 3.0.6 + intl: 0.20.2 + file: 7.0.1 flutter_devicelab: path: ../devicelab - http_parser: 4.0.2 - meta: 1.11.0 - path: 1.9.0 - platform: 3.1.4 - process: 5.0.2 - test: 1.24.9 + http_parser: 4.1.2 + meta: 1.16.0 + path: 1.9.1 + platform: 3.1.6 + process: 5.0.3 + test: 1.25.15 - _discoveryapis_commons: 1.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - _fe_analyzer_shared: 65.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - archive: 3.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _discoveryapis_commons: 1.0.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _fe_analyzer_shared: 80.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + archive: 3.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" checked_yaml: 2.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - gcloud: 0.8.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - googleapis: 3.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - googleapis_auth: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http: 0.13.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - js: 0.6.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - json_annotation: 4.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - metrics_center: 1.0.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - mime: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + clock: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + frontend_server_client: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + gcloud: 0.8.18 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + glob: 2.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + google_identity_services_web: 0.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + googleapis: 12.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + googleapis_auth: 1.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_multi_server: 3.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + io: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + js: 0.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + json_annotation: 4.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + logging: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + metrics_center: 1.0.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + mime: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - petitparser: 6.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + package_config: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + petitparser: 6.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - pubspec_parse: 1.2.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pubspec_parse: 1.5.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" retry: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf: 1.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_static: 1.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_map_stack_trace: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_maps: 0.10.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" standard_message_codec: 0.0.1+4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_core: 0.5.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web: 0.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + typed_data: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vm_service: 15.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + watcher: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket: 0.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket_channel: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" xml: 6.5.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: - test_api: 0.6.1 + test_api: 0.7.4 -# PUBSPEC CHECKSUM: 65d5 +# PUBSPEC CHECKSUM: e365 diff --git a/flutter/dev/bots/run_command.dart b/flutter/dev/bots/run_command.dart index f39d89650b0e448f9e9b3f75328900b8ea8041fa..e70cd2e310ff9f8844dfd9c81835146d2288dea7 100644 --- a/flutter/dev/bots/run_command.dart +++ b/flutter/dev/bots/run_command.dart @@ -18,7 +18,9 @@ import 'utils.dart'; /// If `expectNonZeroExit` is false and the process exits with a non-zero exit /// code fails the test immediately by exiting the test process with exit code /// 1. -Stream runAndGetStdout(String executable, List arguments, { +Stream runAndGetStdout( + String executable, + List arguments, { String? workingDirectory, Map? environment, bool expectNonZeroExit = false, @@ -82,7 +84,9 @@ class CommandResult { /// /// `outputMode` controls where the standard output from the command process /// goes. See [OutputMode]. -Future startCommand(String executable, List arguments, { +Future startCommand( + String executable, + List arguments, { String? workingDirectory, Map? environment, OutputMode outputMode = OutputMode.print, @@ -90,12 +94,15 @@ Future startCommand(String executable, List arguments, { void Function(String, io.Process)? outputListener, }) async { final String relativeWorkingDir = path.relative(workingDirectory ?? io.Directory.current.path); - final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; + final String commandDescription = + '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; print('RUNNING: cd $cyan$relativeWorkingDir$reset; $green$commandDescription$reset'); final Stopwatch time = Stopwatch()..start(); print('workingDirectory: $workingDirectory, executable: $executable, arguments: $arguments'); - final io.Process process = await io.Process.start(executable, arguments, + final io.Process process = await io.Process.start( + executable, + arguments, workingDirectory: workingDirectory, environment: environment, ); @@ -103,36 +110,36 @@ Future startCommand(String executable, List arguments, { process, time, process.stdout - .transform(const Utf8Decoder()) - .transform(const LineSplitter()) - .where((String line) => removeLine == null || !removeLine(line)) - .map((String line) { - final String formattedLine = '$line\n'; - if (outputListener != null) { - outputListener(formattedLine, process); - } - switch (outputMode) { - case OutputMode.print: - print(line); - case OutputMode.capture: - break; - } - return line; - }) - .join('\n'), + .transform(const Utf8Decoder()) + .transform(const LineSplitter()) + .where((String line) => removeLine == null || !removeLine(line)) + .map((String line) { + final String formattedLine = '$line\n'; + if (outputListener != null) { + outputListener(formattedLine, process); + } + switch (outputMode) { + case OutputMode.print: + print(line); + case OutputMode.capture: + break; + } + return line; + }) + .join('\n'), process.stderr - .transform(const Utf8Decoder()) - .transform(const LineSplitter()) - .map((String line) { - switch (outputMode) { - case OutputMode.print: - print(line); - case OutputMode.capture: - break; - } - return line; - }) - .join('\n'), + .transform(const Utf8Decoder()) + .transform(const LineSplitter()) + .map((String line) { + switch (outputMode) { + case OutputMode.print: + print(line); + case OutputMode.capture: + break; + } + return line; + }) + .join('\n'), ); } @@ -150,7 +157,9 @@ Future startCommand(String executable, List arguments, { /// /// `outputMode` controls where the standard output from the command process /// goes. See [OutputMode]. -Future runCommand(String executable, List arguments, { +Future runCommand( + String executable, + List arguments, { String? workingDirectory, Map? environment, bool expectNonZeroExit = false, @@ -160,10 +169,22 @@ Future runCommand(String executable, List arguments, { bool Function(String)? removeLine, void Function(String, io.Process)? outputListener, }) async { - final String commandDescription = '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; + final String commandDescription = + '${path.relative(executable, from: workingDirectory)} ${arguments.join(' ')}'; final String relativeWorkingDir = workingDirectory ?? path.relative(io.Directory.current.path); + if (dryRun) { + printProgress(_prettyPrintRunCommand(executable, arguments, workingDirectory)); + return CommandResult._( + 0, + Duration.zero, + '$executable ${arguments.join(' ')}', + 'Simulated execution due to --dry-run', + ); + } - final Command command = await startCommand(executable, arguments, + final Command command = await startCommand( + executable, + arguments, workingDirectory: workingDirectory, environment: environment, outputMode: outputMode, @@ -178,7 +199,8 @@ Future runCommand(String executable, List arguments, { await command._savedStderr, ); - if ((result.exitCode == 0) == expectNonZeroExit || (expectedExitCode != null && result.exitCode != expectedExitCode)) { + if ((result.exitCode == 0) == expectNonZeroExit || + (expectedExitCode != null && result.exitCode != expectedExitCode)) { // Print the output when we get unexpected results (unless output was // printed already). switch (outputMode) { @@ -190,8 +212,7 @@ Future runCommand(String executable, List arguments, { } final String allOutput = '${result.flattenedStdout}\n${result.flattenedStderr}'; foundError([ - if (failureMessage != null) - failureMessage, + if (failureMessage != null) failureMessage, '${bold}Command: $green$commandDescription$reset', if (failureMessage == null) '$bold${red}Command exited with exit code ${result.exitCode} but expected ${expectNonZeroExit ? (expectedExitCode ?? 'non-zero') : 'zero'} exit code.$reset', @@ -200,11 +221,32 @@ Future runCommand(String executable, List arguments, { '${bold}stdout and stderr output:\n$allOutput', ]); } else { - print('ELAPSED TIME: ${prettyPrintDuration(result.elapsedTime)} for $green$commandDescription$reset in $cyan$relativeWorkingDir$reset'); + print( + 'ELAPSED TIME: ${prettyPrintDuration(result.elapsedTime)} for $green$commandDescription$reset in $cyan$relativeWorkingDir$reset', + ); } return result; } +final String _flutterRoot = path.dirname( + path.dirname(path.dirname(path.fromUri(io.Platform.script))), +); + +String _prettyPrintRunCommand(String executable, List arguments, String? workingDirectory) { + final StringBuffer output = StringBuffer(); + + // Print CWD relative to the root. + output.write('|> '); + output.write(path.relative(executable, from: _flutterRoot)); + if (workingDirectory != null) { + output.write(' (${path.relative(workingDirectory, from: _flutterRoot)})'); + } + output.writeln(': '); + output.writeAll(arguments.map((String a) => ' $a'), '\n'); + + return output.toString(); +} + /// Specifies what to do with the command output from [runCommand] and [startCommand]. enum OutputMode { /// Forwards standard output and standard error streams to the test process' diff --git a/flutter/dev/bots/service_worker_test.dart b/flutter/dev/bots/service_worker_test.dart index 219d36be728114b856ea3083325462d8776d3a01..b1ebb40351969fc3905b2f25248812f9e71e487a 100644 --- a/flutter/dev/bots/service_worker_test.dart +++ b/flutter/dev/bots/service_worker_test.dart @@ -20,8 +20,14 @@ final String _testAppDirectory = path.join(_flutterRoot, 'dev', 'integration_tes final String _testAppWebDirectory = path.join(_testAppDirectory, 'web'); final String _appBuildDirectory = path.join(_testAppDirectory, 'build', 'web'); final String _target = path.join('lib', 'service_worker_test.dart'); -final String _targetWithCachedResources = path.join('lib', 'service_worker_test_cached_resources.dart'); -final String _targetWithBlockedServiceWorkers = path.join('lib', 'service_worker_test_blocked_service_workers.dart'); +final String _targetWithCachedResources = path.join( + 'lib', + 'service_worker_test_cached_resources.dart', +); +final String _targetWithBlockedServiceWorkers = path.join( + 'lib', + 'service_worker_test_blocked_service_workers.dart', +); final String _targetPath = path.join(_testAppDirectory, _target); enum ServiceWorkerTestType { @@ -52,15 +58,42 @@ Future main() async { // to LUCI. await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withoutFlutterJs); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJs); - await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsShort); - await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent); - await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn); - await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsNonceOn); - await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withoutFlutterJs); - await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJs); - await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsShort); - await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent); - await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn); + await runWebServiceWorkerTest( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsShort, + ); + await runWebServiceWorkerTest( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent, + ); + await runWebServiceWorkerTest( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn, + ); + await runWebServiceWorkerTest( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsNonceOn, + ); + await runWebServiceWorkerTestWithCachingResources( + headless: false, + testType: ServiceWorkerTestType.withoutFlutterJs, + ); + await runWebServiceWorkerTestWithCachingResources( + headless: false, + testType: ServiceWorkerTestType.withFlutterJs, + ); + await runWebServiceWorkerTestWithCachingResources( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsShort, + ); + await runWebServiceWorkerTestWithCachingResources( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent, + ); + await runWebServiceWorkerTestWithCachingResources( + headless: false, + testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn, + ); await runWebServiceWorkerTestWithGeneratedEntrypoint(headless: false); await runWebServiceWorkerTestWithBlockedServiceWorkers(headless: false); await runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: false); @@ -74,26 +107,32 @@ Future main() async { // Regression test for https://github.com/flutter/flutter/issues/109093. // // Tests the entrypoint that's generated by `flutter create`. -Future runWebServiceWorkerTestWithGeneratedEntrypoint({ - required bool headless, -}) async { +Future runWebServiceWorkerTestWithGeneratedEntrypoint({required bool headless}) async { await _generateEntrypoint(); - await runWebServiceWorkerTestWithCachingResources(headless: headless, testType: ServiceWorkerTestType.generatedEntrypoint); + await runWebServiceWorkerTestWithCachingResources( + headless: headless, + testType: ServiceWorkerTestType.generatedEntrypoint, + ); } Future _generateEntrypoint() async { - final Directory tempDirectory = Directory.systemTemp.createTempSync('flutter_web_generated_entrypoint.'); - await runCommand( - _flutter, - [ 'create', 'generated_entrypoint_test' ], - workingDirectory: tempDirectory.path, + final Directory tempDirectory = Directory.systemTemp.createTempSync( + 'flutter_web_generated_entrypoint.', + ); + await runCommand(_flutter, [ + 'create', + 'generated_entrypoint_test', + ], workingDirectory: tempDirectory.path); + final File generatedEntrypoint = File( + path.join(tempDirectory.path, 'generated_entrypoint_test', 'web', 'index.html'), ); - final File generatedEntrypoint = File(path.join(tempDirectory.path, 'generated_entrypoint_test', 'web', 'index.html')); final String generatedEntrypointCode = generatedEntrypoint.readAsStringSync(); - final File testEntrypoint = File(path.join( - _testAppWebDirectory, - _testTypeToIndexFile(ServiceWorkerTestType.generatedEntrypoint), - )); + final File testEntrypoint = File( + path.join( + _testAppWebDirectory, + _testTypeToIndexFile(ServiceWorkerTestType.generatedEntrypoint), + ), + ); testEntrypoint.writeAsStringSync(generatedEntrypointCode); tempDirectory.deleteSync(recursive: true); } @@ -104,66 +143,65 @@ Future _setAppVersion(int version) async { (await targetFile.readAsString()).replaceFirst( RegExp(r'CLOSE\?version=\d+'), 'CLOSE?version=$version', - ) + ), ); } String _testTypeToIndexFile(ServiceWorkerTestType type) { return switch (type) { - ServiceWorkerTestType.blockedServiceWorkers => 'index_with_blocked_service_workers.html', - ServiceWorkerTestType.withFlutterJs => 'index_with_flutterjs.html', - ServiceWorkerTestType.withoutFlutterJs => 'index_without_flutterjs.html', - ServiceWorkerTestType.withFlutterJsShort => 'index_with_flutterjs_short.html', - ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent => 'index_with_flutterjs_entrypoint_loaded.html', - ServiceWorkerTestType.withFlutterJsTrustedTypesOn => 'index_with_flutterjs_el_tt_on.html', - ServiceWorkerTestType.withFlutterJsNonceOn => 'index_with_flutterjs_el_nonce.html', - ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion => 'index_with_flutterjs_custom_sw_version.html', - ServiceWorkerTestType.generatedEntrypoint => 'generated_entrypoint.html', + ServiceWorkerTestType.blockedServiceWorkers => 'index_with_blocked_service_workers.html', + ServiceWorkerTestType.withFlutterJs => 'index_with_flutterjs.html', + ServiceWorkerTestType.withoutFlutterJs => 'index_without_flutterjs.html', + ServiceWorkerTestType.withFlutterJsShort => 'index_with_flutterjs_short.html', + ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent => + 'index_with_flutterjs_entrypoint_loaded.html', + ServiceWorkerTestType.withFlutterJsTrustedTypesOn => 'index_with_flutterjs_el_tt_on.html', + ServiceWorkerTestType.withFlutterJsNonceOn => 'index_with_flutterjs_el_nonce.html', + ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion => + 'index_with_flutterjs_custom_sw_version.html', + ServiceWorkerTestType.generatedEntrypoint => 'generated_entrypoint.html', }; } -Future _rebuildApp({ required int version, required ServiceWorkerTestType testType, required String target }) async { +Future _rebuildApp({ + required int version, + required ServiceWorkerTestType testType, + required String target, +}) async { await _setAppVersion(version); - await runCommand( - _flutter, - [ 'clean' ], - workingDirectory: _testAppDirectory, - ); - await runCommand( - 'cp', - [ - _testTypeToIndexFile(testType), - 'index.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand(_flutter, ['clean'], workingDirectory: _testAppDirectory); + await runCommand('cp', [ + _testTypeToIndexFile(testType), + 'index.html', + ], workingDirectory: _testAppWebDirectory); await runCommand( _flutter, ['build', 'web', '--web-resources-cdn', '--profile', '-t', target], workingDirectory: _testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, + environment: {'FLUTTER_WEB': 'true'}, ); } -void _expectRequestCounts( - Map expectedCounts, - Map requestedPathCounts, -) { +void _expectRequestCounts(Map expectedCounts, Map requestedPathCounts) { expect(requestedPathCounts, expectedCounts); requestedPathCounts.clear(); } Future _waitForAppToLoad( - Map waitForCounts, - Map requestedPathCounts, - AppServer? server + Map waitForCounts, + Map requestedPathCounts, + AppServer? server, ) async { print('Waiting for app to load $waitForCounts'); await Future.any(>[ () async { - while (!waitForCounts.entries.every((MapEntry entry) => (requestedPathCounts[entry.key] ?? 0) >= entry.value)) { + int tries = 1; + while (!waitForCounts.entries.every( + (MapEntry entry) => (requestedPathCounts[entry.key] ?? 0) >= entry.value, + )) { + if (tries++ % 20 == 0) { + print('Still waiting. Requested so far: $requestedPathCounts'); + } await Future.delayed(const Duration(milliseconds: 100)); } }(), @@ -201,9 +239,7 @@ Future runWebServiceWorkerTest({ String? reportedVersion; - Future startAppServer({ - required String cacheControl, - }) async { + Future startAppServer({required String cacheControl}) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( @@ -231,14 +267,10 @@ Future runWebServiceWorkerTest({ } // Preserve old index.html as index_og.html so we can restore it later for other tests - await runCommand( - 'mv', - [ - 'index.html', - 'index_og.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index.html', + 'index_og.html', + ], workingDirectory: _testAppWebDirectory); final bool shouldExpectFlutterJs = testType != ServiceWorkerTestType.withoutFlutterJs; @@ -252,31 +284,19 @@ Future runWebServiceWorkerTest({ print('Call update() on the current web worker'); await startAppServer(cacheControl: 'max-age=0'); - await waitForAppToLoad( { - if (shouldExpectFlutterJs) - 'flutter.js': 1, - 'CLOSE': 1, - }); + await waitForAppToLoad({if (shouldExpectFlutterJs) 'flutter.js': 1, 'CLOSE': 1}); expect(reportedVersion, '1'); reportedVersion = null; await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad( { - if (shouldExpectFlutterJs) - 'flutter.js': 2, - 'CLOSE': 2, - }); + await waitForAppToLoad({if (shouldExpectFlutterJs) 'flutter.js': 2, 'CLOSE': 2}); expect(reportedVersion, '1'); reportedVersion = null; await _rebuildApp(version: 2, testType: testType, target: _target); await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad({ - if (shouldExpectFlutterJs) - 'flutter.js': 3, - 'CLOSE': 3, - }); + await waitForAppToLoad({if (shouldExpectFlutterJs) 'flutter.js': 3, 'CLOSE': 3}); expect(reportedVersion, '2'); reportedVersion = null; @@ -290,45 +310,32 @@ Future runWebServiceWorkerTest({ print('With cache: test first page load'); await startAppServer(cacheControl: 'max-age=3600'); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter_service_worker.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter_service_worker.js': 1}); expectRequestCounts({ // Even though the server is caching index.html is downloaded twice, // once by the initial page load, and once by the service worker. // Other resources are loaded once only by the service worker. 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 1, + 'flutter_bootstrap.js': 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); expect(reportedVersion, '1'); reportedVersion = null; print('With cache: test page reload'); await server!.chrome.reloadPage(); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter_service_worker.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter_service_worker.js': 1}); - expectRequestCounts({ - 'flutter_service_worker.js': 1, - 'CLOSE': 1, - }); + expectRequestCounts({'flutter_service_worker.js': 1, 'CLOSE': 1}); expect(reportedVersion, '1'); reportedVersion = null; @@ -337,55 +344,43 @@ Future runWebServiceWorkerTest({ // Since we're caching, we need to ignore cache when reloading the page. await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter_service_worker.js': 2, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter_service_worker.js': 2}); expectRequestCounts({ 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 2, + 'flutter_bootstrap.js': 1, 'main.dart.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/FontManifest.json': 1, 'CLOSE': 1, - if (!headless) - 'favicon.ico': 1, + if (!headless) 'favicon.png': 1, }); expect(reportedVersion, '2'); reportedVersion = null; await server!.stop(); - ////////////////////////////////////////////////////// // Non-caching server ////////////////////////////////////////////////////// print('No cache: test first page load'); await _rebuildApp(version: 3, testType: testType, target: _target); await startAppServer(cacheControl: 'max-age=0'); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter_service_worker.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter_service_worker.js': 1}); expectRequestCounts({ 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'assets/FontManifest.json': 1, 'flutter_service_worker.js': 1, + 'flutter_bootstrap.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); expect(reportedVersion, '3'); @@ -395,18 +390,15 @@ Future runWebServiceWorkerTest({ await server!.chrome.reloadPage(); await waitForAppToLoad({ 'CLOSE': 1, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts({ - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 1, 'CLOSE': 1, - if (!headless) - 'manifest.json': 1, + if (!headless) 'manifest.json': 1, }); expect(reportedVersion, '3'); reportedVersion = null; @@ -420,37 +412,26 @@ Future runWebServiceWorkerTest({ // this test I wasn't able to figure out what's wrong with the way we run // Chrome from tests. await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter_service_worker.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter_service_worker.js': 1}); expectRequestCounts({ 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 2, + 'flutter_bootstrap.js': 1, 'main.dart.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/FontManifest.json': 1, 'CLOSE': 1, - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); expect(reportedVersion, '4'); reportedVersion = null; } finally { - await runCommand( - 'mv', - [ - 'index_og.html', - 'index.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index_og.html', + 'index.html', + ], workingDirectory: _testAppWebDirectory); await _setAppVersion(1); await server?.stop(); } @@ -460,7 +441,7 @@ Future runWebServiceWorkerTest({ Future runWebServiceWorkerTestWithCachingResources({ required bool headless, - required ServiceWorkerTestType testType + required ServiceWorkerTestType testType, }) async { final Map requestedPathCounts = {}; void expectRequestCounts(Map expectedCounts) => @@ -470,9 +451,7 @@ Future runWebServiceWorkerTestWithCachingResources({ Future waitForAppToLoad(Map waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); - Future startAppServer({ - required String cacheControl, - }) async { + Future startAppServer({required String cacheControl}) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( @@ -485,7 +464,7 @@ Future runWebServiceWorkerTestWithCachingResources({ browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: [ - (Request request) { + (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; @@ -499,19 +478,18 @@ Future runWebServiceWorkerTestWithCachingResources({ } // Preserve old index.html as index_og.html so we can restore it later for other tests - await runCommand( - 'mv', - [ - 'index.html', - 'index_og.html', - ], - workingDirectory: _testAppWebDirectory, + await runCommand('mv', [ + 'index.html', + 'index_og.html', + ], workingDirectory: _testAppWebDirectory); + + final bool usesFlutterBootstrapJs = testType == ServiceWorkerTestType.generatedEntrypoint; + final bool shouldExpectFlutterJs = + !usesFlutterBootstrapJs && testType != ServiceWorkerTestType.withoutFlutterJs; + print( + 'BEGIN runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)', ); - final bool shouldExpectFlutterJs = testType != ServiceWorkerTestType.withoutFlutterJs; - - print('BEGIN runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)'); - try { ////////////////////////////////////////////////////// // Caching server @@ -530,19 +508,15 @@ Future runWebServiceWorkerTestWithCachingResources({ // once by the initial page load, and once by the service worker. // Other resources are loaded once only by the service worker. 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 1, + 'flutter_bootstrap.js': usesFlutterBootstrapJs ? 2 : 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); print('With cache: test first page reload'); @@ -589,37 +563,30 @@ Future runWebServiceWorkerTestWithCachingResources({ }); expectRequestCounts({ 'index.html': 2, - if (shouldExpectFlutterJs) - 'flutter.js': 1, + if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 2, + 'flutter_bootstrap.js': usesFlutterBootstrapJs ? 2 : 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'favicon.png': 1}, }); } finally { - await runCommand( - 'mv', - [ - 'index_og.html', - 'index.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index_og.html', + 'index.html', + ], workingDirectory: _testAppWebDirectory); await server?.stop(); } - print('END runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)'); + print( + 'END runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)', + ); } -Future runWebServiceWorkerTestWithBlockedServiceWorkers({ - required bool headless -}) async { +Future runWebServiceWorkerTestWithBlockedServiceWorkers({required bool headless}) async { final Map requestedPathCounts = {}; void expectRequestCounts(Map expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); @@ -628,9 +595,7 @@ Future runWebServiceWorkerTestWithBlockedServiceWorkers({ Future waitForAppToLoad(Map waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); - Future startAppServer({ - required String cacheControl, - }) async { + Future startAppServer({required String cacheControl}) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( @@ -657,24 +622,22 @@ Future runWebServiceWorkerTestWithBlockedServiceWorkers({ } // Preserve old index.html as index_og.html so we can restore it later for other tests - await runCommand( - 'mv', - [ - 'index.html', - 'index_og.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index.html', + 'index_og.html', + ], workingDirectory: _testAppWebDirectory); print('BEGIN runWebServiceWorkerTestWithBlockedServiceWorkers(headless: $headless)'); try { - await _rebuildApp(version: 1, testType: ServiceWorkerTestType.blockedServiceWorkers, target: _targetWithBlockedServiceWorkers); + await _rebuildApp( + version: 1, + testType: ServiceWorkerTestType.blockedServiceWorkers, + target: _targetWithBlockedServiceWorkers, + ); print('Ensure app starts (when service workers are blocked)'); await startAppServer(cacheControl: 'max-age=3600'); - await waitForAppToLoad({ - 'CLOSE': 1, - }); + await waitForAppToLoad({'CLOSE': 1}); expectRequestCounts({ 'index.html': 1, 'flutter.js': 1, @@ -682,31 +645,21 @@ Future runWebServiceWorkerTestWithBlockedServiceWorkers({ 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); } finally { - await runCommand( - 'mv', - [ - 'index_og.html', - 'index.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index_og.html', + 'index.html', + ], workingDirectory: _testAppWebDirectory); await server?.stop(); } print('END runWebServiceWorkerTestWithBlockedServiceWorkers(headless: $headless)'); } /// Regression test for https://github.com/flutter/flutter/issues/130212. -Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ - required bool headless, -}) async { +Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({required bool headless}) async { final Map requestedPathCounts = {}; void expectRequestCounts(Map expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); @@ -715,9 +668,7 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ Future waitForAppToLoad(Map waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); - Future startAppServer({ - required String cacheControl, - }) async { + Future startAppServer({required String cacheControl}) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( @@ -730,7 +681,7 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: [ - (Request request) { + (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; @@ -744,18 +695,18 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ } // Preserve old index.html as index_og.html so we can restore it later for other tests - await runCommand( - 'mv', - [ - 'index.html', - 'index_og.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index.html', + 'index_og.html', + ], workingDirectory: _testAppWebDirectory); print('BEGIN runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: $headless)'); try { - await _rebuildApp(version: 1, testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, target: _target); + await _rebuildApp( + version: 1, + testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, + target: _target, + ); print('Test page load'); await startAppServer(cacheControl: 'max-age=0'); @@ -770,23 +721,17 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ 'main.dart.js': 1, 'CLOSE': 1, 'flutter_service_worker.js': 1, + 'flutter_bootstrap.js': 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); print('Test page reload, ensure service worker is not reloaded'); await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter.js': 1}); expectRequestCounts({ 'index.html': 1, 'flutter.js': 1, @@ -794,21 +739,18 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); print('Test page reload after rebuild, ensure service worker is not reloaded'); - await _rebuildApp(version: 1, testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, target: _target); + await _rebuildApp( + version: 1, + testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, + target: _target, + ); await server!.chrome.reloadPage(ignoreCache: true); - await waitForAppToLoad({ - 'CLOSE': 1, - 'flutter.js': 1, - }); + await waitForAppToLoad({'CLOSE': 1, 'flutter.js': 1}); expectRequestCounts({ 'index.html': 1, 'flutter.js': 1, @@ -816,22 +758,14 @@ Future runWebServiceWorkerTestWithCustomServiceWorkerVersion({ 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, - // In headless mode Chrome does not load 'manifest.json' and 'favicon.ico'. - if (!headless) - ...{ - 'manifest.json': 1, - 'favicon.ico': 1, - }, + // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. + if (!headless) ...{'manifest.json': 1, 'favicon.png': 1}, }); } finally { - await runCommand( - 'mv', - [ - 'index_og.html', - 'index.html', - ], - workingDirectory: _testAppWebDirectory, - ); + await runCommand('mv', [ + 'index_og.html', + 'index.html', + ], workingDirectory: _testAppWebDirectory); await server?.stop(); } print('END runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: $headless)'); diff --git a/flutter/dev/bots/test.dart b/flutter/dev/bots/test.dart index 11fb71c7a978247288b545f848615ab260c954d1..18b76b784001ee683a26f3af7b78bed83ebbd732 100644 --- a/flutter/dev/bots/test.dart +++ b/flutter/dev/bots/test.dart @@ -4,14 +4,12 @@ // Runs the tests for the flutter/flutter repository. // -// // By default, test output is filtered and only errors are shown. (If a // particular test takes longer than _quietTimeout in utils.dart, the output is // shown then also, in case something has hung.) // // --verbose stops the output cleanup and just outputs everything verbatim. // -// // By default, errors are non-fatal; all tests are executed and the output // ends with a summary of the errors that were detected. // @@ -19,14 +17,10 @@ // // --abort-on-error causes the script to exit immediately when hitting an error. // -// // By default, all tests are run. However, the tests support being split by -// shard and subshard. (Inspect the code to see what shards and subshards are -// supported.) -// -// If the CIRRUS_TASK_NAME environment variable exists, it is used to determine -// the shard and sub-shard, by parsing it in the form shard-subshard-platform, -// ignoring the platform. +// shard and subshard. Inspect the code to see what shards and subshards are +// supported, or run with `--dry-run` to get a list of tests that _would_ have +// been executed. // // For local testing you can just set the SHARD and SUBSHARD environment // variables. For example, to run all the framework tests you can just set @@ -43,7 +37,6 @@ // // --test-randomize-ordering-seed= sets the shuffle seed for reproducing runs. // -// // All other arguments are treated as arguments to pass to the flutter tool when // running tests. @@ -52,141 +45,33 @@ import 'dart:core' as system show print; import 'dart:core' hide print; import 'dart:io' as system show exit; import 'dart:io' hide exit; -import 'dart:io' as io; import 'dart:math' as math; -import 'dart:typed_data'; -import 'package:archive/archive.dart'; -import 'package:file/file.dart' as fs; -import 'package:file/local.dart'; -import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; -import 'package:process/process.dart'; -import 'browser.dart'; import 'run_command.dart'; -import 'service_worker_test.dart'; -import 'tool_subsharding.dart'; +import 'suite_runners/run_add_to_app_life_cycle_tests.dart'; +import 'suite_runners/run_analyze_tests.dart'; +import 'suite_runners/run_android_engine_tests.dart'; +import 'suite_runners/run_android_java11_integration_tool_tests.dart'; +import 'suite_runners/run_android_preview_integration_tool_tests.dart'; +import 'suite_runners/run_customer_testing_tests.dart'; +import 'suite_runners/run_docs_tests.dart'; +import 'suite_runners/run_flutter_packages_tests.dart'; +import 'suite_runners/run_framework_coverage_tests.dart'; +import 'suite_runners/run_framework_tests.dart'; +import 'suite_runners/run_fuchsia_precache.dart'; +import 'suite_runners/run_skp_generator_tests.dart'; +import 'suite_runners/run_test_harness_tests.dart'; +import 'suite_runners/run_verify_binaries_codesigned_tests.dart'; +import 'suite_runners/run_web_tests.dart'; import 'utils.dart'; typedef ShardRunner = Future Function(); -/// A function used to validate the output of a test. -/// -/// If the output matches expectations, the function shall return null. -/// -/// If the output does not match expectations, the function shall return an -/// appropriate error message. -typedef OutputChecker = String? Function(CommandResult); - -final String exe = Platform.isWindows ? '.exe' : ''; -final String bat = Platform.isWindows ? '.bat' : ''; -final String flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); -final String flutter = path.join(flutterRoot, 'bin', 'flutter$bat'); -final String dart = path.join(flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dart$exe'); -final String pubCache = path.join(flutterRoot, '.pub-cache'); -final String engineVersionFile = path.join(flutterRoot, 'bin', 'internal', 'engine.version'); -final String engineRealmFile = path.join(flutterRoot, 'bin', 'internal', 'engine.realm'); -final String flutterPackagesVersionFile = path.join(flutterRoot, 'bin', 'internal', 'flutter_packages.version'); - -String get platformFolderName { - if (Platform.isWindows) { - return 'windows-x64'; - } - if (Platform.isMacOS) { - return 'darwin-x64'; - } - if (Platform.isLinux) { - return 'linux-x64'; - } - throw UnsupportedError('The platform ${Platform.operatingSystem} is not supported by this script.'); -} -final String flutterTester = path.join(flutterRoot, 'bin', 'cache', 'artifacts', 'engine', platformFolderName, 'flutter_tester$exe'); - -/// The arguments to pass to `flutter test` (typically the local engine -/// configuration) -- prefilled with the arguments passed to test.dart. -final List flutterTestArgs = []; - /// Environment variables to override the local engine when running `pub test`, /// if such flags are provided to `test.dart`. -final Map localEngineEnv = {}; - -const String kShardKey = 'SHARD'; -const String kSubshardKey = 'SUBSHARD'; - -/// The number of Cirrus jobs that run Web tests in parallel. -/// -/// The default is 8 shards. Typically .cirrus.yml would define the -/// WEB_SHARD_COUNT environment variable rather than relying on the default. -/// -/// WARNING: if you change this number, also change .cirrus.yml -/// and make sure it runs _all_ shards. -/// -/// The last shard also runs the Web plugin tests. -int get webShardCount => Platform.environment.containsKey('WEB_SHARD_COUNT') - ? int.parse(Platform.environment['WEB_SHARD_COUNT']!) - : 8; - -/// Tests that we don't run on Web. -/// -/// In general avoid adding new tests here. If a test cannot run on the web -/// because it fails at runtime, such as when a piece of functionality is not -/// implemented or not implementable on the web, prefer using `skip` in the -/// test code. Only add tests here that cannot be skipped using `skip`. For -/// example: -/// -/// * Test code cannot be compiled because it uses Dart VM-specific -/// functionality. In this case `skip` doesn't help because the code cannot -/// reach the point where it can even run the skipping logic. -/// * Migrations. It is OK to put tests here that need to be temporarily -/// disabled in certain modes because of some migration or initial bringup. -/// -/// The key in the map is the renderer type that the list applies to. The value -/// is the list of tests known to fail for that renderer. -// -// TODO(yjbanov): we're getting rid of this as part of https://github.com/flutter/flutter/projects/60 -const Map> kWebTestFileKnownFailures = >{ - 'html': [ - // These tests are not compilable on the web due to dependencies on - // VM-specific functionality. - 'test/services/message_codecs_vm_test.dart', - 'test/examples/sector_layout_test.dart', - ], - 'canvaskit': [ - // These tests are not compilable on the web due to dependencies on - // VM-specific functionality. - 'test/services/message_codecs_vm_test.dart', - 'test/examples/sector_layout_test.dart', - - // These tests are broken and need to be fixed. - // TODO(yjbanov): https://github.com/flutter/flutter/issues/71604 - 'test/painting/text_style_test.dart', - 'test/material/text_field_test.dart', - 'test/widgets/performance_overlay_test.dart', - 'test/widgets/html_element_view_test.dart', - 'test/cupertino/scaffold_test.dart', - 'test/rendering/platform_view_test.dart', - ], -}; - -const String kTestHarnessShardName = 'test_harness_tests'; -const List _kAllBuildModes = ['debug', 'profile', 'release']; - -// The seed used to shuffle tests. If not passed with -// --test-randomize-ordering-seed= on the command line, it will be set the -// first time it is accessed. Pass zero to turn off shuffling. -String? _shuffleSeed; -String get shuffleSeed { - if (_shuffleSeed == null) { - // Change the seed at 7am, UTC. - final DateTime seedTime = DateTime.now().toUtc().subtract(const Duration(hours: 7)); - // Generates YYYYMMDD as the seed, so that testing continues to fail for a - // day after the seed changes, and on other days the seed can be used to - // replicate failures. - _shuffleSeed = '${seedTime.year * 10000 + seedTime.month * 100 + seedTime.day}'; - } - return _shuffleSeed!; -} +final Map localEngineEnv = {}; /// When you call this, you can pass additional arguments to pass custom /// arguments to flutter test. For example, you might want to call this @@ -201,6 +86,7 @@ String get shuffleSeed { Future main(List args) async { try { printProgress('STARTING ANALYSIS'); + bool dryRunArgSet = false; for (final String arg in args) { if (arg.startsWith('--local-engine=')) { localEngineEnv['FLUTTER_LOCAL_ENGINE'] = arg.substring('--local-engine='.length); @@ -209,10 +95,12 @@ Future main(List args) async { localEngineEnv['FLUTTER_LOCAL_ENGINE_HOST'] = arg.substring('--local-engine-host='.length); flutterTestArgs.add(arg); } else if (arg.startsWith('--local-engine-src-path=')) { - localEngineEnv['FLUTTER_LOCAL_ENGINE_SRC_PATH'] = arg.substring('--local-engine-src-path='.length); + localEngineEnv['FLUTTER_LOCAL_ENGINE_SRC_PATH'] = arg.substring( + '--local-engine-src-path='.length, + ); flutterTestArgs.add(arg); } else if (arg.startsWith('--test-randomize-ordering-seed=')) { - _shuffleSeed = arg.substring('--test-randomize-ordering-seed='.length); + shuffleSeed = arg.substring('--test-randomize-ordering-seed='.length); } else if (arg.startsWith('--verbose')) { print = (Object? message) { system.print(message); @@ -221,39 +109,48 @@ Future main(List args) async { onError = () { system.exit(1); }; + } else if (arg == '--dry-run') { + dryRunArgSet = true; + printProgress('--dry-run enabled. Tests will not actually be executed.'); } else { flutterTestArgs.add(arg); } } - if (Platform.environment.containsKey(CIRRUS_TASK_NAME)) { - printProgress('Running task: ${Platform.environment[CIRRUS_TASK_NAME]}'); + if (dryRunArgSet) { + enableDryRun(); } + final WebTestsSuite webTestsSuite = WebTestsSuite(flutterTestArgs); await selectShard({ - 'add_to_app_life_cycle_tests': _runAddToAppLifeCycleTests, + 'add_to_app_life_cycle_tests': addToAppLifeCycleRunner, 'build_tests': _runBuildTests, - 'framework_coverage': _runFrameworkCoverage, - 'framework_tests': _runFrameworkTests, + 'framework_coverage': frameworkCoverageRunner, + 'framework_tests': frameworkTestsRunner, 'tool_tests': _runToolTests, - // web_tool_tests is also used by HHH: https://dart.googlesource.com/recipes/+/refs/heads/master/recipes/dart/flutter_engine.py 'web_tool_tests': _runWebToolTests, 'tool_integration_tests': _runIntegrationToolTests, - 'android_preview_tool_integration_tests': _runAndroidPreviewIntegrationToolTests, + 'android_preview_tool_integration_tests': androidPreviewIntegrationToolTestsRunner, + 'android_java11_tool_integration_tests': androidJava11IntegrationToolTestsRunner, 'tool_host_cross_arch_tests': _runToolHostCrossArchTests, - // All the unit/widget tests run using `flutter test --platform=chrome --web-renderer=html` - 'web_tests': _runWebHtmlUnitTests, - // All the unit/widget tests run using `flutter test --platform=chrome --web-renderer=canvaskit` - 'web_canvaskit_tests': _runWebCanvasKitUnitTests, + // All the unit/widget tests run using `flutter test --platform=chrome` + 'web_canvaskit_tests': webTestsSuite.runWebCanvasKitUnitTests, + // All the unit/widget tests run using `flutter test --platform=chrome --wasm` + 'web_skwasm_tests': webTestsSuite.runWebSkwasmUnitTests, // All web integration tests - 'web_long_running_tests': _runWebLongRunningTests, - 'flutter_plugins': _runFlutterPackagesTests, - 'skp_generator': _runSkpGeneratorTests, - 'realm_checker': _runRealmCheckerTest, - 'customer_testing': _runCustomerTesting, - 'analyze': _runAnalyze, - 'fuchsia_precache': _runFuchsiaPrecache, - 'docs': _runDocs, - 'verify_binaries_codesigned': _runVerifyCodesigned, - kTestHarnessShardName: _runTestHarnessTests, // Used for testing this script; also run as part of SHARD=framework_tests, SUBSHARD=misc. + 'web_long_running_tests': webTestsSuite.webLongRunningTestsRunner, + 'android_engine_vulkan_tests': + () => runAndroidEngineTests(impellerBackend: ImpellerBackend.vulkan), + 'android_engine_opengles_tests': + () => runAndroidEngineTests(impellerBackend: ImpellerBackend.opengles), + 'flutter_plugins': flutterPackagesRunner, + 'skp_generator': skpGeneratorTestsRunner, + 'customer_testing': customerTestingRunner, + 'analyze': analyzeRunner, + 'fuchsia_precache': fuchsiaPrecacheRunner, + 'snippets': _runSnippetsTests, + 'docs': docsRunner, + 'verify_binaries_codesigned': verifyCodesignedTestRunner, + kTestHarnessShardName: + testHarnessTestsRunner, // Used for testing this script; also run as part of SHARD=framework_tests, SUBSHARD=misc. }); } catch (error, stackTrace) { foundError([ @@ -271,139 +168,10 @@ Future main(List args) async { reportSuccessAndExit('${bold}Test successful.$reset'); } -final String _luciBotId = Platform.environment['SWARMING_BOT_ID'] ?? ''; -final bool _runningInDartHHHBot = - _luciBotId.startsWith('luci-dart-') || _luciBotId.startsWith('dart-tests-'); - -/// Verify the Flutter Engine is the revision in -/// bin/cache/internal/engine.version. -Future _validateEngineHash() async { - if (_runningInDartHHHBot) { - // The Dart HHH bots intentionally modify the local artifact cache - // and then use this script to run Flutter's test suites. - // Because the artifacts have been changed, this particular test will return - // a false positive and should be skipped. - print('${yellow}Skipping Flutter Engine Version Validation for swarming bot $_luciBotId.'); - return; - } - final String expectedVersion = File(engineVersionFile).readAsStringSync().trim(); - final CommandResult result = await runCommand(flutterTester, ['--help'], outputMode: OutputMode.capture); - if (result.flattenedStdout!.isNotEmpty) { - foundError([ - '${red}The stdout of `$flutterTester --help` was not empty:$reset', - ...result.flattenedStdout!.split('\n').map((String line) => ' $gray┆$reset $line'), - ]); - } - final String actualVersion; - try { - actualVersion = result.flattenedStderr!.split('\n').firstWhere((final String line) { - return line.startsWith('Flutter Engine Version:'); - }); - } on StateError { - foundError([ - '${red}Could not find "Flutter Engine Version:" line in `${path.basename(flutterTester)} --help` stderr output:$reset', - ...result.flattenedStderr!.split('\n').map((String line) => ' $gray┆$reset $line'), - ]); - return; - } - if (!actualVersion.contains(expectedVersion)) { - foundError(['${red}Expected "Flutter Engine Version: $expectedVersion", but found "$actualVersion".$reset']); - } -} - -Future _runTestHarnessTests() async { - printProgress('${green}Running test harness tests...$reset'); - - await _validateEngineHash(); - - // Verify that the tests actually return failure on failure and success on - // success. - final String automatedTests = path.join(flutterRoot, 'dev', 'automated_tests'); - - // We want to run these tests in parallel, because they each take some time - // to run (e.g. compiling), so we don't want to run them in series, especially - // on 20-core machines. However, we have a race condition, so for now... - // Race condition issue: https://github.com/flutter/flutter/issues/90026 - final List tests = [ - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'pass_test.dart'), - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'fail_test.dart'), - expectFailure: true, - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'pending_timer_fail_test.dart'), - expectFailure: true, - printOutput: false, - outputChecker: (CommandResult result) { - return result.flattenedStdout!.contains('failingPendingTimerTest') - ? null - : 'Failed to find the stack trace for the pending Timer.\n\n' - 'stdout:\n${result.flattenedStdout}\n\n' - 'stderr:\n${result.flattenedStderr}'; - }), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'crash1_test.dart'), - expectFailure: true, - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'crash2_test.dart'), - expectFailure: true, - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'syntax_error_test.broken_dart'), - expectFailure: true, - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'missing_import_test.broken_dart'), - expectFailure: true, - printOutput: false, - ), - () => _runFlutterTest( - automatedTests, - script: path.join('test_smoke_test', 'disallow_error_reporter_modification_test.dart'), - expectFailure: true, - printOutput: false, - ), - ]; - - List testsToRun; - - // Run all tests unless sharding is explicitly specified. - final String? shardName = Platform.environment[kShardKey]; - if (shardName == kTestHarnessShardName) { - testsToRun = _selectIndexOfTotalSubshard(tests); - } else { - testsToRun = tests; - } - for (final ShardRunner test in testsToRun) { - await test(); - } - - // Verify that we correctly generated the version file. - final String? versionError = await verifyVersion(File(path.join(flutterRoot, 'version'))); - if (versionError != null) { - foundError([versionError]); - } -} - final String _toolsPath = path.join(flutterRoot, 'packages', 'flutter_tools'); Future _runGeneralToolTests() async { - await _runDartTest( + await runDartTest( _toolsPath, testPaths: [path.join('test', 'general.shard')], enableFlutterToolAsserts: false, @@ -416,7 +184,7 @@ Future _runGeneralToolTests() async { } Future _runCommandsToolTests() async { - await _runDartTest( + await runDartTest( _toolsPath, forceSingleCore: true, testPaths: [path.join('test', 'commands.shard')], @@ -424,24 +192,26 @@ Future _runCommandsToolTests() async { } Future _runWebToolTests() async { - final List allFiles = Directory(path.join(_toolsPath, 'test', 'web.shard')) - .listSync(recursive: true).whereType().toList(); + final List allFiles = + Directory( + path.join(_toolsPath, 'test', 'web.shard'), + ).listSync(recursive: true).whereType().toList(); final List allTests = []; for (final File file in allFiles) { if (file.path.endsWith('_test.dart')) { allTests.add(file.path); } } - await _runDartTest( + await runDartTest( _toolsPath, forceSingleCore: true, - testPaths: _selectIndexOfTotalSubshard(allTests), + testPaths: selectIndexOfTotalSubshard(allTests), includeLocalEngineEnv: true, ); } Future _runToolHostCrossArchTests() { - return _runDartTest( + return runDartTest( _toolsPath, // These are integration tests forceSingleCore: true, @@ -450,30 +220,25 @@ Future _runToolHostCrossArchTests() { } Future _runIntegrationToolTests() async { - final List allTests = Directory(path.join(_toolsPath, 'test', 'integration.shard')) - .listSync(recursive: true).whereType() - .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) - .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); - - await _runDartTest( + final List allTests = + Directory(path.join(_toolsPath, 'test', 'integration.shard')) + .listSync(recursive: true) + .whereType() + .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) + .where((String testPath) => path.basename(testPath).endsWith('_test.dart')) + .toList(); + + await runDartTest( _toolsPath, forceSingleCore: true, - testPaths: _selectIndexOfTotalSubshard(allTests), + testPaths: selectIndexOfTotalSubshard(allTests), collectMetrics: true, ); } -Future _runAndroidPreviewIntegrationToolTests() async { - final List allTests = Directory(path.join(_toolsPath, 'test', 'android_preview_integration.shard')) - .listSync(recursive: true).whereType() - .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) - .where((String testPath) => path.basename(testPath).endsWith('_test.dart')).toList(); - - await _runDartTest( - _toolsPath, - forceSingleCore: true, - testPaths: _selectIndexOfTotalSubshard(allTests), - collectMetrics: true, +Future _runWidgetPreviewScaffoldToolTests() async { + await runFlutterTest( + path.join(_toolsPath, 'test', 'widget_preview_scaffold.shard', 'widget_preview_scaffold'), ); } @@ -481,9 +246,28 @@ Future _runToolTests() async { await selectSubshard({ 'general': _runGeneralToolTests, 'commands': _runCommandsToolTests, + 'widget_preview_scaffold': _runWidgetPreviewScaffoldToolTests, }); } +Future _runSnippetsTests() async { + final String snippetsPath = path.join(flutterRoot, 'dev', 'snippets'); + final List allTests = + Directory(path.join(snippetsPath, 'test')) + .listSync(recursive: true) + .whereType() + .map((FileSystemEntity entry) => path.relative(entry.path, from: _toolsPath)) + .where((String testPath) => path.basename(testPath).endsWith('_test.dart')) + .toList(); + + await runDartTest( + snippetsPath, + forceSingleCore: true, + testPaths: selectIndexOfTotalSubshard(allTests), + collectMetrics: true, + ); +} + Future runForbiddenFromReleaseTests() async { // Build a release APK to get the snapshot json. final Directory tempDirectory = Directory.systemTemp.createTempSync('flutter_forbidden_imports.'); @@ -508,31 +292,30 @@ Future runForbiddenFromReleaseTests() async { // First, a smoke test. final List smokeTestArgs = [ path.join(flutterRoot, 'dev', 'forbidden_from_release_tests', 'bin', 'main.dart'), - '--snapshot', path.join(tempDirectory.path, 'snapshot.arm64-v8a.json'), - '--package-config', path.join(flutterRoot, 'examples', 'hello_world', '.dart_tool', 'package_config.json'), - '--forbidden-type', 'package:flutter/src/widgets/framework.dart::Widget', + '--snapshot', + path.join(tempDirectory.path, 'snapshot.arm64-v8a.json'), + '--package-config', + path.join(flutterRoot, 'examples', 'hello_world', '.dart_tool', 'package_config.json'), + '--forbidden-type', + 'package:flutter/src/widgets/framework.dart::Widget', ]; - await runCommand( - dart, - smokeTestArgs, - workingDirectory: flutterRoot, - expectNonZeroExit: true, - ); + await runCommand(dart, smokeTestArgs, workingDirectory: flutterRoot, expectNonZeroExit: true); // Actual test. final List args = [ path.join(flutterRoot, 'dev', 'forbidden_from_release_tests', 'bin', 'main.dart'), - '--snapshot', path.join(tempDirectory.path, 'snapshot.arm64-v8a.json'), - '--package-config', path.join(flutterRoot, 'examples', 'hello_world', '.dart_tool', 'package_config.json'), - '--forbidden-type', 'package:flutter/src/widgets/widget_inspector.dart::WidgetInspectorService', - '--forbidden-type', 'package:flutter/src/widgets/framework.dart::DebugCreator', - '--forbidden-type', 'package:flutter/src/foundation/print.dart::debugPrint', + '--snapshot', + path.join(tempDirectory.path, 'snapshot.arm64-v8a.json'), + '--package-config', + path.join(flutterRoot, 'examples', 'hello_world', '.dart_tool', 'package_config.json'), + '--forbidden-type', + 'package:flutter/src/widgets/widget_inspector.dart::WidgetInspectorService', + '--forbidden-type', + 'package:flutter/src/widgets/framework.dart::DebugCreator', + '--forbidden-type', + 'package:flutter/src/foundation/print.dart::debugPrint', ]; - await runCommand( - dart, - args, - workingDirectory: flutterRoot, - ); + await runCommand(dart, args, workingDirectory: flutterRoot); } /// Verifies that APK, and IPA (if on macOS), and native desktop builds the @@ -543,21 +326,34 @@ Future runForbiddenFromReleaseTests() async { /// /// Also does some checking about types included in hello_world. Future _runBuildTests() async { - final List exampleDirectories = Directory(path.join(flutterRoot, 'examples')).listSync() - // API example builds will be tested in a separate shard. - .where((FileSystemEntity entity) => entity is Directory && path.basename(entity.path) != 'api').cast().toList() - ..add(Directory(path.join(flutterRoot, 'packages', 'integration_test', 'example'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'android_semantics_testing'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'android_views'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'channels'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'hybrid_android_views'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'flutter_gallery'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ios_platform_view_tests'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ios_app_with_extensions'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'non_nullable'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'platform_interaction'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'spell_check'))) - ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ui'))); + final List exampleDirectories = + Directory(path.join(flutterRoot, 'examples')) + .listSync() + // API example builds will be tested in a separate shard. + .where( + (FileSystemEntity entity) => entity is Directory && path.basename(entity.path) != 'api', + ) + .cast() + .toList() + ..add(Directory(path.join(flutterRoot, 'packages', 'integration_test', 'example'))) + ..add( + Directory( + path.join(flutterRoot, 'dev', 'integration_tests', 'android_semantics_testing'), + ), + ) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'android_views'))) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'channels'))) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'hybrid_android_views'))) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'flutter_gallery'))) + ..add( + Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ios_platform_view_tests')), + ) + ..add( + Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ios_app_with_extensions')), + ) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'platform_interaction'))) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'spell_check'))) + ..add(Directory(path.join(flutterRoot, 'dev', 'integration_tests', 'ui'))); // The tests are randomly distributed into subshards so as to get a uniform // distribution of costs, but the seed is fixed so that issues are reproducible. @@ -567,19 +363,25 @@ Future _runBuildTests() async { ...[ // Web compilation tests. () => _flutterBuildDart2js( - path.join('dev', 'integration_tests', 'web'), - path.join('lib', 'main.dart'), - ), + path.join('dev', 'integration_tests', 'web'), + path.join('lib', 'main.dart'), + ), // Should not fail to compile with dart:io. () => _flutterBuildDart2js( - path.join('dev', 'integration_tests', 'web_compile_tests'), - path.join('lib', 'dart_io_import.dart'), - ), + path.join('dev', 'integration_tests', 'web_compile_tests'), + path.join('lib', 'dart_io_import.dart'), + ), + // Should be able to compile with a call to: + // BackgroundIsolateBinaryMessenger.ensureInitialized. + () => _flutterBuildDart2js( + path.join('dev', 'integration_tests', 'web_compile_tests'), + path.join('lib', 'background_isolate_binary_messenger.dart'), + ), ], runForbiddenFromReleaseTests, ]..shuffle(math.Random(0)); - await _runShardRunnerIndexOfTotalSubshard(tests); + await runShardRunnerIndexOfTotalSubshard(tests); } Future _runExampleProjectBuildTests(Directory exampleDirectory, [File? mainFile]) async { @@ -590,113 +392,195 @@ Future _runExampleProjectBuildTests(Directory exampleDirectory, [File? mai if (mainFile != null) path.relative(mainFile.path, from: exampleDirectory.absolute.path), ]; if (Directory(path.join(examplePath, 'android')).existsSync()) { - await _flutterBuildApk(examplePath, release: false, additionalArgs: additionalArgs, verifyCaching: verifyCaching); - await _flutterBuildApk(examplePath, release: true, additionalArgs: additionalArgs, verifyCaching: verifyCaching); + await _flutterBuildApk( + examplePath, + release: false, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); + await _flutterBuildApk( + examplePath, + release: true, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); } else { print('Example project ${path.basename(examplePath)} has no android directory, skipping apk'); } if (Platform.isMacOS) { if (Directory(path.join(examplePath, 'ios')).existsSync()) { - await _flutterBuildIpa(examplePath, release: false, additionalArgs: additionalArgs, verifyCaching: verifyCaching); - await _flutterBuildIpa(examplePath, release: true, additionalArgs: additionalArgs, verifyCaching: verifyCaching); + await _flutterBuildIpa( + examplePath, + release: false, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); + await _flutterBuildIpa( + examplePath, + release: true, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); } else { print('Example project ${path.basename(examplePath)} has no ios directory, skipping ipa'); } } if (Platform.isLinux) { if (Directory(path.join(examplePath, 'linux')).existsSync()) { - await _flutterBuildLinux(examplePath, release: false, additionalArgs: additionalArgs, verifyCaching: verifyCaching); - await _flutterBuildLinux(examplePath, release: true, additionalArgs: additionalArgs, verifyCaching: verifyCaching); + await _flutterBuildLinux( + examplePath, + release: false, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); + await _flutterBuildLinux( + examplePath, + release: true, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); } else { print('Example project ${path.basename(examplePath)} has no linux directory, skipping Linux'); } } if (Platform.isMacOS) { if (Directory(path.join(examplePath, 'macos')).existsSync()) { - await _flutterBuildMacOS(examplePath, release: false, additionalArgs: additionalArgs, verifyCaching: verifyCaching); - await _flutterBuildMacOS(examplePath, release: true, additionalArgs: additionalArgs, verifyCaching: verifyCaching); + await _flutterBuildMacOS( + examplePath, + release: false, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); + await _flutterBuildMacOS( + examplePath, + release: true, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); } else { print('Example project ${path.basename(examplePath)} has no macos directory, skipping macOS'); } } if (Platform.isWindows) { if (Directory(path.join(examplePath, 'windows')).existsSync()) { - await _flutterBuildWin32(examplePath, release: false, additionalArgs: additionalArgs, verifyCaching: verifyCaching); - await _flutterBuildWin32(examplePath, release: true, additionalArgs: additionalArgs, verifyCaching: verifyCaching); + await _flutterBuildWin32( + examplePath, + release: false, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); + await _flutterBuildWin32( + examplePath, + release: true, + additionalArgs: additionalArgs, + verifyCaching: verifyCaching, + ); } else { - print('Example project ${path.basename(examplePath)} has no windows directory, skipping Win32'); + print( + 'Example project ${path.basename(examplePath)} has no windows directory, skipping Win32', + ); } } } -Future _flutterBuildApk(String relativePathToApplication, { +Future _flutterBuildApk( + String relativePathToApplication, { required bool release, bool verifyCaching = false, List additionalArgs = const [], }) async { - printProgress('${green}Testing APK ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...'); - await _flutterBuild(relativePathToApplication, 'APK', 'apk', + printProgress( + '${green}Testing APK ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...', + ); + await _flutterBuild( + relativePathToApplication, + 'APK', + 'apk', release: release, verifyCaching: verifyCaching, - additionalArgs: additionalArgs + additionalArgs: additionalArgs, ); } -Future _flutterBuildIpa(String relativePathToApplication, { +Future _flutterBuildIpa( + String relativePathToApplication, { required bool release, List additionalArgs = const [], bool verifyCaching = false, }) async { assert(Platform.isMacOS); - printProgress('${green}Testing IPA ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...'); - await _flutterBuild(relativePathToApplication, 'IPA', 'ios', + printProgress( + '${green}Testing IPA ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...', + ); + await _flutterBuild( + relativePathToApplication, + 'IPA', + 'ios', release: release, verifyCaching: verifyCaching, additionalArgs: [...additionalArgs, '--no-codesign'], ); } -Future _flutterBuildLinux(String relativePathToApplication, { +Future _flutterBuildLinux( + String relativePathToApplication, { required bool release, bool verifyCaching = false, List additionalArgs = const [], }) async { assert(Platform.isLinux); await runCommand(flutter, ['config', '--enable-linux-desktop']); - printProgress('${green}Testing Linux ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...'); - await _flutterBuild(relativePathToApplication, 'Linux', 'linux', + printProgress( + '${green}Testing Linux ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...', + ); + await _flutterBuild( + relativePathToApplication, + 'Linux', + 'linux', release: release, verifyCaching: verifyCaching, - additionalArgs: additionalArgs + additionalArgs: additionalArgs, ); } -Future _flutterBuildMacOS(String relativePathToApplication, { +Future _flutterBuildMacOS( + String relativePathToApplication, { required bool release, bool verifyCaching = false, List additionalArgs = const [], }) async { assert(Platform.isMacOS); await runCommand(flutter, ['config', '--enable-macos-desktop']); - printProgress('${green}Testing macOS ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...'); - await _flutterBuild(relativePathToApplication, 'macOS', 'macos', + printProgress( + '${green}Testing macOS ${release ? 'release' : 'debug'} build$reset for $cyan$relativePathToApplication$reset...', + ); + await _flutterBuild( + relativePathToApplication, + 'macOS', + 'macos', release: release, verifyCaching: verifyCaching, - additionalArgs: additionalArgs + additionalArgs: additionalArgs, ); } -Future _flutterBuildWin32(String relativePathToApplication, { +Future _flutterBuildWin32( + String relativePathToApplication, { required bool release, bool verifyCaching = false, List additionalArgs = const [], }) async { assert(Platform.isWindows); - printProgress('${green}Testing ${release ? 'release' : 'debug'} Windows build$reset for $cyan$relativePathToApplication$reset...'); - await _flutterBuild(relativePathToApplication, 'Windows', 'windows', + printProgress( + '${green}Testing ${release ? 'release' : 'debug'} Windows build$reset for $cyan$relativePathToApplication$reset...', + ); + await _flutterBuild( + relativePathToApplication, + 'Windows', + 'windows', release: release, verifyCaching: verifyCaching, - additionalArgs: additionalArgs + additionalArgs: additionalArgs, ); } @@ -708,36 +592,26 @@ Future _flutterBuild( bool verifyCaching = false, List additionalArgs = const [], }) async { - await runCommand(flutter, - [ + await runCommand(flutter, [ + 'build', + platformBuildName, + ...additionalArgs, + if (release) '--release' else '--debug', + '-v', + ], workingDirectory: path.join(flutterRoot, relativePathToApplication)); + + if (verifyCaching) { + printProgress( + '${green}Testing $platformLabel cache$reset for $cyan$relativePathToApplication$reset...', + ); + await runCommand(flutter, [ 'build', platformBuildName, + '--performance-measurement-file=perf.json', ...additionalArgs, - if (release) - '--release' - else - '--debug', + if (release) '--release' else '--debug', '-v', - ], - workingDirectory: path.join(flutterRoot, relativePathToApplication), - ); - - if (verifyCaching) { - printProgress('${green}Testing $platformLabel cache$reset for $cyan$relativePathToApplication$reset...'); - await runCommand(flutter, - [ - 'build', - platformBuildName, - '--performance-measurement-file=perf.json', - ...additionalArgs, - if (release) - '--release' - else - '--debug', - '-v', - ], - workingDirectory: path.join(flutterRoot, relativePathToApplication), - ); + ], workingDirectory: path.join(flutterRoot, relativePathToApplication)); final File file = File(path.join(flutterRoot, relativePathToApplication, 'perf.json')); if (!_allTargetsCached(file)) { foundError([ @@ -749,1844 +623,27 @@ Future _flutterBuild( } bool _allTargetsCached(File performanceFile) { - final Map data = json.decode(performanceFile.readAsStringSync()) - as Map; - final List> targets = (data['targets']! as List) - .cast>(); + if (dryRun) { + return true; + } + final Map data = + json.decode(performanceFile.readAsStringSync()) as Map; + final List> targets = + (data['targets']! as List).cast>(); return targets.every((Map element) => element['skipped'] == true); } -Future _flutterBuildDart2js(String relativePathToApplication, String target, { bool expectNonZeroExit = false }) async { +Future _flutterBuildDart2js( + String relativePathToApplication, + String target, { + bool expectNonZeroExit = false, +}) async { printProgress('${green}Testing Dart2JS build$reset for $cyan$relativePathToApplication$reset...'); - await runCommand(flutter, + await runCommand( + flutter, ['build', 'web', '-v', '--target=$target'], workingDirectory: path.join(flutterRoot, relativePathToApplication), expectNonZeroExit: expectNonZeroExit, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); -} - -Future _runAddToAppLifeCycleTests() async { - if (Platform.isMacOS) { - printProgress('${green}Running add-to-app life cycle iOS integration tests$reset...'); - final String addToAppDir = path.join(flutterRoot, 'dev', 'integration_tests', 'ios_add2app_life_cycle'); - await runCommand('./build_and_test.sh', - [], - workingDirectory: addToAppDir, - ); - } else { - printProgress('${yellow}Skipped on this platform (only iOS has add-to-add lifecycle tests at this time).$reset'); - } -} - -Future _runFrameworkTests() async { - final List trackWidgetCreationAlternatives = ['--track-widget-creation', '--no-track-widget-creation']; - - Future runWidgets() async { - printProgress('${green}Running packages/flutter tests $reset for ${cyan}test/widgets/$reset'); - for (final String trackWidgetCreationOption in trackWidgetCreationAlternatives) { - await _runFlutterTest( - path.join(flutterRoot, 'packages', 'flutter'), - options: [trackWidgetCreationOption], - tests: [ path.join('test', 'widgets') + path.separator ], - ); - } - // Try compiling code outside of the packages/flutter directory with and without --track-widget-creation - for (final String trackWidgetCreationOption in trackWidgetCreationAlternatives) { - await _runFlutterTest( - path.join(flutterRoot, 'dev', 'integration_tests', 'flutter_gallery'), - options: [trackWidgetCreationOption], - fatalWarnings: false, // until we've migrated video_player - ); - } - // Run release mode tests (see packages/flutter/test_release/README.md) - await _runFlutterTest( - path.join(flutterRoot, 'packages', 'flutter'), - options: ['--dart-define=dart.vm.product=true'], - tests: ['test_release${path.separator}'], - ); - // Run profile mode tests (see packages/flutter/test_profile/README.md) - await _runFlutterTest( - path.join(flutterRoot, 'packages', 'flutter'), - options: ['--dart-define=dart.vm.product=false', '--dart-define=dart.vm.profile=true'], - tests: ['test_profile${path.separator}'], - ); - } - - Future runLibraries() async { - final List tests = Directory(path.join(flutterRoot, 'packages', 'flutter', 'test')) - .listSync(followLinks: false) - .whereType() - .where((Directory dir) => !dir.path.endsWith('widgets')) - .map((Directory dir) => path.join('test', path.basename(dir.path)) + path.separator) - .toList(); - printProgress('${green}Running packages/flutter tests$reset for $cyan${tests.join(", ")}$reset'); - for (final String trackWidgetCreationOption in trackWidgetCreationAlternatives) { - await _runFlutterTest( - path.join(flutterRoot, 'packages', 'flutter'), - options: [trackWidgetCreationOption], - tests: tests, - ); - } - } - - Future runExampleTests() async { - // TODO(gspencergoog): Currently Linux LUCI bots can't run desktop Flutter applications, https://github.com/flutter/flutter/issues/90676 - if (!Platform.isLinux || ciProvider != CiProviders.luci) { - await runCommand( - flutter, - ['config', '--enable-${Platform.operatingSystem}-desktop'], - workingDirectory: flutterRoot, - ); - await runCommand( - dart, - [path.join(flutterRoot, 'dev', 'tools', 'examples_smoke_test.dart')], - workingDirectory: path.join(flutterRoot, 'examples', 'api'), - ); - } - for (final FileSystemEntity entity in Directory(path.join(flutterRoot, 'examples')).listSync()) { - if (entity is! Directory || !Directory(path.join(entity.path, 'test')).existsSync()) { - continue; - } - await _runFlutterTest(entity.path); - } - } - - Future runTracingTests() async { - final String tracingDirectory = path.join(flutterRoot, 'dev', 'tracing_tests'); - - // run the tests for debug mode - await _runFlutterTest(tracingDirectory, options: ['--enable-vmservice']); - - Future> verifyTracingAppBuild({ - required String modeArgument, - required String sourceFile, - required Set allowed, - required Set disallowed, - }) async { - try { - await runCommand( - flutter, - [ - 'build', 'appbundle', '--$modeArgument', path.join('lib', sourceFile), - ], - workingDirectory: tracingDirectory, - ); - final Archive archive = ZipDecoder().decodeBytes(File(path.join(tracingDirectory, 'build', 'app', 'outputs', 'bundle', modeArgument, 'app-$modeArgument.aab')).readAsBytesSync()); - final ArchiveFile libapp = archive.findFile('base/lib/arm64-v8a/libapp.so')!; - final Uint8List libappBytes = libapp.content as Uint8List; // bytes decompressed here - final String libappStrings = utf8.decode(libappBytes, allowMalformed: true); - await runCommand(flutter, ['clean'], workingDirectory: tracingDirectory); - final List results = []; - for (final String pattern in allowed) { - if (!libappStrings.contains(pattern)) { - results.add('When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.'); - } - } - for (final String pattern in disallowed) { - if (libappStrings.contains(pattern)) { - results.add('When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.'); - } - } - return results; - } catch (error, stackTrace) { - return [ - error.toString(), - ...stackTrace.toString().trimRight().split('\n'), - ]; - } - } - - final List results = []; - results.addAll(await verifyTracingAppBuild( - modeArgument: 'profile', - sourceFile: 'control.dart', // this is the control, the other two below are the actual test - allowed: { - 'TIMELINE ARGUMENTS TEST CONTROL FILE', - 'toTimelineArguments used in non-debug build', // we call toTimelineArguments directly to check the message does exist - }, - disallowed: { - 'BUILT IN DEBUG MODE', 'BUILT IN RELEASE MODE', - }, - )); - results.addAll(await verifyTracingAppBuild( - modeArgument: 'profile', - sourceFile: 'test.dart', - allowed: { - 'BUILT IN PROFILE MODE', 'RenderTest.performResize called', // controls - 'BUILD', 'LAYOUT', 'PAINT', // we output these to the timeline in profile builds - // (LAYOUT and PAINT also exist because of NEEDS-LAYOUT and NEEDS-PAINT in RenderObject.toStringShort) - }, - disallowed: { - 'BUILT IN DEBUG MODE', 'BUILT IN RELEASE MODE', - 'TestWidget.debugFillProperties called', 'RenderTest.debugFillProperties called', // debug only - 'toTimelineArguments used in non-debug build', // entire function should get dropped by tree shaker - }, - )); - results.addAll(await verifyTracingAppBuild( - modeArgument: 'release', - sourceFile: 'test.dart', - allowed: { - 'BUILT IN RELEASE MODE', 'RenderTest.performResize called', // controls - }, - disallowed: { - 'BUILT IN DEBUG MODE', 'BUILT IN PROFILE MODE', - 'BUILD', 'LAYOUT', 'PAINT', // these are only used in Timeline.startSync calls that should not appear in release builds - 'TestWidget.debugFillProperties called', 'RenderTest.debugFillProperties called', // debug only - 'toTimelineArguments used in non-debug build', // not included in release builds - }, - )); - if (results.isNotEmpty) { - foundError(results); - } - } - - Future runFixTests(String package) async { - final List args = [ - 'fix', - '--compare-to-golden', - ]; - await runCommand( - dart, - args, - workingDirectory: path.join(flutterRoot, 'packages', package, 'test_fixes'), - ); - } - - Future runPrivateTests() async { - final List args = [ - 'run', - 'bin/test_private.dart', - ]; - final Map environment = { - 'FLUTTER_ROOT': flutterRoot, - if (Directory(pubCache).existsSync()) - 'PUB_CACHE': pubCache, - }; - adjustEnvironmentToEnableFlutterAsserts(environment); - await runCommand( - dart, - args, - workingDirectory: path.join(flutterRoot, 'packages', 'flutter', 'test_private'), - environment: environment, - ); - } - - // Tests that take longer than average to run. This is usually because they - // need to compile something large or make use of the analyzer for the test. - // These tests need to be platform agnostic as they are only run on a linux - // machine to save on execution time and cost. - Future runSlow() async { - printProgress('${green}Running slow package tests$reset for directories other than packages/flutter'); - await runTracingTests(); - await runFixTests('flutter'); - await runFixTests('flutter_test'); - await runFixTests('integration_test'); - await runPrivateTests(); - } - - Future runMisc() async { - printProgress('${green}Running package tests$reset for directories other than packages/flutter'); - await _runTestHarnessTests(); - await runExampleTests(); - await _runFlutterTest( - path.join(flutterRoot, 'dev', 'a11y_assessments'), - tests: [ 'test' ], - ); - await _runDartTest(path.join(flutterRoot, 'dev', 'bots')); - await _runDartTest(path.join(flutterRoot, 'dev', 'devicelab'), ensurePrecompiledTool: false); // See https://github.com/flutter/flutter/issues/86209 - await _runDartTest(path.join(flutterRoot, 'dev', 'conductor', 'core'), forceSingleCore: true); - // TODO(gspencergoog): Remove the exception for fatalWarnings once https://github.com/flutter/flutter/issues/113782 has landed. - await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'android_semantics_testing'), fatalWarnings: false); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'ui')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'manual_tests')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'tools')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'tools', 'vitool')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'tools', 'gen_defaults')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'tools', 'gen_keycodes')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'benchmarks', 'test_apps', 'stocks')); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_driver'), tests: [path.join('test', 'src', 'real_tests')]); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'integration_test'), options: [ - '--enable-vmservice', - // Web-specific tests depend on Chromium, so they run as part of the web_long_running_tests shard. - '--exclude-tags=web', - ]); - // Run java unit tests for integration_test - // - // Generate Gradle wrapper if it doesn't exist. - Process.runSync( - flutter, - ['build', 'apk', '--config-only'], - workingDirectory: path.join(flutterRoot, 'packages', 'integration_test', 'example', 'android'), - ); - await runCommand( - path.join(flutterRoot, 'packages', 'integration_test', 'example', 'android', 'gradlew$bat'), - [ - ':integration_test:testDebugUnitTest', - '--tests', - 'dev.flutter.plugins.integration_test.FlutterDeviceScreenshotTest', - ], - workingDirectory: path.join(flutterRoot, 'packages', 'integration_test', 'example', 'android'), - ); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_goldens')); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_localizations')); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_test')); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'fuchsia_remote_debug_protocol')); - await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'non_nullable')); - const String httpClientWarning = - 'Warning: At least one test in this suite creates an HttpClient. When running a test suite that uses\n' - 'TestWidgetsFlutterBinding, all HTTP requests will return status code 400, and no network request\n' - 'will actually be made. Any test expecting a real network connection and status code will fail.\n' - 'To test code that needs an HttpClient, provide your own HttpClient implementation to the code under\n' - 'test, so that your test can consistently provide a testable response to the code under test.'; - await _runFlutterTest( - path.join(flutterRoot, 'packages', 'flutter_test'), - script: path.join('test', 'bindings_test_failure.dart'), - expectFailure: true, - printOutput: false, - outputChecker: (CommandResult result) { - final Iterable matches = httpClientWarning.allMatches(result.flattenedStdout!); - if (matches.isEmpty || matches.length > 1) { - return 'Failed to print warning about HttpClientUsage, or printed it too many times.\n\n' - 'stdout:\n${result.flattenedStdout}\n\n' - 'stderr:\n${result.flattenedStderr}'; - } - return null; - }, - ); - } - - await selectSubshard({ - 'widgets': runWidgets, - 'libraries': runLibraries, - 'slow': runSlow, - 'misc': runMisc, - }); -} - -Future _runFrameworkCoverage() async { - final File coverageFile = File(path.join(flutterRoot, 'packages', 'flutter', 'coverage', 'lcov.info')); - if (!coverageFile.existsSync()) { - foundError([ - '${red}Coverage file not found.$reset', - 'Expected to find: $cyan${coverageFile.absolute.path}$reset', - 'This file is normally obtained by running `${green}flutter update-packages$reset`.', - ]); - return; - } - coverageFile.deleteSync(); - await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter'), - options: const ['--coverage'], - ); - if (!coverageFile.existsSync()) { - foundError([ - '${red}Coverage file not found.$reset', - 'Expected to find: $cyan${coverageFile.absolute.path}$reset', - 'This file should have been generated by the `${green}flutter test --coverage$reset` script, but was not.', - ]); - return; - } -} - -Future _runWebHtmlUnitTests() { - return _runWebUnitTests('html'); -} - -Future _runWebCanvasKitUnitTests() { - return _runWebUnitTests('canvaskit'); -} - -Future _runWebUnitTests(String webRenderer) async { - final Map subshards = {}; - - final Directory flutterPackageDirectory = Directory(path.join(flutterRoot, 'packages', 'flutter')); - final Directory flutterPackageTestDirectory = Directory(path.join(flutterPackageDirectory.path, 'test')); - - final List allTests = flutterPackageTestDirectory - .listSync() - .whereType() - .expand((Directory directory) => directory - .listSync(recursive: true) - .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart')) - ) - .whereType() - .map((File file) => path.relative(file.path, from: flutterPackageDirectory.path)) - .where((String filePath) => !kWebTestFileKnownFailures[webRenderer]!.contains(path.split(filePath).join('/'))) - .toList() - // Finally we shuffle the list because we want the average cost per file to be uniformly - // distributed. If the list is not sorted then different shards and batches may have - // very different characteristics. - // We use a constant seed for repeatability. - ..shuffle(math.Random(0)); - - assert(webShardCount >= 1); - final int testsPerShard = (allTests.length / webShardCount).ceil(); - assert(testsPerShard * webShardCount >= allTests.length); - - // This for loop computes all but the last shard. - for (int index = 0; index < webShardCount - 1; index += 1) { - subshards['$index'] = () => _runFlutterWebTest( - webRenderer, - flutterPackageDirectory.path, - allTests.sublist( - index * testsPerShard, - (index + 1) * testsPerShard, - ), - ); - } - - // The last shard also runs the flutter_web_plugins tests. - // - // We make sure the last shard ends in _last so it's easier to catch mismatches - // between `.cirrus.yml` and `test.dart`. - subshards['${webShardCount - 1}_last'] = () async { - await _runFlutterWebTest( - webRenderer, - flutterPackageDirectory.path, - allTests.sublist( - (webShardCount - 1) * testsPerShard, - allTests.length, - ), - ); - await _runFlutterWebTest( - webRenderer, - path.join(flutterRoot, 'packages', 'flutter_web_plugins'), - ['test'], - ); - await _runFlutterWebTest( - webRenderer, - path.join(flutterRoot, 'packages', 'flutter_driver'), - [path.join('test', 'src', 'web_tests', 'web_extension_test.dart')], - ); - }; - - await selectSubshard(subshards); -} - -/// Coarse-grained integration tests running on the Web. -Future _runWebLongRunningTests() async { - final String engineVersion = File(engineVersionFile).readAsStringSync().trim(); - final String engineRealm = File(engineRealmFile).readAsStringSync().trim(); - if (engineRealm.isNotEmpty) { - return; - } - final List tests = [ - for (final String buildMode in _kAllBuildModes) ...[ - () => _runFlutterDriverWebTest( - testAppDirectory: path.join('packages', 'integration_test', 'example'), - target: path.join('test_driver', 'failure.dart'), - buildMode: buildMode, - renderer: 'canvaskit', - // This test intentionally fails and prints stack traces in the browser - // logs. To avoid confusion, silence browser output. - silenceBrowserOutput: true, - ), - () => _runFlutterDriverWebTest( - testAppDirectory: path.join('packages', 'integration_test', 'example'), - target: path.join('integration_test', 'example_test.dart'), - driver: path.join('test_driver', 'integration_test.dart'), - buildMode: buildMode, - renderer: 'canvaskit', - expectWriteResponseFile: true, - expectResponseFileContent: 'null', - ), - () => _runFlutterDriverWebTest( - testAppDirectory: path.join('packages', 'integration_test', 'example'), - target: path.join('integration_test', 'extended_test.dart'), - driver: path.join('test_driver', 'extended_integration_test.dart'), - buildMode: buildMode, - renderer: 'canvaskit', - expectWriteResponseFile: true, - expectResponseFileContent: ''' -{ - "screenshots": [ - { - "screenshotName": "platform_name", - "bytes": [] - }, - { - "screenshotName": "platform_name_2", - "bytes": [] - } - ] -}''', - ), - ], - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - () => _runWebE2eTest('platform_messages_integration', buildMode: 'debug', renderer: 'canvaskit'), - () => _runWebE2eTest('platform_messages_integration', buildMode: 'profile', renderer: 'html'), - () => _runWebE2eTest('platform_messages_integration', buildMode: 'release', renderer: 'html'), - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - () => _runWebE2eTest('profile_diagnostics_integration', buildMode: 'debug', renderer: 'html'), - () => _runWebE2eTest('profile_diagnostics_integration', buildMode: 'profile', renderer: 'canvaskit'), - () => _runWebE2eTest('profile_diagnostics_integration', buildMode: 'release', renderer: 'html'), - - // This test is only known to work in debug mode. - () => _runWebE2eTest('scroll_wheel_integration', buildMode: 'debug', renderer: 'html'), - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - () => _runWebE2eTest('text_editing_integration', buildMode: 'debug', renderer: 'canvaskit'), - () => _runWebE2eTest('text_editing_integration', buildMode: 'profile', renderer: 'html'), - () => _runWebE2eTest('text_editing_integration', buildMode: 'release', renderer: 'html'), - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - () => _runWebE2eTest('url_strategy_integration', buildMode: 'debug', renderer: 'html'), - () => _runWebE2eTest('url_strategy_integration', buildMode: 'profile', renderer: 'canvaskit'), - () => _runWebE2eTest('url_strategy_integration', buildMode: 'release', renderer: 'html'), - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - () => _runWebE2eTest('capabilities_integration_canvaskit', buildMode: 'debug', renderer: 'auto'), - () => _runWebE2eTest('capabilities_integration_canvaskit', buildMode: 'profile', renderer: 'canvaskit'), - () => _runWebE2eTest('capabilities_integration_html', buildMode: 'release', renderer: 'html'), - - // This test doesn't do anything interesting w.r.t. rendering, so we don't run the full build mode x renderer matrix. - // CacheWidth and CacheHeight are only currently supported in CanvasKit mode, so we don't run the test in HTML mode. - () => _runWebE2eTest('cache_width_cache_height_integration', buildMode: 'debug', renderer: 'auto'), - () => _runWebE2eTest('cache_width_cache_height_integration', buildMode: 'profile', renderer: 'canvaskit'), - - () => _runWebTreeshakeTest(), - - () => _runFlutterDriverWebTest( - testAppDirectory: path.join(flutterRoot, 'examples', 'hello_world'), - target: 'test_driver/smoke_web_engine.dart', - buildMode: 'profile', - renderer: 'auto', - ), - () => _runGalleryE2eWebTest('debug'), - () => _runGalleryE2eWebTest('debug', canvasKit: true), - () => _runGalleryE2eWebTest('profile'), - () => _runGalleryE2eWebTest('profile', canvasKit: true), - () => _runGalleryE2eWebTest('release'), - () => _runGalleryE2eWebTest('release', canvasKit: true), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withoutFlutterJs), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withFlutterJs), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withFlutterJsShort), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn), - () => runWebServiceWorkerTest(headless: true, testType: ServiceWorkerTestType.withFlutterJsNonceOn), - () => runWebServiceWorkerTestWithCachingResources(headless: true, testType: ServiceWorkerTestType.withoutFlutterJs), - () => runWebServiceWorkerTestWithCachingResources(headless: true, testType: ServiceWorkerTestType.withFlutterJs), - () => runWebServiceWorkerTestWithCachingResources(headless: true, testType: ServiceWorkerTestType.withFlutterJsShort), - () => runWebServiceWorkerTestWithCachingResources(headless: true, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent), - () => runWebServiceWorkerTestWithCachingResources(headless: true, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn), - () => runWebServiceWorkerTestWithGeneratedEntrypoint(headless: true), - () => runWebServiceWorkerTestWithBlockedServiceWorkers(headless: true), - () => runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: true), - () => _runWebStackTraceTest('profile', 'lib/stack_trace.dart'), - () => _runWebStackTraceTest('release', 'lib/stack_trace.dart'), - () => _runWebStackTraceTest('profile', 'lib/framework_stack_trace.dart'), - () => _runWebStackTraceTest('release', 'lib/framework_stack_trace.dart'), - () => _runWebDebugTest('lib/stack_trace.dart'), - () => _runWebDebugTest('lib/framework_stack_trace.dart'), - () => _runWebDebugTest('lib/web_directory_loading.dart'), - () => _runWebDebugTest('lib/web_resources_cdn_test.dart', - additionalArguments: [ - '--dart-define=TEST_FLUTTER_ENGINE_VERSION=$engineVersion', - ]), - () => _runWebDebugTest('test/test.dart'), - () => _runWebDebugTest('lib/null_safe_main.dart'), - () => _runWebDebugTest('lib/web_define_loading.dart', - additionalArguments: [ - '--dart-define=test.valueA=Example,A', - '--dart-define=test.valueB=Value', - ] - ), - () => _runWebReleaseTest('lib/web_define_loading.dart', - additionalArguments: [ - '--dart-define=test.valueA=Example,A', - '--dart-define=test.valueB=Value', - ] - ), - () => _runWebDebugTest('lib/sound_mode.dart'), - () => _runWebReleaseTest('lib/sound_mode.dart'), - () => _runFlutterWebTest( - 'html', - path.join(flutterRoot, 'packages', 'integration_test'), - ['test/web_extension_test.dart'], - ), - () => _runFlutterWebTest( - 'canvaskit', - path.join(flutterRoot, 'packages', 'integration_test'), - ['test/web_extension_test.dart'], - ), - ]; - - // Shuffling mixes fast tests with slow tests so shards take roughly the same - // amount of time to run. - tests.shuffle(math.Random(0)); - - await _ensureChromeDriverIsRunning(); - await _runShardRunnerIndexOfTotalSubshard(tests); - await _stopChromeDriver(); -} - -/// Runs one of the `dev/integration_tests/web_e2e_tests` tests. -Future _runWebE2eTest( - String name, { - required String buildMode, - required String renderer, -}) async { - await _runFlutterDriverWebTest( - target: path.join('test_driver', '$name.dart'), - buildMode: buildMode, - renderer: renderer, - testAppDirectory: path.join(flutterRoot, 'dev', 'integration_tests', 'web_e2e_tests'), - ); -} - -Future _runFlutterDriverWebTest({ - required String target, - required String buildMode, - required String renderer, - required String testAppDirectory, - String? driver, - bool expectFailure = false, - bool silenceBrowserOutput = false, - bool expectWriteResponseFile = false, - String expectResponseFileContent = '', -}) async { - printProgress('${green}Running integration tests $target in $buildMode mode.$reset'); - await runCommand( - flutter, - [ 'clean' ], - workingDirectory: testAppDirectory, - ); - final String responseFile = - path.join(testAppDirectory, 'build', 'integration_response_data.json'); - if (File(responseFile).existsSync()) { - File(responseFile).deleteSync(); - } - await runCommand( - flutter, - [ - ...flutterTestArgs, - 'drive', - if (driver != null) '--driver=$driver', - '--target=$target', - '--browser-name=chrome', - '-d', - 'web-server', - '--$buildMode', - '--web-renderer=$renderer', - ], - expectNonZeroExit: expectFailure, - workingDirectory: testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - removeLine: (String line) { - if (!silenceBrowserOutput) { - return false; - } - if (line.trim().startsWith('[INFO]')) { - return true; - } - return false; - }, - ); - if (expectWriteResponseFile) { - if (!File(responseFile).existsSync()) { - foundError([ - '$bold${red}Command did not write the response file but expected response file written.$reset', - ]); - } else { - final String response = File(responseFile).readAsStringSync(); - if (response != expectResponseFileContent) { - foundError([ - '$bold${red}Command write the response file with $response but expected response file with $expectResponseFileContent.$reset', - ]); - } - } - } -} - -// Compiles a sample web app and checks that its JS doesn't contain certain -// debug code that we expect to be tree shaken out. -// -// The app is compiled in `--profile` mode to prevent the compiler from -// minifying the symbols. -Future _runWebTreeshakeTest() async { - final String testAppDirectory = path.join(flutterRoot, 'dev', 'integration_tests', 'web_e2e_tests'); - final String target = path.join('lib', 'treeshaking_main.dart'); - await runCommand( - flutter, - [ 'clean' ], - workingDirectory: testAppDirectory, + environment: {'FLUTTER_WEB': 'true'}, ); - await runCommand( - flutter, - [ - 'build', - 'web', - '--target=$target', - '--profile', - ], - workingDirectory: testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); - - final File mainDartJs = File(path.join(testAppDirectory, 'build', 'web', 'main.dart.js')); - final String javaScript = mainDartJs.readAsStringSync(); - - // Check that we're not looking at minified JS. Otherwise this test would result in false positive. - expect(javaScript.contains('RootElement'), true); - - const String word = 'debugFillProperties'; - int count = 0; - int pos = javaScript.indexOf(word); - final int contentLength = javaScript.length; - while (pos != -1) { - count += 1; - pos += word.length; - if (pos >= contentLength || count > 100) { - break; - } - pos = javaScript.indexOf(word, pos); - } - - // The following are classes from `timeline.dart` that should be treeshaken - // off unless the app (typically a benchmark) uses methods that need them. - expect(javaScript.contains('AggregatedTimedBlock'), false); - expect(javaScript.contains('AggregatedTimings'), false); - expect(javaScript.contains('_BlockBuffer'), false); - expect(javaScript.contains('_StringListChain'), false); - expect(javaScript.contains('_Float64ListChain'), false); - - const int kMaxExpectedDebugFillProperties = 11; - if (count > kMaxExpectedDebugFillProperties) { - throw Exception( - 'Too many occurrences of "$word" in compiled JavaScript.\n' - 'Expected no more than $kMaxExpectedDebugFillProperties, but found $count.' - ); - } -} - -/// Returns the commit hash of the flutter/packages repository that's rolled in. -/// -/// The flutter/packages repository is a downstream dependency, it is only used -/// by flutter/flutter for testing purposes, to assure stable tests for a given -/// flutter commit the flutter/packages commit hash to test against is coded in -/// the bin/internal/flutter_packages.version file. -/// -/// The `filesystem` parameter specified filesystem to read the packages version file from. -/// The `packagesVersionFile` parameter allows specifying an alternative path for the -/// packages version file, when null [flutterPackagesVersionFile] is used. -Future getFlutterPackagesVersion({ - fs.FileSystem fileSystem = const LocalFileSystem(), - String? packagesVersionFile, -}) async { - final File versionFile = fileSystem.file(packagesVersionFile ?? flutterPackagesVersionFile); - final String versionFileContents = await versionFile.readAsString(); - return versionFileContents.trim(); -} - -/// Executes the test suite for the flutter/packages repo. -Future _runFlutterPackagesTests() async { - Future runAnalyze() async { - printProgress('${green}Running analysis for flutter/packages$reset'); - final Directory checkout = Directory.systemTemp.createTempSync('flutter_packages.'); - await runCommand( - 'git', - [ - '-c', - 'core.longPaths=true', - 'clone', - 'https://github.com/flutter/packages.git', - '.', - ], - workingDirectory: checkout.path, - ); - final String packagesCommit = await getFlutterPackagesVersion(); - await runCommand( - 'git', - [ - '-c', - 'core.longPaths=true', - 'checkout', - packagesCommit, - ], - workingDirectory: checkout.path, - ); - // Prep the repository tooling. - // This test does not use tool_runner.sh because in this context the test - // should always run on the entire packages repo, while tool_runner.sh - // is designed for flutter/packages CI and only analyzes changed repository - // files when run for anything but master. - final String toolDir = path.join(checkout.path, 'script', 'tool'); - await runCommand( - 'dart', - [ - 'pub', - 'get', - ], - workingDirectory: toolDir, - ); - final String toolScript = path.join(toolDir, 'bin', 'flutter_plugin_tools.dart'); - await runCommand( - 'dart', - [ - 'run', - toolScript, - 'analyze', - // Fetch the oldest possible dependencies, rather than the newest, to - // insulate flutter/flutter from out-of-band failures when new versions - // of dependencies are published. This compensates for the fact that - // flutter/packages doesn't use pinned dependencies, and for the - // purposes of this test using old dependencies is fine. See - // https://github.com/flutter/flutter/issues/129633 - '--downgrade', - '--custom-analysis=script/configs/custom_analysis.yaml', - ], - workingDirectory: checkout.path, - ); - } - await selectSubshard({ - 'analyze': runAnalyze, - }); -} - -// Runs customer_testing. -Future _runCustomerTesting() async { - printProgress('${green}Running customer testing$reset'); - await runCommand( - 'git', - [ - 'fetch', - 'origin', - 'master', - ], - workingDirectory: flutterRoot, - ); - await runCommand( - 'git', - [ - 'checkout', - 'master', - ], - workingDirectory: flutterRoot, - ); - final Map env = Platform.environment; - final String? revision = env['REVISION']; - if (revision != null) { - await runCommand( - 'git', - [ - 'checkout', - revision, - ], - workingDirectory: flutterRoot, - ); - } - final String winScript = path.join(flutterRoot, 'dev', 'customer_testing', 'ci.bat'); - await runCommand( - Platform.isWindows? winScript: './ci.sh', - [], - workingDirectory: path.join(flutterRoot, 'dev', 'customer_testing'), - ); -} - -// Runs analysis tests. -Future _runAnalyze() async { - printProgress('${green}Running analysis testing$reset'); - await runCommand( - 'dart', - [ - '--enable-asserts', - path.join(flutterRoot, 'dev', 'bots', 'analyze.dart'), - ], - workingDirectory: flutterRoot, - ); -} - -// Runs flutter_precache. -Future _runFuchsiaPrecache() async { - printProgress('${green}Running flutter precache tests$reset'); - await runCommand( - 'flutter', - [ - 'config', - '--enable-fuchsia', - ], - workingDirectory: flutterRoot, - ); - await runCommand( - 'flutter', - [ - 'precache', - '--flutter_runner', - '--fuchsia', - '--no-android', - '--no-ios', - '--force', - ], - workingDirectory: flutterRoot, - ); -} - -// Runs docs. -Future _runDocs() async { - printProgress('${green}Running flutter doc tests$reset'); - await runCommand( - './dev/bots/docs.sh', - [ - '--output', - 'dev/docs/api_docs.zip', - '--keep-staging', - '--staging-dir', - 'dev/docs', - ], - workingDirectory: flutterRoot, - ); -} - -// Verifies binaries are codesigned. -Future _runVerifyCodesigned() async { - printProgress('${green}Running binaries codesign verification$reset'); - await runCommand( - 'flutter', - [ - 'precache', - '--android', - '--ios', - '--macos' - ], - workingDirectory: flutterRoot, - ); - - await verifyExist(flutterRoot); - await verifySignatures(flutterRoot); -} - -const List expectedEntitlements = [ - 'com.apple.security.cs.allow-jit', - 'com.apple.security.cs.allow-unsigned-executable-memory', - 'com.apple.security.cs.allow-dyld-environment-variables', - 'com.apple.security.network.client', - 'com.apple.security.network.server', - 'com.apple.security.cs.disable-library-validation', -]; - -/// Binaries that are expected to be codesigned and have entitlements. -/// -/// This list should be kept in sync with the actual contents of Flutter's -/// cache. -List binariesWithEntitlements(String flutterRoot) { - return [ - 'artifacts/engine/android-arm-profile/darwin-x64/gen_snapshot', - 'artifacts/engine/android-arm-release/darwin-x64/gen_snapshot', - 'artifacts/engine/android-arm64-profile/darwin-x64/gen_snapshot', - 'artifacts/engine/android-arm64-release/darwin-x64/gen_snapshot', - 'artifacts/engine/android-x64-profile/darwin-x64/gen_snapshot', - 'artifacts/engine/android-x64-release/darwin-x64/gen_snapshot', - 'artifacts/engine/darwin-x64-profile/gen_snapshot', - 'artifacts/engine/darwin-x64-profile/gen_snapshot_arm64', - 'artifacts/engine/darwin-x64-profile/gen_snapshot_x64', - 'artifacts/engine/darwin-x64-release/gen_snapshot', - 'artifacts/engine/darwin-x64-release/gen_snapshot_arm64', - 'artifacts/engine/darwin-x64-release/gen_snapshot_x64', - 'artifacts/engine/darwin-x64/flutter_tester', - 'artifacts/engine/darwin-x64/gen_snapshot', - 'artifacts/engine/darwin-x64/gen_snapshot_arm64', - 'artifacts/engine/darwin-x64/gen_snapshot_x64', - 'artifacts/engine/ios-profile/gen_snapshot_arm64', - 'artifacts/engine/ios-release/gen_snapshot_arm64', - 'artifacts/engine/ios/gen_snapshot_arm64', - 'artifacts/libimobiledevice/idevicescreenshot', - 'artifacts/libimobiledevice/idevicesyslog', - 'artifacts/libimobiledevice/libimobiledevice-1.0.6.dylib', - 'artifacts/libplist/libplist-2.0.3.dylib', - 'artifacts/openssl/libcrypto.1.1.dylib', - 'artifacts/openssl/libssl.1.1.dylib', - 'artifacts/usbmuxd/iproxy', - 'artifacts/usbmuxd/libusbmuxd-2.0.6.dylib', - 'dart-sdk/bin/dart', - 'dart-sdk/bin/dartaotruntime', - 'dart-sdk/bin/utils/gen_snapshot', - 'dart-sdk/bin/utils/wasm-opt', - ] - .map((String relativePath) => path.join(flutterRoot, 'bin', 'cache', relativePath)).toList(); -} - -/// Binaries that are only expected to be codesigned. -/// -/// This list should be kept in sync with the actual contents of Flutter's -/// cache. -List binariesWithoutEntitlements(String flutterRoot) { - return [ - 'artifacts/engine/darwin-x64-profile/FlutterMacOS.framework/Versions/A/FlutterMacOS', - 'artifacts/engine/darwin-x64-release/FlutterMacOS.framework/Versions/A/FlutterMacOS', - 'artifacts/engine/darwin-x64/FlutterMacOS.framework/Versions/A/FlutterMacOS', - 'artifacts/engine/darwin-x64/font-subset', - 'artifacts/engine/darwin-x64/impellerc', - 'artifacts/engine/darwin-x64/libpath_ops.dylib', - 'artifacts/engine/darwin-x64/libtessellator.dylib', - 'artifacts/engine/ios-profile/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios-profile/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/engine/ios-profile/extension_safe/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios-profile/extension_safe/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/engine/ios-release/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios-release/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/engine/ios-release/extension_safe/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios-release/extension_safe/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/engine/ios/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/engine/ios/extension_safe/Flutter.xcframework/ios-arm64/Flutter.framework/Flutter', - 'artifacts/engine/ios/extension_safe/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter', - 'artifacts/ios-deploy/ios-deploy', - ] - .map((String relativePath) => path.join(flutterRoot, 'bin', 'cache', relativePath)).toList(); -} - -/// xcframeworks that are expected to be codesigned. -/// -/// This list should be kept in sync with the actual contents of Flutter's -/// cache. -List signedXcframeworks(String flutterRoot) { - return [ - 'artifacts/engine/ios-profile/Flutter.xcframework', - 'artifacts/engine/ios-profile/extension_safe/Flutter.xcframework', - 'artifacts/engine/ios-release/Flutter.xcframework', - 'artifacts/engine/ios-release/extension_safe/Flutter.xcframework', - 'artifacts/engine/ios/Flutter.xcframework', - 'artifacts/engine/ios/extension_safe/Flutter.xcframework', - ] - .map((String relativePath) => path.join(flutterRoot, 'bin', 'cache', relativePath)).toList(); -} - -/// Verify the existence of all expected binaries in cache. -/// -/// This function ignores code signatures and entitlements, and is intended to -/// be run on every commit. It should throw if either new binaries are added -/// to the cache or expected binaries removed. In either case, this class' -/// [binariesWithEntitlements] or [binariesWithoutEntitlements] lists should -/// be updated accordingly. -Future verifyExist( - String flutterRoot, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager() -}) async { - final Set foundFiles = {}; - final String cacheDirectory = path.join(flutterRoot, 'bin', 'cache'); - - for (final String binaryPath - in await findBinaryPaths(cacheDirectory, processManager: processManager)) { - if (binariesWithEntitlements(flutterRoot).contains(binaryPath)) { - foundFiles.add(binaryPath); - } else if (binariesWithoutEntitlements(flutterRoot).contains(binaryPath)) { - foundFiles.add(binaryPath); - } else { - throw Exception( - 'Found unexpected binary in cache: $binaryPath'); - } - } - - final List allExpectedFiles = binariesWithEntitlements(flutterRoot) + binariesWithoutEntitlements(flutterRoot); - if (foundFiles.length < allExpectedFiles.length) { - final List unfoundFiles = allExpectedFiles - .where( - (String file) => !foundFiles.contains(file), - ) - .toList(); - print( - 'Expected binaries not found in cache:\n\n${unfoundFiles.join('\n')}\n\n' - 'If this commit is removing binaries from the cache, this test should be fixed by\n' - 'removing the relevant entry from either the "binariesWithEntitlements" or\n' - '"binariesWithoutEntitlements" getters in dev/tools/lib/codesign.dart.', - ); - throw Exception('Did not find all expected binaries!'); - } - - print('All expected binaries present.'); -} - -/// Verify code signatures and entitlements of all binaries in the cache. -Future verifySignatures( - String flutterRoot, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager()} -) async { - final List unsignedFiles = []; - final List wrongEntitlementBinaries = []; - final List unexpectedFiles = []; - final String cacheDirectory = path.join(flutterRoot, 'bin', 'cache'); - - final List binariesAndXcframeworks = - (await findBinaryPaths(cacheDirectory, processManager: processManager)) + (await findXcframeworksPaths(cacheDirectory, processManager: processManager)); - - for (final String pathToCheck in binariesAndXcframeworks) { - bool verifySignature = false; - bool verifyEntitlements = false; - if (binariesWithEntitlements(flutterRoot).contains(pathToCheck)) { - verifySignature = true; - verifyEntitlements = true; - } - if (binariesWithoutEntitlements(flutterRoot).contains(pathToCheck)) { - verifySignature = true; - } - if (signedXcframeworks(flutterRoot).contains(pathToCheck)) { - verifySignature = true; - } - if (!verifySignature && !verifyEntitlements) { - unexpectedFiles.add(pathToCheck); - print('Unexpected binary or xcframework $pathToCheck found in cache!'); - continue; - } - print('Verifying the code signature of $pathToCheck'); - final io.ProcessResult codeSignResult = await processManager.run( - [ - 'codesign', - '-vvv', - pathToCheck, - ], - ); - if (codeSignResult.exitCode != 0) { - unsignedFiles.add(pathToCheck); - print( - 'File "$pathToCheck" does not appear to be codesigned.\n' - 'The `codesign` command failed with exit code ${codeSignResult.exitCode}:\n' - '${codeSignResult.stderr}\n', - ); - continue; - } - if (verifyEntitlements) { - print('Verifying entitlements of $pathToCheck'); - if (!(await hasExpectedEntitlements(pathToCheck, flutterRoot, processManager: processManager))) { - wrongEntitlementBinaries.add(pathToCheck); - } - } - } - - // First print all deviations from expectations - if (unsignedFiles.isNotEmpty) { - print('Found ${unsignedFiles.length} unsigned files:'); - unsignedFiles.forEach(print); - } - - if (wrongEntitlementBinaries.isNotEmpty) { - print('Found ${wrongEntitlementBinaries.length} files with unexpected entitlements:'); - wrongEntitlementBinaries.forEach(print); - } - - if (unexpectedFiles.isNotEmpty) { - print('Found ${unexpectedFiles.length} unexpected files in the cache:'); - unexpectedFiles.forEach(print); - } - - // Finally, exit on any invalid state - if (unsignedFiles.isNotEmpty) { - throw Exception('Test failed because unsigned files detected.'); - } - - if (wrongEntitlementBinaries.isNotEmpty) { - throw Exception( - 'Test failed because files found with the wrong entitlements:\n' - '${wrongEntitlementBinaries.join('\n')}', - ); - } - - if (unexpectedFiles.isNotEmpty) { - throw Exception('Test failed because unexpected files found in the cache.'); - } - print('Verified that files are codesigned and have expected entitlements.'); -} - -/// Find every binary file in the given [rootDirectory]. -Future> findBinaryPaths( - String rootDirectory, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager() -}) async { - final List allBinaryPaths = []; - final io.ProcessResult result = await processManager.run( - [ - 'find', - rootDirectory, - '-type', - 'f', - ], - ); - final List allFiles = (result.stdout as String) - .split('\n') - .where((String s) => s.isNotEmpty) - .toList(); - - await Future.forEach(allFiles, (String filePath) async { - if (await isBinary(filePath, processManager: processManager)) { - allBinaryPaths.add(filePath); - print('Found: $filePath\n'); - } - }); - return allBinaryPaths; -} - -/// Find every xcframework in the given [rootDirectory]. -Future> findXcframeworksPaths( - String rootDirectory, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager() - }) async { - final io.ProcessResult result = await processManager.run( - [ - 'find', - rootDirectory, - '-type', - 'd', - '-name', - '*xcframework', - ], - ); - final List allXcframeworkPaths = LineSplitter.split(result.stdout as String) - .where((String s) => s.isNotEmpty) - .toList(); - for (final String path in allXcframeworkPaths) { - print('Found: $path\n'); - } - return allXcframeworkPaths; -} - -/// Check mime-type of file at [filePath] to determine if it is binary. -Future isBinary( - String filePath, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager()} -) async { - final io.ProcessResult result = await processManager.run( - [ - 'file', - '--mime-type', - '-b', // is binary - filePath, - ], - ); - return (result.stdout as String).contains('application/x-mach-binary'); -} - -/// Check if the binary has the expected entitlements. -Future hasExpectedEntitlements( - String binaryPath, - String flutterRoot, - {@visibleForTesting ProcessManager processManager = const LocalProcessManager()} -) async { - final io.ProcessResult entitlementResult = await processManager.run( - [ - 'codesign', - '--display', - '--entitlements', - ':-', - binaryPath, - ], - ); - - if (entitlementResult.exitCode != 0) { - print( - 'The `codesign --entitlements` command failed with exit code ${entitlementResult.exitCode}:\n' - '${entitlementResult.stderr}\n', - ); - return false; - } - - bool passes = true; - final String output = entitlementResult.stdout as String; - for (final String entitlement in expectedEntitlements) { - final bool entitlementExpected = - binariesWithEntitlements(flutterRoot).contains(binaryPath); - if (output.contains(entitlement) != entitlementExpected) { - print( - 'File "$binaryPath" ${entitlementExpected ? 'does not have expected' : 'has unexpected'} ' - 'entitlement $entitlement.', - ); - passes = false; - } - } - return passes; -} - -/// Runs the skp_generator from the flutter/tests repo. -/// -/// See also the customer_tests shard. -/// -/// Generated SKPs are ditched, this just verifies that it can run without failure. -Future _runSkpGeneratorTests() async { - printProgress('${green}Running skp_generator from flutter/tests$reset'); - final Directory checkout = Directory.systemTemp.createTempSync('flutter_skp_generator.'); - await runCommand( - 'git', - [ - '-c', - 'core.longPaths=true', - 'clone', - 'https://github.com/flutter/tests.git', - '.', - ], - workingDirectory: checkout.path, - ); - await runCommand( - './build.sh', - [ ], - workingDirectory: path.join(checkout.path, 'skp_generator'), - ); -} - -Future _runRealmCheckerTest() async { - final String engineRealm = File(engineRealmFile).readAsStringSync().trim(); - if (engineRealm.isNotEmpty) { - foundError(['The checked-in engine.realm file must be empty.']); - } -} - -// The `chromedriver` process created by this test. -// -// If an existing chromedriver is already available on port 4444, the existing -// process is reused and this variable remains null. -Command? _chromeDriver; - -Future _isChromeDriverRunning() async { - try { - final RawSocket socket = await RawSocket.connect('localhost', 4444); - socket.shutdown(SocketDirection.both); - await socket.close(); - return true; - } on SocketException { - return false; - } -} - -Future _ensureChromeDriverIsRunning() async { - // If we cannot connect to ChromeDriver, assume it is not running. Launch it. - if (!await _isChromeDriverRunning()) { - printProgress('Starting chromedriver'); - // Assume chromedriver is in the PATH. - _chromeDriver = await startCommand( - // TODO(ianh): this is the only remaining consumer of startCommand other than runCommand - // and it doesn't use most of startCommand's features; we could simplify this a lot by - // inlining the relevant parts of startCommand here. - 'chromedriver', - ['--port=4444'], - ); - while (!await _isChromeDriverRunning()) { - await Future.delayed(const Duration(milliseconds: 100)); - print('Waiting for chromedriver to start up.'); - } - } - - final HttpClient client = HttpClient(); - final Uri chromeDriverUrl = Uri.parse('http://localhost:4444/status'); - final HttpClientRequest request = await client.getUrl(chromeDriverUrl); - final HttpClientResponse response = await request.close(); - final Map webDriverStatus = json.decode(await response.transform(utf8.decoder).join()) as Map; - client.close(); - final bool webDriverReady = (webDriverStatus['value'] as Map)['ready'] as bool; - if (!webDriverReady) { - throw Exception('WebDriver not available.'); - } -} - -Future _stopChromeDriver() async { - if (_chromeDriver == null) { - return; - } - print('Stopping chromedriver'); - _chromeDriver!.process.kill(); -} - -/// Exercises the old gallery in a browser for a long period of time, looking -/// for memory leaks and dangling pointers. -/// -/// This is not a performance test. -/// -/// If [canvasKit] is set to true, runs the test in CanvasKit mode. -/// -/// The test is written using `package:integration_test` (despite the "e2e" in -/// the name, which is there for historic reasons). -Future _runGalleryE2eWebTest(String buildMode, { bool canvasKit = false }) async { - printProgress('${green}Running flutter_gallery integration test in --$buildMode using ${canvasKit ? 'CanvasKit' : 'HTML'} renderer.$reset'); - final String testAppDirectory = path.join(flutterRoot, 'dev', 'integration_tests', 'flutter_gallery'); - await runCommand( - flutter, - [ 'clean' ], - workingDirectory: testAppDirectory, - ); - await runCommand( - flutter, - [ - ...flutterTestArgs, - 'drive', - if (canvasKit) - '--dart-define=FLUTTER_WEB_USE_SKIA=true', - if (!canvasKit) - '--dart-define=FLUTTER_WEB_USE_SKIA=false', - if (!canvasKit) - '--dart-define=FLUTTER_WEB_AUTO_DETECT=false', - '--driver=test_driver/transitions_perf_e2e_test.dart', - '--target=test_driver/transitions_perf_e2e.dart', - '--browser-name=chrome', - '-d', - 'web-server', - '--$buildMode', - ], - workingDirectory: testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); -} - -Future _runWebStackTraceTest(String buildMode, String entrypoint) async { - final String testAppDirectory = path.join(flutterRoot, 'dev', 'integration_tests', 'web'); - final String appBuildDirectory = path.join(testAppDirectory, 'build', 'web'); - - // Build the app. - await runCommand( - flutter, - [ 'clean' ], - workingDirectory: testAppDirectory, - ); - await runCommand( - flutter, - [ - 'build', - 'web', - '--$buildMode', - '-t', - entrypoint, - ], - workingDirectory: testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); - - // Run the app. - final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); - final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); - final String result = await evalTestAppInChrome( - appUrl: 'http://localhost:$serverPort/index.html', - appDirectory: appBuildDirectory, - serverPort: serverPort, - browserDebugPort: browserDebugPort, - ); - - if (!result.contains('--- TEST SUCCEEDED ---')) { - foundError([ - result, - '${red}Web stack trace integration test failed.$reset', - ]); - } -} - -/// Run a web integration test in release mode. -Future _runWebReleaseTest(String target, { - List additionalArguments = const[], -}) async { - final String testAppDirectory = path.join(flutterRoot, 'dev', 'integration_tests', 'web'); - final String appBuildDirectory = path.join(testAppDirectory, 'build', 'web'); - - // Build the app. - await runCommand( - flutter, - [ 'clean' ], - workingDirectory: testAppDirectory, - ); - await runCommand( - flutter, - [ - ...flutterTestArgs, - 'build', - 'web', - '--release', - ...additionalArguments, - '-t', - target, - ], - workingDirectory: testAppDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); - - // Run the app. - final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); - final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); - final String result = await evalTestAppInChrome( - appUrl: 'http://localhost:$serverPort/index.html', - appDirectory: appBuildDirectory, - serverPort: serverPort, - browserDebugPort: browserDebugPort, - ); - - if (!result.contains('--- TEST SUCCEEDED ---')) { - foundError([ - result, - '${red}Web release mode test failed.$reset', - ]); - } -} - -/// Debug mode is special because `flutter build web` doesn't build in debug mode. -/// -/// Instead, we use `flutter run --debug` and sniff out the standard output. -Future _runWebDebugTest(String target, { - List additionalArguments = const[], -}) async { - final String testAppDirectory = path.join(flutterRoot, 'dev', 'integration_tests', 'web'); - bool success = false; - final Map environment = { - 'FLUTTER_WEB': 'true', - }; - adjustEnvironmentToEnableFlutterAsserts(environment); - final CommandResult result = await runCommand( - flutter, - [ - 'run', - '--debug', - '-d', - 'chrome', - '--web-run-headless', - '--dart-define=FLUTTER_WEB_USE_SKIA=false', - '--dart-define=FLUTTER_WEB_AUTO_DETECT=false', - ...additionalArguments, - '-t', - target, - ], - outputMode: OutputMode.capture, - outputListener: (String line, Process process) { - if (line.contains('--- TEST SUCCEEDED ---')) { - success = true; - } - if (success || line.contains('--- TEST FAILED ---')) { - process.stdin.add('q'.codeUnits); - } - }, - workingDirectory: testAppDirectory, - environment: environment, - ); - - if (!success) { - foundError([ - result.flattenedStdout!, - result.flattenedStderr!, - '${red}Web stack trace integration test failed.$reset', - ]); - } -} - -Future _runFlutterWebTest(String webRenderer, String workingDirectory, List tests) async { - await runCommand( - flutter, - [ - 'test', - if (ciProvider == CiProviders.cirrus) - '--concurrency=1', // do not parallelize on Cirrus, to reduce flakiness - '-v', - '--platform=chrome', - '--web-renderer=$webRenderer', - '--dart-define=DART_HHH_BOT=$_runningInDartHHHBot', - ...flutterTestArgs, - ...tests, - ], - workingDirectory: workingDirectory, - environment: { - 'FLUTTER_WEB': 'true', - }, - ); -} - -// TODO(sigmund): includeLocalEngineEnv should default to true. Currently we -// only enable it on flutter-web test because some test suites do not work -// properly when overriding the local engine (for example, because some platform -// dependent targets are only built on some engines). -// See https://github.com/flutter/flutter/issues/72368 -Future _runDartTest(String workingDirectory, { - List? testPaths, - bool enableFlutterToolAsserts = true, - bool useBuildRunner = false, - String? coverage, - bool forceSingleCore = false, - Duration? perTestTimeout, - bool includeLocalEngineEnv = false, - bool ensurePrecompiledTool = true, - bool shuffleTests = true, - bool collectMetrics = false, -}) async { - int? cpus; - final String? cpuVariable = Platform.environment['CPU']; // CPU is set in cirrus.yml - if (cpuVariable != null) { - cpus = int.tryParse(cpuVariable, radix: 10); - if (cpus == null) { - foundError([ - '${red}The CPU environment variable, if set, must be set to the integer number of available cores.$reset', - 'Actual value: "$cpuVariable"', - ]); - return; - } - } else { - cpus = 2; // Don't default to 1, otherwise we won't catch race conditions. - } - // Integration tests that depend on external processes like chrome - // can get stuck if there are multiple instances running at once. - if (forceSingleCore) { - cpus = 1; - } - - const LocalFileSystem fileSystem = LocalFileSystem(); - final File metricFile = fileSystem.file(path.join(flutterRoot, 'metrics.json')); - final List args = [ - 'run', - 'test', - '--file-reporter=json:${metricFile.path}', - if (shuffleTests) '--test-randomize-ordering-seed=$shuffleSeed', - '-j$cpus', - if (!hasColor) - '--no-color', - if (coverage != null) - '--coverage=$coverage', - if (perTestTimeout != null) - '--timeout=${perTestTimeout.inMilliseconds}ms', - if (testPaths != null) - for (final String testPath in testPaths) - testPath, - ]; - final Map environment = { - 'FLUTTER_ROOT': flutterRoot, - if (includeLocalEngineEnv) - ...localEngineEnv, - if (Directory(pubCache).existsSync()) - 'PUB_CACHE': pubCache, - }; - if (enableFlutterToolAsserts) { - adjustEnvironmentToEnableFlutterAsserts(environment); - } - if (ensurePrecompiledTool) { - // We rerun the `flutter` tool here just to make sure that it is compiled - // before tests run, because the tests might time out if they have to rebuild - // the tool themselves. - await runCommand(flutter, ['--version'], environment: environment); - } - await runCommand( - dart, - args, - workingDirectory: workingDirectory, - environment: environment, - removeLine: useBuildRunner ? (String line) => line.startsWith('[INFO]') : null, - ); - - final TestFileReporterResults test = TestFileReporterResults.fromFile(metricFile); // --file-reporter name - final File info = fileSystem.file(path.join(flutterRoot, 'error.log')); - info.writeAsStringSync(json.encode(test.errors)); - - if (collectMetrics) { - try { - final List testList = []; - final Map allTestSpecs = test.allTestSpecs; - for (final TestSpecs testSpecs in allTestSpecs.values) { - testList.add(testSpecs.toJson()); - } - if (testList.isNotEmpty) { - final String testJson = json.encode(testList); - final File testResults = fileSystem.file( - path.join(flutterRoot, 'test_results.json')); - testResults.writeAsStringSync(testJson); - } - } on fs.FileSystemException catch (e) { - print('Failed to generate metrics: $e'); - } - } -} - -Future _runFlutterTest(String workingDirectory, { - String? script, - bool expectFailure = false, - bool printOutput = true, - OutputChecker? outputChecker, - List options = const [], - Map? environment, - List tests = const [], - bool shuffleTests = true, - bool fatalWarnings = true, -}) async { - assert(!printOutput || outputChecker == null, 'Output either can be printed or checked but not both'); - - final List tags = []; - // Recipe-configured reduced test shards will only execute tests with the - // appropriate tag. - if (Platform.environment['REDUCED_TEST_SET'] == 'True') { - tags.addAll(['-t', 'reduced-test-set']); - } - - final List args = [ - 'test', - if (shuffleTests) '--test-randomize-ordering-seed=$shuffleSeed', - if (fatalWarnings) '--fatal-warnings', - ...options, - ...tags, - ...flutterTestArgs, - ]; - - if (script != null) { - final String fullScriptPath = path.join(workingDirectory, script); - if (!FileSystemEntity.isFileSync(fullScriptPath)) { - foundError([ - '${red}Could not find test$reset: $green$fullScriptPath$reset', - 'Working directory: $cyan$workingDirectory$reset', - 'Script: $green$script$reset', - if (!printOutput) - 'This is one of the tests that does not normally print output.', - ]); - return; - } - args.add(script); - } - - args.addAll(tests); - - final OutputMode outputMode = outputChecker == null && printOutput - ? OutputMode.print - : OutputMode.capture; - - final CommandResult result = await runCommand( - flutter, - args, - workingDirectory: workingDirectory, - expectNonZeroExit: expectFailure, - outputMode: outputMode, - environment: environment, - ); - - if (outputChecker != null) { - final String? message = outputChecker(result); - if (message != null) { - foundError([message]); - } - } -} - -/// This will force the next run of the Flutter tool (if it uses the provided -/// environment) to have asserts enabled, by setting an environment variable. -void adjustEnvironmentToEnableFlutterAsserts(Map environment) { - // If an existing env variable exists append to it, but only if - // it doesn't appear to already include enable-asserts. - String toolsArgs = Platform.environment['FLUTTER_TOOL_ARGS'] ?? ''; - if (!toolsArgs.contains('--enable-asserts')) { - toolsArgs += ' --enable-asserts'; - } - environment['FLUTTER_TOOL_ARGS'] = toolsArgs.trim(); -} - -enum CiProviders { - cirrus, - luci, -} - -CiProviders? get ciProvider { - if (Platform.environment['CIRRUS_CI'] == 'true') { - return CiProviders.cirrus; - } - if (Platform.environment['LUCI_CONTEXT'] != null) { - return CiProviders.luci; - } - return null; -} - -/// Checks the given file's contents to determine if they match the allowed -/// pattern for version strings. -/// -/// Returns null if the contents are good. Returns a string if they are bad. -/// The string is an error message. -Future verifyVersion(File file) async { - final RegExp pattern = RegExp( - r'^(\d+)\.(\d+)\.(\d+)((-\d+\.\d+)?\.pre(\.\d+)?)?$'); - if (!file.existsSync()) { - return 'The version logic failed to create the Flutter version file.'; - } - final String version = await file.readAsString(); - if (version == '0.0.0-unknown') { - return 'The version logic failed to determine the Flutter version.'; - } - if (!version.contains(pattern)) { - return 'The version logic generated an invalid version string: "$version".'; - } - return null; -} - -/// Parse (one-)index/total-named subshards from environment variable SUBSHARD -/// and equally distribute [tests] between them. -/// Subshard format is "{index}_{total number of shards}". -/// The scheduler can change the number of total shards without needing an additional -/// commit in this repository. -/// -/// Examples: -/// 1_3 -/// 2_3 -/// 3_3 -List _selectIndexOfTotalSubshard(List tests, {String subshardKey = kSubshardKey}) { - // Example: "1_3" means the first (one-indexed) shard of three total shards. - final String? subshardName = Platform.environment[subshardKey]; - if (subshardName == null) { - print('$kSubshardKey environment variable is missing, skipping sharding'); - return tests; - } - printProgress('$bold$subshardKey=$subshardName$reset'); - - final RegExp pattern = RegExp(r'^(\d+)_(\d+)$'); - final Match? match = pattern.firstMatch(subshardName); - if (match == null || match.groupCount != 2) { - foundError([ - '${red}Invalid subshard name "$subshardName". Expected format "[int]_[int]" ex. "1_3"', - ]); - throw Exception('Invalid subshard name: $subshardName'); - } - // One-indexed. - final int index = int.parse(match.group(1)!); - final int total = int.parse(match.group(2)!); - if (index > total) { - foundError([ - '${red}Invalid subshard name "$subshardName". Index number must be greater or equal to total.', - ]); - return []; - } - - final int testsPerShard = (tests.length / total).ceil(); - final int start = (index - 1) * testsPerShard; - final int end = math.min(index * testsPerShard, tests.length); - - print('Selecting subshard $index of $total (tests ${start + 1}-$end of ${tests.length})'); - return tests.sublist(start, end); -} - -Future _runShardRunnerIndexOfTotalSubshard(List tests) async { - final List sublist = _selectIndexOfTotalSubshard(tests); - for (final ShardRunner test in sublist) { - await test(); - } -} - -Future selectShard(Map shards) => _runFromList(shards, kShardKey, 'shard', 0); -Future selectSubshard(Map subshards) => _runFromList(subshards, kSubshardKey, 'subshard', 1); - -const String CIRRUS_TASK_NAME = 'CIRRUS_TASK_NAME'; - -Future _runFromList(Map items, String key, String name, int positionInTaskName) async { - String? item = Platform.environment[key]; - if (item == null && Platform.environment.containsKey(CIRRUS_TASK_NAME)) { - final List parts = Platform.environment[CIRRUS_TASK_NAME]!.split('-'); - assert(positionInTaskName < parts.length); - item = parts[positionInTaskName]; - } - if (item == null) { - for (final String currentItem in items.keys) { - printProgress('$bold$key=$currentItem$reset'); - await items[currentItem]!(); - } - } else { - printProgress('$bold$key=$item$reset'); - if (!items.containsKey(item)) { - foundError([ - '${red}Invalid $name: $item$reset', - 'The available ${name}s are: ${items.keys.join(", ")}', - ]); - return; - } - await items[item]!(); - } } diff --git a/flutter/dev/bots/tool_subsharding.dart b/flutter/dev/bots/tool_subsharding.dart index f9cbb3cfa15593424868dee82268d4bc321a9aac..c473132459ee311c2c3af78fea4f0deb820932f1 100644 --- a/flutter/dev/bots/tool_subsharding.dart +++ b/flutter/dev/bots/tool_subsharding.dart @@ -6,35 +6,22 @@ import 'dart:convert'; import 'dart:io'; class TestSpecs { - - TestSpecs({ - required this.path, - required this.startTime, - }); + TestSpecs({required this.path, required this.startTime}); final String path; int startTime; int? _endTime; - int get milliseconds { - return endTime - startTime; - } + int get milliseconds => endTime - startTime; set endTime(int value) { _endTime = value; } - int get endTime { - if (_endTime == null) { - return 0; - } - return _endTime!; - } + int get endTime => _endTime ?? 0; String toJson() { - return json.encode( - {'path': path, 'runtime': milliseconds.toString()} - ); + return json.encode({'path': path, 'runtime': milliseconds.toString()}); } } @@ -56,7 +43,14 @@ class TestFileReporterResults { final List errors = []; for (final String metric in metrics.readAsLinesSync()) { - final Map entry = json.decode(metric) as Map; + /// Using print within a test adds the printed content to the json file report + /// as \u0000 making the file parsing step fail. The content of the json file + /// is expected to be a json dictionary per line and the following line removes + /// all the additional content at the beginning of the line until it finds the + /// first opening curly bracket. + // TODO(godofredoc): remove when https://github.com/flutter/flutter/issues/145553 is fixed. + final String sanitizedMetric = metric.replaceAll(RegExp(r'$.*{'), '{'); + final Map entry = json.decode(sanitizedMetric) as Map; if (entry.containsKey('suite')) { final Map suite = entry['suite']! as Map; addTestSpec(suite, entry['time']! as int, testSpecs); @@ -65,26 +59,27 @@ class TestFileReporterResults { final int suiteID = group['suiteID']! as int; addMetricDone(suiteID, entry['time']! as int, testSpecs); } else if (entry.containsKey('error')) { - final String stackTrace = entry.containsKey('stackTrace') ? entry['stackTrace']! as String : ''; + final String stackTrace = + entry.containsKey('stackTrace') ? entry['stackTrace']! as String : ''; errors.add('${entry['error']}\n $stackTrace'); } else if (entry.containsKey('success') && entry['success'] == true) { hasFailedTests = false; } } - return TestFileReporterResults._(allTestSpecs: testSpecs, hasFailedTests: hasFailedTests, errors: errors); + return TestFileReporterResults._( + allTestSpecs: testSpecs, + hasFailedTests: hasFailedTests, + errors: errors, + ); } final Map allTestSpecs; final bool hasFailedTests; final List errors; - static void addTestSpec(Map suite, int time, Map allTestSpecs) { - allTestSpecs[suite['id']! as int] = TestSpecs( - path: suite['path']! as String, - startTime: time, - ); + allTestSpecs[suite['id']! as int] = TestSpecs(path: suite['path']! as String, startTime: time); } static void addMetricDone(int suiteID, int time, Map allTestSpecs) { diff --git a/flutter/dev/bots/unpublish_package.dart b/flutter/dev/bots/unpublish_package.dart index 74290d5fb7aee90fff057002ddc8542fbd879394..9b5ffd428f2c8a40dc2c8b51b169fff321f25053 100644 --- a/flutter/dev/bots/unpublish_package.dart +++ b/flutter/dev/bots/unpublish_package.dart @@ -50,16 +50,16 @@ enum Channel { dev, beta, stable } String getChannelName(Channel channel) { return switch (channel) { - Channel.beta => 'beta', - Channel.dev => 'dev', + Channel.beta => 'beta', + Channel.dev => 'dev', Channel.stable => 'stable', }; } Channel fromChannelName(String? name) { return switch (name) { - 'beta' => Channel.beta, - 'dev' => Channel.dev, + 'beta' => Channel.beta, + 'dev' => Channel.dev, 'stable' => Channel.stable, _ => throw ArgumentError('Invalid channel name.'), }; @@ -69,16 +69,16 @@ enum PublishedPlatform { linux, macos, windows } String getPublishedPlatform(PublishedPlatform platform) { return switch (platform) { - PublishedPlatform.linux => 'linux', - PublishedPlatform.macos => 'macos', + PublishedPlatform.linux => 'linux', + PublishedPlatform.macos => 'macos', PublishedPlatform.windows => 'windows', }; } PublishedPlatform fromPublishedPlatform(String name) { return switch (name) { - 'linux' => PublishedPlatform.linux, - 'macos' => PublishedPlatform.macos, + 'linux' => PublishedPlatform.linux, + 'macos' => PublishedPlatform.macos, 'windows' => PublishedPlatform.windows, _ => throw ArgumentError('Invalid published platform name.'), }; @@ -150,42 +150,36 @@ class ProcessRunner { workingDirectory: workingDirectory.absolute.path, environment: environment, ); - process.stdout.listen( - (List event) { - output.addAll(event); - if (subprocessOutput) { - stdout.add(event); - } - }, - onDone: () async => stdoutComplete.complete(), - ); + process.stdout.listen((List event) { + output.addAll(event); + if (subprocessOutput) { + stdout.add(event); + } + }, onDone: () async => stdoutComplete.complete()); if (subprocessOutput) { - process.stderr.listen( - (List event) { - stderr.add(event); - }, - onDone: () async => stderrComplete.complete(), - ); + process.stderr.listen((List event) { + stderr.add(event); + }, onDone: () async => stderrComplete.complete()); } else { stderrComplete.complete(); } } on ProcessException catch (e) { - final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' + final String message = + 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' 'failed with:\n$e'; throw UnpublishException(message); } on ArgumentError catch (e) { - final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' + final String message = + 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} ' 'failed with:\n$e'; throw UnpublishException(message); } final int exitCode = await allComplete(); if (exitCode != 0 && !failOk) { - final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} failed'; - throw UnpublishException( - message, - ProcessResult(0, exitCode, null, 'returned $exitCode'), - ); + final String message = + 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} failed'; + throw UnpublishException(message, ProcessResult(0, exitCode, null, 'returned $exitCode')); } return utf8.decoder.convert(output).trim(); } @@ -200,12 +194,12 @@ class ArchiveUnpublisher { this.confirmed = false, ProcessManager? processManager, bool subprocessOutput = true, - }) : assert(revisionsBeingRemoved.length == 40), - metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}', - _processRunner = ProcessRunner( - processManager: processManager ?? const LocalProcessManager(), - subprocessOutput: subprocessOutput, - ); + }) : assert(revisionsBeingRemoved.length == 40), + metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}', + _processRunner = ProcessRunner( + processManager: processManager ?? const LocalProcessManager(), + subprocessOutput: subprocessOutput, + ); final PublishedPlatform platform; final String metadataGsPath; @@ -214,17 +208,23 @@ class ArchiveUnpublisher { final bool confirmed; final Directory tempDir; final ProcessRunner _processRunner; - static String getMetadataFilename(PublishedPlatform platform) => 'releases_${getPublishedPlatform(platform)}.json'; + static String getMetadataFilename(PublishedPlatform platform) => + 'releases_${getPublishedPlatform(platform)}.json'; /// Remove the archive from Google Storage. Future unpublishArchive() async { final Map jsonData = await _loadMetadata(); - final List> releases = (jsonData['releases'] as List).map>((dynamic entry) { - final Map mapEntry = entry as Map; - return mapEntry.cast(); - }).toList(); + final List> releases = + (jsonData['releases'] as List).map>((dynamic entry) { + final Map mapEntry = entry as Map; + return mapEntry.cast(); + }).toList(); final Map> paths = await _getArchivePaths(releases); - releases.removeWhere((Map value) => revisionsBeingRemoved.contains(value['hash']) && channels.contains(fromChannelName(value['channel']))); + releases.removeWhere( + (Map value) => + revisionsBeingRemoved.contains(value['hash']) && + channels.contains(fromChannelName(value['channel'])), + ); releases.sort((Map a, Map b) { final DateTime aDate = DateTime.parse(a['release_date']!); final DateTime bDate = DateTime.parse(b['release_date']!); @@ -232,22 +232,29 @@ class ArchiveUnpublisher { }); jsonData['releases'] = releases; for (final Channel channel in channels) { - if (!revisionsBeingRemoved.contains((jsonData['current_release'] as Map)[getChannelName(channel)])) { + if (!revisionsBeingRemoved.contains( + (jsonData['current_release'] as Map)[getChannelName(channel)], + )) { // Don't replace the current release if it's not one of the revisions we're removing. continue; } - final Map replacementRelease = releases.firstWhere((Map value) => value['channel'] == getChannelName(channel)); - (jsonData['current_release'] as Map)[getChannelName(channel)] = replacementRelease['hash']; + final Map replacementRelease = releases.firstWhere( + (Map value) => value['channel'] == getChannelName(channel), + ); + (jsonData['current_release'] as Map)[getChannelName(channel)] = + replacementRelease['hash']; print( '${confirmed ? 'Reverting' : 'Would revert'} current ${getChannelName(channel)} ' - '${getPublishedPlatform(platform)} release to ${replacementRelease['hash']} (version ${replacementRelease['version']}).' + '${getPublishedPlatform(platform)} release to ${replacementRelease['hash']} (version ${replacementRelease['version']}).', ); } await _cloudRemoveArchive(paths); await _updateMetadata(jsonData); } - Future>> _getArchivePaths(List> releases) async { + Future>> _getArchivePaths( + List> releases, + ) async { final Set hashes = {}; final Map> paths = >{}; for (final Map revision in releases) { @@ -259,18 +266,20 @@ class ArchiveUnpublisher { paths[channel]![hash] = revision['archive']!; } } - final Set missingRevisions = revisionsBeingRemoved.difference(hashes.intersection(revisionsBeingRemoved)); + final Set missingRevisions = revisionsBeingRemoved.difference( + hashes.intersection(revisionsBeingRemoved), + ); if (missingRevisions.isNotEmpty) { final bool plural = missingRevisions.length > 1; - throw UnpublishException('Revision${plural ? 's' : ''} $missingRevisions ${plural ? 'are' : 'is'} not present in the server metadata.'); + throw UnpublishException( + 'Revision${plural ? 's' : ''} $missingRevisions ${plural ? 'are' : 'is'} not present in the server metadata.', + ); } return paths; } Future> _loadMetadata() async { - final File metadataFile = File( - path.join(tempDir.absolute.path, getMetadataFilename(platform)), - ); + final File metadataFile = File(path.join(tempDir.absolute.path, getMetadataFilename(platform))); // Always run this, even in dry runs. await _runGsUtil(['cp', metadataGsPath, metadataFile.absolute.path], confirm: true); final String currentMetadata = metadataFile.readAsStringSync(); @@ -293,12 +302,12 @@ class ArchiveUnpublisher { // Windows wants to echo the commands that execute in gsutil.bat to the // stdout when we do that. So, we copy the file locally and then read it // back in. - final File metadataFile = File( - path.join(tempDir.absolute.path, getMetadataFilename(platform)), - ); + final File metadataFile = File(path.join(tempDir.absolute.path, getMetadataFilename(platform))); const JsonEncoder encoder = JsonEncoder.withIndent(' '); metadataFile.writeAsStringSync(encoder.convert(jsonData)); - print('${confirmed ? 'Overwriting' : 'Would overwrite'} $metadataGsPath with contents of ${metadataFile.absolute.path}'); + print( + '${confirmed ? 'Overwriting' : 'Would overwrite'} $metadataGsPath with contents of ${metadataFile.absolute.path}', + ); await _cloudReplaceDest(metadataFile.absolute.path, metadataGsPath); } @@ -310,11 +319,7 @@ class ArchiveUnpublisher { }) async { final List command = ['gsutil', '--', ...args]; if (confirm) { - return _processRunner.runProcess( - command, - workingDirectory: workingDirectory, - failOk: failOk, - ); + return _processRunner.runProcess(command, workingDirectory: workingDirectory, failOk: failOk); } else { print('Would run: ${command.join(' ')}'); return ''; @@ -372,25 +377,34 @@ void _printBanner(String message) { /// Prepares a flutter git repo to be removed from the published cloud storage. Future main(List rawArguments) async { - final List allowedChannelValues = Channel.values.map((Channel channel) => getChannelName(channel)).toList(); - final List allowedPlatformNames = PublishedPlatform.values.map((PublishedPlatform platform) => getPublishedPlatform(platform)).toList(); + final List allowedChannelValues = + Channel.values.map((Channel channel) => getChannelName(channel)).toList(); + final List allowedPlatformNames = + PublishedPlatform.values + .map((PublishedPlatform platform) => getPublishedPlatform(platform)) + .toList(); final ArgParser argParser = ArgParser(); argParser.addOption( 'temp_dir', - help: 'A location where temporary files may be written. Defaults to a ' + help: + 'A location where temporary files may be written. Defaults to a ' 'directory in the system temp folder. If a temp_dir is not ' 'specified, then by default a generated temporary directory will be ' 'created, used, and removed automatically when the script exits.', ); - argParser.addMultiOption('revision', - help: 'The Flutter git repo revisions to remove from the published site. ' - 'Must be full 40-character hashes. More than one may be specified, ' - 'either by giving the option more than once, or by giving a comma ' - 'separated list. Required.'); + argParser.addMultiOption( + 'revision', + help: + 'The Flutter git repo revisions to remove from the published site. ' + 'Must be full 40-character hashes. More than one may be specified, ' + 'either by giving the option more than once, or by giving a comma ' + 'separated list. Required.', + ); argParser.addMultiOption( 'channel', allowed: allowedChannelValues, - help: 'The Flutter channels to remove the archives corresponding to the ' + help: + 'The Flutter channels to remove the archives corresponding to the ' 'revisions given with --revision. More than one may be specified, ' 'either by giving the option more than once, or by giving a ' 'comma separated list. If not specified, then the archives from all ' @@ -399,24 +413,22 @@ Future main(List rawArguments) async { argParser.addMultiOption( 'platform', allowed: allowedPlatformNames, - help: 'The Flutter platforms to remove the archive from. May specify more ' + help: + 'The Flutter platforms to remove the archive from. May specify more ' 'than one, either by giving the option more than once, or by giving a ' 'comma separated list. If not specified, then the archives from all ' 'platforms that a revision appears in will be removed.', ); argParser.addFlag( 'confirm', - help: 'If set, will actually remove the archive from Google Cloud Storage ' + help: + 'If set, will actually remove the archive from Google Cloud Storage ' 'upon successful execution of this script. Published archives will be ' 'removed from this directory: $baseUrl$releaseFolder. This option ' 'must be set to perform any action on the server, otherwise only a dry ' 'run is performed.', ); - argParser.addFlag( - 'help', - negatable: false, - help: 'Print help for this command.', - ); + argParser.addFlag('help', negatable: false, help: 'Print help for this command.'); final ArgResults parsedArguments = argParser.parse(rawArguments); @@ -437,7 +449,9 @@ Future main(List rawArguments) async { } for (final String revision in revisions) { if (revision.length != 40) { - errorExit('Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.'); + errorExit( + 'Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.', + ); } if (revision.contains(RegExp(r'[^a-fA-F0-9]'))) { errorExit('Invalid argument: --revision "$revision" contains non-hex characters.'); @@ -458,15 +472,21 @@ Future main(List rawArguments) async { } if (!(parsedArguments['confirm'] as bool)) { - _printBanner('This will be just a dry run. To actually perform the changes below, re-run with --confirm argument.'); + _printBanner( + 'This will be just a dry run. To actually perform the changes below, re-run with --confirm argument.', + ); } final List channelArg = parsedArguments['channel'] as List; final List channelOptions = channelArg.isNotEmpty ? channelArg : allowedChannelValues; - final Set channels = channelOptions.map((String value) => fromChannelName(value)).toSet(); + final Set channels = + channelOptions.map((String value) => fromChannelName(value)).toSet(); final List platformArg = parsedArguments['platform'] as List; final List platformOptions = platformArg.isNotEmpty ? platformArg : allowedPlatformNames; - final List platforms = platformOptions.map((String value) => fromPublishedPlatform(value)).toList(); + final List platforms = + platformOptions + .map((String value) => fromPublishedPlatform(value)) + .toList(); int exitCode = 0; late String message; late String stack; @@ -497,7 +517,9 @@ Future main(List rawArguments) async { errorExit('$message\n$stack', exitCode: exitCode); } if (!(parsedArguments['confirm'] as bool)) { - _printBanner('This was just a dry run. To actually perform the above changes, re-run with --confirm argument.'); + _printBanner( + 'This was just a dry run. To actually perform the above changes, re-run with --confirm argument.', + ); } exit(0); } diff --git a/flutter/dev/bots/utils.dart b/flutter/dev/bots/utils.dart index 165fc3792370c04337e9d07d9de69059377ea4a6..45033ca39886eadfcf97977d8124ff48930ddcc1 100644 --- a/flutter/dev/bots/utils.dart +++ b/flutter/dev/bots/utils.dart @@ -3,30 +3,101 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:convert'; import 'dart:core' hide print; import 'dart:io' as system show exit; import 'dart:io' hide exit; import 'dart:math' as math; +import 'package:analyzer/dart/analysis/results.dart'; +import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/source/line_info.dart'; +import 'package:collection/collection.dart'; +import 'package:file/file.dart' as fs; +import 'package:file/local.dart'; import 'package:meta/meta.dart'; +import 'package:path/path.dart' as path; -const Duration _quietTimeout = Duration(minutes: 10); // how long the output should be hidden between calls to printProgress before just being verbose +import 'run_command.dart'; +import 'tool_subsharding.dart'; + +typedef ShardRunner = Future Function(); + +/// A function used to validate the output of a test. +/// +/// If the output matches expectations, the function shall return null. +/// +/// If the output does not match expectations, the function shall return an +/// appropriate error message. +typedef OutputChecker = String? Function(CommandResult); + +const Duration _quietTimeout = Duration( + minutes: 10, +); // how long the output should be hidden between calls to printProgress before just being verbose // If running from LUCI set to False. -final bool isLuci = Platform.environment['LUCI_CI'] == 'True'; +final bool isLuci = Platform.environment['LUCI_CI'] == 'True'; final bool hasColor = stdout.supportsAnsiEscapes && !isLuci; - +final bool _isRandomizationOff = + bool.tryParse(Platform.environment['TEST_RANDOMIZATION_OFF'] ?? '') ?? false; final String bold = hasColor ? '\x1B[1m' : ''; // shard titles final String red = hasColor ? '\x1B[31m' : ''; // errors final String green = hasColor ? '\x1B[32m' : ''; // section titles, commands -final String yellow = hasColor ? '\x1B[33m' : ''; // indications that a test was skipped (usually renders orange or brown) +final String yellow = + hasColor + ? '\x1B[33m' + : ''; // indications that a test was skipped (usually renders orange or brown) final String cyan = hasColor ? '\x1B[36m' : ''; // paths final String reverse = hasColor ? '\x1B[7m' : ''; // clocks -final String gray = hasColor ? '\x1B[30m' : ''; // subtle decorative items (usually renders as dark gray) +final String gray = + hasColor ? '\x1B[30m' : ''; // subtle decorative items (usually renders as dark gray) final String white = hasColor ? '\x1B[37m' : ''; // last log line (usually renders as light gray) final String reset = hasColor ? '\x1B[0m' : ''; +final String exe = Platform.isWindows ? '.exe' : ''; +final String bat = Platform.isWindows ? '.bat' : ''; +final String flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); +final String flutter = path.join(flutterRoot, 'bin', 'flutter$bat'); +final String dart = path.join(flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dart$exe'); +final String pubCache = path.join(flutterRoot, '.pub-cache'); +final String engineVersionFile = path.join(flutterRoot, 'bin', 'cache', 'engine.stamp'); +final String luciBotId = Platform.environment['SWARMING_BOT_ID'] ?? ''; +final bool runningInDartHHHBot = + luciBotId.startsWith('luci-dart-') || luciBotId.startsWith('dart-tests-'); + +const String kShardKey = 'SHARD'; +const String kSubshardKey = 'SUBSHARD'; +const String kTestHarnessShardName = 'test_harness_tests'; + +/// Environment variables to override the local engine when running `pub test`, +/// if such flags are provided to `test.dart`. +final Map localEngineEnv = {}; + +/// The arguments to pass to `flutter test` (typically the local engine +/// configuration) -- prefilled with the arguments passed to test.dart. +final List flutterTestArgs = []; + +/// Whether execution should be simulated for debugging purposes. +/// +/// When `true`, calls to [runCommand] print to [io.stdout] instead of running +/// the process. This is useful for determining what an invocation of `test.dart` +/// _might_ due if not invoked with `--dry-run`, or otherwise determine what the +/// different test shards and sub-shards are configured as. +bool get dryRun => _dryRun ?? false; + +/// Switches [dryRun] to `true`. +/// +/// Expected to be called at most once during execution of a process. +void enableDryRun() { + if (_dryRun != null) { + throw StateError('Should only be called at most once'); + } + _dryRun = true; +} + +bool? _dryRun; + const int kESC = 0x1B; const int kOpenSquareBracket = 0x5B; const int kCSIParameterRangeStart = 0x30; @@ -36,7 +107,6 @@ const int kCSIIntermediateRangeEnd = 0x2F; const int kCSIFinalRangeStart = 0x40; const int kCSIFinalRangeEnd = 0x7E; - String get redLine { if (hasColor) { return '$red${'━' * stdout.terminalColumns}$reset'; @@ -47,10 +117,10 @@ String get redLine { String get clock { final DateTime now = DateTime.now(); return '$reverse▌' - '${now.hour.toString().padLeft(2, "0")}:' - '${now.minute.toString().padLeft(2, "0")}:' - '${now.second.toString().padLeft(2, "0")}' - '▐$reset'; + '${now.hour.toString().padLeft(2, "0")}:' + '${now.minute.toString().padLeft(2, "0")}:' + '${now.second.toString().padLeft(2, "0")}' + '▐$reset'; } String prettyPrintDuration(Duration duration) { @@ -91,6 +161,10 @@ final List _pendingLogs = []; Timer? _hideTimer; // When this is null, the output is verbose. void foundError(List messages) { + if (dryRun) { + printProgress(messages.join('\n')); + return; + } assert(messages.isNotEmpty); // Make the error message easy to notice in the logs by // wrapping it in a red box. @@ -133,16 +207,16 @@ Never reportErrorsAndExit(String message) { _hideTimer = null; print('$clock $message$reset'); print(redLine); - print('${red}For your convenience, the error messages reported above are repeated here:$reset'); + print('${red}The error messages reported above are repeated here:$reset'); final bool printSeparators = _errorMessages.any((List messages) => messages.length > 1); if (printSeparators) { - print(' 🙙 🙛 '); + print(' -- This line intentionally left blank -- '); } for (int index = 0; index < _errorMessages.length * 2 - 1; index += 1) { if (index.isEven) { _errorMessages[index ~/ 2].forEach(print); } else if (printSeparators) { - print(' 🙙 🙛 '); + print(' -- This line intentionally left blank -- '); } } print(redLine); @@ -185,21 +259,29 @@ void _printQuietly(Object? message) { int index = start; int length = 0; while (index < line.length && length < stdout.terminalColumns) { - if (line.codeUnitAt(index) == kESC) { // 0x1B + if (line.codeUnitAt(index) == kESC) { + // 0x1B index += 1; - if (index < line.length && line.codeUnitAt(index) == kOpenSquareBracket) { // 0x5B, [ + if (index < line.length && line.codeUnitAt(index) == kOpenSquareBracket) { + // 0x5B, [ // That was the start of a CSI sequence. index += 1; - while (index < line.length && line.codeUnitAt(index) >= kCSIParameterRangeStart - && line.codeUnitAt(index) <= kCSIParameterRangeEnd) { // 0x30..0x3F + while (index < line.length && + line.codeUnitAt(index) >= kCSIParameterRangeStart && + line.codeUnitAt(index) <= kCSIParameterRangeEnd) { + // 0x30..0x3F index += 1; // ...parameter bytes... } - while (index < line.length && line.codeUnitAt(index) >= kCSIIntermediateRangeStart - && line.codeUnitAt(index) <= kCSIIntermediateRangeEnd) { // 0x20..0x2F + while (index < line.length && + line.codeUnitAt(index) >= kCSIIntermediateRangeStart && + line.codeUnitAt(index) <= kCSIIntermediateRangeEnd) { + // 0x20..0x2F index += 1; // ...intermediate bytes... } - if (index < line.length && line.codeUnitAt(index) >= kCSIFinalRangeStart - && line.codeUnitAt(index) <= kCSIFinalRangeEnd) { // 0x40..0x7E + if (index < line.length && + line.codeUnitAt(index) >= kCSIFinalRangeStart && + line.codeUnitAt(index) <= kCSIFinalRangeEnd) { + // 0x40..0x7E index += 1; // ...final byte. } } @@ -228,7 +310,7 @@ void _printLoudly(String message) { // THE FOLLOWING CODE IS A VIOLATION OF OUR STYLE GUIDE // BECAUSE IT INTRODUCES A VERY FLAKY RACE CONDITION -// https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#never-check-if-a-port-is-available-before-using-it-never-add-timeouts-and-other-race-conditions +// https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#never-check-if-a-port-is-available-before-using-it-never-add-timeouts-and-other-race-conditions // DO NOT USE THE FOLLOWING FUNCTIONS // DO NOT WRITE CODE LIKE THE FOLLOWING FUNCTIONS // https://github.com/flutter/flutter/issues/109474 @@ -253,3 +335,411 @@ Future _isPortAvailable(int port) async { return true; } } + +String locationInFile(ResolvedUnitResult unit, AstNode node, String workingDirectory) { + return '${path.relative(path.relative(unit.path, from: workingDirectory))}:${unit.lineInfo.getLocation(node.offset).lineNumber}'; +} + +/// Whether the given [AstNode] within the `compilationUnit` is under the effect +/// of an inline ignore directive described by `ignoreDirectivePattern`. +/// +/// The `compilationUnit` parameter is the parsed dart file containing the given +/// [AstNode]. The `ignoreDirectivePattern` is a [Pattern] that should precisely +/// match the ignore directive of interest (including the slashes, example: +/// `// flutter_ignore: deprecation_syntax`). +/// +/// The implementation assumes the `ignoreDirectivePattern` matches no more than +/// one line. It searches for the given `ignoreDirectivePattern` in the +/// `compilationUnit`, that either starts the line above the given `node`, or +/// appears after `node` but on the same line, such that the ignore directive +/// works the same way as dart's "ignore" comment: it can either be added above +/// or after the line that needs to be exemped. +bool hasInlineIgnore( + AstNode node, + ParseStringResult compilationUnit, + Pattern ignoreDirectivePattern, +) { + final LineInfo lineInfo = compilationUnit.lineInfo; + // In case the node has multiple lines, match from its start offset. + final String textAfterNode = compilationUnit.content.substring( + node.offset, + // This assumes every line ends with a newline character (including the last + // line) and the new line character is not included to match the given pattern. + lineInfo.getOffsetOfLineAfter(node.offset) - 1, + ); + if (textAfterNode.contains(ignoreDirectivePattern)) { + return true; + } + // The lineNumber getter uses one-based index while everything else uses zero-based index. + final int lineNumber = lineInfo.getLocation(node.offset).lineNumber - 1; + if (lineNumber <= 0) { + return false; + } + return compilationUnit.content + .substring(lineInfo.getOffsetOfLine(lineNumber - 1), lineInfo.getOffsetOfLine(lineNumber)) + .trimLeft() + .contains(ignoreDirectivePattern); +} + +// The seed used to shuffle tests. If not passed with +// --test-randomize-ordering-seed= on the command line, it will be set the +// first time it is accessed. Pass zero to turn off shuffling. +String? _shuffleSeed; + +set shuffleSeed(String? newSeed) { + _shuffleSeed = newSeed; +} + +String get shuffleSeed { + if (_shuffleSeed != null) { + return _shuffleSeed!; + } + // Attempt to load from the command-line argument + final String? seedArg = Platform.environment['--test-randomize-ordering-seed']; + if (seedArg != null) { + return seedArg; + } + // Fallback to the original time-based seed generation + final DateTime seedTime = DateTime.now().toUtc().subtract(const Duration(hours: 7)); + _shuffleSeed = '${seedTime.year * 10000 + seedTime.month * 100 + seedTime.day}'; + return _shuffleSeed!; +} + +// TODO(sigmund): includeLocalEngineEnv should default to true. Currently we +// only enable it on flutter-web test because some test suites do not work +// properly when overriding the local engine (for example, because some platform +// dependent targets are only built on some engines). +// See https://github.com/flutter/flutter/issues/72368 +Future runDartTest( + String workingDirectory, { + List? testPaths, + bool enableFlutterToolAsserts = true, + bool useBuildRunner = false, + String? coverage, + bool forceSingleCore = false, + Duration? perTestTimeout, + bool includeLocalEngineEnv = false, + bool ensurePrecompiledTool = true, + bool shuffleTests = true, + bool collectMetrics = false, + List? tags, + bool runSkipped = false, +}) async { + // TODO(matanlurey): Consider Platform.numberOfProcessors instead. + // See https://github.com/flutter/flutter/issues/161399. + int cpus = 2; + + // Integration tests that depend on external processes like chrome + // can get stuck if there are multiple instances running at once. + if (forceSingleCore) { + cpus = 1; + } + + const LocalFileSystem fileSystem = LocalFileSystem(); + final String suffix = DateTime.now().microsecondsSinceEpoch.toString(); + final File metricFile = fileSystem.systemTempDirectory.childFile('metrics_$suffix.json'); + final List args = [ + 'run', + 'test', + '--reporter=expanded', + '--file-reporter=json:${metricFile.path}', + if (shuffleTests) '--test-randomize-ordering-seed=$shuffleSeed', + '-j$cpus', + if (!hasColor) '--no-color', + if (coverage != null) '--coverage=$coverage', + if (perTestTimeout != null) '--timeout=${perTestTimeout.inMilliseconds}ms', + if (runSkipped) '--run-skipped', + if (tags != null) ...tags.map((String t) => '--tags=$t'), + if (testPaths != null) + for (final String testPath in testPaths) testPath, + ]; + final Map environment = { + 'FLUTTER_ROOT': flutterRoot, + if (includeLocalEngineEnv) ...localEngineEnv, + if (Directory(pubCache).existsSync()) 'PUB_CACHE': pubCache, + }; + if (enableFlutterToolAsserts) { + adjustEnvironmentToEnableFlutterAsserts(environment); + } + if (ensurePrecompiledTool) { + // We rerun the `flutter` tool here just to make sure that it is compiled + // before tests run, because the tests might time out if they have to rebuild + // the tool themselves. + await runCommand(flutter, ['--version'], environment: environment); + } + await runCommand( + dart, + args, + workingDirectory: workingDirectory, + environment: environment, + removeLine: useBuildRunner ? (String line) => line.startsWith('[INFO]') : null, + ); + + if (dryRun) { + return; + } + + final TestFileReporterResults test = TestFileReporterResults.fromFile( + metricFile, + ); // --file-reporter name + final File info = fileSystem.file(path.join(flutterRoot, 'error.log')); + info.writeAsStringSync(json.encode(test.errors)); + + if (collectMetrics) { + try { + final List testList = []; + final Map allTestSpecs = test.allTestSpecs; + for (final TestSpecs testSpecs in allTestSpecs.values) { + testList.add(testSpecs.toJson()); + } + if (testList.isNotEmpty) { + final String testJson = json.encode(testList); + final File testResults = fileSystem.file(path.join(flutterRoot, 'test_results.json')); + testResults.writeAsStringSync(testJson); + } + } on fs.FileSystemException catch (e) { + print('Failed to generate metrics: $e'); + } + } + + // metriciFile is a transitional file that needs to be deleted once it is parsed. + // TODO(godofredoc): Ensure metricFile is parsed and aggregated before deleting. + // https://github.com/flutter/flutter/issues/146003 + metricFile.deleteSync(); +} + +Future runFlutterTest( + String workingDirectory, { + String? script, + bool expectFailure = false, + bool printOutput = true, + OutputChecker? outputChecker, + List options = const [], + Map? environment, + List tests = const [], + bool shuffleTests = true, + bool fatalWarnings = true, +}) async { + assert( + !printOutput || outputChecker == null, + 'Output either can be printed or checked but not both', + ); + + final List tags = []; + // Recipe-configured reduced test shards will only execute tests with the + // appropriate tag. + if (Platform.environment['REDUCED_TEST_SET'] == 'True') { + tags.addAll(['-t', 'reduced-test-set']); + } + + const LocalFileSystem fileSystem = LocalFileSystem(); + final String suffix = DateTime.now().microsecondsSinceEpoch.toString(); + final File metricFile = fileSystem.systemTempDirectory.childFile('metrics_$suffix.json'); + final List args = [ + 'test', + '--reporter=expanded', + '--file-reporter=json:${metricFile.path}', + if (shuffleTests && !_isRandomizationOff) '--test-randomize-ordering-seed=$shuffleSeed', + if (fatalWarnings) '--fatal-warnings', + ...options, + ...tags, + ...flutterTestArgs, + ]; + + if (script != null) { + final String fullScriptPath = path.join(workingDirectory, script); + if (!FileSystemEntity.isFileSync(fullScriptPath)) { + foundError([ + '${red}Could not find test$reset: $green$fullScriptPath$reset', + 'Working directory: $cyan$workingDirectory$reset', + 'Script: $green$script$reset', + if (!printOutput) 'This is one of the tests that does not normally print output.', + ]); + return; + } + args.add(script); + } + + args.addAll(tests); + + final OutputMode outputMode = + outputChecker == null && printOutput ? OutputMode.print : OutputMode.capture; + + final CommandResult result = await runCommand( + flutter, + args, + workingDirectory: workingDirectory, + expectNonZeroExit: expectFailure, + outputMode: outputMode, + environment: environment, + ); + + // metriciFile is a transitional file that needs to be deleted once it is parsed. + // TODO(godofredoc): Ensure metricFile is parsed and aggregated before deleting. + // https://github.com/flutter/flutter/issues/146003 + if (!dryRun) { + metricFile.deleteSync(); + } + + if (outputChecker != null) { + final String? message = outputChecker(result); + if (message != null) { + foundError([message]); + } + } +} + +/// This will force the next run of the Flutter tool (if it uses the provided +/// environment) to have asserts enabled, by setting an environment variable. +void adjustEnvironmentToEnableFlutterAsserts(Map environment) { + // If an existing env variable exists append to it, but only if + // it doesn't appear to already include enable-asserts. + String toolsArgs = Platform.environment['FLUTTER_TOOL_ARGS'] ?? ''; + if (!toolsArgs.contains('--enable-asserts')) { + toolsArgs += ' --enable-asserts'; + } + environment['FLUTTER_TOOL_ARGS'] = toolsArgs.trim(); +} + +Future selectShard(Map shards) => + _runFromList(shards, kShardKey, 'shard', 0); +Future selectSubshard(Map subshards) => + _runFromList(subshards, kSubshardKey, 'subshard', 1); + +Future runShardRunnerIndexOfTotalSubshard(List tests) async { + final List sublist = selectIndexOfTotalSubshard(tests); + for (final ShardRunner test in sublist) { + await test(); + } +} + +/// Parse (one-)index/total-named subshards from environment variable SUBSHARD +/// and equally distribute [tests] between them. +/// The format of SUBSHARD is "{index}_{total number of shards}". +/// The scheduler can change the number of total shards without needing an additional +/// commit in this repository. +/// +/// Examples: +/// 1_3 +/// 2_3 +/// 3_3 +List selectIndexOfTotalSubshard(List tests, {String subshardKey = kSubshardKey}) { + // Example: "1_3" means the first (one-indexed) shard of three total shards. + final String? subshardName = Platform.environment[subshardKey]; + if (subshardName == null) { + print('$kSubshardKey environment variable is missing, skipping sharding'); + return tests; + } + printProgress('$bold$subshardKey=$subshardName$reset'); + + final RegExp pattern = RegExp(r'^(\d+)_(\d+)$'); + final Match? match = pattern.firstMatch(subshardName); + if (match == null || match.groupCount != 2) { + foundError([ + '${red}Invalid subshard name "$subshardName". Expected format "[int]_[int]" ex. "1_3"', + ]); + throw Exception('Invalid subshard name: $subshardName'); + } + // One-indexed. + final int index = int.parse(match.group(1)!); + final int total = int.parse(match.group(2)!); + if (index > total) { + foundError([ + '${red}Invalid subshard name "$subshardName". Index number must be greater or equal to total.', + ]); + return []; + } + + final (int start, int end) = selectTestsForSubShard( + testCount: tests.length, + subShardIndex: index, + subShardCount: total, + ); + print('Selecting subshard $index of $total (tests ${start + 1}-$end of ${tests.length})'); + return tests.sublist(start, end); +} + +/// Finds the interval of tests that a subshard is responsible for testing. +@visibleForTesting +(int start, int end) selectTestsForSubShard({ + required int testCount, + required int subShardIndex, + required int subShardCount, +}) { + // While there exists a closed formula figuring out the range of tests the + // subshard is responsible for, modeling this as a simulation of distributing + // items equally into buckets is more intuitive. + // + // A bucket represents how many tests a subshard should be allocated. + final List buckets = List.filled(subShardCount, 0); + // First, allocate an equal number of items to each bucket. + for (int i = 0; i < buckets.length; i++) { + buckets[i] = (testCount / subShardCount).floor(); + } + // For the N leftover items, put one into each of the first N buckets. + final int remainingItems = testCount % buckets.length; + for (int i = 0; i < remainingItems; i++) { + buckets[i] += 1; + } + + // Lastly, compute the indices of the items in buckets[index]. + // We derive this from the toal number items in previous buckets and the number + // of items in this bucket. + final int numberOfItemsInPreviousBuckets = + subShardIndex == 0 ? 0 : buckets.sublist(0, subShardIndex - 1).sum; + final int start = numberOfItemsInPreviousBuckets; + final int end = start + buckets[subShardIndex - 1]; + + return (start, end); +} + +Future _runFromList( + Map items, + String key, + String name, + int positionInTaskName, +) async { + try { + final String? item = Platform.environment[key]; + if (item == null) { + for (final String currentItem in items.keys) { + printProgress('$bold$key=$currentItem$reset'); + await items[currentItem]!(); + } + } else { + printProgress('$bold$key=$item$reset'); + if (!items.containsKey(item)) { + foundError([ + '${red}Invalid $name: $item$reset', + 'The available ${name}s are: ${items.keys.join(", ")}', + ]); + return; + } + await items[item]!(); + } + } catch (_) { + if (!dryRun) { + rethrow; + } + } +} + +/// Checks the given file's contents to determine if they match the allowed +/// pattern for version strings. +/// +/// Returns null if the contents are good. Returns a string if they are bad. +/// The string is an error message. +Future verifyVersion(File file) async { + final RegExp pattern = RegExp(r'^(\d+)\.(\d+)\.(\d+)((-\d+\.\d+)?\.pre(\.\d+)?)?$'); + if (!file.existsSync()) { + return 'The version logic failed to create the Flutter version file.'; + } + final String version = await file.readAsString(); + if (version == '0.0.0-unknown') { + return 'The version logic failed to determine the Flutter version.'; + } + if (!version.contains(pattern)) { + return 'The version logic generated an invalid version string: "$version".'; + } + return null; +} diff --git a/flutter/dev/conductor/README.md b/flutter/dev/conductor/README.md index 8899226c38bca213a61569d89904f4e6b6413b7d..d406d7f140b33b6c787566563af07166d1e5a896 100644 --- a/flutter/dev/conductor/README.md +++ b/flutter/dev/conductor/README.md @@ -1,17 +1,17 @@ # Flutter Conductor Command-line tool for managing a release of the Flutter SDK. Also see -https://github.com/flutter/flutter/wiki/Release-process for more information on +[Release Process](../../docs/releases/Release-process.md) for more information on the release process. -## Requirements +## Conductor Requirements -Some basic requirements to conduct a release are: +Some basic requirements to run conductor are: - a Linux or macOS computer set up for Flutter development. The conductor does not support Windows. - git -- Mirrors on GitHub of the Flutter +- Mirrors on GitHub of the Flutter ** [framework](https://github.com/flutter/flutter) and [engine](https://github.com/flutter/engine) repositories. @@ -23,6 +23,8 @@ unlock your ssh key for the session; if you do not, each time the conductor attempts to interact with a remote, the user will be prompted to enter their ssh key password. +** Confirm that your personal GitHub clone of flutter/flutter is named flutter and flutter/engine is named engine. If not you will need to use flags to override the defaults. + ## Usage The main entrypoint for the conductor is [bin/conductor](bin/conductor). For @@ -35,13 +37,11 @@ All available commands can be seen via: Releases are initialized with the `start` sub-command, like: -``` +```sh conductor start \ --candidate-branch=flutter-2.2-candidate.10 \ --release-channel=beta \ --github-username=kingOfDevelopers \ - --engine-cherrypicks=72114dafe28c8700f1d5d629c6ae9d34172ba395 \ - --framework-cherrypicks=a3e66b396746f6581b2b7efd1b0d0f0074215128,d8d853436206e86f416236b930e97779b143a100 \ --dart-revision=4511eb2a779a612d9d6b2012123575013e0aef12 \ ``` @@ -77,26 +77,6 @@ step with the command: `conductor next` -### Apply Engine Cherrypicks - -The tool will attempt to auto-apply all engine cherrypicks. However, any -cherrypicks that result in a merge conflict will be reverted and it is left to -the user to manually cherry-pick them (with the command `git cherry-pick -$REVISION`) and resolve the merge conflict in their checkout. - -Once a PR is opened, the user must validate CI builds. If there are regressions -(or if the `licenses_check` fails, then -`//engine/ci/licenses_golden/licenses_third_party` must be updated to match the -output of the failing test), then the user must fix these tests in their local -checkout and push their changes again. - -### Apply Framework Cherrypicks - -The tool will attempt to auto-apply all framework cherrypicks. However, any -cherrypicks that result in a merge conflict will be reverted and it is left to -the user to manually cherry-pick them (with the command `git cherry-pick -$REVISION`) and resolve the merge conflict in their checkout. - ### Publish Version This step will add a version git tag to the final Framework commit and push it @@ -116,3 +96,7 @@ For the final step, the user must manually verify that packaging builds have finished successfully. The SDK compressed archives will not be available from the website until the packaging build has finished. The conductor will produce links to the dashboards for monitoring CI builds. + +### Post verificaion steps (mostly communication) + +Googler instructions for post release documented at go/flutter-release-workflow#notify diff --git a/flutter/dev/conductor/RELEASE_ONBOARDING.md b/flutter/dev/conductor/RELEASE_ONBOARDING.md new file mode 100644 index 0000000000000000000000000000000000000000..9253bc33513cf03ea404b90a4207ddf3ff4ffc24 --- /dev/null +++ b/flutter/dev/conductor/RELEASE_ONBOARDING.md @@ -0,0 +1,71 @@ +# Release engineer/manager onboarding + +Googler facing documentation can be found at go/flutter-release-workflow. + +### Responsibility + +Release engineer is responsible for: +* Branch alignment and/or shepherding cherry picks +* Decision making related to cherry pick risk +* Verification that pre and post submits pass prior to publishing +* Contributor facing communication +* Some public facing post release communication + +In the past (and possibly in the future) there was a distinction between a release engineer and release manager. +For now the responsibilities are the same and we will refer to the person managing the release as a release engineer. + +## Onboarding + +One time setup instructions for new or returning release engineers. + +### Groups/Permissions + +#### Join flutter-hackers on GitHub + +https://github.com/orgs/flutter/teams/flutter-hackers/members + +#### [Googler only] Join mdb/flutter-infra + +Possibly not required +https://ganpati2.corp.google.com/propose_membership?parent=9147533327&child=$me.prod + +#### Join the flutter-announce google group + +Ping any current release engineer to add you as an owner and give you publish access. +https://groups.google.com/g/flutter-announce/members?q=role:owner&pli=1 + +TODO include screenshot + +#### [Googler only] Install tool-proxy-client + +From a glinux machine run `sudo apt install tool-proxy-client`. + +`tool-proxy-client` is the tool that enables/enforces 2 party authorization for controlled builds. + +#### [Googler only] Confirm access to release calendar + +Public and Beta releases and timelines +go/dash-team-releases + +#### [Googler only] Join release chatroom + +Release hotline https://chat.google.com/room/AAAA6RKcK2k?cls=7 + +#### [Googler only] join mdb/flutter-release-team + +Controls who can approve 2 party auth requests. +https://ganpati2.corp.google.com/propose_membership?parent=100213927583&child=$me.prod + +#### Setup conductor + +Conductor is a dart command line interface for common release tasks. +Its instructions are in README.md. + +#### [Googler only] Confirm access to Apple signing cert update doc + +go/flutter-signing-apple-contracts +Also confirm access to valentine entries listed in that doc. + +#### [Googler only] Access release engineer doc + +Confirm access to go/release-eng-retros diff --git a/flutter/dev/customer_testing/README.md b/flutter/dev/customer_testing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b21722a2fc211b4fc1e4f99c2ef15fda8f86a10 --- /dev/null +++ b/flutter/dev/customer_testing/README.md @@ -0,0 +1,16 @@ +# customer_testing + +This tool checks out at the commit SHA +specified in [`tests.version`](tests.version), and runs the tests registered to +verify that end-user apps and libraries are working at the current tip-of-tree +of Flutter. + +To (locally) test a specific SHA, use `ci.dart`: + +```sh +cd dev/customer_testing +dart ci.dart [sha] +``` + +Or, to update the SHA for our CI, edit and send a PR for +[`tests.version`](tests.version). diff --git a/flutter/dev/customer_testing/ci.bat b/flutter/dev/customer_testing/ci.bat index 769a2555e9801cb0b581724ee58957167353c645..5f46e378b06c3f481916c23b3e42a839fc525a12 100644 --- a/flutter/dev/customer_testing/ci.bat +++ b/flutter/dev/customer_testing/ci.bat @@ -6,22 +6,18 @@ REM found in the LICENSE file. REM This should match the ci.sh file in this directory. REM This is called from the LUCI recipes: -REM https://flutter.googlesource.com/recipes/+/refs/heads/master/recipe_modules/adhoc_validation/resources/customer_testing.bat +REM https://github.com/flutter/flutter/blob/main/dev/bots/suite_runners/run_customer_testing_tests.dart +REM This script does not assume that "flutter update-packages" has been +REM run, to allow CIs to save time by skipping that steps since it's +REM largely not needed to run the flutter/tests tests. +REM +REM However, we do need to update this directory. +SETLOCAL +cd /d %~dp0 ECHO. ECHO Updating pub packages... CALL dart pub get -CD ..\tools -CALL dart pub get -CD ..\customer_testing - -ECHO. -ECHO Finding correct version of customer tests... -CMD /S /C "IF EXIST "..\..\bin\cache\pkg\tests\" RMDIR /S /Q ..\..\bin\cache\pkg\tests" -git clone https://github.com/flutter/tests.git ..\..\bin\cache\pkg\tests -FOR /F "usebackq tokens=*" %%a IN (`dart --enable-asserts ..\tools\bin\find_commit.dart . master ..\..\bin\cache\pkg\tests main`) DO git -C ..\..\bin\cache\pkg\tests checkout %%a -ECHO. -ECHO Running tests... -CD ..\..\bin\cache\pkg\tests -CALL dart --enable-asserts ..\..\..\..\dev\customer_testing\run_tests.dart --verbose --skip-on-fetch-failure --skip-template registry/*.test +REM Run the cross-platform script. +CALL ..\..\bin\dart.bat ci.dart diff --git a/flutter/dev/customer_testing/ci.dart b/flutter/dev/customer_testing/ci.dart new file mode 100644 index 0000000000000000000000000000000000000000..024e7067499a8785b57c6a09d2e392b254e9619a --- /dev/null +++ b/flutter/dev/customer_testing/ci.dart @@ -0,0 +1,91 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' as io; + +import 'package:path/path.dart' as p; + +/// To run this script, either: +/// +/// ```sh +/// cd dev/customer_testing +/// dart ci.dart [sha] +/// ``` +/// +/// Or: +/// +/// ```sh +/// ./dev/customer_testing/ci.sh +/// ./dev/customer_testing/ci.bat +/// ``` +void main(List args) async { + final String sha; + if (args.isEmpty) { + sha = io.File('tests.version').readAsStringSync().trim(); + } else if (args.length == 1) { + sha = args.first; + } else { + io.stderr.writeln('Usage: dart ci.dart [sha]'); + io.exitCode = 1; + return; + } + + final String flutterRootPath = p.canonicalize('../../'); + final io.Directory testsCacheDir = io.Directory( + p.join(flutterRootPath, 'bin', 'cache', 'pkg', 'tests'), + ); + + if (testsCacheDir.existsSync()) { + io.stderr.writeln('Cleaning up existing repo: ${testsCacheDir.path}'); + testsCacheDir.deleteSync(recursive: true); + } + + io.stderr.writeln('Cloning flutter/tests'); + final io.Process clone = await io.Process.start('git', [ + 'clone', + '--depth', + '1', + 'https://github.com/flutter/tests.git', + testsCacheDir.path, + ], mode: io.ProcessStartMode.inheritStdio); + if ((await clone.exitCode) != 0) { + io.exitCode = 1; + return; + } + + io.stderr.writeln('Fetching/checking out $sha'); + final io.Process fetch = await io.Process.start( + 'git', + ['fetch', 'origin', sha], + mode: io.ProcessStartMode.inheritStdio, + workingDirectory: testsCacheDir.path, + ); + if ((await fetch.exitCode) != 0) { + io.exitCode = 1; + return; + } + final io.Process checkout = await io.Process.start( + 'git', + ['checkout', sha], + mode: io.ProcessStartMode.inheritStdio, + workingDirectory: testsCacheDir.path, + ); + if ((await checkout.exitCode) != 0) { + io.exitCode = 1; + return; + } + + io.stderr.writeln('Running tests...'); + final io.Process test = await io.Process.start('dart', [ + '--enable-asserts', + 'run_tests.dart', + '--skip-on-fetch-failure', + '--skip-template', + p.posix.joinAll([...p.split(testsCacheDir.path), 'registry', '*.test']), + ], mode: io.ProcessStartMode.inheritStdio); + if ((await test.exitCode) != 0) { + io.exitCode = 1; + return; + } +} diff --git a/flutter/dev/customer_testing/ci.sh b/flutter/dev/customer_testing/ci.sh index 48b42a83530d870aa62df291f3de5dc09f00ae5d..c9c8d4a7f0c98e4d988ab030438d9c4e9637bd71 100644 --- a/flutter/dev/customer_testing/ci.sh +++ b/flutter/dev/customer_testing/ci.sh @@ -5,33 +5,31 @@ # This should match the ci.bat file in this directory. -# This is called from .cirrus.yml and the LUCI recipes: -# https://flutter.googlesource.com/recipes/+/refs/heads/master/recipe_modules/adhoc_validation/resources/customer_testing.sh +# This is called from the LUCI recipes: +# https://github.com/flutter/flutter/blob/main/dev/bots/suite_runners/run_customer_testing_tests.dart -set -ex +set -e + +function script_location() { + local script_location="${BASH_SOURCE[0]}" + # Resolve symlinks + while [[ -h "$script_location" ]]; do + DIR="$(cd -P "$( dirname "$script_location")" >/dev/null && pwd)" + script_location="$(readlink "$script_location")" + [[ "$script_location" != /* ]] && script_location="$DIR/$script_location" + done + cd -P "$(dirname "$script_location")" >/dev/null && pwd +} + +# So that users can run this script from anywhere and it will work as expected. +cd "$(script_location)" # This script does not assume that "flutter update-packages" has been # run, to allow CIs to save time by skipping that steps since it's # largely not needed to run the flutter/tests tests. # -# However, we do need to update this directory and the tools directory. +# However, we do need to update this directory. dart pub get -(cd ../tools; dart pub get) # used for find_commit.dart below - -# Next we need to update the flutter/tests checkout. -# -# We use find_commit.dart so that we pull the version of flutter/tests -# that was contemporary when the branch we are on was created. That -# way, we can still run the tests on long-lived branches without being -# affected by breaking changes on trunk causing changes to the tests -# that wouldn't work on the long-lived branch. -# -# (This also prevents trunk from suddenly failing when tests are -# revved on flutter/tests -- if you rerun a passing customer_tests -# shard, it should still pass, even if we rolled one of the tests.) -rm -rf ../../bin/cache/pkg/tests -git clone https://github.com/flutter/tests.git ../../bin/cache/pkg/tests -git -C ../../bin/cache/pkg/tests checkout `dart --enable-asserts ../tools/bin/find_commit.dart . master ../../bin/cache/pkg/tests main` -# Finally, run the tests. -dart --enable-asserts run_tests.dart --verbose --skip-on-fetch-failure --skip-template ../../bin/cache/pkg/tests/registry/*.test +# Run the cross-platform script. +../../bin/dart run ci.dart diff --git a/flutter/dev/customer_testing/pubspec.yaml b/flutter/dev/customer_testing/pubspec.yaml index c6587aceb68ac023a275a1232c6fc0800e236863..55825db31e479c7163e172c0d0963498dfb87411 100644 --- a/flutter/dev/customer_testing/pubspec.yaml +++ b/flutter/dev/customer_testing/pubspec.yaml @@ -2,58 +2,59 @@ name: customer_testing description: Tool to run the tests listed in the flutter/tests repository. environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: - args: 2.4.2 - path: 1.9.0 - glob: 2.1.2 - meta: 1.11.0 + args: 2.7.0 + path: 1.9.1 + glob: 2.1.3 + meta: 1.16.0 - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + file: 7.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: - test: 1.24.9 + test: 1.25.15 - _fe_analyzer_shared: 65.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - analyzer: 6.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - js: 0.6.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - mime: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _fe_analyzer_shared: 80.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + analyzer: 7.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + crypto: 3.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + frontend_server_client: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_multi_server: 3.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_parser: 4.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + io: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + js: 0.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + logging: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + mime: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + package_config: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf: 1.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_core: 0.5.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web: 0.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_static: 1.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_map_stack_trace: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_maps: 0.10.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_api: 0.7.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + typed_data: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vm_service: 15.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + watcher: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket: 0.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket_channel: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" -# PUBSPEC CHECKSUM: fb60 +# PUBSPEC CHECKSUM: c1ed diff --git a/flutter/dev/customer_testing/run_tests.dart b/flutter/dev/customer_testing/run_tests.dart index cb3f421418629c477d81c245ccd567178ea0eab7..509e908b7e2fef1e311e0583906a4b9b25dfb8af 100644 --- a/flutter/dev/customer_testing/run_tests.dart +++ b/flutter/dev/customer_testing/run_tests.dart @@ -17,50 +17,37 @@ Future main(List arguments) async { // Return true if successful, false if failed. Future run(List arguments) async { - final ArgParser argParser = ArgParser( - allowTrailingOptions: false, - usageLineLength: 72, - ) - ..addOption( - 'repeat', - defaultsTo: '1', - help: 'How many times to run each test. Set to a high value to look for flakes. If a test specifies a number of iterations, the lower of the two values is used.', - valueHelp: 'count', - ) - ..addOption( - 'shards', - defaultsTo: '1', - help: 'How many shards to split the tests into. Used in continuous integration.', - valueHelp: 'count', - ) - ..addOption( - 'shard-index', - defaultsTo: '0', - help: 'The current shard to run the tests with the range [0 .. shards - 1]. Used in continuous integration.', - valueHelp: 'count', - ) - ..addFlag( - 'skip-on-fetch-failure', - help: 'Whether to skip tests that we fail to download.', - ) - ..addFlag( - 'skip-template', - help: 'Whether to skip tests named "template.test".', - ) - ..addFlag( - 'verbose', - help: 'Describe what is happening in detail.', - ) - ..addFlag( - 'help', - negatable: false, - help: 'Print this help message.', - ); + final ArgParser argParser = + ArgParser(allowTrailingOptions: false, usageLineLength: 72) + ..addOption( + 'repeat', + defaultsTo: '1', + help: + 'How many times to run each test. Set to a high value to look for flakes. If a test specifies a number of iterations, the lower of the two values is used.', + valueHelp: 'count', + ) + ..addOption( + 'shards', + defaultsTo: '1', + help: 'How many shards to split the tests into. Used in continuous integration.', + valueHelp: 'count', + ) + ..addOption( + 'shard-index', + defaultsTo: '0', + help: + 'The current shard to run the tests with the range [0 .. shards - 1]. Used in continuous integration.', + valueHelp: 'count', + ) + ..addFlag('skip-on-fetch-failure', help: 'Whether to skip tests that we fail to download.') + ..addFlag('skip-template', help: 'Whether to skip tests named "template.test".') + ..addFlag('verbose', help: 'Describe what is happening in detail.') + ..addFlag('help', negatable: false, help: 'Print this help message.'); void printHelp() { print('run_tests.dart [options...] path/to/file1.test path/to/file2.test...'); print('For details on the test registry format, see:'); - print(' https://github.com/flutter/tests/blob/master/registry/template.test'); + print(' https://github.com/flutter/tests/blob/main/registry/template.test'); print(''); print(argParser.usage); print(''); @@ -82,14 +69,24 @@ Future run(List arguments) async { final bool help = parsedArguments['help'] as bool; final int? numberShards = int.tryParse(parsedArguments['shards'] as String); final int? shardIndex = int.tryParse(parsedArguments['shard-index'] as String); - final List files = parsedArguments - .rest - .expand((String path) => Glob(path).listFileSystemSync(const LocalFileSystem())) - .whereType() - .where((File file) => !skipTemplate || path.basename(file.path) != 'template.test') - .toList(); + final List files = + parsedArguments.rest + .expand((String path) => Glob(path).listFileSystemSync(const LocalFileSystem())) + .whereType() + .where((File file) => !skipTemplate || path.basename(file.path) != 'template.test') + .toList(); + + if (files.isEmpty && parsedArguments.rest.isNotEmpty) { + print('No files resolved from glob(s): ${parsedArguments.rest}'); + } - if (help || repeat == null || files.isEmpty || numberShards == null || numberShards <= 0 || shardIndex == null || shardIndex < 0) { + if (help || + repeat == null || + files.isEmpty || + numberShards == null || + numberShards <= 0 || + shardIndex == null || + shardIndex < 0) { printHelp(); if (verbose) { if (repeat == null) { @@ -98,17 +95,23 @@ Future run(List arguments) async { if (numberShards == null) { print('Error: Could not parse shards count ("${parsedArguments['shards']}")'); } else if (numberShards < 1) { - print('Error: The specified shards count ($numberShards) is less than 1. It must be greater than zero.'); + print( + 'Error: The specified shards count ($numberShards) is less than 1. It must be greater than zero.', + ); } if (shardIndex == null) { print('Error: Could not parse shard index ("${parsedArguments['shard-index']}")'); } else if (shardIndex < 0) { - print('Error: The specified shard index ($shardIndex) is negative. It must be in the range [0 .. shards - 1].'); + print( + 'Error: The specified shard index ($shardIndex) is negative. It must be in the range [0 .. shards - 1].', + ); } if (parsedArguments.rest.isEmpty) { print('Error: No file arguments specified.'); } else if (files.isEmpty) { - print('Error: File arguments ("${parsedArguments.rest.join('", "')}") did not identify any real files.'); + print( + 'Error: File arguments ("${parsedArguments.rest.join('", "')}") did not identify any real files.', + ); } } return help; @@ -117,7 +120,7 @@ Future run(List arguments) async { if (shardIndex > numberShards - 1) { print( 'Error: The specified shard index ($shardIndex) is more than the specified number of shards ($numberShards). ' - 'It must be in the range [0 .. shards - 1].' + 'It must be in the range [0 .. shards - 1].', ); return false; } diff --git a/flutter/dev/customer_testing/tests.version b/flutter/dev/customer_testing/tests.version new file mode 100644 index 0000000000000000000000000000000000000000..ed08f117aafcd4deb7da778a376536b735952c27 --- /dev/null +++ b/flutter/dev/customer_testing/tests.version @@ -0,0 +1 @@ +3566ea0e688123cecc2b605bda13732adc1e610a diff --git a/flutter/dev/devicelab/README.md b/flutter/dev/devicelab/README.md index 5781861339cd83dcdedaa06b0fe242885672a769..3b1091a16c54162b2f368b2caa74f6ed99273225 100644 --- a/flutter/dev/devicelab/README.md +++ b/flutter/dev/devicelab/README.md @@ -28,7 +28,7 @@ DeviceLab tests are run against physical devices in Flutter's lab (the Tasks specify the type of device they are to run on (`linux_android`, `mac_ios`, `mac_android`, `windows_android`, etc). When a device in the lab is free, it -will pickup tasks that need to be completed. +will pick up tasks that need to be completed. 1. If the task succeeds, the test runner reports the success and uploads its performance metrics to Flutter's infrastructure. Not all tasks record @@ -56,9 +56,16 @@ You can find where your Android SDK is using `flutter doctor -v`. ### Warnings -Running the devicelab will do things to your environment. +Running DeviceLab tests locally will do things to your environment. -Notably, it will start and stop Gradle, for instance. +Notably: + +- It will automatically start and stop Gradle on your machine +- It will automatically reboot your target Android or iOS device after a certain amount of tests before running any additional tests on it. See the `checkForRebootRequired()` in `flutter/dev/devicelab/lib/framework/framework.dart` and `device.reboot()` in `flutter/dev/devicelab/lib/framework/devices.dart` for more. + +### Running tests in `test/...` + +`dart test test/{NAME_OF_TEST}` ### Running specific tests @@ -78,6 +85,14 @@ To run multiple tests, repeat option `-t` (`--task`) multiple times: ../../bin/cache/dart-sdk/bin/dart bin/run.dart -t test1 -t test2 -t test3 ``` +### Running tests without automatic retries + +By default, DeviceLab tests have an automatic retry logic built in. Any failing tests will be retried 2 additional times. This can be skipped by specifying the `--exit` option: + +```sh +../../bin/cache/dart-sdk/bin/dart bin/test_runner.dart test --exit -t {NAME_OF_TEST} +``` + ### Running tests against a local engine build To run device lab tests against a local engine build, pass the appropriate @@ -217,7 +232,7 @@ _TASK_- the name of your test that also matches the name of the file in `bin/tasks` without the `.dart` extension. 1. Add target to - [.ci.yaml](https://github.com/flutter/flutter/blob/master/.ci.yaml) + [.ci.yaml](https://github.com/flutter/flutter/blob/main/.ci.yaml) * Mirror an existing one that has the recipe `devicelab_drone` If your test needs to run on multiple operating systems, create a separate @@ -225,8 +240,8 @@ target for each operating system. ## Adding tests to presubmit -Flutter's DeviceLab has a limited capacity in presubmit. File an infra ticket -to investigate feasibility of adding a test to presubmit. +Flutter's DeviceLab has a limited capacity in presubmit. File a `team-infra` +issue to investigate feasibility of adding a test to presubmit. ## Migrating to build and test model @@ -237,7 +252,7 @@ and the test will run based on the artifact against a testbed with a device. Steps: -1. Update the task class to extend [`BuildTestTask`](https://github.com/flutter/flutter/blob/master/dev/devicelab/lib/tasks/build_test_task.dart) +1. Update the task class to extend [`BuildTestTask`](https://github.com/flutter/flutter/blob/main/dev/devicelab/lib/tasks/build_test_task.dart) - Override function `getBuildArgs` - Override function `getTestArgs` - Override function `parseTaskResult` diff --git a/flutter/dev/devicelab/pubspec.yaml b/flutter/dev/devicelab/pubspec.yaml index f7f12535b6cf54e251186a2516144019a81f1c07..1f42321e7ea2d536884c7517b8d82470c1aba809 100644 --- a/flutter/dev/devicelab/pubspec.yaml +++ b/flutter/dev/devicelab/pubspec.yaml @@ -3,74 +3,76 @@ description: Flutter continuous integration performance and correctness tests. homepage: https://github.com/flutter/flutter environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: - archive: 3.3.2 - args: 2.4.2 - file: 7.0.0 - http: 0.13.6 - logging: 1.2.0 - meta: 1.11.0 - metrics_center: 1.0.12 - path: 1.9.0 - platform: 3.1.4 - process: 5.0.2 - pubspec_parse: 1.2.3 - shelf: 1.4.1 - shelf_static: 1.1.2 - stack_trace: 1.11.1 - vm_service: 13.0.0 - web: 0.4.0 + archive: 3.6.1 + args: 2.7.0 + file: 7.0.1 + http: 1.3.0 + logging: 1.3.0 + meta: 1.16.0 + metrics_center: 1.0.13 + path: 1.9.1 + platform: 3.1.6 + process: 5.0.3 + pubspec_parse: 1.5.0 + shelf: 1.4.2 + shelf_static: 1.1.3 + stack_trace: 1.12.1 + vm_service: 15.0.0 + web: 1.1.1 webkit_inspection_protocol: 1.2.1 xml: 6.5.0 standard_message_codec: 0.0.1+4 - _discoveryapis_commons: 1.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _discoveryapis_commons: 1.0.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" checked_yaml: 2.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - gcloud: 0.8.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - googleapis: 3.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - googleapis_auth: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - js: 0.6.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - json_annotation: 4.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - mime: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - petitparser: 6.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + crypto: 3.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + gcloud: 0.8.18 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + google_identity_services_web: 0.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + googleapis: 12.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + googleapis_auth: 1.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_parser: 4.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + json_annotation: 4.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + mime: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + petitparser: 6.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" retry: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + typed_data: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: - test: 1.24.9 + test: 1.25.15 - _fe_analyzer_shared: 65.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - analyzer: 6.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + _fe_analyzer_shared: 80.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + analyzer: 7.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + frontend_server_client: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + glob: 2.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + http_multi_server: 3.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + io: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + js: 0.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + package_config: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_core: 0.5.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_map_stack_trace: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_maps: 0.10.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_api: 0.7.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + watcher: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket: 0.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + web_socket_channel: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" -# PUBSPEC CHECKSUM: ba43 +# PUBSPEC CHECKSUM: 00d7 diff --git a/flutter/dev/docs/README.md b/flutter/dev/docs/README.md index 097097fd1aea53e2cdae7004035aef11ab76a13b..29ad418d6768ddec2b04e914ee01ce251b65899a 100644 --- a/flutter/dev/docs/README.md +++ b/flutter/dev/docs/README.md @@ -25,7 +25,7 @@ the following locations: * [Web Embedder](dart-ui_web/dart-ui_web-library.html) * [Installation](https://flutter.dev/docs/get-started/install) * [Codelabs](https://flutter.dev/docs/codelabs) -* [Contributing to Flutter](https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md) +* [Contributing to Flutter](https://github.com/flutter/flutter/blob/main/CONTRIBUTING.md) ## Offline Documentation diff --git a/flutter/dev/docs/analytics-footer.html b/flutter/dev/docs/analytics-footer.html index 133ecf3bd3e732d430c72e06a6257b4d90fcb215..1a37e1d6659e8d9c1fc10d9f15de8e9225454c3b 100644 --- a/flutter/dev/docs/analytics-footer.html +++ b/flutter/dev/docs/analytics-footer.html @@ -2,3 +2,8 @@ + + + + + diff --git a/flutter/dev/docs/analytics-header.html b/flutter/dev/docs/analytics-header.html index bed08523614067d3eeadcacf48ba1e60ecfd6901..6ccb4f2d50414237bec1b09e4e738ad2c25508b9 100644 --- a/flutter/dev/docs/analytics-header.html +++ b/flutter/dev/docs/analytics-header.html @@ -5,3 +5,6 @@ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f) })(window,document,'script','dataLayer','GTM-ND4LWWZ'); + + + diff --git a/flutter/dev/forbidden_from_release_tests/pubspec.yaml b/flutter/dev/forbidden_from_release_tests/pubspec.yaml index a3316fe369eb2acfaf3922b9913ea5ded4c6ce76..185316c35c41ad38fa53c8ed6acca1db6cc28fbe 100644 --- a/flutter/dev/forbidden_from_release_tests/pubspec.yaml +++ b/flutter/dev/forbidden_from_release_tests/pubspec.yaml @@ -2,18 +2,18 @@ name: forbidden_from_release_tests publish_to: 'none' environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: - args: 2.4.2 - file: 7.0.0 - package_config: 2.1.0 - path: 1.9.0 - process: 5.0.2 + args: 2.7.0 + file: 7.0.1 + package_config: 2.2.0 + path: 1.9.1 + process: 5.0.3 vm_snapshot_analysis: 0.7.6 - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - meta: 1.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - platform: 3.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + meta: 1.16.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + platform: 3.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" -# PUBSPEC CHECKSUM: 018d +# PUBSPEC CHECKSUM: 069b diff --git a/flutter/dev/integration_tests/README.md b/flutter/dev/integration_tests/README.md index 4be32c8212ebe4de57659b82a85538bdb81a7306..1fded8c2da3ce8ef5f40360702d2e3d4e2470cba 100644 --- a/flutter/dev/integration_tests/README.md +++ b/flutter/dev/integration_tests/README.md @@ -9,7 +9,7 @@ Intended for use with devicelab tests. If you want to run a driver test locally, to debug a problem with a test, you can use this command from the appropriate subdirectory: -```shell +```sh flutter drive -t --driver ``` @@ -18,3 +18,7 @@ For example: ```sh flutter drive -t lib/keyboard_resize.dart --driver test_driver/keyboard_resize_test.dart ``` + +## New tests require new CI runner +Adding code to this directory will not automatically cause it to be run by any already existing ci tooling. +This directory is intentinally a "choose your own adventure" piece of tooling. diff --git a/flutter/dev/manual_tests/android/build.gradle b/flutter/dev/manual_tests/android/build.gradle index a2a88669529869e1fd2debbc4b67f4f7415b93ae..bedac9d2d4db435dfecb639ddd968f06a9375609 100644 --- a/flutter/dev/manual_tests/android/build.gradle +++ b/flutter/dev/manual_tests/android/build.gradle @@ -6,23 +6,6 @@ // To update all the build.gradle files in the Flutter repo, // See dev/tools/bin/generate_gradle_lockfiles.dart. -buildscript { - ext.kotlin_version = '1.7.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:7.3.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } - - configurations.classpath { - resolutionStrategy.activateDependencyLocking() - } -} - allprojects { repositories { google() diff --git a/flutter/dev/manual_tests/android/buildscript-gradle.lockfile b/flutter/dev/manual_tests/android/buildscript-gradle.lockfile index eb605802d98f5f505e9112f6f1d9c85b5269553d..545abc59e924a9127dd0d66b4c85bb9e855adb90 100644 --- a/flutter/dev/manual_tests/android/buildscript-gradle.lockfile +++ b/flutter/dev/manual_tests/android/buildscript-gradle.lockfile @@ -1,64 +1,68 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -androidx.databinding:databinding-common:7.3.0=classpath -androidx.databinding:databinding-compiler-common:7.3.0=classpath -com.android.databinding:baseLibrary:7.3.0=classpath -com.android.tools.analytics-library:crash:30.3.0=classpath -com.android.tools.analytics-library:protos:30.3.0=classpath -com.android.tools.analytics-library:shared:30.3.0=classpath -com.android.tools.analytics-library:tracker:30.3.0=classpath +androidx.databinding:databinding-common:8.7.0=classpath +androidx.databinding:databinding-compiler-common:8.7.0=classpath +com.android.application:com.android.application.gradle.plugin:8.7.0=classpath +com.android.databinding:baseLibrary:8.7.0=classpath +com.android.tools.analytics-library:crash:31.7.0=classpath +com.android.tools.analytics-library:protos:31.7.0=classpath +com.android.tools.analytics-library:shared:31.7.0=classpath +com.android.tools.analytics-library:tracker:31.7.0=classpath com.android.tools.build.jetifier:jetifier-core:1.0.0-beta10=classpath com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta10=classpath -com.android.tools.build:aapt2-proto:7.3.0-8691043=classpath -com.android.tools.build:aaptcompiler:7.3.0=classpath -com.android.tools.build:apksig:7.3.0=classpath -com.android.tools.build:apkzlib:7.3.0=classpath -com.android.tools.build:builder-model:7.3.0=classpath -com.android.tools.build:builder-test-api:7.3.0=classpath -com.android.tools.build:builder:7.3.0=classpath -com.android.tools.build:bundletool:1.9.0=classpath -com.android.tools.build:gradle-api:7.3.0=classpath -com.android.tools.build:gradle:7.3.0=classpath -com.android.tools.build:manifest-merger:30.3.0=classpath +com.android.tools.build:aapt2-proto:8.7.0-12006047=classpath +com.android.tools.build:aaptcompiler:8.7.0=classpath +com.android.tools.build:apksig:8.7.0=classpath +com.android.tools.build:apkzlib:8.7.0=classpath +com.android.tools.build:builder-model:8.7.0=classpath +com.android.tools.build:builder-test-api:8.7.0=classpath +com.android.tools.build:builder:8.7.0=classpath +com.android.tools.build:bundletool:1.17.1=classpath +com.android.tools.build:gradle-api:8.7.0=classpath +com.android.tools.build:gradle-settings-api:8.7.0=classpath +com.android.tools.build:gradle:8.7.0=classpath +com.android.tools.build:manifest-merger:31.7.0=classpath com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api=classpath -com.android.tools.ddms:ddmlib:30.3.0=classpath -com.android.tools.layoutlib:layoutlib-api:30.3.0=classpath -com.android.tools.lint:lint-model:30.3.0=classpath -com.android.tools.lint:lint-typedef-remover:30.3.0=classpath -com.android.tools.utp:android-device-provider-ddmlib-proto:30.3.0=classpath -com.android.tools.utp:android-device-provider-gradle-proto:30.3.0=classpath -com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:30.3.0=classpath -com.android.tools.utp:android-test-plugin-host-coverage-proto:30.3.0=classpath -com.android.tools.utp:android-test-plugin-host-retention-proto:30.3.0=classpath -com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.3.0=classpath -com.android.tools:annotations:30.3.0=classpath -com.android.tools:common:30.3.0=classpath -com.android.tools:dvlib:30.3.0=classpath -com.android.tools:repository:30.3.0=classpath -com.android.tools:sdk-common:30.3.0=classpath -com.android.tools:sdklib:30.3.0=classpath -com.android:signflinger:7.3.0=classpath -com.android:zipflinger:7.3.0=classpath -com.github.gundy:semver4j:0.16.4=classpath +com.android.tools.ddms:ddmlib:31.7.0=classpath +com.android.tools.layoutlib:layoutlib-api:31.7.0=classpath +com.android.tools.lint:lint-model:31.7.0=classpath +com.android.tools.lint:lint-typedef-remover:31.7.0=classpath +com.android.tools.utp:android-device-provider-ddmlib-proto:31.7.0=classpath +com.android.tools.utp:android-device-provider-gradle-proto:31.7.0=classpath +com.android.tools.utp:android-device-provider-profile-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-apk-installer-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-coverage-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-emulator-control-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-logcat-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-host-retention-proto:31.7.0=classpath +com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:31.7.0=classpath +com.android.tools:annotations:31.7.0=classpath +com.android.tools:common:31.7.0=classpath +com.android.tools:dvlib:31.7.0=classpath +com.android.tools:repository:31.7.0=classpath +com.android.tools:sdk-common:31.7.0=classpath +com.android.tools:sdklib:31.7.0=classpath +com.android:signflinger:8.7.0=classpath +com.android:zipflinger:8.7.0=classpath com.google.android:annotations:4.1.1.4=classpath -com.google.api.grpc:proto-google-common-protos:2.0.1=classpath +com.google.api.grpc:proto-google-common-protos:2.17.0=classpath com.google.auto.value:auto-value-annotations:1.6.2=classpath com.google.code.findbugs:jsr305:3.0.2=classpath -com.google.code.gson:gson:2.8.9=classpath -com.google.crypto.tink:tink:1.3.0-rc2=classpath +com.google.code.gson:gson:2.10.1=classpath +com.google.crypto.tink:tink:1.7.0=classpath com.google.dagger:dagger:2.28.3=classpath -com.google.errorprone:error_prone_annotations:2.4.0=classpath +com.google.errorprone:error_prone_annotations:2.18.0=classpath com.google.flatbuffers:flatbuffers-java:1.12.0=classpath com.google.guava:failureaccess:1.0.1=classpath -com.google.guava:guava:30.1-jre=classpath +com.google.guava:guava:32.0.1-jre=classpath com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=classpath -com.google.j2objc:j2objc-annotations:1.3=classpath +com.google.j2objc:j2objc-annotations:2.8=classpath com.google.jimfs:jimfs:1.1=classpath -com.google.protobuf:protobuf-java-util:3.17.2=classpath -com.google.protobuf:protobuf-java:3.17.2=classpath -com.google.testing.platform:core-proto:0.0.8-alpha07=classpath -com.googlecode.json-simple:json-simple:1.1=classpath +com.google.protobuf:protobuf-java-util:3.22.3=classpath +com.google.protobuf:protobuf-java:3.22.3=classpath +com.google.testing.platform:core-proto:0.0.9-alpha02=classpath com.googlecode.juniversalchardet:juniversalchardet:1.0.3=classpath com.squareup:javapoet:1.10.0=classpath com.squareup:javawriter:2.5.0=classpath @@ -66,28 +70,27 @@ com.sun.activation:javax.activation:1.2.0=classpath com.sun.istack:istack-commons-runtime:3.0.8=classpath com.sun.xml.fastinfoset:FastInfoset:1.2.16=classpath commons-codec:commons-codec:1.11=classpath -commons-io:commons-io:2.4=classpath +commons-io:commons-io:2.13.0=classpath commons-logging:commons-logging:1.2=classpath -de.undercouch:gradle-download-task:4.1.1=classpath -io.grpc:grpc-api:1.39.0=classpath -io.grpc:grpc-context:1.39.0=classpath -io.grpc:grpc-core:1.39.0=classpath -io.grpc:grpc-netty:1.39.0=classpath -io.grpc:grpc-protobuf-lite:1.39.0=classpath -io.grpc:grpc-protobuf:1.39.0=classpath -io.grpc:grpc-stub:1.39.0=classpath -io.netty:netty-buffer:4.1.52.Final=classpath -io.netty:netty-codec-http2:4.1.52.Final=classpath -io.netty:netty-codec-http:4.1.52.Final=classpath -io.netty:netty-codec-socks:4.1.52.Final=classpath -io.netty:netty-codec:4.1.52.Final=classpath -io.netty:netty-common:4.1.52.Final=classpath -io.netty:netty-handler-proxy:4.1.52.Final=classpath -io.netty:netty-handler:4.1.52.Final=classpath -io.netty:netty-resolver:4.1.52.Final=classpath -io.netty:netty-transport:4.1.52.Final=classpath -io.perfmark:perfmark-api:0.23.0=classpath -it.unimi.dsi:fastutil:8.4.0=classpath +io.grpc:grpc-api:1.57.0=classpath +io.grpc:grpc-context:1.57.0=classpath +io.grpc:grpc-core:1.57.0=classpath +io.grpc:grpc-netty:1.57.0=classpath +io.grpc:grpc-protobuf-lite:1.57.0=classpath +io.grpc:grpc-protobuf:1.57.0=classpath +io.grpc:grpc-stub:1.57.0=classpath +io.netty:netty-buffer:4.1.93.Final=classpath +io.netty:netty-codec-http2:4.1.93.Final=classpath +io.netty:netty-codec-http:4.1.93.Final=classpath +io.netty:netty-codec-socks:4.1.93.Final=classpath +io.netty:netty-codec:4.1.93.Final=classpath +io.netty:netty-common:4.1.93.Final=classpath +io.netty:netty-handler-proxy:4.1.93.Final=classpath +io.netty:netty-handler:4.1.93.Final=classpath +io.netty:netty-resolver:4.1.93.Final=classpath +io.netty:netty-transport-native-unix-common:4.1.93.Final=classpath +io.netty:netty-transport:4.1.93.Final=classpath +io.perfmark:perfmark-api:0.26.0=classpath jakarta.activation:jakarta.activation-api:1.2.1=classpath jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=classpath javax.annotation:javax.annotation-api:1.3.2=classpath @@ -96,57 +99,60 @@ net.java.dev.jna:jna-platform:5.6.0=classpath net.java.dev.jna:jna:5.6.0=classpath net.sf.jopt-simple:jopt-simple:4.9=classpath net.sf.kxml:kxml2:2.3.0=classpath -org.apache.commons:commons-compress:1.20=classpath -org.apache.httpcomponents:httpclient:4.5.13=classpath -org.apache.httpcomponents:httpcore:4.4.13=classpath +org.apache.commons:commons-compress:1.21=classpath +org.apache.httpcomponents:httpclient:4.5.14=classpath +org.apache.httpcomponents:httpcore:4.4.16=classpath org.apache.httpcomponents:httpmime:4.5.6=classpath -org.bitbucket.b_c:jose4j:0.7.0=classpath -org.bouncycastle:bcpkix-jdk15on:1.67=classpath -org.bouncycastle:bcprov-jdk15on:1.67=classpath -org.checkerframework:checker-qual:3.5.0=classpath -org.codehaus.mojo:animal-sniffer-annotations:1.19=classpath +org.bitbucket.b_c:jose4j:0.9.5=classpath +org.bouncycastle:bcpkix-jdk18on:1.77=classpath +org.bouncycastle:bcprov-jdk18on:1.77=classpath +org.bouncycastle:bcutil-jdk18on:1.77=classpath +org.checkerframework:checker-qual:3.33.0=classpath +org.codehaus.mojo:animal-sniffer-annotations:1.23=classpath org.glassfish.jaxb:jaxb-runtime:2.3.2=classpath org.glassfish.jaxb:txw2:2.3.2=classpath org.jdom:jdom2:2.0.6=classpath org.jetbrains.intellij.deps:trove4j:1.0.20200330=classpath -org.jetbrains.kotlin:kotlin-android-extensions:1.7.10=classpath -org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.7.10=classpath -org.jetbrains.kotlin:kotlin-build-common:1.7.10=classpath -org.jetbrains.kotlin:kotlin-compiler-embeddable:1.7.10=classpath -org.jetbrains.kotlin:kotlin-compiler-runner:1.7.10=classpath -org.jetbrains.kotlin:kotlin-daemon-client:1.7.10=classpath -org.jetbrains.kotlin:kotlin-daemon-embeddable:1.7.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.7.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-idea:1.7.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.7.10=classpath -org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10=classpath -org.jetbrains.kotlin:kotlin-klib-commonizer-api:1.7.10=classpath -org.jetbrains.kotlin:kotlin-native-utils:1.7.10=classpath -org.jetbrains.kotlin:kotlin-project-model:1.7.10=classpath -org.jetbrains.kotlin:kotlin-reflect:1.5.31=classpath -org.jetbrains.kotlin:kotlin-scripting-common:1.7.10=classpath -org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.7.10=classpath -org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.7.10=classpath -org.jetbrains.kotlin:kotlin-scripting-jvm:1.7.10=classpath -org.jetbrains.kotlin:kotlin-stdlib-common:1.5.31=classpath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.31=classpath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.31=classpath -org.jetbrains.kotlin:kotlin-stdlib:1.5.31=classpath -org.jetbrains.kotlin:kotlin-tooling-core:1.7.10=classpath -org.jetbrains.kotlin:kotlin-tooling-metadata:1.7.10=classpath -org.jetbrains.kotlin:kotlin-util-io:1.7.10=classpath -org.jetbrains.kotlin:kotlin-util-klib:1.7.10=classpath +org.jetbrains.kotlin.android:org.jetbrains.kotlin.android.gradle.plugin:1.8.10=classpath +org.jetbrains.kotlin:kotlin-android-extensions:1.8.10=classpath +org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.8.10=classpath +org.jetbrains.kotlin:kotlin-build-common:1.8.10=classpath +org.jetbrains.kotlin:kotlin-compiler-embeddable:1.8.10=classpath +org.jetbrains.kotlin:kotlin-compiler-runner:1.8.10=classpath +org.jetbrains.kotlin:kotlin-daemon-client:1.8.10=classpath +org.jetbrains.kotlin:kotlin-daemon-embeddable:1.8.10=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.8.10=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-idea-proto:1.8.10=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-idea:1.8.10=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.8.10=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10=classpath +org.jetbrains.kotlin:kotlin-klib-commonizer-api:1.8.10=classpath +org.jetbrains.kotlin:kotlin-native-utils:1.8.10=classpath +org.jetbrains.kotlin:kotlin-project-model:1.8.10=classpath +org.jetbrains.kotlin:kotlin-reflect:1.9.20=classpath +org.jetbrains.kotlin:kotlin-scripting-common:1.8.10=classpath +org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.8.10=classpath +org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.8.10=classpath +org.jetbrains.kotlin:kotlin-scripting-jvm:1.8.10=classpath +org.jetbrains.kotlin:kotlin-stdlib-common:1.9.20=classpath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.20=classpath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.20=classpath +org.jetbrains.kotlin:kotlin-stdlib:1.9.20=classpath +org.jetbrains.kotlin:kotlin-tooling-core:1.8.10=classpath +org.jetbrains.kotlin:kotlin-util-io:1.8.10=classpath +org.jetbrains.kotlin:kotlin-util-klib:1.8.10=classpath org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=classpath -org.jetbrains:annotations:13.0=classpath -org.json:json:20180813=classpath +org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:1.4.0=classpath +org.jetbrains.kotlinx:kotlinx-serialization-core:1.4.0=classpath +org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.4.0=classpath +org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0=classpath +org.jetbrains:annotations:23.0.0=classpath org.jvnet.staxex:stax-ex:1.8.1=classpath -org.ow2.asm:asm-analysis:9.1=classpath -org.ow2.asm:asm-commons:9.1=classpath -org.ow2.asm:asm-tree:9.1=classpath -org.ow2.asm:asm-util:9.1=classpath -org.ow2.asm:asm:9.1=classpath +org.ow2.asm:asm-analysis:9.6=classpath +org.ow2.asm:asm-commons:9.6=classpath +org.ow2.asm:asm-tree:9.6=classpath +org.ow2.asm:asm-util:9.6=classpath +org.ow2.asm:asm:9.6=classpath org.slf4j:slf4j-api:1.7.30=classpath org.tensorflow:tensorflow-lite-metadata:0.1.0-rc2=classpath -xerces:xercesImpl:2.12.0=classpath -xml-apis:xml-apis:1.4.01=classpath empty= diff --git a/flutter/dev/manual_tests/android/gradle.properties b/flutter/dev/manual_tests/android/gradle.properties index 598d13fee446372f156ecc38527b54c7cdcc8e3b..f018a61817f55e78bb92ce8df2dda423ec570a4a 100644 --- a/flutter/dev/manual_tests/android/gradle.properties +++ b/flutter/dev/manual_tests/android/gradle.properties @@ -1,3 +1,3 @@ -org.gradle.jvmargs=-Xmx4G +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true diff --git a/flutter/dev/manual_tests/android/project-app.lockfile b/flutter/dev/manual_tests/android/project-app.lockfile index 5e0f607feb0aaf79295d2b5c9bd6b6c3943e6799..0305482bdbcacad8460db1dfb973f6ecc37adaa0 100644 --- a/flutter/dev/manual_tests/android/project-app.lockfile +++ b/flutter/dev/manual_tests/android/project-app.lockfile @@ -1,28 +1,39 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -androidx.activity:activity:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation-experimental:1.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.annotation:annotation:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-common:2.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.arch.core:core-runtime:2.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.activity:activity:1.8.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.annotation:annotation-experimental:1.4.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.annotation:annotation-jvm:1.8.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.annotation:annotation:1.8.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.arch.core:core-common:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.arch.core:core-runtime:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath androidx.collection:collection:1.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.core:core:1.6.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.concurrent:concurrent-futures:1.1.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +androidx.core:core-ktx:1.13.1=debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.core:core-ktx:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata +androidx.core:core:1.13.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath androidx.customview:customview:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.fragment:fragment:1.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common-java8:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-common:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-livedata:2.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-runtime:2.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.fragment:fragment:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.interpolator:interpolator:1.0.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-common-java8:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-common:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-livedata-core-ktx:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-livedata-core:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-livedata:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-process:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-runtime:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-viewmodel-savedstate:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-viewmodel:2.7.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath androidx.loader:loader:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.savedstate:savedstate:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.tracing:tracing:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.profileinstaller:profileinstaller:1.3.1=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +androidx.savedstate:savedstate:1.2.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.startup:startup-runtime:1.1.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.tracing:tracing:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath androidx.versionedparcelable:versionedparcelable:1.1.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath androidx.viewpager:viewpager:1.0.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window-java:1.0.0-beta04=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -androidx.window:window:1.0.0-beta04=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.window.extensions.core:core:1.0.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +androidx.window:window-java:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.window:window:1.2.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath com.android.tools.analytics-library:protos:27.1.3=lintClassPath com.android.tools.analytics-library:shared:27.1.3=lintClassPath com.android.tools.analytics-library:tracker:27.1.3=lintClassPath @@ -36,6 +47,8 @@ com.android.tools.build:builder:4.1.3=lintClassPath com.android.tools.build:gradle-api:4.1.3=lintClassPath com.android.tools.build:manifest-merger:27.1.3=lintClassPath com.android.tools.ddms:ddmlib:27.1.3=lintClassPath +com.android.tools.ddms:ddmlib:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib +com.android.tools.emulator:proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention com.android.tools.external.com-intellij:intellij-core:27.1.3=lintClassPath com.android.tools.external.com-intellij:kotlin-compiler:27.1.3=lintClassPath com.android.tools.external.org-jetbrains:uast:27.1.3=lintClassPath @@ -46,37 +59,100 @@ com.android.tools.lint:lint-gradle-api:27.1.3=lintClassPath com.android.tools.lint:lint-gradle:27.1.3=lintClassPath com.android.tools.lint:lint-model:27.1.3=lintClassPath com.android.tools.lint:lint:27.1.3=lintClassPath +com.android.tools.utp:android-device-provider-ddmlib-proto:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib +com.android.tools.utp:android-device-provider-ddmlib:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib +com.android.tools.utp:android-device-provider-gradle-proto:31.7.0=_internal-unified-test-platform-android-device-provider-gradle +com.android.tools.utp:android-device-provider-gradle:31.7.0=_internal-unified-test-platform-android-device-provider-gradle +com.android.tools.utp:android-device-provider-profile-proto:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle +com.android.tools.utp:android-device-provider-profile:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle +com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output +com.android.tools.utp:android-test-plugin-host-additional-test-output:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output +com.android.tools.utp:android-test-plugin-host-apk-installer-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-apk-installer +com.android.tools.utp:android-test-plugin-host-apk-installer:31.7.0=_internal-unified-test-platform-android-test-plugin-host-apk-installer +com.android.tools.utp:android-test-plugin-host-coverage-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-coverage +com.android.tools.utp:android-test-plugin-host-coverage:31.7.0=_internal-unified-test-platform-android-test-plugin-host-coverage +com.android.tools.utp:android-test-plugin-host-device-info-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-device-info +com.android.tools.utp:android-test-plugin-host-device-info:31.7.0=_internal-unified-test-platform-android-test-plugin-host-device-info +com.android.tools.utp:android-test-plugin-host-emulator-control-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control +com.android.tools.utp:android-test-plugin-host-emulator-control:31.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control +com.android.tools.utp:android-test-plugin-host-logcat-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-logcat +com.android.tools.utp:android-test-plugin-host-logcat:31.7.0=_internal-unified-test-platform-android-test-plugin-host-logcat +com.android.tools.utp:android-test-plugin-host-retention-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-host-retention +com.android.tools.utp:android-test-plugin-host-retention:31.7.0=_internal-unified-test-platform-android-test-plugin-host-retention +com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:31.7.0=_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.android.tools.utp:android-test-plugin-result-listener-gradle:31.7.0=_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.android.tools.utp:utp-common:31.7.0=_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention com.android.tools:annotations:27.1.3=lintClassPath +com.android.tools:annotations:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle com.android.tools:common:27.1.3=lintClassPath +com.android.tools:common:31.7.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle com.android.tools:dvlib:27.1.3=lintClassPath com.android.tools:repository:27.1.3=lintClassPath com.android.tools:sdk-common:27.1.3=lintClassPath com.android.tools:sdklib:27.1.3=lintClassPath com.android:signflinger:4.1.3=lintClassPath com.android:zipflinger:4.1.3=lintClassPath -com.google.code.findbugs:jsr305:3.0.2=lintClassPath +com.getkeepsafe.relinker:relinker:1.4.5=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +com.google.android:annotations:4.1.1.4=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.api.grpc:proto-google-common-protos:2.17.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.code.findbugs:jsr305:3.0.2=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath +com.google.code.gson:gson:2.10.1=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle com.google.code.gson:gson:2.8.5=lintClassPath +com.google.crypto.tink:tink:1.7.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control +com.google.errorprone:error_prone_annotations:2.18.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle com.google.errorprone:error_prone_annotations:2.3.2=lintClassPath -com.google.guava:failureaccess:1.0.1=lintClassPath +com.google.guava:failureaccess:1.0.1=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath com.google.guava:guava:28.1-jre=lintClassPath -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=lintClassPath +com.google.guava:guava:32.0.1-jre=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.guava:listenablefuture:1.0=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,lintClassPath com.google.j2objc:j2objc-annotations:1.3=lintClassPath +com.google.j2objc:j2objc-annotations:2.8=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle com.google.jimfs:jimfs:1.1=lintClassPath com.google.protobuf:protobuf-java:3.10.0=lintClassPath +com.google.protobuf:protobuf-java:3.22.3=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.testing.platform:android-device-provider-local:0.0.9-alpha02=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.testing.platform:android-driver-instrumentation:0.0.9-alpha02=_internal-unified-test-platform-android-driver-instrumentation,_internal-unified-test-platform-android-test-plugin-host-emulator-control +com.google.testing.platform:android-test-plugin:0.0.9-alpha02=_internal-unified-test-platform-android-test-plugin +com.google.testing.platform:core-proto:0.0.9-alpha02=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +com.google.testing.platform:core:0.0.9-alpha02=_internal-unified-test-platform-core +com.google.testing.platform:launcher:0.0.9-alpha02=_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-launcher com.googlecode.json-simple:json-simple:1.1=lintClassPath com.squareup:javawriter:2.5.0=lintClassPath com.sun.activation:javax.activation:1.2.0=lintClassPath com.sun.istack:istack-commons-runtime:3.0.7=lintClassPath com.sun.xml.fastinfoset:FastInfoset:1.2.15=lintClassPath commons-codec:commons-codec:1.10=lintClassPath +commons-io:commons-io:2.13.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention commons-logging:commons-logging:1.2=lintClassPath +io.grpc:grpc-api:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-context:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-core:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-netty:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-protobuf-lite:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-protobuf:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.grpc:grpc-stub:1.57.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-buffer:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-codec-http2:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-codec-http:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-codec-socks:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-codec:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-common:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-handler-proxy:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-handler:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-resolver:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-transport-native-unix-common:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.netty:netty-transport:4.1.93.Final=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +io.perfmark:perfmark-api:0.26.0=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle it.unimi.dsi:fastutil:7.2.0=lintClassPath javax.activation:javax.activation-api:1.2.0=lintClassPath +javax.annotation:javax.annotation-api:1.3.2=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle javax.inject:javax.inject:1=lintClassPath javax.xml.bind:jaxb-api:2.3.1=lintClassPath -net.java.dev.jna:jna:5.6.0=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +net.java.dev.jna:jna-platform:5.6.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +net.java.dev.jna:jna:5.6.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath net.sf.jopt-simple:jopt-simple:4.9=lintClassPath -net.sf.kxml:kxml2:2.3.0=lintClassPath +net.sf.kxml:kxml2:2.3.0=_internal-unified-test-platform-android-device-provider-ddmlib,lintClassPath org.apache.commons:commons-compress:1.12=lintClassPath org.apache.httpcomponents:httpclient:4.5.6=lintClassPath org.apache.httpcomponents:httpcore:4.4.10=lintClassPath @@ -84,38 +160,60 @@ org.apache.httpcomponents:httpmime:4.5.6=lintClassPath org.bouncycastle:bcpkix-jdk15on:1.56=lintClassPath org.bouncycastle:bcprov-jdk15on:1.56=lintClassPath org.checkerframework:checker-qual:2.8.1=lintClassPath +org.checkerframework:checker-qual:3.33.0=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle org.codehaus.groovy:groovy-all:2.4.15=lintClassPath org.codehaus.mojo:animal-sniffer-annotations:1.18=lintClassPath +org.codehaus.mojo:animal-sniffer-annotations:1.23=_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle org.glassfish.jaxb:jaxb-runtime:2.3.1=lintClassPath org.glassfish.jaxb:txw2:2.3.1=lintClassPath org.jacoco:org.jacoco.agent:0.8.7=androidJacocoAnt org.jacoco:org.jacoco.ant:0.8.7=androidJacocoAnt org.jacoco:org.jacoco.core:0.8.7=androidJacocoAnt org.jacoco:org.jacoco.report:0.8.7=androidJacocoAnt -org.jetbrains.intellij.deps:trove4j:1.0.20200330=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-compiler-embeddable:1.7.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-daemon-embeddable:1.7.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-klib-commonizer-embeddable:1.7.10=kotlinKlibCommonizerClasspath +org.jetbrains.intellij.deps:trove4j:1.0.20200330=kotlinBuildToolsApiClasspath,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-build-common:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-build-tools-api:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-build-tools-impl:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-compiler-embeddable:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-compiler-embeddable:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-compiler-runner:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-daemon-client:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-daemon-embeddable:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-daemon-embeddable:1.9.20=kotlinBuildToolsApiClasspath +org.jetbrains.kotlin:kotlin-klib-commonizer-embeddable:1.8.10=kotlinKlibCommonizerClasspath org.jetbrains.kotlin:kotlin-reflect:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-reflect:1.7.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath -org.jetbrains.kotlin:kotlin-script-runtime:1.7.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-reflect:1.6.10=kotlinBuildToolsApiClasspath,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-script-runtime:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-script-runtime:1.9.20=kotlinBuildToolsApiClasspath org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-common:1.5.31=debugApiDependenciesMetadata,profileApiDependenciesMetadata,releaseApiDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib-common:1.7.10=debugAndroidTestCompileClasspath,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,implementationDependenciesMetadata,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-common:1.7.10=implementationDependenciesMetadata +org.jetbrains.kotlin:kotlin-stdlib-common:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-stdlib-common:1.8.22=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-common:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30=debugApiDependenciesMetadata,profileApiDependenciesMetadata,releaseApiDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10=debugAndroidTestCompileClasspath,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,implementationDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10=implementationDependenciesMetadata +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.20=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.20=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle org.jetbrains.kotlin:kotlin-stdlib:1.3.72=lintClassPath -org.jetbrains.kotlin:kotlin-stdlib:1.5.31=debugApiDependenciesMetadata,profileApiDependenciesMetadata,releaseApiDependenciesMetadata -org.jetbrains.kotlin:kotlin-stdlib:1.7.10=debugAndroidTestCompileClasspath,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,implementationDependenciesMetadata,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:atomicfu:0.16.3=debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata -org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath -org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:1.7.10=implementationDependenciesMetadata +org.jetbrains.kotlin:kotlin-stdlib:1.8.10=kotlinCompilerClasspath,kotlinKlibCommonizerClasspath +org.jetbrains.kotlin:kotlin-stdlib:1.8.22=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:1.9.20=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,kotlinBuildToolsApiClasspath +org.jetbrains.kotlinx:atomicfu:0.20.2=debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata +org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=kotlinBuildToolsApiClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.1=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4=_internal-unified-test-platform-android-device-provider-ddmlib,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle +org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.1=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath org.jetbrains.trove4j:trove4j:20160824=lintClassPath -org.jetbrains:annotations:13.0=debugAndroidTestCompileClasspath,debugApiDependenciesMetadata,debugCompileClasspath,debugImplementationDependenciesMetadata,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,implementationDependenciesMetadata,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath,lintClassPath,profileApiDependenciesMetadata,profileCompileClasspath,profileImplementationDependenciesMetadata,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseApiDependenciesMetadata,releaseCompileClasspath,releaseImplementationDependenciesMetadata,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains:annotations:13.0=_internal-unified-test-platform-android-device-provider-gradle,_internal-unified-test-platform-android-test-plugin-host-additional-test-output,_internal-unified-test-platform-android-test-plugin-host-apk-installer,_internal-unified-test-platform-android-test-plugin-host-coverage,_internal-unified-test-platform-android-test-plugin-host-device-info,_internal-unified-test-platform-android-test-plugin-host-emulator-control,_internal-unified-test-platform-android-test-plugin-host-logcat,_internal-unified-test-platform-android-test-plugin-host-retention,_internal-unified-test-platform-android-test-plugin-result-listener-gradle,debugApiDependenciesMetadata,debugImplementationDependenciesMetadata,implementationDependenciesMetadata,kotlinBuildToolsApiClasspath,kotlinCompilerClasspath,kotlinKlibCommonizerClasspath,lintClassPath,profileApiDependenciesMetadata,profileImplementationDependenciesMetadata,releaseApiDependenciesMetadata,releaseImplementationDependenciesMetadata +org.jetbrains:annotations:23.0.0=_internal-unified-test-platform-android-device-provider-ddmlib,debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath org.jvnet.staxex:stax-ex:1.8=lintClassPath org.ow2.asm:asm-analysis:7.0=lintClassPath org.ow2.asm:asm-analysis:9.1=androidJacocoAnt diff --git a/flutter/dev/manual_tests/android/settings.gradle b/flutter/dev/manual_tests/android/settings.gradle index eec0e0e6a7f3fa2c1780635724cf551743d3f9dc..4a155b35ec304af4a4baaf5f5fcbe6d0ac296764 100644 --- a/flutter/dev/manual_tests/android/settings.gradle +++ b/flutter/dev/manual_tests/android/settings.gradle @@ -18,11 +18,24 @@ pluginManagement { includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") - plugins { - id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + repositories { + google() + mavenCentral() + gradlePluginPortal() } } -include ":app" +buildscript { + dependencyLocking { + lockFile = file("${rootProject.projectDir}/buildscript-gradle.lockfile") + lockAllConfigurations() + } +} -apply from: "${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle/app_plugin_loader.gradle" +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.7.0" apply false + id "org.jetbrains.kotlin.android" version "1.8.10" apply false +} + +include ":app" diff --git a/flutter/dev/manual_tests/lib/actions.dart b/flutter/dev/manual_tests/lib/actions.dart index 0e494d12b3f4990ac67b74f26bcb462e4fd0fa2f..3ff5c829ca93a84ffa12eefb7e72407b5708f0e6 100644 --- a/flutter/dev/manual_tests/lib/actions.dart +++ b/flutter/dev/manual_tests/lib/actions.dart @@ -10,10 +10,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { - runApp(const MaterialApp( - title: 'Actions Demo', - home: FocusDemo(), - )); + runApp(const MaterialApp(title: 'Actions Demo', home: FocusDemo())); } /// A class that can hold invocation information that an [UndoableAction] can @@ -22,11 +19,7 @@ void main() { /// Instances of this class are returned from [UndoableAction]s and placed on /// the undo stack when they are invoked. class Memento extends Object with Diagnosticable { - const Memento({ - required this.name, - required this.undo, - required this.redo, - }); + const Memento({required this.name, required this.undo, required this.redo}); /// Returns true if this Memento can be used to undo. /// @@ -190,7 +183,9 @@ class UndoAction extends Action { if (buildContext == null) { return; } - final UndoableActionDispatcher manager = Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext!) as UndoableActionDispatcher; + final UndoableActionDispatcher manager = + Actions.of(primaryFocus?.context ?? FocusDemo.appKey.currentContext!) + as UndoableActionDispatcher; manager.undo(); } } @@ -223,18 +218,22 @@ class RedoAction extends Action { } /// An action that can be undone. -abstract class UndoableAction extends Action { } +abstract class UndoableAction extends Action {} class UndoableFocusActionBase extends UndoableAction { @override @mustCallSuper Memento invoke(T intent) { final FocusNode? previousFocus = primaryFocus; - return Memento(name: previousFocus!.debugLabel!, undo: () { - previousFocus.requestFocus(); - }, redo: () { - return invoke(intent); - }); + return Memento( + name: previousFocus!.debugLabel!, + undo: () { + previousFocus.requestFocus(); + }, + redo: () { + return invoke(intent); + }, + ); } } @@ -384,8 +383,19 @@ class _FocusDemoState extends State { policy: ReadingOrderTraversalPolicy(), child: Shortcuts( shortcuts: { - SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS, shift: true): const RedoIntent(), - SingleActivator(LogicalKeyboardKey.keyZ, meta: Platform.isMacOS, control: !Platform.isMacOS): const UndoIntent(), + SingleActivator( + LogicalKeyboardKey.keyZ, + meta: Platform.isMacOS, + control: !Platform.isMacOS, + shift: true, + ): + const RedoIntent(), + SingleActivator( + LogicalKeyboardKey.keyZ, + meta: Platform.isMacOS, + control: !Platform.isMacOS, + ): + const UndoIntent(), }, child: FocusScope( key: FocusDemo.appKey, @@ -394,68 +404,70 @@ class _FocusDemoState extends State { child: DefaultTextStyle( style: textTheme.headlineMedium!, child: Scaffold( - appBar: AppBar( - title: const Text('Actions Demo'), - ), + appBar: AppBar(title: const Text('Actions Demo')), body: Center( - child: Builder(builder: (BuildContext context) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton(name: 'One'), - DemoButton(name: 'Two'), - DemoButton(name: 'Three'), - ], - ), - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton(name: 'Four'), - DemoButton(name: 'Five'), - DemoButton(name: 'Six'), - ], - ), - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton(name: 'Seven'), - DemoButton(name: 'Eight'), - DemoButton(name: 'Nine'), - ], - ), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: const EdgeInsets.all(8.0), - child: ElevatedButton( - onPressed: canUndo - ? () { - Actions.invoke(context, const UndoIntent()); - } - : null, - child: const Text('UNDO'), + child: Builder( + builder: (BuildContext context) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DemoButton(name: 'One'), + DemoButton(name: 'Two'), + DemoButton(name: 'Three'), + ], + ), + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DemoButton(name: 'Four'), + DemoButton(name: 'Five'), + DemoButton(name: 'Six'), + ], + ), + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DemoButton(name: 'Seven'), + DemoButton(name: 'Eight'), + DemoButton(name: 'Nine'), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: + canUndo + ? () { + Actions.invoke(context, const UndoIntent()); + } + : null, + child: const Text('UNDO'), + ), ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: ElevatedButton( - onPressed: canRedo - ? () { - Actions.invoke(context, const RedoIntent()); - } - : null, - child: const Text('REDO'), + Padding( + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + onPressed: + canRedo + ? () { + Actions.invoke(context, const RedoIntent()); + } + : null, + child: const Text('REDO'), + ), ), - ), - ], - ), - ], - ); - }), + ], + ), + ], + ); + }, + ), ), ), ), diff --git a/flutter/dev/manual_tests/lib/animated_icons.dart b/flutter/dev/manual_tests/lib/animated_icons.dart index daa3f572c0023711c8a9bc67715d98ed7f8248ed..cbcd16e42dcc980ed5aaf58cea74f10205be45f8 100644 --- a/flutter/dev/manual_tests/lib/animated_icons.dart +++ b/flutter/dev/manual_tests/lib/animated_icons.dart @@ -9,12 +9,7 @@ class AnimatedIconsTestApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Animated Icons Test', - home: Scaffold( - body: IconsList(), - ), - ); + return const MaterialApp(title: 'Animated Icons Test', home: Scaffold(body: IconsList())); } } @@ -39,23 +34,26 @@ class IconSampleRow extends StatefulWidget { } class IconSampleRowState extends State with SingleTickerProviderStateMixin { - late final AnimationController progress = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); + late final AnimationController progress = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 300), + ); @override Widget build(BuildContext context) { return ListTile( leading: InkWell( - onTap: () { progress.forward(from: 0.0); }, - child: AnimatedIcon( - icon: widget.sample.icon, - progress: progress, - color: Colors.lightBlue, - ), + onTap: () { + progress.forward(from: 0.0); + }, + child: AnimatedIcon(icon: widget.sample.icon, progress: progress, color: Colors.lightBlue), ), title: Text(widget.sample.description), subtitle: Slider( value: progress.value, - onChanged: (double v) { progress.animateTo(v, duration: Duration.zero); }, + onChanged: (double v) { + progress.animateTo(v, duration: Duration.zero); + }, ), ); } @@ -77,7 +75,7 @@ class IconSampleRowState extends State with SingleTickerProviderS } } -const List samples = [ +const List samples = [ IconSample(AnimatedIcons.arrow_menu, 'arrow_menu'), IconSample(AnimatedIcons.menu_arrow, 'menu_arrow'), diff --git a/flutter/dev/manual_tests/lib/card_collection.dart b/flutter/dev/manual_tests/lib/card_collection.dart index 93abfc7e497454af387c7eadda36c4c880450d2d..01b8a4d6fb96c3faf9a0fb4b132063cd8c6aee41 100644 --- a/flutter/dev/manual_tests/lib/card_collection.dart +++ b/flutter/dev/manual_tests/lib/card_collection.dart @@ -7,8 +7,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; class CardModel { - CardModel(this.value, this.height) : - textController = TextEditingController(text: 'Item $value'); + CardModel(this.value, this.height) : textController = TextEditingController(text: 'Item $value'); int value; double height; @@ -25,19 +24,46 @@ class CardCollection extends StatefulWidget { } class CardCollectionState extends State { - - static const TextStyle cardLabelStyle = - TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold); + static const TextStyle cardLabelStyle = TextStyle( + color: Colors.white, + fontSize: 18.0, + fontWeight: FontWeight.bold, + ); // TODO(hansmuller): need a local image asset - static const String _sunshineURL = 'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg'; + static const String _sunshineURL = + 'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg'; static const double kCardMargins = 8.0; static const double kFixedCardHeight = 100.0; static const List _cardHeights = [ - 48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, - 48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, - 48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, + 48.0, + 63.0, + 85.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, + 48.0, + 63.0, + 85.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, + 48.0, + 63.0, + 85.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, ]; MaterialColor _primaryColor = Colors.deepPurple; @@ -53,13 +79,10 @@ class CardCollectionState extends State { if (_fixedSizeCards) { return; } - _cardModels = List.generate( - _cardModels.length, - (int i) { - _cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i]; - return _cardModels[i]; - }, - ); + _cardModels = List.generate(_cardModels.length, (int i) { + _cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i]; + return _cardModels[i]; + }); } void _initVariableSizedCardModels() { @@ -71,10 +94,7 @@ class CardCollectionState extends State { void _initFixedSizedCardModels() { const int cardCount = 27; - _cardModels = List.generate( - cardCount, - (int i) => CardModel(i, kFixedCardHeight), - ); + _cardModels = List.generate(cardCount, (int i) => CardModel(i, kFixedCardHeight)); } void _initCardModels() { @@ -109,24 +129,76 @@ class CardCollectionState extends State { buildDrawerCheckbox('Make card labels editable', _editable, _toggleEditable), buildDrawerCheckbox('Fixed size cards', _fixedSizeCards, _toggleFixedSizeCards), buildDrawerCheckbox('Let the sun shine', _sunshine, _toggleSunshine), - buildDrawerCheckbox('Vary font sizes', _varyFontSizes, _toggleVaryFontSizes, enabled: !_editable), + buildDrawerCheckbox( + 'Vary font sizes', + _varyFontSizes, + _toggleVaryFontSizes, + enabled: !_editable, + ), const Divider(), - buildDrawerColorRadioItem('Deep Purple', Colors.deepPurple, _primaryColor, _selectColor), + buildDrawerColorRadioItem( + 'Deep Purple', + Colors.deepPurple, + _primaryColor, + _selectColor, + ), buildDrawerColorRadioItem('Green', Colors.green, _primaryColor, _selectColor), buildDrawerColorRadioItem('Amber', Colors.amber, _primaryColor, _selectColor), buildDrawerColorRadioItem('Teal', Colors.teal, _primaryColor, _selectColor), const Divider(), - buildDrawerDirectionRadioItem('Dismiss horizontally', DismissDirection.horizontal, _dismissDirection, _changeDismissDirection, icon: Icons.code), - buildDrawerDirectionRadioItem('Dismiss left', DismissDirection.endToStart, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_back), - buildDrawerDirectionRadioItem('Dismiss right', DismissDirection.startToEnd, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_forward), + buildDrawerDirectionRadioItem( + 'Dismiss horizontally', + DismissDirection.horizontal, + _dismissDirection, + _changeDismissDirection, + icon: Icons.code, + ), + buildDrawerDirectionRadioItem( + 'Dismiss left', + DismissDirection.endToStart, + _dismissDirection, + _changeDismissDirection, + icon: Icons.arrow_back, + ), + buildDrawerDirectionRadioItem( + 'Dismiss right', + DismissDirection.startToEnd, + _dismissDirection, + _changeDismissDirection, + icon: Icons.arrow_forward, + ), const Divider(), - buildFontRadioItem('Left-align text', TextAlign.left, _textAlign, _changeTextAlign, icon: Icons.format_align_left, enabled: !_editable), - buildFontRadioItem('Center-align text', TextAlign.center, _textAlign, _changeTextAlign, icon: Icons.format_align_center, enabled: !_editable), - buildFontRadioItem('Right-align text', TextAlign.right, _textAlign, _changeTextAlign, icon: Icons.format_align_right, enabled: !_editable), + buildFontRadioItem( + 'Left-align text', + TextAlign.left, + _textAlign, + _changeTextAlign, + icon: Icons.format_align_left, + enabled: !_editable, + ), + buildFontRadioItem( + 'Center-align text', + TextAlign.center, + _textAlign, + _changeTextAlign, + icon: Icons.format_align_center, + enabled: !_editable, + ), + buildFontRadioItem( + 'Right-align text', + TextAlign.right, + _textAlign, + _changeTextAlign, + icon: Icons.format_align_right, + enabled: !_editable, + ), const Divider(), ListTile( leading: const Icon(Icons.dvr), - onTap: () { debugDumpApp(); debugDumpRenderTree(); }, + onTap: () { + debugDumpApp(); + debugDumpRenderTree(); + }, title: const Text('Dump App to Console'), ), ], @@ -184,22 +256,44 @@ class CardCollectionState extends State { }); } - Widget buildDrawerCheckbox(String label, bool value, void Function() callback, { bool enabled = true }) { + Widget buildDrawerCheckbox( + String label, + bool value, + void Function() callback, { + bool enabled = true, + }) { return ListTile( onTap: enabled ? callback : null, title: Text(label), trailing: Checkbox( value: value, - onChanged: enabled ? (_) { callback(); } : null, + onChanged: + enabled + ? (_) { + callback(); + } + : null, ), ); } - Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged onChanged, { IconData? icon, bool enabled = true }) { + Widget buildDrawerColorRadioItem( + String label, + MaterialColor itemValue, + MaterialColor currentValue, + ValueChanged onChanged, { + IconData? icon, + bool enabled = true, + }) { return ListTile( leading: Icon(icon), title: Text(label), - onTap: enabled ? () { onChanged(itemValue); } : null, + onTap: + enabled + ? () { + onChanged(itemValue); + } + : null, trailing: Radio( value: itemValue, groupValue: currentValue, @@ -208,11 +302,23 @@ class CardCollectionState extends State { ); } - Widget buildDrawerDirectionRadioItem(String label, DismissDirection itemValue, DismissDirection currentValue, ValueChanged onChanged, { IconData? icon, bool enabled = true }) { + Widget buildDrawerDirectionRadioItem( + String label, + DismissDirection itemValue, + DismissDirection currentValue, + ValueChanged onChanged, { + IconData? icon, + bool enabled = true, + }) { return ListTile( leading: Icon(icon), title: Text(label), - onTap: enabled ? () { onChanged(itemValue); } : null, + onTap: + enabled + ? () { + onChanged(itemValue); + } + : null, trailing: Radio( value: itemValue, groupValue: currentValue, @@ -221,11 +327,23 @@ class CardCollectionState extends State { ); } - Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged onChanged, { IconData? icon, bool enabled = true }) { + Widget buildFontRadioItem( + String label, + TextAlign itemValue, + TextAlign currentValue, + ValueChanged onChanged, { + IconData? icon, + bool enabled = true, + }) { return ListTile( leading: Icon(icon), title: Text(label), - onTap: enabled ? () { onChanged(itemValue); } : null, + onTap: + enabled + ? () { + onChanged(itemValue); + } + : null, trailing: Radio( value: itemValue, groupValue: currentValue, @@ -236,14 +354,15 @@ class CardCollectionState extends State { AppBar _buildAppBar(BuildContext context) { return AppBar( - actions: [ - Text(_dismissDirectionText(_dismissDirection)), - ], + actions: [Text(_dismissDirectionText(_dismissDirection))], flexibleSpace: Container( padding: const EdgeInsets.only(left: 72.0), height: 128.0, alignment: const Alignment(-1.0, 0.5), - child: Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.titleLarge), + child: Text( + 'Swipe Away: ${_cardModels.length}', + style: Theme.of(context).primaryTextTheme.titleLarge, + ), ), ); } @@ -253,31 +372,32 @@ class CardCollectionState extends State { final Widget card = Dismissible( key: ObjectKey(cardModel), direction: _dismissDirection, - onDismissed: (DismissDirection direction) { dismissCard(cardModel); }, + onDismissed: (DismissDirection direction) { + dismissCard(cardModel); + }, child: Card( color: _primaryColor[cardModel.color], child: Container( height: cardModel.height, padding: const EdgeInsets.all(kCardMargins), - child: _editable ? - Center( - child: TextField( - key: GlobalObjectKey(cardModel), - controller: cardModel.textController, - ), - ) - : DefaultTextStyle.merge( - style: cardLabelStyle.copyWith( - fontSize: _varyFontSizes ? 5.0 + index : null - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text(cardModel.textController.text, textAlign: _textAlign), - ], - ), - ), + child: + _editable + ? Center( + child: TextField( + key: GlobalObjectKey(cardModel), + controller: cardModel.textController, + ), + ) + : DefaultTextStyle.merge( + style: cardLabelStyle.copyWith(fontSize: _varyFontSizes ? 5.0 + index : null), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(cardModel.textController.text, textAlign: _textAlign), + ], + ), + ), ), ), ); @@ -328,7 +448,8 @@ class CardCollectionState extends State { children: [ leftArrowIcon, Expanded( - child: Text(backgroundMessage, + child: Text( + backgroundMessage, style: backgroundTextStyle, textAlign: TextAlign.center, ), @@ -350,12 +471,11 @@ class CardCollectionState extends State { Shader _createShader(Rect bounds) { return const LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [Color(0x00FFFFFF), Color(0xFFFFFFFF)], - stops: [0.1, 0.35], - ) - .createShader(bounds); + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0x00FFFFFF), Color(0xFFFFFFFF)], + stops: [0.1, 0.35], + ).createShader(bounds); } @override @@ -382,21 +502,12 @@ class CardCollectionState extends State { ); return Theme( - data: ThemeData( - primarySwatch: _primaryColor, - ), - child: Scaffold( - appBar: _buildAppBar(context), - drawer: _buildDrawer(), - body: body, - ), + data: ThemeData(primarySwatch: _primaryColor), + child: Scaffold(appBar: _buildAppBar(context), drawer: _buildDrawer(), body: body), ); } } void main() { - runApp(const MaterialApp( - title: 'Cards', - home: CardCollection(), - )); + runApp(const MaterialApp(title: 'Cards', home: CardCollection())); } diff --git a/flutter/dev/manual_tests/lib/color_testing_demo.dart b/flutter/dev/manual_tests/lib/color_testing_demo.dart index 05c71e3c08c8cb21a791663e13bc509f6e2dc623..9b4f0f4aa42d741392381a83c93810a896dabead 100644 --- a/flutter/dev/manual_tests/lib/color_testing_demo.dart +++ b/flutter/dev/manual_tests/lib/color_testing_demo.dart @@ -14,9 +14,13 @@ class ColorDemoHome extends StatelessWidget { body: ListView( padding: const EdgeInsets.all(5.0), children: [ - Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/gbr.png'), + Image.network( + 'https://flutter.github.io/assets-for-api-docs/assets/tests/colors/gbr.png', + ), Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/tf.png'), - Image.network('https://flutter.github.io/assets-for-api-docs/assets/tests/colors/wide-gamut.png'), + Image.network( + 'https://flutter.github.io/assets-for-api-docs/assets/tests/colors/wide-gamut.png', + ), const GradientRow(leftColor: Color(0xFFFF0000), rightColor: Color(0xFF00FF00)), const GradientRow(leftColor: Color(0xFF0000FF), rightColor: Color(0xFFFFFF00)), const GradientRow(leftColor: Color(0xFFFF0000), rightColor: Color(0xFF0000FF)), @@ -43,7 +47,7 @@ class ColorDemoHome extends StatelessWidget { } class GradientRow extends StatelessWidget { - const GradientRow({ super.key, required this.rightColor, required this.leftColor }); + const GradientRow({super.key, required this.rightColor, required this.leftColor}); final Color leftColor; final Color rightColor; @@ -56,7 +60,7 @@ class GradientRow extends StatelessWidget { gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, - colors: [ leftColor, rightColor ], + colors: [leftColor, rightColor], ), ), ); @@ -64,22 +68,16 @@ class GradientRow extends StatelessWidget { } class ColorRow extends StatelessWidget { - const ColorRow({ super.key, required this.color }); + const ColorRow({super.key, required this.color}); final Color color; @override Widget build(BuildContext context) { - return Container( - height: 100.0, - color: color, - ); + return Container(height: 100.0, color: color); } } void main() { - runApp(const MaterialApp( - title: 'Color Testing Demo', - home: ColorDemoHome(), - )); + runApp(const MaterialApp(title: 'Color Testing Demo', home: ColorDemoHome())); } diff --git a/flutter/dev/manual_tests/lib/density.dart b/flutter/dev/manual_tests/lib/density.dart index 801ac9c30947d4efd9da9f64c54dec08d2c5bafc..501027e9fc3f9e2cc5ac0319fb263a3aeac19a52 100644 --- a/flutter/dev/manual_tests/lib/density.dart +++ b/flutter/dev/manual_tests/lib/density.dart @@ -28,10 +28,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: _title, - home: MyHomePage(), - ); + return const MaterialApp(title: _title, home: MyHomePage()); } } @@ -114,13 +111,7 @@ class LabeledCheckbox extends StatelessWidget { Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, - children: [ - Checkbox( - onChanged: onChanged, - value: value, - ), - Text(label), - ], + children: [Checkbox(onChanged: onChanged, value: value), Text(label)], ); } } @@ -163,21 +154,19 @@ class _OptionsState extends State { double sliderValue = 0.0; String _densityToProfile(VisualDensity density) { - if (density == VisualDensity.standard) { - return 'standard'; - } else if (density == VisualDensity.compact) { - return 'compact'; - } else if (density == VisualDensity.comfortable) { - return 'comfortable'; - } - return 'custom'; + return switch (density) { + VisualDensity.standard => 'standard', + VisualDensity.compact => 'compact', + VisualDensity.comfortable => 'comfortable', + _ => 'custom', + }; } VisualDensity _profileToDensity(String? profile) { return switch (profile) { - 'standard' => VisualDensity.standard, + 'standard' => VisualDensity.standard, 'comfortable' => VisualDensity.comfortable, - 'compact' => VisualDensity.compact, + 'compact' => VisualDensity.compact, 'custom' || _ => widget.model.density, }; } @@ -193,160 +182,162 @@ class _OptionsState extends State { return Padding( padding: const EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 10.0), - child: Builder(builder: (BuildContext context) { - return DefaultTextStyle( - style: TextStyle(color: Colors.grey[50]), - child: Column( - children: [ - Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - const Text('Text Scale'), - Expanded( - child: SliderTheme( - data: controlTheme, - child: Slider( - label: '${widget.model.size}', - min: 0.5, - max: 3.0, - onChanged: (double value) { - widget.model.size = value; - }, - value: widget.model.size, + child: Builder( + builder: (BuildContext context) { + return DefaultTextStyle( + style: TextStyle(color: Colors.grey[50]), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + const Text('Text Scale'), + Expanded( + child: SliderTheme( + data: controlTheme, + child: Slider( + label: '${widget.model.size}', + min: 0.5, + max: 3.0, + onChanged: (double value) { + widget.model.size = value; + }, + value: widget.model.size, + ), ), ), - ), - Text( - widget.model.size.toStringAsFixed(3), - style: TextStyle(color: Colors.grey[50]), - ), - ], + Text( + widget.model.size.toStringAsFixed(3), + style: TextStyle(color: Colors.grey[50]), + ), + ], + ), ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - const Text('X Density'), - Expanded( - child: SliderTheme( - data: controlTheme, - child: Slider( - label: widget.model.density.horizontal.toStringAsFixed(1), - min: VisualDensity.minimumDensity, - max: VisualDensity.maximumDensity, - onChanged: (double value) { - widget.model.density = widget.model.density.copyWith( - horizontal: value, - vertical: widget.model.density.vertical, - ); - }, - value: widget.model.density.horizontal, + Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + const Text('X Density'), + Expanded( + child: SliderTheme( + data: controlTheme, + child: Slider( + label: widget.model.density.horizontal.toStringAsFixed(1), + min: VisualDensity.minimumDensity, + max: VisualDensity.maximumDensity, + onChanged: (double value) { + widget.model.density = widget.model.density.copyWith( + horizontal: value, + vertical: widget.model.density.vertical, + ); + }, + value: widget.model.density.horizontal, + ), ), ), - ), - Text( - widget.model.density.horizontal.toStringAsFixed(3), - style: TextStyle(color: Colors.grey[50]), - ), - ], + Text( + widget.model.density.horizontal.toStringAsFixed(3), + style: TextStyle(color: Colors.grey[50]), + ), + ], + ), ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - const Text('Y Density'), - Expanded( - child: SliderTheme( - data: controlTheme, - child: Slider( - label: widget.model.density.vertical.toStringAsFixed(1), - min: VisualDensity.minimumDensity, - max: VisualDensity.maximumDensity, - onChanged: (double value) { - widget.model.density = widget.model.density.copyWith( - horizontal: widget.model.density.horizontal, - vertical: value, - ); - }, - value: widget.model.density.vertical, + Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + const Text('Y Density'), + Expanded( + child: SliderTheme( + data: controlTheme, + child: Slider( + label: widget.model.density.vertical.toStringAsFixed(1), + min: VisualDensity.minimumDensity, + max: VisualDensity.maximumDensity, + onChanged: (double value) { + widget.model.density = widget.model.density.copyWith( + horizontal: widget.model.density.horizontal, + vertical: value, + ); + }, + value: widget.model.density.vertical, + ), ), ), + Text( + widget.model.density.vertical.toStringAsFixed(3), + style: TextStyle(color: Colors.grey[50]), + ), + ], + ), + ), + Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Theme( + data: Theme.of(context).copyWith(canvasColor: Colors.grey[600]), + child: DropdownButton( + style: TextStyle(color: Colors.grey[50]), + isDense: true, + onChanged: (String? value) { + widget.model.density = _profileToDensity(value); + }, + items: const >[ + DropdownMenuItem(value: 'standard', child: Text('Standard')), + DropdownMenuItem( + value: 'comfortable', + child: Text('Comfortable'), + ), + DropdownMenuItem(value: 'compact', child: Text('Compact')), + DropdownMenuItem(value: 'custom', child: Text('Custom')), + ], + value: _densityToProfile(widget.model.density), + ), ), - Text( - widget.model.density.vertical.toStringAsFixed(3), - style: TextStyle(color: Colors.grey[50]), + LabeledCheckbox( + label: 'Enabled', + onChanged: (bool? checked) { + widget.model.enable = checked ?? false; + }, + value: widget.model.enable, ), - ], - ), - ), - Wrap( - alignment: WrapAlignment.center, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - Theme( - data: Theme.of(context).copyWith(canvasColor: Colors.grey[600]), - child: DropdownButton( - style: TextStyle(color: Colors.grey[50]), - isDense: true, - onChanged: (String? value) { - widget.model.density = _profileToDensity(value); + LabeledCheckbox( + label: 'Slow', + onChanged: (bool? checked) { + widget.model.slowAnimations = checked ?? false; + Future.delayed(const Duration(milliseconds: 150)).then((_) { + if (widget.model.slowAnimations) { + timeDilation = 20.0; + } else { + timeDilation = 1.0; + } + }); }, - items: const >[ - DropdownMenuItem( - value: 'standard', - child: Text('Standard'), - ), - DropdownMenuItem(value: 'comfortable', child: Text('Comfortable')), - DropdownMenuItem(value: 'compact', child: Text('Compact')), - DropdownMenuItem(value: 'custom', child: Text('Custom')), - ], - value: _densityToProfile(widget.model.density), + value: widget.model.slowAnimations, ), - ), - LabeledCheckbox( - label: 'Enabled', - onChanged: (bool? checked) { - widget.model.enable = checked ?? false; - }, - value: widget.model.enable, - ), - LabeledCheckbox( - label: 'Slow', - onChanged: (bool? checked) { - widget.model.slowAnimations = checked ?? false; - Future.delayed(const Duration(milliseconds: 150)).then((_) { - if (widget.model.slowAnimations) { - timeDilation = 20.0; - } else { - timeDilation = 1.0; - } - }); - }, - value: widget.model.slowAnimations, - ), - LabeledCheckbox( - label: 'RTL', - onChanged: (bool? checked) { - widget.model.rtl = checked ?? false; - }, - value: widget.model.rtl, - ), - MaterialButton( - onPressed: () { - widget.model.reset(); - sliderValue = 0.0; - }, - child: Text('Reset', style: TextStyle(color: Colors.grey[50])), - ), - ], - ), - ], - ), - ); - }), + LabeledCheckbox( + label: 'RTL', + onChanged: (bool? checked) { + widget.model.rtl = checked ?? false; + }, + value: widget.model.rtl, + ), + MaterialButton( + onPressed: () { + widget.model.reset(); + sliderValue = 0.0; + }, + child: Text('Reset', style: TextStyle(color: Colors.grey[50])), + ), + ], + ), + ], + ), + ); + }, + ), ); } } @@ -366,10 +357,7 @@ class _ControlTile extends StatelessWidget { children: [ Align( alignment: AlignmentDirectional.topStart, - child: Text( - label, - textAlign: TextAlign.start, - ), + child: Text(label, textAlign: TextAlign.start), ), child, ], @@ -408,13 +396,12 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { - final ThemeData theme = ThemeData( - primarySwatch: m2Swatch, - ); + final ThemeData theme = ThemeData(primarySwatch: m2Swatch); final Widget label = Text(_model.rtl ? 'اضغط علي' : 'Press Me'); - textController.text = _model.rtl - ? 'يعتمد القرار الجيد على المعرفة وليس على الأرقام.' - : 'A good decision is based on knowledge and not on numbers.'; + textController.text = + _model.rtl + ? 'يعتمد القرار الجيد على المعرفة وليس على الأرقام.' + : 'A good decision is based on knowledge and not on numbers.'; final List tiles = [ _ControlTile( @@ -425,28 +412,33 @@ class _MyHomePageState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ ListTile( - title: Text(_model.rtl ? 'هذا عنوان طويل نسبيا' : 'This is a relatively long title'), + title: Text( + _model.rtl ? 'هذا عنوان طويل نسبيا' : 'This is a relatively long title', + ), onTap: () {}, ), ListTile( title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'), - subtitle: - Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'), + subtitle: Text( + _model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.', + ), trailing: const Icon(Icons.check_box), onTap: () {}, ), ListTile( title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'), - subtitle: - Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'), + subtitle: Text( + _model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.', + ), leading: const Icon(Icons.check_box), dense: true, onTap: () {}, ), ListTile( title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'), - subtitle: - Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'), + subtitle: Text( + _model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.', + ), dense: true, leading: const Icon(Icons.add_box), trailing: const Icon(Icons.check_box), @@ -454,8 +446,9 @@ class _MyHomePageState extends State { ), ListTile( title: Text(_model.rtl ? 'هذا عنوان قصير' : 'This is a short title'), - subtitle: - Text(_model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.'), + subtitle: Text( + _model.rtl ? 'هذا عنوان فرعي مناسب.' : 'This is an appropriate subtitle.', + ), isThreeLine: true, leading: const Icon(Icons.add_box), trailing: const Icon(Icons.check_box), @@ -481,13 +474,8 @@ class _MyHomePageState extends State { border: OutlineInputBorder(), ), ), - TextField( - controller: textController, - ), - TextField( - controller: textController, - maxLines: 3, - ), + TextField(controller: textController), + TextField(controller: textController, maxLines: 3), ], ), ), @@ -520,7 +508,7 @@ class _MyHomePageState extends State { child: TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, - backgroundColor: m2Swatch[200] + backgroundColor: m2Swatch[200], ), onPressed: _model.enable ? () {} : null, child: label, @@ -536,10 +524,7 @@ class _MyHomePageState extends State { ), _ControlTile( label: _model.rtl ? 'زر المخطط التفصيلي' : 'Outlined Button', - child: OutlinedButton( - onPressed: _model.enable ? () {} : null, - child: label, - ), + child: OutlinedButton(onPressed: _model.enable ? () {} : null, child: label), ), _ControlTile( label: _model.rtl ? 'خانات الاختيار' : 'Checkboxes', @@ -547,13 +532,14 @@ class _MyHomePageState extends State { mainAxisAlignment: MainAxisAlignment.center, children: List.generate(checkboxValues.length, (int index) { return Checkbox( - onChanged: _model.enable - ? (bool? value) { - setState(() { - checkboxValues[index] = value ?? false; - }); - } - : null, + onChanged: + _model.enable + ? (bool? value) { + setState(() { + checkboxValues[index] = value ?? false; + }); + } + : null, value: checkboxValues[index], ); }), @@ -565,13 +551,14 @@ class _MyHomePageState extends State { mainAxisAlignment: MainAxisAlignment.center, children: List.generate(4, (int index) { return Radio( - onChanged: _model.enable - ? (int? value) { - setState(() { - radioValue = value!; - }); - } - : null, + onChanged: + _model.enable + ? (int? value) { + setState(() { + radioValue = value!; + }); + } + : null, groupValue: radioValue, value: index, ); @@ -616,17 +603,15 @@ class _MyHomePageState extends State { data: Theme.of(context).copyWith(visualDensity: _model.density), child: Directionality( textDirection: _model.rtl ? TextDirection.rtl : TextDirection.ltr, - child: Builder(builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)), - child: SizedBox.expand( - child: ListView( - children: tiles, - ), - ), - ); - }), + child: Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(textScaler: TextScaler.linear(_model.size)), + child: SizedBox.expand(child: ListView(children: tiles)), + ); + }, + ), ), ), ), diff --git a/flutter/dev/manual_tests/lib/drag_and_drop.dart b/flutter/dev/manual_tests/lib/drag_and_drop.dart index bcdbcd49690da5f79113b6088921ef84f898fe3a..20a17e8450776996fd932214e41a0499c6ffeb52 100644 --- a/flutter/dev/manual_tests/lib/drag_and_drop.dart +++ b/flutter/dev/manual_tests/lib/drag_and_drop.dart @@ -32,10 +32,7 @@ class ExampleDragTargetState extends State { margin: const EdgeInsets.all(10.0), decoration: BoxDecoration( color: data.isEmpty ? _color : Colors.grey.shade200, - border: Border.all( - width: 3.0, - color: data.isEmpty ? Colors.white : Colors.blue, - ), + border: Border.all(width: 3.0, color: data.isEmpty ? Colors.white : Colors.blue), ), ); }, @@ -44,7 +41,7 @@ class ExampleDragTargetState extends State { } class Dot extends StatefulWidget { - const Dot({ super.key, this.color, this.size, this.child, this.tappable = false }); + const Dot({super.key, this.color, this.size, this.child, this.tappable = false}); final Color? color; final double? size; @@ -54,13 +51,21 @@ class Dot extends StatefulWidget { @override DotState createState() => DotState(); } + class DotState extends State { int taps = 0; @override Widget build(BuildContext context) { return GestureDetector( - onTap: widget.tappable ? () { setState(() { taps += 1; }); } : null, + onTap: + widget.tappable + ? () { + setState(() { + taps += 1; + }); + } + : null, child: Container( width: widget.size, height: widget.size, @@ -103,24 +108,16 @@ class ExampleDragSource extends StatelessWidget { final Widget contents = DefaultTextStyle( style: Theme.of(context).textTheme.bodyMedium!, textAlign: TextAlign.center, - child: Dot( - color: color, - size: size, - child: Center(child: child), - ), + child: Dot(color: color, size: size, child: Center(child: child)), ); - Widget feedback = Opacity( - opacity: 0.75, - child: contents, - ); + Widget feedback = Opacity(opacity: 0.75, child: contents); Offset feedbackOffset; DragAnchorStrategy dragAnchorStrategy; if (!under) { feedback = Transform( - transform: Matrix4.identity() - ..translate(-size / 2.0, -(size / 2.0 + kFingerSize)), + transform: Matrix4.identity()..translate(-size / 2.0, -(size / 2.0 + kFingerSize)), child: feedback, ); feedbackOffset = const Offset(0.0, -kFingerSize); @@ -161,10 +158,11 @@ class DashOutlineCirclePainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final double radius = size.shortestSide / 2.0; - final Paint paint = Paint() - ..color = const Color(0xFF000000) - ..style = PaintingStyle.stroke - ..strokeWidth = radius / 10.0; + final Paint paint = + Paint() + ..color = const Color(0xFF000000) + ..style = PaintingStyle.stroke + ..strokeWidth = radius / 10.0; final Path path = Path(); final Rect box = Offset.zero & size; for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) { @@ -203,9 +201,7 @@ class MovableBall extends StatelessWidget { const Widget dashedBall = SizedBox( width: kBallSize, height: kBallSize, - child: CustomPaint( - painter: DashOutlineCirclePainter() - ), + child: CustomPaint(painter: DashOutlineCirclePainter()), ); if (position == ballPosition) { return Draggable( @@ -217,7 +213,9 @@ class MovableBall extends StatelessWidget { ); } else { return DragTarget( - onAcceptWithDetails: (DragTargetDetails data) { callback(position); }, + onAcceptWithDetails: (DragTargetDetails data) { + callback(position); + }, builder: (BuildContext context, List accepted, List rejected) { return dashedBall; }, @@ -237,25 +235,22 @@ class DragAndDropAppState extends State { int position = 1; void moveBall(int newPosition) { - setState(() { position = newPosition; }); + setState(() { + position = newPosition; + }); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Drag and Drop Flutter Demo'), - ), + appBar: AppBar(title: const Text('Drag and Drop Flutter Demo')), body: Column( children: [ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - ExampleDragSource( - color: Colors.yellow.shade300, - child: const Text('under'), - ), + ExampleDragSource(color: Colors.yellow.shade300, child: const Text('under')), ExampleDragSource( color: Colors.green.shade300, under: false, @@ -297,8 +292,5 @@ class DragAndDropAppState extends State { } void main() { - runApp(const MaterialApp( - title: 'Drag and Drop Flutter Demo', - home: DragAndDropApp(), - )); + runApp(const MaterialApp(title: 'Drag and Drop Flutter Demo', home: DragAndDropApp())); } diff --git a/flutter/dev/manual_tests/lib/focus.dart b/flutter/dev/manual_tests/lib/focus.dart index 6680909e45c13e48a2e0415356fde7293015684d..f0f6bb11da31ae7a80523faa9bcce0f304d2e11a 100644 --- a/flutter/dev/manual_tests/lib/focus.dart +++ b/flutter/dev/manual_tests/lib/focus.dart @@ -6,14 +6,16 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { - runApp(const MaterialApp( - title: 'Focus Demo', - home: FocusDemo(), - )); + runApp(const MaterialApp(title: 'Focus Demo', home: FocusDemo())); } class DemoButton extends StatefulWidget { - const DemoButton({super.key, required this.name, this.canRequestFocus = true, this.autofocus = false}); + const DemoButton({ + super.key, + required this.name, + this.canRequestFocus = true, + this.autofocus = false, + }); final String name; final bool canRequestFocus; @@ -25,8 +27,8 @@ class DemoButton extends StatefulWidget { class _DemoButtonState extends State { late final FocusNode focusNode = FocusNode( - debugLabel: widget.name, - canRequestFocus: widget.canRequestFocus, + debugLabel: widget.name, + canRequestFocus: widget.canRequestFocus, ); @override @@ -97,8 +99,8 @@ class _FocusDemoState extends State { print('Keys down: ${HardwareKeyboard.instance.logicalKeysPressed}'); if (event.logicalKey == LogicalKeyboardKey.tab) { debugDumpFocusTree(); - if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) - || HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)) { + if (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) || + HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)) { print('Moving to previous.'); node.previousFocus(); return KeyEventResult.handled; @@ -108,20 +110,15 @@ class _FocusDemoState extends State { return KeyEventResult.handled; } } - if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { - node.focusInDirection(TraversalDirection.left); - return KeyEventResult.handled; - } - if (event.logicalKey == LogicalKeyboardKey.arrowRight) { - node.focusInDirection(TraversalDirection.right); - return KeyEventResult.handled; - } - if (event.logicalKey == LogicalKeyboardKey.arrowUp) { - node.focusInDirection(TraversalDirection.up); - return KeyEventResult.handled; - } - if (event.logicalKey == LogicalKeyboardKey.arrowDown) { - node.focusInDirection(TraversalDirection.down); + final TraversalDirection? direction = switch (event.logicalKey) { + LogicalKeyboardKey.arrowLeft => TraversalDirection.left, + LogicalKeyboardKey.arrowRight => TraversalDirection.right, + LogicalKeyboardKey.arrowUp => TraversalDirection.up, + LogicalKeyboardKey.arrowDown => TraversalDirection.down, + _ => null, + }; + if (direction != null) { + node.focusInDirection(direction); return KeyEventResult.handled; } } @@ -141,65 +138,57 @@ class _FocusDemoState extends State { child: DefaultTextStyle( style: textTheme.headlineMedium!, child: Scaffold( - appBar: AppBar( - title: const Text('Focus Demo'), - ), - floatingActionButton: FloatingActionButton( - child: const Text('+'), - onPressed: () {}, - ), + appBar: AppBar(title: const Text('Focus Demo')), + floatingActionButton: FloatingActionButton(child: const Text('+'), onPressed: () {}), body: Center( - child: Builder(builder: (BuildContext context) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton( - name: 'One', - autofocus: true, - ), - ], - ), - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton(name: 'Two'), - DemoButton( - name: 'Three', - canRequestFocus: false, + child: Builder( + builder: (BuildContext context) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [DemoButton(name: 'One', autofocus: true)], + ), + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DemoButton(name: 'Two'), + DemoButton(name: 'Three', canRequestFocus: false), + ], + ), + const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + DemoButton(name: 'Four'), + DemoButton(name: 'Five'), + DemoButton(name: 'Six'), + ], + ), + OutlinedButton( + onPressed: () => print('pressed'), + child: const Text('PRESS ME'), + ), + const Padding( + padding: EdgeInsets.all(8.0), + child: TextField( + decoration: InputDecoration(labelText: 'Enter Text', filled: true), ), - ], - ), - const Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - DemoButton(name: 'Four'), - DemoButton(name: 'Five'), - DemoButton(name: 'Six'), - ], - ), - OutlinedButton(onPressed: () => print('pressed'), child: const Text('PRESS ME')), - const Padding( - padding: EdgeInsets.all(8.0), - child: TextField( - decoration: InputDecoration(labelText: 'Enter Text', filled: true), ), - ), - const Padding( - padding: EdgeInsets.all(8.0), - child: TextField( - decoration: InputDecoration( - border: OutlineInputBorder(), - labelText: 'Enter Text', - filled: false, + const Padding( + padding: EdgeInsets.all(8.0), + child: TextField( + decoration: InputDecoration( + border: OutlineInputBorder(), + labelText: 'Enter Text', + filled: false, + ), ), ), - ), - ], - ); - }), + ], + ); + }, + ), ), ), ), diff --git a/flutter/dev/manual_tests/lib/hardware_keyboard.dart b/flutter/dev/manual_tests/lib/hardware_keyboard.dart index e841011ca234ca6760c240708c906be0a0f17c5d..fea6404fdfbf9b240f10a9f8f8cf8d11077b13c8 100644 --- a/flutter/dev/manual_tests/lib/hardware_keyboard.dart +++ b/flutter/dev/manual_tests/lib/hardware_keyboard.dart @@ -6,17 +6,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { - runApp(MaterialApp( - title: 'Hardware Key Demo', - home: Scaffold( - appBar: AppBar( - title: const Text('Hardware Key Demo'), - ), - body: const Center( - child: HardwareKeyboardDemo(), + runApp( + MaterialApp( + title: 'Hardware Key Demo', + home: Scaffold( + appBar: AppBar(title: const Text('Hardware Key Demo')), + body: const Center(child: HardwareKeyboardDemo()), ), ), - )); + ); } class HardwareKeyboardDemo extends StatefulWidget { @@ -68,7 +66,8 @@ class _HardwareKeyboardDemoState extends State { final List dataText = [ Text('${_event.runtimeType}'), - if (_event?.character?.isNotEmpty ?? false) Text('character produced: "${_event?.character}"'), + if (_event?.character?.isNotEmpty ?? false) + Text('character produced: "${_event?.character}"'), ]; dataText.add(Text('logical: ${_event?.logicalKey}')); dataText.add(Text('physical: ${_event?.physicalKey}')); @@ -82,10 +81,7 @@ class _HardwareKeyboardDemoState extends State { dataText.add(Text(pressed.join(' '))); return DefaultTextStyle( style: textTheme.titleMedium!, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: dataText, - ), + child: Column(mainAxisAlignment: MainAxisAlignment.center, children: dataText), ); }, ), diff --git a/flutter/dev/manual_tests/lib/hover.dart b/flutter/dev/manual_tests/lib/hover.dart index 9992914c3186061fb99f7011560fea86fa0a8781..498df5c393e1602701cb190dcf619b696c053aa0 100644 --- a/flutter/dev/manual_tests/lib/hover.dart +++ b/flutter/dev/manual_tests/lib/hover.dart @@ -5,10 +5,7 @@ import 'package:flutter/material.dart'; void main() { - runApp(const MaterialApp( - title: 'Hover Demo', - home: HoverDemo(), - )); + runApp(const MaterialApp(title: 'Hover Demo', home: HoverDemo())); } class HoverDemo extends StatefulWidget { @@ -24,63 +21,62 @@ class _HoverDemoState extends State { final TextTheme textTheme = Theme.of(context).textTheme; final ButtonStyle overrideFocusColor = ButtonStyle( overlayColor: MaterialStateProperty.resolveWith((Set states) { - return states.contains(MaterialState.focused) ? Colors.deepOrangeAccent : Colors.transparent; - }) + return states.contains(MaterialState.focused) + ? Colors.deepOrangeAccent + : Colors.transparent; + }), ); return DefaultTextStyle( style: textTheme.headlineMedium!, child: Scaffold( - appBar: AppBar( - title: const Text('Hover Demo'), - ), - floatingActionButton: FloatingActionButton( - child: const Text('+'), - onPressed: () {}, - ), + appBar: AppBar(title: const Text('Hover Demo')), + floatingActionButton: FloatingActionButton(child: const Text('+'), onPressed: () {}), body: Center( - child: Builder(builder: (BuildContext context) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Row( - children: [ - ElevatedButton( - onPressed: () => print('Button pressed.'), - style: overrideFocusColor, - child: const Text('Button'), - ), - TextButton( - onPressed: () => print('Button pressed.'), - style: overrideFocusColor, - child: const Text('Button'), - ), - IconButton( - onPressed: () => print('Button pressed'), - icon: const Icon(Icons.access_alarm), - focusColor: Colors.deepOrangeAccent, + child: Builder( + builder: (BuildContext context) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Row( + children: [ + ElevatedButton( + onPressed: () => print('Button pressed.'), + style: overrideFocusColor, + child: const Text('Button'), + ), + TextButton( + onPressed: () => print('Button pressed.'), + style: overrideFocusColor, + child: const Text('Button'), + ), + IconButton( + onPressed: () => print('Button pressed'), + icon: const Icon(Icons.access_alarm), + focusColor: Colors.deepOrangeAccent, + ), + ], + ), + const Padding( + padding: EdgeInsets.all(8.0), + child: TextField( + decoration: InputDecoration(labelText: 'Enter Text', filled: true), ), - ], - ), - const Padding( - padding: EdgeInsets.all(8.0), - child: TextField( - decoration: InputDecoration(labelText: 'Enter Text', filled: true), ), - ), - const Padding( - padding: EdgeInsets.all(8.0), - child: TextField( - decoration: InputDecoration( - border: OutlineInputBorder(), - labelText: 'Enter Text', - filled: false, + const Padding( + padding: EdgeInsets.all(8.0), + child: TextField( + decoration: InputDecoration( + border: OutlineInputBorder(), + labelText: 'Enter Text', + filled: false, + ), ), ), - ), - ], - ); - }), + ], + ); + }, + ), ), ), ); diff --git a/flutter/dev/manual_tests/lib/main.dart b/flutter/dev/manual_tests/lib/main.dart index 347520d9712d32d616ef6beff85f74ec6ca6c549..63cfbac5cf0fec5c0a1ada5f6779bd5976a32cc1 100644 --- a/flutter/dev/manual_tests/lib/main.dart +++ b/flutter/dev/manual_tests/lib/main.dart @@ -5,10 +5,10 @@ import 'package:flutter/widgets.dart'; void main() { - runApp(const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Text('flutter run -t xxx.dart'), + runApp( + const Directionality( + textDirection: TextDirection.ltr, + child: Center(child: Text('flutter run -t xxx.dart')), ), - )); + ); } diff --git a/flutter/dev/manual_tests/lib/material_arc.dart b/flutter/dev/manual_tests/lib/material_arc.dart index 8eb731392432241c8b5c08f215d55ed0e1b3784b..0d026eddf7f4a6d46929a31636ed4b43cb9cba61 100644 --- a/flutter/dev/manual_tests/lib/material_arc.dart +++ b/flutter/dev/manual_tests/lib/material_arc.dart @@ -5,10 +5,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -enum _DragTarget { - start, - end -} +enum _DragTarget { start, end } // How close a drag's start position must be to the target point. This is // a distance squared. @@ -40,22 +37,21 @@ class _DragHandler extends Drag { } } -class _IgnoreDrag extends Drag { -} +class _IgnoreDrag extends Drag {} class _PointDemoPainter extends CustomPainter { - _PointDemoPainter({ - Animation? repaint, - required this.arc, - }) : _repaint = repaint, super(repaint: repaint); + _PointDemoPainter({Animation? repaint, required this.arc}) + : _repaint = repaint, + super(repaint: repaint); final MaterialPointArcTween arc; final Animation? _repaint; void drawPoint(Canvas canvas, Offset point, Color color) { - final Paint paint = Paint() - ..color = color.withOpacity(0.25) - ..style = PaintingStyle.fill; + final Paint paint = + Paint() + ..color = color.withOpacity(0.25) + ..style = PaintingStyle.fill; canvas.drawCircle(point, _kPointRadius, paint); paint ..color = color @@ -73,7 +69,8 @@ class _PointDemoPainter extends CustomPainter { } paint - ..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720 + ..isAntiAlias = + false // Work-around for github.com/flutter/flutter/issues/5720 ..color = Colors.green.withOpacity(0.25) ..strokeWidth = 4.0 ..style = PaintingStyle.stroke; @@ -94,8 +91,8 @@ class _PointDemoPainter extends CustomPainter { @override bool hitTest(Offset position) { - return (arc.begin! - position).distanceSquared < _kTargetSlop - || (arc.end! - position).distanceSquared < _kTargetSlop; + return (arc.begin! - position).distanceSquared < _kTargetSlop || + (arc.end! - position).distanceSquared < _kTargetSlop; } @override @@ -103,7 +100,7 @@ class _PointDemoPainter extends CustomPainter { } class _PointDemo extends StatefulWidget { - const _PointDemo({ super.key, required this.controller }); + const _PointDemo({super.key, required this.controller}); final AnimationController controller; @@ -189,20 +186,18 @@ class _PointDemoState extends State<_PointDemo> { return RawGestureDetector( behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque, gestures: { - ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => ImmediateMultiDragGestureRecognizer(), - (ImmediateMultiDragGestureRecognizer instance) { - instance.onStart = _handleOnStart; - }, - ), + ImmediateMultiDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => ImmediateMultiDragGestureRecognizer(), + (ImmediateMultiDragGestureRecognizer instance) { + instance.onStart = _handleOnStart; + }, + ), }, child: ClipRect( child: CustomPaint( key: _painterKey, - foregroundPainter: _PointDemoPainter( - repaint: _animation, - arc: arc, - ), + foregroundPainter: _PointDemoPainter(repaint: _animation, arc: arc), // Watch out: if this IgnorePointer is left out, then gestures that // fail _PointDemoPainter.hitTest() will still be recognized because // they do overlap this child, which is as big as the CustomPaint. @@ -223,18 +218,18 @@ class _PointDemoState extends State<_PointDemo> { } class _RectangleDemoPainter extends CustomPainter { - _RectangleDemoPainter({ - required Animation repaint, - required this.arc, - }) : _repaint = repaint, super(repaint: repaint); + _RectangleDemoPainter({required Animation repaint, required this.arc}) + : _repaint = repaint, + super(repaint: repaint); final MaterialRectArcTween arc; final Animation _repaint; void drawPoint(Canvas canvas, Offset p, Color color) { - final Paint paint = Paint() - ..color = color.withOpacity(0.25) - ..style = PaintingStyle.fill; + final Paint paint = + Paint() + ..color = color.withOpacity(0.25) + ..style = PaintingStyle.fill; canvas.drawCircle(p, _kPointRadius, paint); paint ..color = color @@ -244,10 +239,11 @@ class _RectangleDemoPainter extends CustomPainter { } void drawRect(Canvas canvas, Rect rect, Color color) { - final Paint paint = Paint() - ..color = color.withOpacity(0.25) - ..strokeWidth = 4.0 - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = color.withOpacity(0.25) + ..strokeWidth = 4.0 + ..style = PaintingStyle.stroke; canvas.drawRect(rect, paint); drawPoint(canvas, rect.center, color); } @@ -261,8 +257,8 @@ class _RectangleDemoPainter extends CustomPainter { @override bool hitTest(Offset position) { - return (arc.begin!.center - position).distanceSquared < _kTargetSlop - || (arc.end!.center - position).distanceSquared < _kTargetSlop; + return (arc.begin!.center - position).distanceSquared < _kTargetSlop || + (arc.end!.center - position).distanceSquared < _kTargetSlop; } @override @@ -270,7 +266,7 @@ class _RectangleDemoPainter extends CustomPainter { } class _RectangleDemo extends StatefulWidget { - const _RectangleDemo({ super.key, required this.controller }); + const _RectangleDemo({super.key, required this.controller}); final AnimationController controller; @@ -281,7 +277,10 @@ class _RectangleDemo extends StatefulWidget { class _RectangleDemoState extends State<_RectangleDemo> { final GlobalKey _painterKey = GlobalKey(); - late final CurvedAnimation _animation = CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn); + late final CurvedAnimation _animation = CurvedAnimation( + parent: widget.controller, + curve: Curves.fastOutSlowIn, + ); _DragTarget? _dragTarget; Size? _screenSize; Rect? _begin; @@ -342,12 +341,16 @@ class _RectangleDemoState extends State<_RectangleDemo> { if (_screenSize == null || _screenSize != screenSize) { _screenSize = screenSize; _begin = Rect.fromLTWH( - screenSize.width * 0.5, screenSize.height * 0.2, - screenSize.width * 0.4, screenSize.height * 0.2, + screenSize.width * 0.5, + screenSize.height * 0.2, + screenSize.width * 0.4, + screenSize.height * 0.2, ); _end = Rect.fromLTWH( - screenSize.width * 0.1, screenSize.height * 0.4, - screenSize.width * 0.3, screenSize.height * 0.3, + screenSize.width * 0.1, + screenSize.height * 0.4, + screenSize.width * 0.3, + screenSize.height * 0.3, ); } @@ -355,20 +358,18 @@ class _RectangleDemoState extends State<_RectangleDemo> { return RawGestureDetector( behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque, gestures: { - ImmediateMultiDragGestureRecognizer: GestureRecognizerFactoryWithHandlers( - () => ImmediateMultiDragGestureRecognizer(), - (ImmediateMultiDragGestureRecognizer instance) { - instance.onStart = _handleOnStart; - }, - ), + ImmediateMultiDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => ImmediateMultiDragGestureRecognizer(), + (ImmediateMultiDragGestureRecognizer instance) { + instance.onStart = _handleOnStart; + }, + ), }, child: ClipRect( child: CustomPaint( key: _painterKey, - foregroundPainter: _RectangleDemoPainter( - repaint: _animation, - arc: arc, - ), + foregroundPainter: _RectangleDemoPainter(repaint: _animation, arc: arc), // Watch out: if this IgnorePointer is left out, then gestures that // fail _RectDemoPainter.hitTest() will still be recognized because // they do overlap this child, which is as big as the CustomPaint. @@ -402,7 +403,7 @@ class _ArcDemo { } class AnimationDemo extends StatefulWidget { - const AnimationDemo({ super.key }); + const AnimationDemo({super.key}); @override State createState() => _AnimationDemoState(); @@ -411,16 +412,10 @@ class AnimationDemo extends StatefulWidget { class _AnimationDemoState extends State with TickerProviderStateMixin { late final List<_ArcDemo> _allDemos = <_ArcDemo>[ _ArcDemo('POINT', (_ArcDemo demo) { - return _PointDemo( - key: demo.key, - controller: demo.controller, - ); + return _PointDemo(key: demo.key, controller: demo.controller); }, this), _ArcDemo('RECTANGLE', (_ArcDemo demo) { - return _RectangleDemo( - key: demo.key, - controller: demo.controller, - ); + return _RectangleDemo(key: demo.key, controller: demo.controller); }, this), ]; @@ -461,7 +456,5 @@ class _AnimationDemoState extends State with TickerProviderStateM } void main() { - runApp(const MaterialApp( - home: AnimationDemo(), - )); + runApp(const MaterialApp(home: AnimationDemo())); } diff --git a/flutter/dev/manual_tests/lib/menu_anchor.dart b/flutter/dev/manual_tests/lib/menu_anchor.dart index df218cafa0afccd59f0cd252f197bd24fd146965..7200e36e0339ec215c999559edf0a76c55ff2188 100644 --- a/flutter/dev/manual_tests/lib/menu_anchor.dart +++ b/flutter/dev/manual_tests/lib/menu_anchor.dart @@ -6,14 +6,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { - runApp( - const MaterialApp( - title: 'Menu Tester', - home: Material( - child: Home(), - ), - ), - ); + runApp(const MaterialApp(title: 'Menu Tester', home: Material(child: Home()))); } class Home extends StatefulWidget { @@ -43,17 +36,11 @@ class _HomeState extends State { menuTheme = const MenuThemeData( style: MenuStyle( shape: MaterialStatePropertyAll( - RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(10), - ), - ), + RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))), ), backgroundColor: MaterialStatePropertyAll(Colors.blue), elevation: MaterialStatePropertyAll(10), - padding: MaterialStatePropertyAll( - EdgeInsetsDirectional.all(20), - ), + padding: MaterialStatePropertyAll(EdgeInsetsDirectional.all(20)), ), ); menuButtonTheme = const MenuButtonThemeData( @@ -68,9 +55,7 @@ class _HomeState extends State { shape: MaterialStatePropertyAll(RoundedRectangleBorder()), backgroundColor: MaterialStatePropertyAll(Colors.blue), elevation: MaterialStatePropertyAll(10), - padding: MaterialStatePropertyAll( - EdgeInsetsDirectional.all(20), - ), + padding: MaterialStatePropertyAll(EdgeInsetsDirectional.all(20)), ), ); } @@ -82,16 +67,17 @@ class _HomeState extends State { child: Theme( data: theme.copyWith( visualDensity: _density, - menuTheme: _transparent - ? MenuThemeData( - style: MenuStyle( - backgroundColor: MaterialStatePropertyAll( - Colors.blue.withOpacity(0.12), + menuTheme: + _transparent + ? MenuThemeData( + style: MenuStyle( + backgroundColor: MaterialStatePropertyAll( + Colors.blue.withOpacity(0.12), + ), + elevation: const MaterialStatePropertyAll(0), ), - elevation: const MaterialStatePropertyAll(0), - ), - ) - : menuTheme, + ) + : menuTheme, menuBarTheme: menuBarTheme, menuButtonTheme: menuButtonTheme, ), @@ -273,10 +259,7 @@ class _ControlsState extends State<_Controls> { divisions: 12, onChanged: (double value) { widget.onDensityChanged( - VisualDensity( - horizontal: value, - vertical: widget.density.vertical, - ), + VisualDensity(horizontal: value, vertical: widget.density.vertical), ); }, ), @@ -288,10 +271,7 @@ class _ControlsState extends State<_Controls> { divisions: 12, onChanged: (double value) { widget.onDensityChanged( - VisualDensity( - horizontal: widget.density.horizontal, - vertical: value, - ), + VisualDensity(horizontal: widget.density.horizontal, vertical: value), ); }, ), @@ -314,7 +294,7 @@ class _ControlsState extends State<_Controls> { } }, ), - const Text('RTL Text') + const Text('RTL Text'), ], ), Row( @@ -330,7 +310,7 @@ class _ControlsState extends State<_Controls> { } }, ), - const Text('Add Item') + const Text('Add Item'), ], ), Row( @@ -346,7 +326,7 @@ class _ControlsState extends State<_Controls> { } }, ), - const Text('Enable Accelerators') + const Text('Enable Accelerators'), ], ), Row( @@ -362,7 +342,7 @@ class _ControlsState extends State<_Controls> { } }, ), - const Text('Transparent') + const Text('Transparent'), ], ), Row( @@ -378,7 +358,7 @@ class _ControlsState extends State<_Controls> { } }, ), - const Text('Funky Theme') + const Text('Funky Theme'), ], ), ], @@ -436,11 +416,7 @@ class _ControlSlider extends StatelessWidget { } class _TestMenus extends StatefulWidget { - const _TestMenus({ - required this.menuController, - this.addItem = false, - this.accelerators = false, - }); + const _TestMenus({required this.menuController, this.addItem = false, this.accelerators = false}); final MenuController menuController; final bool addItem; @@ -480,8 +456,8 @@ class _TestMenusState extends State<_TestMenus> { setState(() { checkboxState = switch (checkboxState) { false => true, - true => null, - null => false, + true => null, + null => false, }; }); } @@ -575,10 +551,7 @@ List createTestMenus({ bool includeExtraGroups = false, bool accelerators = false, }) { - Widget submenuButton( - TestMenu menu, { - required List menuChildren, - }) { + Widget submenuButton(TestMenu menu, {required List menuChildren}) { return SubmenuButton( onOpen: onOpen != null ? () => onOpen(menu) : null, onClose: onClose != null ? () => onClose(menu) : null, @@ -616,7 +589,10 @@ List createTestMenus({ key: key, value: checkboxValue, tristate: tristate, - onChanged: enabled && onCheckboxChanged != null ? (bool? value) => onCheckboxChanged(menu, value) : null, + onChanged: + enabled && onCheckboxChanged != null + ? (bool? value) => onCheckboxChanged(menu, value) + : null, shortcut: menu.shortcut, trailingIcon: trailingIcon, child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label), @@ -678,22 +654,25 @@ List createTestMenus({ TestMenu.mainMenu2, menuChildren: [ MenuAcceleratorCallbackBinding( - onInvoke: onPressed != null - ? () { - onPressed.call(TestMenu.testButton); - menuController?.close(); - } - : null, - child: TextButton( - onPressed: onPressed != null - ? () { + onInvoke: + onPressed != null + ? () { onPressed.call(TestMenu.testButton); menuController?.close(); } - : null, - child: accelerators - ? MenuAcceleratorLabel(TestMenu.testButton.acceleratorLabel) - : Text(TestMenu.testButton.label), + : null, + child: TextButton( + onPressed: + onPressed != null + ? () { + onPressed.call(TestMenu.testButton); + menuController?.close(); + } + : null, + child: + accelerators + ? MenuAcceleratorLabel(TestMenu.testButton.acceleratorLabel) + : Text(TestMenu.testButton.label), ), ), menuItemButton(TestMenu.subMenu3), @@ -708,7 +687,7 @@ List createTestMenus({ debugPrint('Focused Item: $primaryFocus'); }, child: const Text('Print Focused Item'), - ) + ), ], ), submenuButton( @@ -737,11 +716,8 @@ List createTestMenus({ submenuButton( TestMenu.subSubMenu3, menuChildren: [ - for (int i=0; i < 100; ++i) - MenuItemButton( - onPressed: () {}, - child: Text('Menu Item $i'), - ), + for (int i = 0; i < 100; ++i) + MenuItemButton(onPressed: () {}, child: Text('Menu Item $i')), ], ), ], diff --git a/flutter/dev/manual_tests/lib/overlay_geometry.dart b/flutter/dev/manual_tests/lib/overlay_geometry.dart index 813b31303c0a12dc4bce4c6df84ccad058beabce..5da71e7355e7490fcbb8d5d20e93b37ac161db83 100644 --- a/flutter/dev/manual_tests/lib/overlay_geometry.dart +++ b/flutter/dev/manual_tests/lib/overlay_geometry.dart @@ -19,10 +19,7 @@ class CardModel { enum MarkerType { topLeft, bottomRight, touch } class _MarkerPainter extends CustomPainter { - const _MarkerPainter({ - required this.size, - required this.type, - }); + const _MarkerPainter({required this.size, required this.type}); final double size; final MarkerType type; @@ -37,30 +34,27 @@ class _MarkerPainter extends CustomPainter { ..color = const Color(0xFFFFFFFF) ..style = PaintingStyle.stroke ..strokeWidth = 1.0; - if (type == MarkerType.topLeft) { - canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint); - canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint); - } - if (type == MarkerType.bottomRight) { - canvas.drawLine(Offset(r, r), Offset(1.0, r), paint); - canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint); + + switch (type) { + case MarkerType.topLeft: + canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint); + canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint); + case MarkerType.bottomRight: + canvas.drawLine(Offset(r, r), Offset(1.0, r), paint); + canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint); + case MarkerType.touch: + break; } } @override bool shouldRepaint(_MarkerPainter oldPainter) { - return oldPainter.size != size - || oldPainter.type != type; + return oldPainter.size != size || oldPainter.type != type; } } class Marker extends StatelessWidget { - const Marker({ - super.key, - this.type = MarkerType.touch, - this.position, - this.size = 40.0, - }); + const Marker({super.key, this.type = MarkerType.touch, this.position, this.size = 40.0}); final Offset? position; final double size; @@ -73,14 +67,7 @@ class Marker extends StatelessWidget { top: position!.dy - size / 2.0, width: size, height: size, - child: IgnorePointer( - child: CustomPaint( - painter: _MarkerPainter( - size: size, - type: type, - ), - ), - ), + child: IgnorePointer(child: CustomPaint(painter: _MarkerPainter(size: size, type: type))), ); } } @@ -95,13 +82,17 @@ class OverlayGeometryApp extends StatefulWidget { typedef CardTapCallback = void Function(GlobalKey targetKey, Offset globalPosition); class CardBuilder extends SliverChildDelegate { - CardBuilder({List? cardModels, this.onTapUp }) : cardModels = cardModels ?? []; + CardBuilder({List? cardModels, this.onTapUp}) + : cardModels = cardModels ?? []; final List cardModels; final CardTapCallback? onTapUp; - static const TextStyle cardLabelStyle = - TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold); + static const TextStyle cardLabelStyle = TextStyle( + color: Colors.white, + fontSize: 18.0, + fontWeight: FontWeight.bold, + ); @override Widget? build(BuildContext context, int index) { @@ -111,7 +102,9 @@ class CardBuilder extends SliverChildDelegate { final CardModel cardModel = cardModels[index]; return GestureDetector( key: cardModel.key, - onTapUp: (TapUpDetails details) { onTapUp!(cardModel.targetKey, details.globalPosition); }, + onTapUp: (TapUpDetails details) { + onTapUp!(cardModel.targetKey, details.globalPosition); + }, child: Card( key: cardModel.targetKey, color: cardModel.color, @@ -142,12 +135,40 @@ class OverlayGeometryAppState extends State { void initState() { super.initState(); final List cardHeights = [ - 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, - 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, - 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, + 48.0, + 63.0, + 82.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, + 48.0, + 63.0, + 82.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, + 48.0, + 63.0, + 82.0, + 146.0, + 60.0, + 55.0, + 84.0, + 96.0, + 50.0, ]; cardModels = List.generate(cardHeights.length, (int i) { - final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardHeights.length); + final Color? color = Color.lerp( + Colors.red.shade300, + Colors.blue.shade900, + i / cardHeights.length, + ); return CardModel(i, cardHeights[i], color!); }); } @@ -188,26 +209,17 @@ class OverlayGeometryAppState extends State { child: NotificationListener( onNotification: handleScrollNotification, child: ListView.custom( - childrenDelegate: CardBuilder( - cardModels: cardModels, - onTapUp: handleTapUp, - ), + childrenDelegate: CardBuilder(cardModels: cardModels, onTapUp: handleTapUp), ), ), ), ), - for (final MarkerType type in markers.keys) - Marker(type: type, position: markers[type]), + for (final MarkerType type in markers.keys) Marker(type: type, position: markers[type]), ], ); } } void main() { - runApp( - const MaterialApp( - title: 'Cards', - home: OverlayGeometryApp(), - ), - ); + runApp(const MaterialApp(title: 'Cards', home: OverlayGeometryApp())); } diff --git a/flutter/dev/manual_tests/lib/page_view.dart b/flutter/dev/manual_tests/lib/page_view.dart index 25b9a79d4cca43d4332485c9b1342231bd84bc24..b156ef2f13ddb6bdc9aead19845d19781ebe1115 100644 --- a/flutter/dev/manual_tests/lib/page_view.dart +++ b/flutter/dev/manual_tests/lib/page_view.dart @@ -33,13 +33,20 @@ class PageViewAppState extends State { ]; cardModels = List.generate(cardSizes.length, (int i) { - final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardSizes.length); + final Color? color = Color.lerp( + Colors.red.shade300, + Colors.blue.shade900, + i / cardSizes.length, + ); return CardModel(i, cardSizes[i], color!); }); } - static const TextStyle cardLabelStyle = - TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold); + static const TextStyle cardLabelStyle = TextStyle( + color: Colors.white, + fontSize: 18.0, + fontWeight: FontWeight.bold, + ); List cardModels = []; Size pageSize = const Size(200.0, 200.0); @@ -57,22 +64,17 @@ class PageViewAppState extends State { ), ); - final BoxConstraints constraints = (scrollDirection == Axis.vertical) - ? BoxConstraints.tightFor(height: pageSize.height) - : BoxConstraints.tightFor(width: pageSize.width); + final BoxConstraints constraints = + (scrollDirection == Axis.vertical) + ? BoxConstraints.tightFor(height: pageSize.height) + : BoxConstraints.tightFor(width: pageSize.width); - return Container( - key: cardModel.key, - constraints: constraints, - child: Center(child: card), - ); + return Container(key: cardModel.key, constraints: constraints, child: Center(child: card)); } void switchScrollDirection() { setState(() { - scrollDirection = (scrollDirection == Axis.vertical) - ? Axis.horizontal - : Axis.vertical; + scrollDirection = flipAxis(scrollDirection); }); } @@ -111,12 +113,7 @@ class PageViewAppState extends State { } AppBar _buildAppBar() { - return AppBar( - title: const Text('PageView'), - actions: [ - Text(scrollDirection == Axis.horizontal ? 'horizontal' : 'vertical'), - ], - ); + return AppBar(title: const Text('PageView'), actions: [Text(scrollDirection.name)]); } Widget _buildBody(BuildContext context) { @@ -131,20 +128,11 @@ class PageViewAppState extends State { Widget build(BuildContext context) { return IconTheme( data: const IconThemeData(color: Colors.white), - child: Scaffold( - appBar: _buildAppBar(), - drawer: _buildDrawer(), - body: _buildBody(context), - ), + child: Scaffold(appBar: _buildAppBar(), drawer: _buildDrawer(), body: _buildBody(context)), ); } } void main() { - runApp( - const MaterialApp( - title: 'PageView', - home: PageViewApp(), - ), - ); + runApp(const MaterialApp(title: 'PageView', home: PageViewApp())); } diff --git a/flutter/dev/manual_tests/lib/star_border.dart b/flutter/dev/manual_tests/lib/star_border.dart index d5096d0667174fc840baf86fd7e1b79f3b21d4dd..396c146ad825d092126efd6a2d9239ed35cff395 100644 --- a/flutter/dev/manual_tests/lib/star_border.dart +++ b/flutter/dev/manual_tests/lib/star_border.dart @@ -7,23 +7,14 @@ import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); -enum LerpTarget { - circle, - roundedRect, - rect, - stadium, - polygon, - star, -} +enum LerpTarget { circle, roundedRect, rect, stadium, polygon, star } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { - return const MaterialApp( - home: MyHomePage(), - ); + return const MaterialApp(home: MyHomePage()); } } @@ -60,10 +51,7 @@ class _MyHomePageState extends State { return SafeArea( child: Scaffold( key: scaffoldKey, - appBar: AppBar( - title: const Text('Star Border'), - backgroundColor: const Color(0xff323232), - ), + appBar: AppBar(title: const Text('Star Border'), backgroundColor: const Color(0xff323232)), body: Column( children: [ ColoredBox(color: Colors.grey.shade200, child: Options(_model)), @@ -77,18 +65,22 @@ class _MyHomePageState extends State { height: 200, decoration: ShapeDecoration( color: Colors.blue.shade100, - shape: lerpBorder( - StarBorder.polygon( - side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2), - sides: _model.points, - pointRounding: _model.pointRounding, - rotation: _model.rotation, - squash: _model.squash, - ), - _model._lerpTarget, - _model._lerpAmount, - to: _model.lerpTo, - )!, + shape: + lerpBorder( + StarBorder.polygon( + side: const BorderSide( + strokeAlign: BorderSide.strokeAlignCenter, + width: 2, + ), + sides: _model.points, + pointRounding: _model.pointRounding, + rotation: _model.rotation, + squash: _model.squash, + ), + _model._lerpTarget, + _model._lerpAmount, + to: _model.lerpTo, + )!, ), child: const Text('Polygon'), ), @@ -98,20 +90,24 @@ class _MyHomePageState extends State { height: 200, decoration: ShapeDecoration( color: Colors.blue.shade100, - shape: lerpBorder( - StarBorder( - side: const BorderSide(strokeAlign: BorderSide.strokeAlignCenter, width: 2), - points: _model.points, - innerRadiusRatio: _model.innerRadiusRatio, - pointRounding: _model.pointRounding, - valleyRounding: _model.valleyRounding, - rotation: _model.rotation, - squash: _model.squash, - ), - _model._lerpTarget, - _model._lerpAmount, - to: _model.lerpTo, - )!, + shape: + lerpBorder( + StarBorder( + side: const BorderSide( + strokeAlign: BorderSide.strokeAlignCenter, + width: 2, + ), + points: _model.points, + innerRadiusRatio: _model.innerRadiusRatio, + pointRounding: _model.pointRounding, + valleyRounding: _model.valleyRounding, + rotation: _model.rotation, + squash: _model.squash, + ), + _model._lerpTarget, + _model._lerpAmount, + to: _model.lerpTo, + )!, ), child: const Text('Star'), ), @@ -334,10 +330,11 @@ class _OptionsState extends State { ), ), OutlinedButton( - child: const Text('Nearest'), - onPressed: () { - widget.model.points = widget.model.points.roundToDouble(); - }), + child: const Text('Nearest'), + onPressed: () { + widget.model.points = widget.model.points.roundToDouble(); + }, + ), ], ), ), @@ -372,24 +369,30 @@ class _OptionsState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row(children: [ - Radio( + Row( + children: [ + Radio( value: true, groupValue: widget.model.lerpTo, onChanged: (bool? value) { widget.model.lerpTo = value!; - }), - const Text('To'), - ]), - Row(children: [ - Radio( + }, + ), + const Text('To'), + ], + ), + Row( + children: [ + Radio( value: false, groupValue: widget.model.lerpTo, onChanged: (bool? value) { widget.model.lerpTo = value!; - }), - const Text('From'), - ]) + }, + ), + const Text('From'), + ], + ), ], ), ), @@ -398,9 +401,15 @@ class _OptionsState extends State { children: [ Expanded( child: DropdownButton( - items: LerpTarget.values.map>((LerpTarget target) { - return DropdownMenuItem(value: target, child: Text(target.name)); - }).toList(), + items: + LerpTarget.values.map>(( + LerpTarget target, + ) { + return DropdownMenuItem( + value: target, + child: Text(target.name), + ); + }).toList(), value: widget.model.lerpTarget, onChanged: (LerpTarget? value) { if (value == null) { @@ -461,9 +470,7 @@ class ControlSlider extends StatelessWidget { value: value, ), ), - Text( - value.toStringAsFixed(3), - ), + Text(value.toStringAsFixed(3)), ], ), ); @@ -474,58 +481,16 @@ const Color lerpToColor = Colors.red; const BorderSide lerpToBorder = BorderSide(width: 5, color: lerpToColor); ShapeBorder? lerpBorder(StarBorder border, LerpTarget target, double t, {bool to = true}) { - switch (target) { - case LerpTarget.circle: - if (to) { - return border.lerpTo(const CircleBorder(side: lerpToBorder, eccentricity: 0.5), t); - } else { - return border.lerpFrom(const CircleBorder(side: lerpToBorder, eccentricity: 0.5), t); - } - case LerpTarget.roundedRect: - if (to) { - return border.lerpTo( - const RoundedRectangleBorder( - side: lerpToBorder, - borderRadius: BorderRadius.all( - Radius.circular(10), - ), - ), - t, - ); - } else { - return border.lerpFrom( - const RoundedRectangleBorder( - side: lerpToBorder, - borderRadius: BorderRadius.all( - Radius.circular(10), - ), - ), - t, - ); - } - case LerpTarget.rect: - if (to) { - return border.lerpTo(const RoundedRectangleBorder(side: lerpToBorder), t); - } else { - return border.lerpFrom(const RoundedRectangleBorder(side: lerpToBorder), t); - } - case LerpTarget.stadium: - if (to) { - return border.lerpTo(const StadiumBorder(side: lerpToBorder), t); - } else { - return border.lerpFrom(const StadiumBorder(side: lerpToBorder), t); - } - case LerpTarget.polygon: - if (to) { - return border.lerpTo(const StarBorder.polygon(side: lerpToBorder, sides: 4), t); - } else { - return border.lerpFrom(const StarBorder.polygon(side: lerpToBorder, sides: 4), t); - } - case LerpTarget.star: - if (to) { - return border.lerpTo(const StarBorder(side: lerpToBorder, innerRadiusRatio: .5), t); - } else { - return border.lerpFrom(const StarBorder(side: lerpToBorder, innerRadiusRatio: .5), t); - } - } + final OutlinedBorder targetBorder = switch (target) { + LerpTarget.circle => const CircleBorder(side: lerpToBorder, eccentricity: 0.5), + LerpTarget.rect => const RoundedRectangleBorder(side: lerpToBorder), + LerpTarget.stadium => const StadiumBorder(side: lerpToBorder), + LerpTarget.polygon => const StarBorder.polygon(side: lerpToBorder, sides: 4), + LerpTarget.star => const StarBorder(side: lerpToBorder, innerRadiusRatio: 0.5), + LerpTarget.roundedRect => RoundedRectangleBorder( + side: lerpToBorder, + borderRadius: BorderRadius.circular(10), + ), + }; + return to ? border.lerpTo(targetBorder, t) : border.lerpFrom(targetBorder, t); } diff --git a/flutter/dev/manual_tests/lib/text.dart b/flutter/dev/manual_tests/lib/text.dart index 8c2400b302a7f1d72998f014fbbf94533dc9a571..69eee34ccd225824101b07fc061dfce77c951ec8 100644 --- a/flutter/dev/manual_tests/lib/text.dart +++ b/flutter/dev/manual_tests/lib/text.dart @@ -11,22 +11,24 @@ import 'package:flutter/scheduler.dart'; int seed = 0; void main() { - runApp(MaterialApp( - title: 'Text tester', - home: const Home(), - routes: { - 'underlines': (BuildContext context) => const Underlines(), - 'fallback': (BuildContext context) => const Fallback(), - 'bidi': (BuildContext context) => const Bidi(), - 'fuzzer': (BuildContext context) => Fuzzer(seed: seed), - 'zalgo': (BuildContext context) => Zalgo(seed: seed), - 'painting': (BuildContext context) => Painting(seed: seed), - }, - )); + runApp( + MaterialApp( + title: 'Text tester', + home: const Home(), + routes: { + 'underlines': (BuildContext context) => const Underlines(), + 'fallback': (BuildContext context) => const Fallback(), + 'bidi': (BuildContext context) => const Bidi(), + 'fuzzer': (BuildContext context) => Fuzzer(seed: seed), + 'zalgo': (BuildContext context) => Zalgo(seed: seed), + 'painting': (BuildContext context) => Painting(seed: seed), + }, + ), + ); } class Home extends StatefulWidget { - const Home({ super.key }); + const Home({super.key}); @override State createState() => _HomeState(); @@ -47,7 +49,9 @@ class _HomeState extends State { foregroundColor: Colors.white, backgroundColor: Colors.red.shade800, ), - onPressed: () { Navigator.pushNamed(context, 'underlines'); }, + onPressed: () { + Navigator.pushNamed(context, 'underlines'); + }, child: const Text('Test Underlines'), ), TextButton( @@ -55,7 +59,9 @@ class _HomeState extends State { foregroundColor: Colors.white, backgroundColor: Colors.orange.shade700, ), - onPressed: () { Navigator.pushNamed(context, 'fallback'); }, + onPressed: () { + Navigator.pushNamed(context, 'fallback'); + }, child: const Text('Test Font Fallback'), ), TextButton( @@ -63,7 +69,9 @@ class _HomeState extends State { foregroundColor: Colors.black, backgroundColor: Colors.yellow.shade700, ), - onPressed: () { Navigator.pushNamed(context, 'bidi'); }, + onPressed: () { + Navigator.pushNamed(context, 'bidi'); + }, child: const Text('Test Bidi Formatting'), ), TextButton( @@ -71,7 +79,9 @@ class _HomeState extends State { foregroundColor: Colors.black, backgroundColor: Colors.green.shade400, ), - onPressed: () { Navigator.pushNamed(context, 'fuzzer'); }, + onPressed: () { + Navigator.pushNamed(context, 'fuzzer'); + }, child: const Text('TextSpan Fuzzer'), ), TextButton( @@ -79,7 +89,9 @@ class _HomeState extends State { foregroundColor: Colors.white, backgroundColor: Colors.blue.shade400, ), - onPressed: () { Navigator.pushNamed(context, 'zalgo'); }, + onPressed: () { + Navigator.pushNamed(context, 'zalgo'); + }, child: const Text('Diacritics Fuzzer'), ), TextButton( @@ -87,7 +99,9 @@ class _HomeState extends State { foregroundColor: Colors.black, backgroundColor: Colors.purple.shade200, ), - onPressed: () { Navigator.pushNamed(context, 'painting'); }, + onPressed: () { + Navigator.pushNamed(context, 'painting'); + }, child: const Text('Painting Fuzzer'), ), ], @@ -118,7 +132,7 @@ class _HomeState extends State { } class Fuzzer extends StatefulWidget { - const Fuzzer({ super.key, required this.seed }); + const Fuzzer({super.key, required this.seed}); final int seed; @@ -129,7 +143,9 @@ class Fuzzer extends StatefulWidget { class _FuzzerState extends State with SingleTickerProviderStateMixin { TextSpan _textSpan = const TextSpan(text: 'Welcome to the Flutter text fuzzer.'); late final Ticker _ticker = createTicker(_updateTextSpan)..start(); - late final math.Random _random = math.Random(widget.seed); // providing a seed is important for reproducibility; + late final math.Random _random = math.Random( + widget.seed, + ); // providing a seed is important for reproducibility; @override void initState() { @@ -153,7 +169,10 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { return TextSpan( text: _fiddleWithText(node.text), style: _fiddleWithStyle(node.style), - children: _fiddleWithChildren(node.children?.map((InlineSpan child) => _fiddleWith(child as TextSpan)).toList() ?? []), + children: _fiddleWithChildren( + node.children?.map((InlineSpan child) => _fiddleWith(child as TextSpan)).toList() ?? + [], + ), ); } @@ -198,7 +217,8 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { switch (_random.nextInt(10)) { case 0: if (value == null) { - return pickFromList(_random, Colors.primaries)[(_random.nextInt(9) + 1) * 100]; + return pickFromList(_random, Colors.primaries)[(_random.nextInt(9) + 1) * + 100]; } switch (_random.nextInt(4)) { case 0: @@ -234,13 +254,26 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { case 30: return TextDecoration.overline; case 90: - return TextDecoration.combine([TextDecoration.underline, TextDecoration.lineThrough]); + return TextDecoration.combine([ + TextDecoration.underline, + TextDecoration.lineThrough, + ]); case 91: - return TextDecoration.combine([TextDecoration.underline, TextDecoration.overline]); + return TextDecoration.combine([ + TextDecoration.underline, + TextDecoration.overline, + ]); case 92: - return TextDecoration.combine([TextDecoration.lineThrough, TextDecoration.overline]); + return TextDecoration.combine([ + TextDecoration.lineThrough, + TextDecoration.overline, + ]); case 93: - return TextDecoration.combine([TextDecoration.underline, TextDecoration.lineThrough, TextDecoration.overline]); + return TextDecoration.combine([ + TextDecoration.underline, + TextDecoration.lineThrough, + TextDecoration.overline, + ]); } return null; } @@ -352,9 +385,7 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { } TextSpan _createRandomTextSpan() { - return TextSpan( - text: _createRandomText(), - ); + return TextSpan(text: _createRandomText()); } String? _createRandomText() { @@ -493,7 +524,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { if (_random.nextInt(20) > 0) { buffer.writeCharCode(randomCharacter(_random)); } else { - buffer.write(zalgo(_random, _random.nextInt(2) + 1, includeSpacingCombiningMarks: true)); + buffer.write( + zalgo(_random, _random.nextInt(2) + 1, includeSpacingCombiningMarks: true), + ); } } return buffer.toString(); @@ -540,14 +573,13 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { } class Underlines extends StatefulWidget { - const Underlines({ super.key }); + const Underlines({super.key}); @override State createState() => _UnderlinesState(); } class _UnderlinesState extends State { - String _text = 'i'; final TextStyle _style = TextStyle( @@ -563,8 +595,17 @@ class _UnderlinesState extends State { alignment: Alignment.centerLeft, heightFactor: 1.0, child: Container( - decoration: const BoxDecoration(color: Color(0xFF333333), border: Border(right: BorderSide(color: Colors.white, width: 0.0))), - child: Text(_text, style: style != null ? _style.copyWith(decoration: TextDecoration.underline, decorationStyle: style) : _style), + decoration: const BoxDecoration( + color: Color(0xFF333333), + border: Border(right: BorderSide(color: Colors.white, width: 0.0)), + ), + child: Text( + _text, + style: + style != null + ? _style.copyWith(decoration: TextDecoration.underline, decorationStyle: style) + : _style, + ), ), ); } @@ -587,7 +628,8 @@ class _UnderlinesState extends State { child: ListBody( children: [ _wrap(null), - for (final TextDecorationStyle style in TextDecorationStyle.values) _wrap(style), + for (final TextDecorationStyle style in TextDecorationStyle.values) + _wrap(style), ], ), ), @@ -606,9 +648,7 @@ class _UnderlinesState extends State { _text += 'i'; }); }, - style: TextButton.styleFrom( - backgroundColor: Colors.yellow, - ), + style: TextButton.styleFrom(backgroundColor: Colors.yellow), child: const Text('ADD i'), ), TextButton( @@ -617,9 +657,7 @@ class _UnderlinesState extends State { _text += 'w'; }); }, - style: TextButton.styleFrom( - backgroundColor: Colors.yellow, - ), + style: TextButton.styleFrom(backgroundColor: Colors.yellow), child: const Text('ADD w'), ), TextButton( @@ -627,11 +665,14 @@ class _UnderlinesState extends State { foregroundColor: Colors.white, backgroundColor: Colors.red, ), - onPressed: _text == '' ? null : () { - setState(() { - _text = _text.substring(0, _text.length - 1); - }); - }, + onPressed: + _text == '' + ? null + : () { + setState(() { + _text = _text.substring(0, _text.length - 1); + }); + }, child: const Text('REMOVE'), ), ], @@ -645,14 +686,15 @@ class _UnderlinesState extends State { } class Fallback extends StatefulWidget { - const Fallback({ super.key }); + const Fallback({super.key}); @override State createState() => _FallbackState(); } class _FallbackState extends State { - static const String multiScript = 'A1!aÀàĀāƁƀḂⱠꜲꬰəͲἀἏЀЖԠꙐꙮՁخ‎ࡔࠇܦআਉઐଘஇఘಧൺඣᭆᯔᮯ᳇ꠈᜅᩌꪈ༇ꥄꡙꫤ᧰៘꧁꧂ᜰᨏᯤᢆᣭᗗꗃⵞ𐒎߷ጩꬤ𖠺‡₩℻Ⅷ↹⋇⏳ⓖ╋▒◛⚧⑆שׁ🅕㊼龜ポ䷤🂡'; + static const String multiScript = + 'A1!aÀàĀāƁƀḂⱠꜲꬰəͲἀἏЀЖԠꙐꙮՁخ‎ࡔࠇܦআਉઐଘஇఘಧൺඣᭆᯔᮯ᳇ꠈᜅᩌꪈ༇ꥄꡙꫤ᧰៘꧁꧂ᜰᨏᯤᢆᣭᗗꗃⵞ𐒎߷ጩꬤ𖠺‡₩℻Ⅷ↹⋇⏳ⓖ╋▒◛⚧⑆שׁ🅕㊼龜ポ䷤🂡'; static const List androidFonts = [ 'sans-serif', @@ -665,10 +707,7 @@ class _FallbackState extends State { 'sans-serif-smallcaps', ]; - static const TextStyle style = TextStyle( - inherit: false, - color: Colors.white, - ); + static const TextStyle style = TextStyle(inherit: false, color: Colors.white); double _fontSize = 3.0; @@ -694,10 +733,7 @@ class _FallbackState extends State { for (final String font in androidFonts) Text( multiScript, - style: style.copyWith( - fontFamily: font, - fontSize: math.exp(_fontSize), - ), + style: style.copyWith(fontFamily: font, fontSize: math.exp(_fontSize)), ), ], ), @@ -712,10 +748,7 @@ class _FallbackState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ - const Padding( - padding: EdgeInsets.only(bottom: 10.0), - child: Text('Font size'), - ), + const Padding(padding: EdgeInsets.only(bottom: 10.0), child: Text('Font size')), Expanded( child: Slider( min: 2.0, @@ -740,7 +773,7 @@ class _FallbackState extends State { } class Bidi extends StatefulWidget { - const Bidi({ super.key }); + const Bidi({super.key}); @override State createState() => _BidiState(); @@ -757,11 +790,46 @@ class _BidiState extends State { RichText( text: TextSpan( children: [ - TextSpan(text: 'abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.blue.shade100)), - TextSpan(text: 'ghi', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 40.0, color: Colors.blue.shade500)), - TextSpan(text: 'mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 40.0, color: Colors.blue.shade900)), - TextSpan(text: 'LKJ', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 40.0, color: Colors.blue.shade700)), - TextSpan(text: 'FED', style: TextStyle(fontWeight: FontWeight.w300, fontSize: 40.0, color: Colors.blue.shade300)), + TextSpan( + text: 'abc', + style: TextStyle( + fontWeight: FontWeight.w100, + fontSize: 40.0, + color: Colors.blue.shade100, + ), + ), + TextSpan( + text: 'ghi', + style: TextStyle( + fontWeight: FontWeight.w400, + fontSize: 40.0, + color: Colors.blue.shade500, + ), + ), + TextSpan( + text: 'mno', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 40.0, + color: Colors.blue.shade900, + ), + ), + TextSpan( + text: 'LKJ', + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 40.0, + color: Colors.blue.shade700, + ), + ), + TextSpan( + text: 'FED', + style: TextStyle( + fontWeight: FontWeight.w300, + fontSize: 40.0, + color: Colors.blue.shade300, + ), + ), ], ), textAlign: TextAlign.center, @@ -770,11 +838,46 @@ class _BidiState extends State { RichText( text: TextSpan( children: [ - TextSpan(text: '${Unicode.LRO}abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.blue.shade100)), - TextSpan(text: '${Unicode.RLO}DEF', style: TextStyle(fontWeight: FontWeight.w300, fontSize: 40.0, color: Colors.blue.shade300)), - TextSpan(text: '${Unicode.LRO}ghi', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 40.0, color: Colors.blue.shade500)), - TextSpan(text: '${Unicode.RLO}JKL', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 40.0, color: Colors.blue.shade700)), - TextSpan(text: '${Unicode.LRO}mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 40.0, color: Colors.blue.shade900)), + TextSpan( + text: '${Unicode.LRO}abc', + style: TextStyle( + fontWeight: FontWeight.w100, + fontSize: 40.0, + color: Colors.blue.shade100, + ), + ), + TextSpan( + text: '${Unicode.RLO}DEF', + style: TextStyle( + fontWeight: FontWeight.w300, + fontSize: 40.0, + color: Colors.blue.shade300, + ), + ), + TextSpan( + text: '${Unicode.LRO}ghi', + style: TextStyle( + fontWeight: FontWeight.w400, + fontSize: 40.0, + color: Colors.blue.shade500, + ), + ), + TextSpan( + text: '${Unicode.RLO}JKL', + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 40.0, + color: Colors.blue.shade700, + ), + ), + TextSpan( + text: '${Unicode.LRO}mno', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 40.0, + color: Colors.blue.shade900, + ), + ), ], ), textAlign: TextAlign.center, @@ -784,9 +887,30 @@ class _BidiState extends State { RichText( text: TextSpan( children: [ - TextSpan(text: '${Unicode.LRO}abc${Unicode.RLO}D', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)), - TextSpan(text: 'EF${Unicode.LRO}gh', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)), - TextSpan(text: 'i${Unicode.RLO}JKL${Unicode.LRO}mno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)), + TextSpan( + text: '${Unicode.LRO}abc${Unicode.RLO}D', + style: TextStyle( + fontWeight: FontWeight.w100, + fontSize: 40.0, + color: Colors.orange.shade100, + ), + ), + TextSpan( + text: 'EF${Unicode.LRO}gh', + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 50.0, + color: Colors.orange.shade500, + ), + ), + TextSpan( + text: 'i${Unicode.RLO}JKL${Unicode.LRO}mno', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 60.0, + color: Colors.orange.shade900, + ), + ), ], ), textAlign: TextAlign.center, @@ -795,19 +919,65 @@ class _BidiState extends State { RichText( text: TextSpan( children: [ - TextSpan(text: 'abc', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)), - TextSpan(text: 'gh', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)), - TextSpan(text: 'imno', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)), - TextSpan(text: 'LKJ', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 60.0, color: Colors.orange.shade900)), - TextSpan(text: 'FE', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 50.0, color: Colors.orange.shade500)), - TextSpan(text: 'D', style: TextStyle(fontWeight: FontWeight.w100, fontSize: 40.0, color: Colors.orange.shade100)), + TextSpan( + text: 'abc', + style: TextStyle( + fontWeight: FontWeight.w100, + fontSize: 40.0, + color: Colors.orange.shade100, + ), + ), + TextSpan( + text: 'gh', + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 50.0, + color: Colors.orange.shade500, + ), + ), + TextSpan( + text: 'imno', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 60.0, + color: Colors.orange.shade900, + ), + ), + TextSpan( + text: 'LKJ', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 60.0, + color: Colors.orange.shade900, + ), + ), + TextSpan( + text: 'FE', + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 50.0, + color: Colors.orange.shade500, + ), + ), + TextSpan( + text: 'D', + style: TextStyle( + fontWeight: FontWeight.w100, + fontSize: 40.0, + color: Colors.orange.shade100, + ), + ), ], ), textAlign: TextAlign.center, textDirection: TextDirection.ltr, ), const SizedBox(height: 40.0), - const Text('The pairs of lines above should match exactly.', textAlign: TextAlign.center, style: TextStyle(inherit: false, fontSize: 14.0, color: Colors.white)), + const Text( + 'The pairs of lines above should match exactly.', + textAlign: TextAlign.center, + style: TextStyle(inherit: false, fontSize: 14.0, color: Colors.white), + ), ], ), ); @@ -815,7 +985,7 @@ class _BidiState extends State { } class Zalgo extends StatefulWidget { - const Zalgo({ super.key, required this.seed }); + const Zalgo({super.key, required this.seed}); final int seed; @@ -866,11 +1036,7 @@ class _ZalgoState extends State with SingleTickerProviderStateMixin { child: RichText( text: TextSpan( text: _text, - style: TextStyle( - inherit: false, - fontSize: 96.0, - color: Colors.red.shade200, - ), + style: TextStyle(inherit: false, fontSize: 96.0, color: Colors.red.shade200), ), ), ), @@ -921,7 +1087,7 @@ class _ZalgoState extends State with SingleTickerProviderStateMixin { } class Painting extends StatefulWidget { - const Painting({ super.key, required this.seed }); + const Painting({super.key, required this.seed}); final int seed; @@ -955,7 +1121,8 @@ class _PaintingState extends State with SingleTickerProviderStateMixin void _update(Duration? duration) { setState(() { final StringBuffer buffer = StringBuffer(); - final int targetLength = _random.nextInt(20) + (_ellipsize ? MediaQuery.of(context).size.width.round() : 1); + final int targetLength = + _random.nextInt(20) + (_ellipsize ? MediaQuery.of(context).size.width.round() : 1); for (int index = 0; index < targetLength; index += 1) { if (_random.nextInt(5) > 0) { buffer.writeCharCode(randomCharacter(_random)); @@ -966,13 +1133,18 @@ class _PaintingState extends State with SingleTickerProviderStateMixin _text = buffer.toString(); }); SchedulerBinding.instance.addPostFrameCallback((Duration duration) { - if (mounted && intrinsicKey.currentContext?.size?.height != controlKey.currentContext?.size?.height) { + if (mounted && + intrinsicKey.currentContext?.size?.height != controlKey.currentContext?.size?.height) { debugPrint('Found some text that unexpectedly renders at different heights.'); debugPrint('Text: $_text'); - debugPrint(_text?.runes.map((int index) { - final String hexa = index.toRadixString(16).padLeft(4, '0'); - return 'U+$hexa'; - }).join(' ')); + debugPrint( + _text?.runes + .map((int index) { + final String hexa = index.toRadixString(16).padLeft(4, '0'); + return 'U+$hexa'; + }) + .join(' '), + ); setState(() { _ticker.stop(); }); @@ -1000,7 +1172,8 @@ class _PaintingState extends State with SingleTickerProviderStateMixin right: 0.0, child: Align( alignment: Alignment.topCenter, - child: IntrinsicWidth( // to test shrink-wrap vs rendering + child: IntrinsicWidth( + // to test shrink-wrap vs rendering child: RichText( key: intrinsicKey, textAlign: TextAlign.center, @@ -1027,11 +1200,7 @@ class _PaintingState extends State with SingleTickerProviderStateMixin overflow: _ellipsize ? TextOverflow.ellipsis : TextOverflow.clip, text: TextSpan( text: _text, - style: const TextStyle( - inherit: false, - fontSize: 28.0, - color: Colors.white, - ), + style: const TextStyle(inherit: false, fontSize: 28.0, color: Colors.white), ), ), ), @@ -1069,9 +1238,7 @@ class _PaintingState extends State with SingleTickerProviderStateMixin }); }, ), - const ListTile( - title: Text('There should be no red visible.'), - ), + const ListTile(title: Text('There should be no red visible.')), Container( alignment: AlignmentDirectional.centerEnd, @@ -1084,10 +1251,20 @@ class _PaintingState extends State with SingleTickerProviderStateMixin child: const Text('ITERATE'), ), TextButton( - onPressed: _ticker.isActive ? null : () { - print('The currently visible text is: $_text'); - print(_text?.runes.map((int value) => 'U+${value.toRadixString(16).padLeft(4, '0').toUpperCase()}').join(' ')); - }, + onPressed: + _ticker.isActive + ? null + : () { + print('The currently visible text is: $_text'); + print( + _text?.runes + .map( + (int value) => + 'U+${value.toRadixString(16).padLeft(4, '0').toUpperCase()}', + ) + .join(' '), + ); + }, child: const Text('DUMP TEXT TO LOGS'), ), ], @@ -1102,15 +1279,22 @@ class _PaintingState extends State with SingleTickerProviderStateMixin } } -String zalgo(math.Random random, int targetLength, { bool includeSpacingCombiningMarks = false, String? base }) { +String zalgo( + math.Random random, + int targetLength, { + bool includeSpacingCombiningMarks = false, + String? base, +}) { // The following three tables are derived from UnicodeData.txt: // http://unicode.org/Public/UNIDATA/UnicodeData.txt // There are three groups, character classes Mc, Me, and Mn. - const List enclosingCombiningMarks = [ // Me + const List enclosingCombiningMarks = [ + // Me 0x00488, 0x00489, 0x01ABE, 0x020DD, 0x020DE, 0x020DF, 0x020E0, 0x020E2, 0x020E3, 0x020E4, 0x0A670, 0x0A671, 0x0A672, ]; - const List nonspacingCombiningMarks = [ // Mn + const List nonspacingCombiningMarks = [ + // Mn 0x00300, 0x00301, 0x00302, 0x00303, 0x00304, 0x00305, 0x00306, 0x00307, 0x00308, 0x00309, 0x0030A, 0x0030B, 0x0030C, 0x0030D, 0x0030E, 0x0030F, 0x00310, 0x00311, 0x00312, 0x00313, 0x00314, @@ -1364,7 +1548,8 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin 0xE01E3, 0xE01E4, 0xE01E5, 0xE01E6, 0xE01E7, 0xE01E8, 0xE01E9, 0xE01EA, 0xE01EB, 0xE01EC, 0xE01ED, 0xE01EE, 0xE01EF, ]; - const List spacingCombiningMarks = [ // Mc + const List spacingCombiningMarks = [ + // Mc 0x00903, 0x0093B, 0x0093E, 0x0093F, 0x00940, 0x00949, 0x0094A, 0x0094B, 0x0094C, 0x0094E, 0x0094F, 0x00982, 0x00983, 0x009BE, 0x009BF, 0x009C0, 0x009C7, 0x009C8, 0x009CB, 0x009CC, 0x009D7, diff --git a/flutter/dev/manual_tests/pubspec.yaml b/flutter/dev/manual_tests/pubspec.yaml index 6e5d6f6afc2716fb04603061704dd045e2b253fa..e31e056b503ae60ca8e3523f1b67054ecf23a080 100644 --- a/flutter/dev/manual_tests/pubspec.yaml +++ b/flutter/dev/manual_tests/pubspec.yaml @@ -1,40 +1,40 @@ name: manual_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter - characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - meta: 1.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + characters: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + material_color_utilities: 0.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + meta: 1.16.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: flutter_test: sdk: flutter - async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker: 10.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_flutter_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - leak_tracker_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" - vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + async: 2.13.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + clock: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + fake_async: 1.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker: 10.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_flutter_testing: 3.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + matcher: 0.12.17 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + path: 1.9.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + stream_channel: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_api: 0.7.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vm_service: 15.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: uses-material-design: true -# PUBSPEC CHECKSUM: 8023 +# PUBSPEC CHECKSUM: 5b23 diff --git a/flutter/dev/manual_tests/test/mock_image_http.dart b/flutter/dev/manual_tests/test/mock_image_http.dart index 1e0067d918b4972060793d83c8475403643f2897..a65a808f83369263d35e490cd71899d32894b86e 100644 --- a/flutter/dev/manual_tests/test/mock_image_http.dart +++ b/flutter/dev/manual_tests/test/mock_image_http.dart @@ -51,17 +51,20 @@ class FakeHttpClientResponse extends Fake implements HttpClientResponse { final FakeHttpHeaders headers = FakeHttpHeaders(); @override - HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed; + HttpClientResponseCompressionState get compressionState => + HttpClientResponseCompressionState.notCompressed; @override - StreamSubscription> listen(void Function(List)? onData, { + StreamSubscription> listen( + void Function(List)? onData, { void Function()? onDone, Function? onError, bool? cancelOnError, }) { - return Stream>.fromIterable(>[kTransparentImage]) - .listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError); + return Stream>.fromIterable(>[ + kTransparentImage, + ]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError); } } -class FakeHttpHeaders extends Fake implements HttpHeaders { } +class FakeHttpHeaders extends Fake implements HttpHeaders {} diff --git a/flutter/dev/manual_tests/web/index.html b/flutter/dev/manual_tests/web/index.html index 095c2ba12c297bc001edd43d4bcfd5fc5f254e52..2d74051d4e9c67199ad16d1e53e08b09aa72ebce 100644 --- a/flutter/dev/manual_tests/web/index.html +++ b/flutter/dev/manual_tests/web/index.html @@ -21,11 +21,10 @@ found in the LICENSE file. --> - - + diff --git a/flutter/dev/manual_tests/windows/runner/runner.exe.manifest b/flutter/dev/manual_tests/windows/runner/runner.exe.manifest index a42ea7687cb67e55af955dc8874a072e087ce3ed..153653e8d67f81b901d28257a65908f3278e058d 100644 --- a/flutter/dev/manual_tests/windows/runner/runner.exe.manifest +++ b/flutter/dev/manual_tests/windows/runner/runner.exe.manifest @@ -9,12 +9,6 @@ - - - - - - diff --git a/flutter/dev/manual_tests/windows/runner/utils.cpp b/flutter/dev/manual_tests/windows/runner/utils.cpp index b849ce2c32702dc4b1f35161e794e7dcc5a81ef8..6abcd650420706858d2bff4ec04d4fbd993b4652 100644 --- a/flutter/dev/manual_tests/windows/runner/utils.cpp +++ b/flutter/dev/manual_tests/windows/runner/utils.cpp @@ -49,12 +49,12 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } - int target_length = ::WideCharToMultiByte( + unsigned int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr) -1; // remove the trailing null character std::string utf8_string; - if (target_length <= 0 || target_length > utf8_string.max_size()) { + if (target_length == 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); diff --git a/flutter/dev/missing_dependency_tests/pubspec.yaml b/flutter/dev/missing_dependency_tests/pubspec.yaml index 6499f49c5f8a10cf33f07fb4535e97ad8541cdf4..68f3a0b52485cd2972983fc3bb776eda0059061b 100644 --- a/flutter/dev/missing_dependency_tests/pubspec.yaml +++ b/flutter/dev/missing_dependency_tests/pubspec.yaml @@ -1,7 +1,7 @@ name: missing_dependency_tests environment: - sdk: '>=3.2.0-0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/flutter/dev/snippets/bin/snippets.dart b/flutter/dev/snippets/bin/snippets.dart index eb73a4b8ffb1b9f77ac3b4029f1da87b5bea6204..fd0649895181ca1ef09722fadfd52a700507bbcb 100644 --- a/flutter/dev/snippets/bin/snippets.dart +++ b/flutter/dev/snippets/bin/snippets.dart @@ -13,7 +13,6 @@ import 'package:process/process.dart'; import 'package:snippets/snippets.dart'; const String _kElementOption = 'element'; -const String _kFormatOutputOption = 'format-output'; const String _kHelpOption = 'help'; const String _kInputOption = 'input'; const String _kLibraryOption = 'library'; @@ -57,40 +56,37 @@ String getChannelName({ Platform platform = const LocalPlatform(), ProcessManager processManager = const LocalProcessManager(), }) { - final String? envReleaseChannel = platform.environment['LUCI_BRANCH']?.trim(); - if (['master', 'stable', 'main'].contains(envReleaseChannel)) { + switch (platform.environment['LUCI_BRANCH']?.trim()) { // Backward compatibility: Still support running on "master", but pretend it is "main". - if (envReleaseChannel == 'master') { + case 'master' || 'main': return 'main'; - } - return envReleaseChannel!; + case 'stable': + return 'stable'; } final RegExp gitBranchRegexp = RegExp(r'^## (?.*)'); final ProcessResult gitResult = processManager.runSync( - ['git', 'status', '-b', '--porcelain'], - // Use the FLUTTER_ROOT, if defined. - workingDirectory: platform.environment['FLUTTER_ROOT']?.trim() ?? - filesystem.currentDirectory.path, - // Adding extra debugging output to help debug why git status inexplicably fails - // (random non-zero error code) about 2% of the time. - environment: {'GIT_TRACE': '2', 'GIT_TRACE_SETUP': '2'}); + ['git', 'status', '-b', '--porcelain'], + // Use the FLUTTER_ROOT, if defined. + workingDirectory: + platform.environment['FLUTTER_ROOT']?.trim() ?? filesystem.currentDirectory.path, + // Adding extra debugging output to help debug why git status inexplicably fails + // (random non-zero error code) about 2% of the time. + environment: {'GIT_TRACE': '2', 'GIT_TRACE_SETUP': '2'}, + ); if (gitResult.exitCode != 0) { throw GitStatusFailed(gitResult); } - final RegExpMatch? gitBranchMatch = gitBranchRegexp - .firstMatch((gitResult.stdout as String).trim().split('\n').first); + final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch( + (gitResult.stdout as String).trim().split('\n').first, + ); return gitBranchMatch == null ? '' : gitBranchMatch.namedGroup('branch')!.split('...').first; } -const List sampleTypes = [ - 'snippet', - 'sample', - 'dartpad', -]; +const List sampleTypes = ['snippet', 'sample', 'dartpad']; // This is a hack to workaround the fact that git status inexplicably fails // (with random non-zero error code) about 2% of the time. @@ -105,8 +101,7 @@ String getChannelNameWithRetries({ return getChannelName(platform: platform, processManager: processManager); } on GitStatusFailed catch (e) { retryCount += 1; - stderr.write( - 'git status failed, retrying ($retryCount)\nError report:\n$e'); + stderr.write('git status failed, retrying ($retryCount)\nError report:\n$e'); } } @@ -124,18 +119,16 @@ void main(List argList) { defaultsTo: 'dartpad', allowed: sampleTypes, allowedHelp: { - 'dartpad': - 'Produce a code sample application for using in Dartpad.', - 'sample': - 'Produce a code sample application.', - 'snippet': - 'Produce a nicely formatted piece of sample code.', + 'dartpad': 'Produce a code sample application for using in Dartpad.', + 'sample': 'Produce a code sample application.', + 'snippet': 'Produce a nicely formatted piece of sample code.', }, help: 'The type of snippet to produce.', ); parser.addOption( _kOutputOption, - help: 'The output name for the generated sample application. Overrides ' + help: + 'The output name for the generated sample application. Overrides ' 'the naming generated by the --$_kPackageOption/--$_kLibraryOption/--$_kElementOption ' 'arguments. Metadata will be written alongside in a .json file. ' 'The basename of this argument is used as the ID. If this is a ' @@ -171,11 +164,6 @@ void main(List argList) { defaultsTo: environment['INVOCATION_INDEX'], help: 'A unique serial number for this snippet tool invocation.', ); - parser.addFlag( - _kFormatOutputOption, - defaultsTo: true, - help: 'Applies the Dart formatter to the published/extracted sample code.', - ); parser.addFlag( _kHelpOption, negatable: false, @@ -195,8 +183,9 @@ void main(List argList) { if (args[_kInputOption] == null) { stderr.writeln(parser.usage); errorExit( - 'The --$_kInputOption option must be specified, either on the command ' - 'line, or in the INPUT environment variable.'); + 'The --$_kInputOption option must be specified, either on the command ' + 'line, or in the INPUT environment variable.', + ); return; } @@ -206,7 +195,6 @@ void main(List argList) { return; } - final bool formatOutput = args[_kFormatOutputOption]! as bool; final String packageName = args[_kPackageOption] as String? ?? ''; final String libraryName = args[_kLibraryOption] as String? ?? ''; final String elementName = args[_kElementOption] as String? ?? ''; @@ -222,8 +210,7 @@ void main(List argList) { if (outputPath.isAbsolute) { output = outputPath; } else { - output = - filesystem.file(path.join(outputDirectory.path, outputPath.path)); + output = filesystem.file(path.join(outputDirectory.path, outputPath.path)); } } else { final List idParts = []; @@ -240,9 +227,11 @@ void main(List argList) { idParts.add(serial); } if (idParts.isEmpty) { - errorExit('Unable to determine ID. At least one of --$_kPackageOption, ' - '--$_kLibraryOption, --$_kElementOption, -$_kSerialOption, or the environment variables ' - 'PACKAGE_NAME, LIBRARY_NAME, ELEMENT_NAME, or INVOCATION_INDEX must be non-empty.'); + errorExit( + 'Unable to determine ID. At least one of --$_kPackageOption, ' + '--$_kLibraryOption, --$_kElementOption, -$_kSerialOption, or the environment variables ' + 'PACKAGE_NAME, LIBRARY_NAME, ELEMENT_NAME, or INVOCATION_INDEX must be non-empty.', + ); return; } id = idParts.join('.'); @@ -250,9 +239,8 @@ void main(List argList) { } output.parent.createSync(recursive: true); - final int? sourceLine = environment['SOURCE_LINE'] != null - ? int.tryParse(environment['SOURCE_LINE']!) - : null; + final int? sourceLine = + environment['SOURCE_LINE'] != null ? int.tryParse(environment['SOURCE_LINE']!) : null; final String sourcePath = environment['SOURCE_PATH'] ?? 'unknown.dart'; final SnippetDartdocParser sampleParser = SnippetDartdocParser(filesystem); final SourceElement element = sampleParser.parseFromDartdocToolFile( @@ -263,8 +251,7 @@ void main(List argList) { type: sampleType, ); final Map metadata = { - 'channel': getChannelNameWithRetries( - platform: platform, processManager: processManager), + 'channel': getChannelNameWithRetries(platform: platform, processManager: processManager), 'serial': serial, 'id': id, 'package': packageName, @@ -274,11 +261,7 @@ void main(List argList) { for (final CodeSample sample in element.samples) { sample.metadata.addAll(metadata); - snippetGenerator.generateCode( - sample, - output: output, - formatOutput: formatOutput, - ); + snippetGenerator.generateCode(sample, output: output); print(snippetGenerator.generateHtml(sample)); } diff --git a/flutter/dev/snippets/config/README.md b/flutter/dev/snippets/config/README.md index d5539eeb56d51b4eaa79a2bb4372eed7b3e6dd4b..87cc99db451b6aad91c4f5041b141e943210183d 100644 --- a/flutter/dev/snippets/config/README.md +++ b/flutter/dev/snippets/config/README.md @@ -4,4 +4,4 @@ The [snippets] tool uses the files in the `skeletons` directory to inject code blocks generated from `{@tool dartpad}`, `{@tool sample}`, and `{@tool snippet}` sections found in doc comments into the API docs. -[snippets]: https://github.com/flutter/assets-for-api-docs/tree/master/packages/snippets +[snippets]: https://github.com/flutter/assets-for-api-docs/tree/main/packages/snippets diff --git a/flutter/dev/snippets/config/skeletons/dartpad-sample.html b/flutter/dev/snippets/config/skeletons/dartpad-sample.html index 9afc6233d902eadb18da10b1db4b28d256010317..d8ce7cafd31eb41eadfa18d6a43a4787e237ce7b 100644 --- a/flutter/dev/snippets/config/skeletons/dartpad-sample.html +++ b/flutter/dev/snippets/config/skeletons/dartpad-sample.html @@ -13,7 +13,7 @@

{@end-inject-html} \ No newline at end of file diff --git a/flutter/dev/snippets/lib/snippets.dart b/flutter/dev/snippets/lib/snippets.dart index 116ae7970b4ec2c4bcf65a021f9307081f7e99d5..397ce0f56f4e58a5c92b3102d4fbbc926a37aa7b 100644 --- a/flutter/dev/snippets/lib/snippets.dart +++ b/flutter/dev/snippets/lib/snippets.dart @@ -5,7 +5,6 @@ export 'src/analysis.dart'; export 'src/configuration.dart'; export 'src/data_types.dart'; -export 'src/import_sorter.dart'; export 'src/snippet_generator.dart'; export 'src/snippet_parser.dart'; export 'src/util.dart'; diff --git a/flutter/dev/snippets/lib/src/analysis.dart b/flutter/dev/snippets/lib/src/analysis.dart index 73a871ae427840c40e4b5dec024fed6bab5d7c3c..66d3e3fbadedd222e313d990582fcd221ff7fed8 100644 --- a/flutter/dev/snippets/lib/src/analysis.dart +++ b/flutter/dev/snippets/lib/src/analysis.dart @@ -27,8 +27,7 @@ Iterable> getFileDocumentationComments(File file) { /// Gets an iterable over all of the blocks of documentation comments from an /// iterable over the [SourceElement]s involved. -Iterable> getDocumentationComments( - Iterable elements) { +Iterable> getDocumentationComments(Iterable elements) { return elements .where((SourceElement element) => element.comment.isNotEmpty) .map>((SourceElement element) => element.comment); @@ -50,13 +49,13 @@ Iterable getCommentElements(Iterable elements) { /// The `file` argument is used to tag the lines with a filename that they came from. Iterable getElementsFromString(String content, File file) { final ParseStringResult parseResult = parseString( - featureSet: FeatureSet.fromEnableFlags2( - sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(), - flags: [], - ), - content: content); - final _SourceVisitor visitor = - _SourceVisitor(file); + featureSet: FeatureSet.fromEnableFlags2( + sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(), + flags: [], + ), + content: content, + ); + final _SourceVisitor visitor = _SourceVisitor(file); visitor.visitCompilationUnit(parseResult.unit); visitor.assignLineNumbers(); return visitor.elements; @@ -66,18 +65,17 @@ Iterable getElementsFromString(String content, File file) { /// /// Takes an optional [ResourceProvider] to allow reading from a memory /// filesystem. -Iterable getFileElements(File file, - {afs.ResourceProvider? resourceProvider}) { +Iterable getFileElements(File file, {afs.ResourceProvider? resourceProvider}) { resourceProvider ??= afs.PhysicalResourceProvider.INSTANCE; final ParseStringResult parseResult = parseFile( - featureSet: FeatureSet.fromEnableFlags2( - sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(), - flags: [], - ), - path: file.absolute.path, - resourceProvider: resourceProvider); - final _SourceVisitor visitor = - _SourceVisitor(file); + featureSet: FeatureSet.fromEnableFlags2( + sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(), + flags: [], + ), + path: file.absolute.path, + resourceProvider: resourceProvider, + ); + final _SourceVisitor visitor = _SourceVisitor(file); visitor.visitCompilationUnit(parseResult.unit); visitor.assignLineNumbers(); return visitor.elements; @@ -100,13 +98,11 @@ class _SourceVisitor extends RecursiveAstVisitor { for (final SourceElement element in elements) { final List newLines = []; for (final SourceLine line in element.comment) { - final CharacterLocation intervalLine = - lineInfo.getLocation(line.startChar); + final CharacterLocation intervalLine = lineInfo.getLocation(line.startChar); newLines.add(line.copyWith(line: intervalLine.lineNumber)); } final int elementLine = lineInfo.getLocation(element.startPos).lineNumber; - replacedElements - .add(element.copyWith(comment: newLines, startLine: elementLine)); + replacedElements.add(element.copyWith(comment: newLines, startLine: elementLine)); removedElements.add(element); } elements.removeAll(removedElements); @@ -117,13 +113,15 @@ class _SourceVisitor extends RecursiveAstVisitor { final List result = []; if (comment.tokens.isNotEmpty) { for (final Token token in comment.tokens) { - result.add(SourceLine( - token.toString(), - element: element, - file: file, - startChar: token.charOffset, - endChar: token.charEnd, - )); + result.add( + SourceLine( + token.toString(), + element: element, + file: file, + startChar: token.charOffset, + endChar: token.charEnd, + ), + ); } } return result; @@ -157,10 +155,8 @@ class _SourceVisitor extends RecursiveAstVisitor { continue; } List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { - comment = _processComment( - declaration.name.lexeme, node.documentationComment!); + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { + comment = _processComment(declaration.name.lexeme, node.documentationComment!); } elements.add( SourceElement( @@ -180,8 +176,7 @@ class _SourceVisitor extends RecursiveAstVisitor { T? visitGenericTypeAlias(GenericTypeAlias node) { if (isPublic(node.name.lexeme)) { List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { comment = _processComment(node.name.lexeme, node.documentationComment!); } elements.add( @@ -204,11 +199,12 @@ class _SourceVisitor extends RecursiveAstVisitor { continue; } List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { assert(enclosingClass.isNotEmpty); - comment = _processComment('$enclosingClass.${declaration.name.lexeme}', - node.documentationComment!); + comment = _processComment( + '$enclosingClass.${declaration.name.lexeme}', + node.documentationComment!, + ); } elements.add( SourceElement( @@ -228,15 +224,11 @@ class _SourceVisitor extends RecursiveAstVisitor { @override T? visitConstructorDeclaration(ConstructorDeclaration node) { - final String fullName = - '$enclosingClass${node.name == null ? '' : '.${node.name}'}'; - if (isPublic(enclosingClass) && - (node.name == null || isPublic(node.name!.lexeme))) { + final String fullName = '$enclosingClass${node.name == null ? '' : '.${node.name}'}'; + if (isPublic(enclosingClass) && (node.name == null || isPublic(node.name!.lexeme))) { List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { - comment = _processComment( - '$enclosingClass.$fullName', node.documentationComment!); + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { + comment = _processComment('$enclosingClass.$fullName', node.documentationComment!); } elements.add( SourceElement( @@ -258,10 +250,8 @@ class _SourceVisitor extends RecursiveAstVisitor { List comment = []; // Skip functions that are defined inside of methods. if (!isInsideMethod(node)) { - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { - comment = - _processComment(node.name.lexeme, node.documentationComment!); + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { + comment = _processComment(node.name.lexeme, node.documentationComment!); } elements.add( SourceElement( @@ -282,11 +272,12 @@ class _SourceVisitor extends RecursiveAstVisitor { T? visitMethodDeclaration(MethodDeclaration node) { if (isPublic(node.name.lexeme) && isPublic(enclosingClass)) { List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { assert(enclosingClass.isNotEmpty); comment = _processComment( - '$enclosingClass.${node.name.lexeme}', node.documentationComment!); + '$enclosingClass.${node.name.lexeme}', + node.documentationComment!, + ); } elements.add( SourceElement( @@ -315,8 +306,7 @@ class _SourceVisitor extends RecursiveAstVisitor { if (!node.name.lexeme.startsWith('_')) { enclosingClass = node.name.lexeme; List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { comment = _processComment(node.name.lexeme, node.documentationComment!); } elements.add( @@ -340,8 +330,7 @@ class _SourceVisitor extends RecursiveAstVisitor { if (!node.name.lexeme.startsWith('_')) { enclosingClass = node.name.lexeme; List comment = []; - if (node.documentationComment != null && - node.documentationComment!.tokens.isNotEmpty) { + if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) { comment = _processComment(node.name.lexeme, node.documentationComment!); } elements.add( diff --git a/flutter/dev/snippets/lib/src/configuration.dart b/flutter/dev/snippets/lib/src/configuration.dart index cd6e1e3faaa92c912d6c88925674fd9a4c191b23..e635ef9306f21ea004675659be0b0f9cb3d1dc69 100644 --- a/flutter/dev/snippets/lib/src/configuration.dart +++ b/flutter/dev/snippets/lib/src/configuration.dart @@ -27,8 +27,7 @@ class SnippetConfiguration { /// Gets the skeleton file to use for the given [SampleType] and DartPad /// preference. File getHtmlSkeletonFile(String type) { - final String filename = - type == 'dartpad' ? 'dartpad-sample.html' : '$type.html'; + final String filename = type == 'dartpad' ? 'dartpad-sample.html' : '$type.html'; return filesystem.file(path.join(skeletonsDirectory.path, filename)); } } @@ -37,17 +36,22 @@ class SnippetConfiguration { /// locations based in the current location of the snippets main.dart. class FlutterRepoSnippetConfiguration extends SnippetConfiguration { FlutterRepoSnippetConfiguration({required this.flutterRoot, super.filesystem}) - : super( - configDirectory: _underRoot(filesystem, flutterRoot, - const ['dev', 'snippets', 'config']), - skeletonsDirectory: _underRoot(filesystem, flutterRoot, - const ['dev', 'snippets', 'config', 'skeletons']), - ); + : super( + configDirectory: _underRoot(filesystem, flutterRoot, const [ + 'dev', + 'snippets', + 'config', + ]), + skeletonsDirectory: _underRoot(filesystem, flutterRoot, const [ + 'dev', + 'snippets', + 'config', + 'skeletons', + ]), + ); final Directory flutterRoot; - static Directory _underRoot( - FileSystem fs, Directory flutterRoot, List dirs) => - fs.directory(path.canonicalize( - path.joinAll([flutterRoot.absolute.path, ...dirs]))); + static Directory _underRoot(FileSystem fs, Directory flutterRoot, List dirs) => + fs.directory(path.canonicalize(path.joinAll([flutterRoot.absolute.path, ...dirs]))); } diff --git a/flutter/dev/snippets/lib/src/data_types.dart b/flutter/dev/snippets/lib/src/data_types.dart index f19f9e000327ca1a56fdd50ee3efdd8811c8b23d..160c5796c5b7994e1fb0949359f71fb4ec9e24df 100644 --- a/flutter/dev/snippets/lib/src/data_types.dart +++ b/flutter/dev/snippets/lib/src/data_types.dart @@ -27,8 +27,7 @@ class SourceLine { final int indent; final String text; - String toStringWithColumn(int column) => - '$file:$line:${column + indent}: $text'; + String toStringWithColumn(int column) => '$file:$line:${column + indent}: $text'; SourceLine copyWith({ String? element, @@ -71,14 +70,10 @@ class SkeletonInjection { /// A base class to represent a block of any kind of sample code, marked by /// "{@tool (snippet|sample|dartdoc) ...}...{@end-tool}". abstract class CodeSample { - CodeSample( - this.args, - this.input, { - required this.index, - required SourceLine lineProto, - }) : assert(args.isNotEmpty), - _lineProto = lineProto, - sourceFile = null; + CodeSample(this.args, this.input, {required this.index, required SourceLine lineProto}) + : assert(args.isNotEmpty), + _lineProto = lineProto, + sourceFile = null; CodeSample.fromFile( this.args, @@ -86,8 +81,8 @@ abstract class CodeSample { this.sourceFile, { required this.index, required SourceLine lineProto, - }) : assert(args.isNotEmpty), - _lineProto = lineProto; + }) : assert(args.isNotEmpty), + _lineProto = lineProto; final File? sourceFile; final List args; @@ -102,8 +97,7 @@ abstract class CodeSample { bool doneStrippingHeaders = false; try { for (final String line in sourceFile!.readAsLinesSync()) { - if (!doneStrippingHeaders && - RegExp(r'^\s*(\/\/.*)?$').hasMatch(line)) { + if (!doneStrippingHeaders && RegExp(r'^\s*(\/\/.*)?$').hasMatch(line)) { continue; } // Stop skipping lines after the first line that isn't stripped. @@ -121,14 +115,12 @@ abstract class CodeSample { r'(\/\/\*\*+\n)?\/\/\* [▼▲]+.*$(\n\/\/\*\*+)?\n\n?', multiLine: true, ); - _sourceFileContents = - stripped.join('\n').replaceAll(sectionMarkerRegExp, ''); + _sourceFileContents = stripped.join('\n').replaceAll(sectionMarkerRegExp, ''); } return _sourceFileContents ?? ''; } - Iterable get inputStrings => - input.map((SourceLine line) => line.text); + Iterable get inputStrings => input.map((SourceLine line) => line.text); String get inputAsString => inputStrings.join('\n'); /// The index of this sample within the dartdoc comment it came from. @@ -151,9 +143,7 @@ abstract class CodeSample { String toString() { final StringBuffer buf = StringBuffer('${args.join(' ')}:\n'); for (final SourceLine line in input) { - buf.writeln( - '${(line.line == -1 ? '??' : line.line).toString().padLeft(4)}: ${line.text} ', - ); + buf.writeln('${(line.line == -1 ? '??' : line.line).toString().padLeft(4)}: ${line.text} '); } return buf.toString(); } @@ -167,17 +157,9 @@ abstract class CodeSample { /// Snippets are code that is not meant to be run as a complete application, but /// rather as a code usage example. class SnippetSample extends CodeSample { - SnippetSample( - List input, { - required int index, - required SourceLine lineProto, - }) : assumptions = [], - super( - ['snippet'], - input, - index: index, - lineProto: lineProto, - ); + SnippetSample(List input, {required int index, required SourceLine lineProto}) + : assumptions = [], + super(['snippet'], input, index: index, lineProto: lineProto); factory SnippetSample.combine( List sections, { @@ -189,25 +171,16 @@ class SnippetSample extends CodeSample { return SnippetSample(code, index: index, lineProto: lineProto); } - factory SnippetSample.fromStrings(SourceLine firstLine, List code, - {required int index}) { + factory SnippetSample.fromStrings(SourceLine firstLine, List code, {required int index}) { final List codeLines = []; int startPos = firstLine.startChar; for (int i = 0; i < code.length; ++i) { codeLines.add( - firstLine.copyWith( - text: code[i], - line: firstLine.line + i, - startChar: startPos, - ), + firstLine.copyWith(text: code[i], line: firstLine.line + i, startChar: startPos), ); startPos += code[i].length + 1; } - return SnippetSample( - codeLines, - index: index, - lineProto: firstLine, - ); + return SnippetSample(codeLines, index: index, lineProto: firstLine); } factory SnippetSample.surround( @@ -233,8 +206,7 @@ class SnippetSample extends CodeSample { String get template => ''; @override - SourceLine get start => - input.firstWhere((SourceLine line) => line.file != null); + SourceLine get start => input.firstWhere((SourceLine line) => line.file != null); @override String get type => 'snippet'; @@ -253,8 +225,8 @@ class ApplicationSample extends CodeSample { required List args, required int index, required SourceLine lineProto, - }) : assert(args.isNotEmpty), - super(args, input, index: index, lineProto: lineProto); + }) : assert(args.isNotEmpty), + super(args, input, index: index, lineProto: lineProto); ApplicationSample.fromFile({ List input = const [], @@ -262,9 +234,8 @@ class ApplicationSample extends CodeSample { required File sourceFile, required int index, required SourceLine lineProto, - }) : assert(args.isNotEmpty), - super.fromFile(args, input, sourceFile, - index: index, lineProto: lineProto); + }) : assert(args.isNotEmpty), + super.fromFile(args, input, sourceFile, index: index, lineProto: lineProto); @override String get type => 'sample'; @@ -278,12 +249,8 @@ class ApplicationSample extends CodeSample { /// [DartpadSample] represents one `{@tool dartpad ...}...{@end-tool}` block in /// the source file. class DartpadSample extends ApplicationSample { - DartpadSample({ - super.input, - required super.args, - required super.index, - required super.lineProto, - }) : assert(args.isNotEmpty); + DartpadSample({super.input, required super.args, required super.index, required super.lineProto}) + : assert(args.isNotEmpty); DartpadSample.fromFile({ super.input, @@ -291,8 +258,8 @@ class DartpadSample extends ApplicationSample { required super.sourceFile, required super.index, required super.lineProto, - }) : assert(args.isNotEmpty), - super.fromFile(); + }) : assert(args.isNotEmpty), + super.fromFile(); @override String get type => 'dartpad'; @@ -328,14 +295,14 @@ enum SourceElementType { /// Converts the enum type [SourceElementType] to a human readable string. String sourceElementTypeAsString(SourceElementType type) { return switch (type) { - SourceElementType.classType => 'class', - SourceElementType.fieldType => 'field', - SourceElementType.methodType => 'method', - SourceElementType.constructorType => 'constructor', - SourceElementType.typedefType => 'typedef', + SourceElementType.classType => 'class', + SourceElementType.fieldType => 'field', + SourceElementType.methodType => 'method', + SourceElementType.constructorType => 'constructor', + SourceElementType.typedefType => 'typedef', SourceElementType.topLevelVariableType => 'variable', - SourceElementType.functionType => 'function', - SourceElementType.unknownType => 'unknown', + SourceElementType.functionType => 'function', + SourceElementType.unknownType => 'unknown', }; } @@ -360,8 +327,7 @@ class SourceElement { }) { comment ??= []; samples ??= []; - final List commentLines = - comment.map((SourceLine line) => line.text).toList(); + final List commentLines = comment.map((SourceLine line) => line.text).toList(); final String commentString = commentLines.join('\n'); return SourceElement._( type, @@ -394,10 +360,10 @@ class SourceElement { String commentStringWithoutTools = '', String commentStringWithoutCode = '', List commentLines = const [], - }) : _commentString = commentString, - _commentStringWithoutTools = commentStringWithoutTools, - _commentStringWithoutCode = commentStringWithoutCode, - _commentLines = commentLines; + }) : _commentString = commentString, + _commentStringWithoutTools = commentStringWithoutTools, + _commentStringWithoutCode = commentStringWithoutCode, + _commentLines = commentLines; final String _commentString; final String _commentStringWithoutTools; @@ -408,14 +374,15 @@ class SourceElement { // of any dartdoc tools. static String _getCommentStringWithoutTools(String string) { return string.replaceAll( - RegExp(r'(\{@tool ([^}]*)\}.*?\{@end-tool\}|/// ?)', dotAll: true), ''); + RegExp(r'(\{@tool ([^}]*)\}.*?\{@end-tool\}|/// ?)', dotAll: true), + '', + ); } // Includes the description text inside of an "@tool"-based sample, but not // the code itself, or any dartdoc tags. static String _getCommentStringWithoutCode(String string) { - return string.replaceAll( - RegExp(r'([`]{3}.*?[`]{3}|\{@\w+[^}]*\}|/// ?)', dotAll: true), ''); + return string.replaceAll(RegExp(r'([`]{3}.*?[`]{3}|\{@\w+[^}]*\}|/// ?)', dotAll: true), ''); } /// The type of the element @@ -477,7 +444,8 @@ class SourceElement { int get dartpadSampleCount => samples.whereType().length; /// The number of [ApplicationSample]s in the dartdoc comment for this element. - int get applicationSampleCount => samples.where((CodeSample sample) { + int get applicationSampleCount => + samples.where((CodeSample sample) { return sample is ApplicationSample && sample is! DartpadSample; }).length; @@ -494,8 +462,7 @@ class SourceElement { /// Count of comment characters, not including any code samples in the /// comment, after collapsing each run of whitespace to a single space. - int get charCount => - commentStringWithoutCode.replaceAll(RegExp(r'\s+'), ' ').length; + int get charCount => commentStringWithoutCode.replaceAll(RegExp(r'\s+'), ' ').length; /// Whether or not this element's documentation has a "See also:" section in it. bool get hasSeeAlso => commentStringWithoutTools.contains('See also:'); diff --git a/flutter/dev/snippets/lib/src/snippet_generator.dart b/flutter/dev/snippets/lib/src/snippet_generator.dart index 75a0c896e2cd7bf9623e6c4fe42d8b11a86bbf8e..1f7e647af1bd9b9aaf75b699c5fd4ac278ba236c 100644 --- a/flutter/dev/snippets/lib/src/snippet_generator.dart +++ b/flutter/dev/snippets/lib/src/snippet_generator.dart @@ -3,32 +3,29 @@ // found in the LICENSE file. import 'dart:convert'; -import 'dart:io' as io; -import 'package:dart_style/dart_style.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:path/path.dart' as path; import 'configuration.dart'; import 'data_types.dart'; -import 'import_sorter.dart'; import 'util.dart'; /// Generates the snippet HTML, as well as saving the output snippet main to /// the output directory. class SnippetGenerator { - SnippetGenerator( - {SnippetConfiguration? configuration, - FileSystem filesystem = const LocalFileSystem(), - Directory? flutterRoot}) - : flutterRoot = - flutterRoot ?? FlutterInformation.instance.getFlutterRoot(), - configuration = configuration ?? - FlutterRepoSnippetConfiguration( - filesystem: filesystem, - flutterRoot: flutterRoot ?? - FlutterInformation.instance.getFlutterRoot()); + SnippetGenerator({ + SnippetConfiguration? configuration, + FileSystem filesystem = const LocalFileSystem(), + Directory? flutterRoot, + }) : flutterRoot = flutterRoot ?? FlutterInformation.instance.getFlutterRoot(), + configuration = + configuration ?? + FlutterRepoSnippetConfiguration( + filesystem: filesystem, + flutterRoot: flutterRoot ?? FlutterInformation.instance.getFlutterRoot(), + ); final Directory flutterRoot; @@ -38,21 +35,13 @@ class SnippetGenerator { static const JsonEncoder jsonEncoder = JsonEncoder.withIndent(' '); - /// A Dart formatted used to format the snippet code and finished application - /// code. - static DartFormatter formatter = - DartFormatter(pageWidth: 80, fixes: StyleFix.all); - /// Interpolates the [injections] into an HTML skeleton file. /// /// The order of the injections is important. /// /// Takes into account the [type] and doesn't substitute in the id and the app /// if not a [SnippetType.sample] snippet. - String interpolateSkeleton( - CodeSample sample, - String skeleton, - ) { + String interpolateSkeleton(CodeSample sample, String skeleton) { final List codeParts = []; const HtmlEscape htmlEscape = HtmlEscape(); String? language; @@ -72,15 +61,15 @@ class SnippetGenerator { // Only insert a div for the description if there actually is some text there. // This means that the {{description}} marker in the skeleton needs to // be inside of an {@inject-html} block. - final String description = sample.description.trim().isNotEmpty - ? '
{@end-inject-html}${sample.description.trim()}{@inject-html}
' - : ''; + final String description = + sample.description.trim().isNotEmpty + ? '
{@end-inject-html}${sample.description.trim()}{@inject-html}
' + : ''; // DartPad only supports stable or main as valid channels. Use main // if not on stable so that local runs will work (although they will // still take their sample code from the master docs server). - final String channel = - sample.metadata['channel'] == 'stable' ? 'stable' : 'main'; + final String channel = sample.metadata['channel'] == 'stable' ? 'stable' : 'main'; final Map substitutions = { 'description': description, @@ -97,23 +86,21 @@ class SnippetGenerator { ..['serial'] = sample.metadata['serial']?.toString() ?? '0' ..['app'] = htmlEscape.convert(sample.output); } - return skeleton.replaceAllMapped( - RegExp('{{(${substitutions.keys.join('|')})}}'), (Match match) { + return skeleton.replaceAllMapped(RegExp('{{(${substitutions.keys.join('|')})}}'), ( + Match match, + ) { return substitutions[match[1]]!; }); } /// Consolidates all of the snippets and the assumptions into one snippet, in /// order to create a compilable result. - Iterable consolidateSnippets(List samples, - {bool addMarkers = false}) { + Iterable consolidateSnippets(List samples, {bool addMarkers = false}) { if (samples.isEmpty) { return []; } final Iterable snippets = samples.whereType(); - final List snippetLines = [ - ...snippets.first.assumptions, - ]; + final List snippetLines = [...snippets.first.assumptions]; for (final SnippetSample sample in snippets) { parseInput(sample); snippetLines.addAll(_processBlocks(sample)); @@ -122,15 +109,13 @@ class SnippetGenerator { } /// A RegExp that matches a Dart constructor. - static final RegExp _constructorRegExp = - RegExp(r'(const\s+)?_*[A-Z][a-zA-Z0-9<>._]*\('); + static final RegExp _constructorRegExp = RegExp(r'(const\s+)?_*[A-Z][a-zA-Z0-9<>._]*\('); /// A serial number so that we can create unique expression names when we /// generate them. int _expressionId = 0; - List _surround( - String prefix, Iterable body, String suffix) { + List _surround(String prefix, Iterable body, String suffix) { return [ if (prefix.isNotEmpty) SourceLine(prefix), ...body, @@ -143,9 +128,10 @@ class SnippetGenerator { /// processed separately. Uses a primitive heuristic to make sample blocks /// into valid Dart code. List _processBlocks(CodeSample sample) { - final List block = sample.parts - .expand((SkeletonInjection injection) => injection.contents) - .toList(); + final List block = + sample.parts + .expand((SkeletonInjection injection) => injection.contents) + .toList(); if (block.isEmpty) { return []; } @@ -154,23 +140,18 @@ class SnippetGenerator { List _processBlock(List block) { final String firstLine = block.first.text; - if (firstLine.startsWith('new ') || - firstLine.startsWith(_constructorRegExp)) { + if (firstLine.startsWith('new ') || firstLine.startsWith(_constructorRegExp)) { _expressionId += 1; return _surround('dynamic expression$_expressionId = ', block, ';'); } else if (firstLine.startsWith('await ')) { _expressionId += 1; - return _surround( - 'Future expression$_expressionId() async { ', block, ' }'); - } else if (block.first.text.startsWith('class ') || - block.first.text.startsWith('enum ')) { + return _surround('Future expression$_expressionId() async { ', block, ' }'); + } else if (block.first.text.startsWith('class ') || block.first.text.startsWith('enum ')) { return block; - } else if ((block.first.text.startsWith('_') || - block.first.text.startsWith('final ')) && + } else if ((block.first.text.startsWith('_') || block.first.text.startsWith('final ')) && block.first.text.contains(' = ')) { _expressionId += 1; - return _surround( - 'void expression$_expressionId() { ', block.toList(), ' }'); + return _surround('void expression$_expressionId() { ', block.toList(), ' }'); } else { final List buffer = []; int blocks = 0; @@ -218,8 +199,9 @@ class SnippetGenerator { final List description = []; final List components = []; String? language; - final RegExp codeStartEnd = - RegExp(r'^\s*```(?[-\w]+|[-\w]+ (?
[-\w]+))?\s*$'); + final RegExp codeStartEnd = RegExp( + r'^\s*```(?[-\w]+|[-\w]+ (?
[-\w]+))?\s*$', + ); for (final SourceLine line in sample.input) { final RegExpMatch? match = codeStartEnd.firstMatch(line.text); if (match != null) { @@ -228,12 +210,15 @@ class SnippetGenerator { if (match.namedGroup('language') != null) { language = match[1]; if (match.namedGroup('section') != null) { - components.add(SkeletonInjection( - 'code-${match.namedGroup('section')}', [], - language: language!)); - } else { components.add( - SkeletonInjection('code', [], language: language!)); + SkeletonInjection( + 'code-${match.namedGroup('section')}', + [], + language: language!, + ), + ); + } else { + components.add(SkeletonInjection('code', [], language: language!)); } } else { language = null; @@ -249,8 +234,7 @@ class SnippetGenerator { } final List descriptionLines = []; bool lastWasWhitespace = false; - for (final String line in description - .map((SourceLine line) => line.text.trimRight())) { + for (final String line in description.map((SourceLine line) => line.text.trimRight())) { final bool onlyWhitespace = line.trim().isEmpty; if (onlyWhitespace && descriptionLines.isEmpty) { // Don't add whitespace lines until we see something without whitespace. @@ -266,8 +250,7 @@ class SnippetGenerator { } sample.description = descriptionLines.join('\n').trimRight(); sample.parts = [ - if (sample is SnippetSample) - SkeletonInjection('#assumptions', sample.assumptions), + if (sample is SnippetSample) SkeletonInjection('#assumptions', sample.assumptions), ...components, ]; return sample.parts; @@ -282,8 +265,7 @@ class SnippetGenerator { /// Returns a string with the HTML needed to embed in a web page for showing a /// sample on the web page. String generateHtml(CodeSample sample) { - final String skeleton = - _loadFileAsUtf8(configuration.getHtmlSkeletonFile(sample.type)); + final String skeleton = _loadFileAsUtf8(configuration.getHtmlSkeletonFile(sample.type)); return interpolateSkeleton(sample, skeleton); } @@ -295,8 +277,8 @@ class SnippetGenerator { return sample.description.splitMapJoin( '\n', onMatch: (Match match) => match.group(0)!, - onNonMatch: (String nonmatch) => - nonmatch.trimRight().isEmpty ? '//' : '// ${nonmatch.trimRight()}', + onNonMatch: + (String nonmatch) => nonmatch.trimRight().isEmpty ? '//' : '// ${nonmatch.trimRight()}', ); } @@ -315,7 +297,6 @@ class SnippetGenerator { File? output, String? copyright, String? description, - bool formatOutput = true, bool includeAssumptions = false, }) { sample.metadata['copyright'] ??= copyright; @@ -327,99 +308,84 @@ class SnippetGenerator { case ApplicationSample _: final String app = sample.sourceFileContents; sample.output = app; - if (formatOutput) { - final DartFormatter formatter = - DartFormatter(pageWidth: 80, fixes: StyleFix.all); - try { - sample.output = formatter.format(sample.output); - } on FormatterException catch (exception) { - io.stderr - .write('Code to format:\n${_addLineNumbers(sample.output)}\n'); - errorExit('Unable to format sample code: $exception'); - } - sample.output = sortImports(sample.output); - } if (output != null) { output.writeAsStringSync(sample.output); - final File metadataFile = configuration.filesystem.file(path.join( + final File metadataFile = configuration.filesystem.file( + path.join( path.dirname(output.path), - '${path.basenameWithoutExtension(output.path)}.json')); + '${path.basenameWithoutExtension(output.path)}.json', + ), + ); sample.metadata['file'] = path.basename(output.path); final Map metadata = sample.metadata; if (metadata.containsKey('description')) { - metadata['description'] = (metadata['description']! as String) - .replaceAll(RegExp(r'^// ?', multiLine: true), ''); + metadata['description'] = (metadata['description']! as String).replaceAll( + RegExp(r'^// ?', multiLine: true), + '', + ); } metadataFile.writeAsStringSync(jsonEncoder.convert(metadata)); } case SnippetSample _: - String app; - if (sample.sourceFile == null) { - String templateContents; - if (includeAssumptions) { - templateContents = - '${headers.map((SourceLine line) { - return line.text; - }).join('\n')}\n{{#assumptions}}\n{{description}}\n{{code}}'; - } else { - templateContents = '{{description}}\n{{code}}'; - } - app = interpolateTemplate( - snippetData, - templateContents, - sample.metadata, - addCopyright: copyright != null, - ); + String app; + if (sample.sourceFile == null) { + String templateContents; + if (includeAssumptions) { + templateContents = + '${headers.map((SourceLine line) { + return line.text; + }).join('\n')}\n{{#assumptions}}\n{{description}}\n{{code}}'; } else { - app = sample.inputAsString; + templateContents = '{{description}}\n{{code}}'; } - sample.output = app; + app = interpolateTemplate( + snippetData, + templateContents, + sample.metadata, + addCopyright: copyright != null, + ); + } else { + app = sample.inputAsString; + } + sample.output = app; } return sample.output; } - String _addLineNumbers(String code) { - final StringBuffer buffer = StringBuffer(); - int count = 0; - for (final String line in code.split('\n')) { - count++; - buffer.writeln('${count.toString().padLeft(5)}: $line'); - } - return buffer.toString(); - } - /// Computes the headers needed for each snippet file. /// /// Not used for "sample" and "dartpad" samples, which use their own template. List get headers { - return _headers ??= [ - '// generated code', - '// ignore_for_file: unused_import', - '// ignore_for_file: unused_element', - '// ignore_for_file: unused_local_variable', - "import 'dart:async';", - "import 'dart:convert';", - "import 'dart:math' as math;", - "import 'dart:typed_data';", - "import 'dart:ui' as ui;", - "import 'package:flutter_test/flutter_test.dart';", - for (final File file in _listDartFiles(FlutterInformation.instance - .getFlutterRoot() - .childDirectory('packages') - .childDirectory('flutter') - .childDirectory('lib'))) ...[ - '', - '// ${file.path}', - "import 'package:flutter/${path.basename(file.path)}';", - ], - ].map((String code) => SourceLine(code)).toList(); + return _headers ??= + [ + '// generated code', + '// ignore_for_file: unused_import', + '// ignore_for_file: unused_element', + '// ignore_for_file: unused_local_variable', + "import 'dart:async';", + "import 'dart:convert';", + "import 'dart:math' as math;", + "import 'dart:typed_data';", + "import 'dart:ui' as ui;", + "import 'package:flutter_test/flutter_test.dart';", + for (final File file in _listDartFiles( + FlutterInformation.instance + .getFlutterRoot() + .childDirectory('packages') + .childDirectory('flutter') + .childDirectory('lib'), + )) ...[ + '', + '// ${file.path}', + "import 'package:flutter/${path.basename(file.path)}';", + ], + ].map((String code) => SourceLine(code)).toList(); } List? _headers; - static List _listDartFiles(Directory directory, - {bool recursive = false}) { + static List _listDartFiles(Directory directory, {bool recursive = false}) { return directory .listSync(recursive: recursive, followLinks: false) .whereType() diff --git a/flutter/dev/snippets/lib/src/snippet_parser.dart b/flutter/dev/snippets/lib/src/snippet_parser.dart index 9678d6e0ca930d2c2c85ee33b9375d98f32afec2..abc98b2d37d676c2b02a876b1e1131ae74c87acd 100644 --- a/flutter/dev/snippets/lib/src/snippet_parser.dart +++ b/flutter/dev/snippets/lib/src/snippet_parser.dart @@ -29,8 +29,9 @@ class SnippetDartdocParser { static const String _dartDocPrefixWithSpace = '$_dartDocPrefix '; /// A RegExp that matches the beginning of a dartdoc snippet or sample. - static final RegExp _dartDocSampleBeginRegex = - RegExp(r'\{@tool (?sample|snippet|dartpad)(?:| (?[^}]*))\}'); + static final RegExp _dartDocSampleBeginRegex = RegExp( + r'\{@tool (?sample|snippet|dartpad)(?:| (?[^}]*))\}', + ); /// A RegExp that matches the end of a dartdoc snippet or sample. static final RegExp _dartDocSampleEndRegex = RegExp(r'\{@end-tool\}'); @@ -42,8 +43,7 @@ class SnippetDartdocParser { static final RegExp _codeBlockEndRegex = RegExp(r'///\s+```\s*$'); /// A RegExp that matches a linked sample pointer. - static final RegExp _filePointerRegex = - RegExp(r'\*\* See code in (?[^\]]+) \*\*'); + static final RegExp _filePointerRegex = RegExp(r'\*\* See code in (?[^\]]+) \*\*'); /// Parses the assumptions in the "Examples can assume:" block at the top of /// the `assumptionsFile` and adds them to the code samples contained in the @@ -54,8 +54,9 @@ class SnippetDartdocParser { bool silent = true, }) { final List assumptions = parseAssumptions(assumptionsFile); - for (final CodeSample sample in elements - .expand((SourceElement element) => element.samples)) { + for (final CodeSample sample in elements.expand( + (SourceElement element) => element.samples, + )) { if (sample is SnippetSample) { sample.assumptions = assumptions; } @@ -91,22 +92,21 @@ class SnippetDartdocParser { // Snippet input comes in with the comment markers stripped, so we add them // back to make it conform to the source format, so we can use the same // parser for editing samples as we do for processing docs. - ...input - .readAsLinesSync() - .map((String line) => '/// $line'.trimRight()), + ...input.readAsLinesSync().map((String line) => '/// $line'.trimRight()), '/// {@end-tool}', ]; for (final String line in inputStrings) { - lines.add( - SourceLine(line, - element: element ?? '', line: lineNumber, file: sourceFile), - ); + lines.add(SourceLine(line, element: element ?? '', line: lineNumber, file: sourceFile)); lineNumber++; } // No need to get assumptions: dartdoc won't give that to us. final SourceElement newElement = SourceElement( - SourceElementType.unknownType, element!, -1, - file: input, comment: lines); + SourceElementType.unknownType, + element!, + -1, + file: input, + comment: lines, + ); parseFromComments([newElement], silent: silent); for (final CodeSample sample in newElement.samples) { sample.metadata.addAll({ @@ -144,14 +144,16 @@ class SnippetDartdocParser { continue; } if (inPreamble) { - preamble.add(SourceLine( - line.substring(3), - startChar: charPosition, - endChar: charPosition + line.length + 1, - element: '#assumptions', - file: file, - line: lineNumber, - )); + preamble.add( + SourceLine( + line.substring(3), + startChar: charPosition, + endChar: charPosition + line.length + 1, + element: '#assumptions', + file: file, + line: lineNumber, + ), + ); } lineNumber++; charPosition += line.length + 1; @@ -162,10 +164,7 @@ class SnippetDartdocParser { /// This parses the code snippets from the documentation comments in the given /// `elements`, and sets the resulting samples as the `samples` member of /// each element in the supplied iterable. - void parseFromComments( - Iterable elements, { - bool silent = true, - }) { + void parseFromComments(Iterable elements, {bool silent = true}) { int dartpadCount = 0; int sampleCount = 0; int snippetCount = 0; @@ -188,10 +187,12 @@ class SnippetDartdocParser { } if (!silent) { - print('Found:\n' - ' $snippetCount snippet code blocks,\n' - ' $sampleCount non-dartpad sample code sections, and\n' - ' $dartpadCount dartpad sections.\n'); + print( + 'Found:\n' + ' $snippetCount snippet code blocks,\n' + ' $sampleCount non-dartpad sample code sections, and\n' + ' $dartpadCount dartpad sections.\n', + ); } } @@ -216,19 +217,16 @@ class SnippetDartdocParser { final String trimmedLine = line.text.trim(); if (inSnippet) { if (!trimmedLine.startsWith(_dartDocPrefix)) { - throw SnippetException('Snippet section unterminated.', - file: line.file?.path, line: line.line); + throw SnippetException( + 'Snippet section unterminated.', + file: line.file?.path, + line: line.line, + ); } if (_dartDocSampleEndRegex.hasMatch(trimmedLine)) { switch (snippetArgs.first) { case 'snippet': - samples.add( - SnippetSample( - block, - index: index++, - lineProto: line, - ), - ); + samples.add(SnippetSample(block, index: index++, lineProto: line)); case 'sample': if (linkedFile != null) { samples.add( @@ -243,12 +241,7 @@ class SnippetDartdocParser { break; } samples.add( - ApplicationSample( - input: block, - args: snippetArgs, - index: index++, - lineProto: line, - ), + ApplicationSample(input: block, args: snippetArgs, index: index++, lineProto: line), ); case 'dartpad': if (linkedFile != null) { @@ -264,16 +257,10 @@ class SnippetDartdocParser { break; } samples.add( - DartpadSample( - input: block, - args: snippetArgs, - index: index++, - lineProto: line, - ), + DartpadSample(input: block, args: snippetArgs, index: index++, lineProto: line), ); default: - throw SnippetException( - 'Unknown snippet type ${snippetArgs.first}'); + throw SnippetException('Unknown snippet type ${snippetArgs.first}'); } snippetArgs = []; block = []; @@ -299,18 +286,19 @@ class SnippetDartdocParser { } final RegExpMatch match = _filePointerRegex.firstMatch(trimmedLine)!; linkedFile = filesystem.file( - path.join(flutterRoot.absolute.path, match.namedGroup('file'))); + path.join(flutterRoot.absolute.path, match.namedGroup('file')), + ); } else { - block.add(line.copyWith( - text: line.text.replaceFirst(RegExp(r'\s*/// ?'), ''))); + block.add(line.copyWith(text: line.text.replaceFirst(RegExp(r'\s*/// ?'), ''))); } } else { if (_dartDocSampleEndRegex.hasMatch(trimmedLine)) { if (inDart) { throw SnippetException( - "Dart section didn't terminate before end of sample", - file: line.file?.path, - line: line.line); + "Dart section didn't terminate before end of sample", + file: line.file?.path, + line: line.line, + ); } } if (inDart) { @@ -344,10 +332,10 @@ class SnippetDartdocParser { } } if (!inSnippet && !inDart) { - final RegExpMatch? sampleMatch = - _dartDocSampleBeginRegex.firstMatch(trimmedLine); + final RegExpMatch? sampleMatch = _dartDocSampleBeginRegex.firstMatch(trimmedLine); if (sampleMatch != null) { - inSnippet = sampleMatch.namedGroup('type') == 'snippet' || + inSnippet = + sampleMatch.namedGroup('type') == 'snippet' || sampleMatch.namedGroup('type') == 'sample' || sampleMatch.namedGroup('type') == 'dartpad'; if (inSnippet) { @@ -355,12 +343,10 @@ class SnippetDartdocParser { // There are arguments to the snippet tool to keep track of. snippetArgs = [ sampleMatch.namedGroup('type')!, - ..._splitUpQuotedArgs(sampleMatch.namedGroup('args')!) + ..._splitUpQuotedArgs(sampleMatch.namedGroup('args')!), ]; } else { - snippetArgs = [ - sampleMatch.namedGroup('type')!, - ]; + snippetArgs = [sampleMatch.namedGroup('type')!]; } } } @@ -398,10 +384,11 @@ class SnippetDartdocParser { // Match group 3 (value) is a quoted arg, if any, without the quotes. // Match group 4 (unquoted) is the unquoted arg, if any. final RegExp argMatcher = RegExp( - r'(?