Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- novelforge-project/flutter/packages/flutter_tools/bin/analysis_options.yamlAdded+5
- novelforge-project/flutter/packages/flutter_tools/bin/flutter_tools.dartAdded+9
- novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dartAdded+117
- novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_tester.dartAdded+177
- novelforge-project/flutter/packages/flutter_tools/bin/macos_assemble.shAdded+196
- novelforge-project/flutter/packages/flutter_tools/bin/podhelper.rbAdded+359
- novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.batAdded+9
- novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.dartAdded+137
- novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.shAdded+9
- novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.dartAdded+455
- novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.shAdded+29
- novelforge-project/flutter/packages/flutter_tools/bin/xcode_debug.jsAdded+664
- novelforge-project/flutter/packages/flutter_tools/doc/attach.mdAdded+26
- novelforge-project/flutter/packages/flutter_tools/doc/daemon.mdAdded+316
- novelforge-project/flutter/packages/flutter_tools/gradle/aar_init_script.gradleAdded+151
- novelforge-project/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradleAdded+15
- novelforge-project/flutter/packages/flutter_tools/gradle/build.gradle.ktsAdded+35
- novelforge-project/flutter/packages/flutter_tools/gradle/flutter.gradleAdded+14
- novelforge-project/flutter/packages/flutter_tools/gradle/flutter_multidex_keepfile.txtAdded+5
- novelforge-project/flutter/packages/flutter_tools/gradle/flutter_proguard_rules.proAdded+7
- novelforge-project/flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.mdAdded+14
- novelforge-project/flutter/packages/flutter_tools/gradle/module_plugin_loader.gradleAdded+63
- novelforge-project/flutter/packages/flutter_tools/gradle/resolve_dependencies.gradleAdded+67
- novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.ktsAdded+7
- novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versionsAdded+59
- novelforge-project/flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmplAdded+1
- novelforge-project/flutter/packages/flutter_tools/lib/executable.dartAdded+308
- novelforge-project/flutter/packages/flutter_tools/lib/runner.dartAdded+292
- novelforge-project/flutter/packages/flutter_tools/static/Ahem.ttfAdded
- novelforge-project/flutter/packages/flutter_tools/static/custom-devices.schema.jsonAdded+139
- novelforge-project/flutter/packages/flutter_tools/static/index.htmlAdded+34
- novelforge-project/flutter/packages/flutter_tools/templates/README.mdAdded+25
- novelforge-project/flutter/packages/flutter_tools/templates/template_manifest.jsonAdded+369
- novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/README.mdAdded+5
- novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dartAdded+151
- novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dartAdded+135
- novelforge-project/flutter/packages/flutter_tools/test/commands.shard/README.mdAdded+10
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/analytics_test.dartAdded+412
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dartAdded+249
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dartAdded+269
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dartAdded+163
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_start_test.dartAdded+301
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dartAdded+717
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dartAdded+225
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dartAdded+1937
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dartAdded+318
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dartAdded+474
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_sdk_test.dartAdded+569
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dartAdded+1344
- novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dartAdded+110
12345include: ../analysis_options.yaml
linter: rules: avoid_print: false # These are CLI tools which print as a matter of course.123456789// 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 'package:flutter_tools/executable.dart' as executable;
void main(List<String> args) { executable.main(args);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117// 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 'package:args/args.dart';import 'package:flutter_tools/src/asset.dart' hide defaultManifestPath;import 'package:flutter_tools/src/base/common.dart';import 'package:flutter_tools/src/base/context.dart';import 'package:flutter_tools/src/base/file_system.dart' as libfs;import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/build_system/depfile.dart';import 'package:flutter_tools/src/bundle.dart';import 'package:flutter_tools/src/bundle_builder.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/context_runner.dart';import 'package:flutter_tools/src/devfs.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/reporting/reporting.dart';
const String _kOptionPackages = 'packages';const String _kOptionAsset = 'asset-dir';const String _kOptionManifest = 'manifest';const String _kOptionAssetManifestOut = 'asset-manifest-out';const String _kOptionComponentName = 'component-name';const String _kOptionDepfile = 'depfile';const List<String> _kRequiredOptions = <String>[ _kOptionPackages, _kOptionAsset, _kOptionAssetManifestOut, _kOptionComponentName,];
Future<void> main(List<String> args) { return runInContext<void>(() => run(args), overrides: <Type, Generator>{ Usage: () => DisabledUsage(), });}
Future<void> writeFile(libfs.File outputFile, DevFSContent content) async { outputFile.createSync(recursive: true); final List<int> data = await content.contentsAsBytes(); outputFile.writeAsBytesSync(data);}
Future<void> run(List<String> args) async { final ArgParser parser = ArgParser() ..addOption(_kOptionPackages, help: 'The .packages file') ..addOption(_kOptionAsset, help: 'The directory where to put temporary files') ..addOption(_kOptionManifest, help: 'The manifest file') ..addOption(_kOptionAssetManifestOut) ..addOption(_kOptionComponentName) ..addOption(_kOptionDepfile); final ArgResults argResults = parser.parse(args); if (_kRequiredOptions .any((String option) => !argResults.options.contains(option))) { globals.printError('Missing option! All options must be specified.'); exit(1); } Cache.flutterRoot = globals.platform.environment['FLUTTER_ROOT'];
final String assetDir = argResults[_kOptionAsset] as String; final AssetBundle? assets = await buildAssets( manifestPath: argResults[_kOptionManifest] as String? ?? defaultManifestPath, assetDirPath: assetDir, packagesPath: argResults[_kOptionPackages] as String?, targetPlatform: TargetPlatform.fuchsia_arm64 // This is not arch specific. );
if (assets == null) { throwToolExit('Unable to find assets.', exitCode: 1); }
final List<Future<void>> calls = <Future<void>>[]; assets.entries.forEach((String fileName, DevFSContent content) { final libfs.File outputFile = globals.fs.file(globals.fs.path.join(assetDir, fileName)); calls.add(writeFile(outputFile, content)); }); await Future.wait<void>(calls);
final String outputMan = argResults[_kOptionAssetManifestOut] as String; await writeFuchsiaManifest(assets, argResults[_kOptionAsset] as String, outputMan, argResults[_kOptionComponentName] as String);
final String? depfilePath = argResults[_kOptionDepfile] as String?; if (depfilePath != null) { await writeDepfile(assets, outputMan, depfilePath); }}
Future<void> writeDepfile(AssetBundle assets, String outputManifest, String depfilePath) async { final Depfile depfileContent = Depfile( assets.inputFiles, <libfs.File>[globals.fs.file(outputManifest)], ); final DepfileService depfileService = DepfileService( fileSystem: globals.fs, logger: globals.logger, );
final libfs.File depfile = globals.fs.file(depfilePath); await depfile.create(recursive: true); depfileService.writeToFile(depfileContent, depfile);}
Future<void> writeFuchsiaManifest(AssetBundle assets, String outputBase, String fileDest, String componentName) async {
final libfs.File destFile = globals.fs.file(fileDest); await destFile.create(recursive: true); final libfs.IOSink outFile = destFile.openWrite();
for (final String path in assets.entries.keys) { outFile.write('data/$componentName/$path=$outputBase/$path\n'); } await outFile.flush(); await outFile.close();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177// 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:convert' show json;import 'dart:math' as math;
import 'package:args/args.dart';import 'package:flutter_tools/src/artifacts.dart';import 'package:flutter_tools/src/base/common.dart';import 'package:flutter_tools/src/base/context.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/context_runner.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/reporting/reporting.dart';import 'package:flutter_tools/src/test/coverage_collector.dart';import 'package:flutter_tools/src/test/runner.dart';import 'package:flutter_tools/src/test/test_wrapper.dart';
const String _kOptionPackages = 'packages';const String _kOptionShell = 'shell';const String _kOptionTestDirectory = 'test-directory';const String _kOptionSdkRoot = 'sdk-root';const String _kOptionIcudtl = 'icudtl';const String _kOptionTests = 'tests';const String _kOptionCoverageDirectory = 'coverage-directory';const List<String> _kRequiredOptions = <String>[ _kOptionPackages, _kOptionShell, _kOptionSdkRoot, _kOptionIcudtl, _kOptionTests,];const String _kOptionCoverage = 'coverage';const String _kOptionCoveragePath = 'coverage-path';
void main(List<String> args) { runInContext<void>(() => run(args), overrides: <Type, Generator>{ Usage: () => DisabledUsage(), });}
Future<void> run(List<String> args) async { final ArgParser parser = ArgParser() ..addOption(_kOptionPackages, help: 'The .packages file') ..addOption(_kOptionShell, help: 'The Flutter shell binary') ..addOption(_kOptionTestDirectory, help: 'Directory containing the tests') ..addOption(_kOptionSdkRoot, help: 'Path to the SDK platform files') ..addOption(_kOptionIcudtl, help: 'Path to the ICU data file') ..addOption(_kOptionTests, help: 'Path to json file that maps Dart test files to precompiled dill files') ..addOption(_kOptionCoverageDirectory, help: 'The path to the directory that will have coverage collected') ..addFlag(_kOptionCoverage, negatable: false, help: 'Whether to collect coverage information.', ) ..addOption(_kOptionCoveragePath, defaultsTo: 'coverage/lcov.info', help: 'Where to store coverage information (if coverage is enabled).', ); final ArgResults argResults = parser.parse(args); if (_kRequiredOptions .any((String option) => !argResults.options.contains(option))) { throwToolExit('Missing option! All options must be specified.'); } final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.'); try { Cache.flutterRoot = tempDir.path;
final String shellPath = globals.fs.file(argResults[_kOptionShell]).resolveSymbolicLinksSync(); if (!globals.fs.isFileSync(shellPath)) { throwToolExit('Cannot find Flutter shell at $shellPath'); }
final Directory sdkRootSrc = globals.fs.directory(argResults[_kOptionSdkRoot]); if (!globals.fs.isDirectorySync(sdkRootSrc.path)) { throwToolExit('Cannot find SDK files at ${sdkRootSrc.path}'); } Directory? coverageDirectory; final String? coverageDirectoryPath = argResults[_kOptionCoverageDirectory] as String?; if (coverageDirectoryPath != null) { if (!globals.fs.isDirectorySync(coverageDirectoryPath)) { throwToolExit('Cannot find coverage directory at $coverageDirectoryPath'); } coverageDirectory = globals.fs.directory(coverageDirectoryPath); }
// Put the tester shell where runTests expects it. // TODO(garymm): Switch to a Fuchsia-specific Artifacts impl. final Artifacts artifacts = globals.artifacts!; final Link testerDestLink = globals.fs.link(artifacts.getArtifactPath(Artifact.flutterTester)); testerDestLink.parent.createSync(recursive: true); testerDestLink.createSync(globals.fs.path.absolute(shellPath));
final Directory sdkRootDest = globals.fs.directory(artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath)); sdkRootDest.createSync(recursive: true); for (final FileSystemEntity artifact in sdkRootSrc.listSync()) { globals.fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path); } // TODO(tvolkert): Remove once flutter_tester no longer looks for this. globals.fs.link(sdkRootDest.childFile('platform.dill').path).createSync('platform_strong.dill');
Directory? testDirectory; CoverageCollector? collector; if (argResults['coverage'] as bool? ?? false) { // If we have a specified coverage directory then accept all libraries by // setting libraryNames to null. final Set<String>? libraryNames = coverageDirectory != null ? null : <String>{FlutterProject.current().manifest.appName}; final String packagesPath = globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)); collector = CoverageCollector( packagesPath: packagesPath, libraryNames: libraryNames, resolver: await CoverageCollector.getResolver(packagesPath)); if (!argResults.options.contains(_kOptionTestDirectory)) { throwToolExit('Use of --coverage requires setting --test-directory'); } testDirectory = globals.fs.directory(argResults[_kOptionTestDirectory]); }
final Map<String, String> tests = <String, String>{}; final List<Map<String, dynamic>> jsonList = List<Map<String, dynamic>>.from( (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List<dynamic>).cast<Map<String, dynamic>>()); for (final Map<String, dynamic> map in jsonList) { final String source = globals.fs.file(map['source']).resolveSymbolicLinksSync(); final String dill = globals.fs.file(map['dill']).resolveSymbolicLinksSync(); tests[source] = dill; }
// TODO(dnfield): This should be injected. exitCode = await const FlutterTestRunner().runTests( const TestWrapper(), tests.keys.map(Uri.file).toList(), debuggingOptions: DebuggingOptions.enabled( BuildInfo( BuildMode.debug, '', treeShakeIcons: false, packagesPath: globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)), ), ), watcher: collector, enableVmService: collector != null, precompiledDillFiles: tests, concurrency: math.max(1, globals.platform.numberOfProcessors - 2), icudtlPath: globals.fs.path.absolute(argResults[_kOptionIcudtl] as String), coverageDirectory: coverageDirectory, );
if (collector != null) { // collector expects currentDirectory to be the root of the dart // package (i.e. contains lib/ and test/ sub-dirs). In some cases, // test files may appear to be in the root directory. if (coverageDirectory == null) { globals.fs.currentDirectory = testDirectory!.parent; } else { globals.fs.currentDirectory = testDirectory; } if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath] as String?, coverageDirectory: coverageDirectory)) { throwToolExit('Failed to collect coverage data'); } } } finally { tempDir.deleteSync(recursive: true); } // TODO(ianh): There's apparently some sort of lost async task keeping the // process open. Remove the next line once that's been resolved. exit(exitCode);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196#!/usr/bin/env bash# 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.
# TODO(zanderso): refactor this and xcode_backend.sh into one script# once iOS is using 'assemble'.RunCommand() { if [[ -n "$VERBOSE_SCRIPT_LOGGING" ]]; then echo "♦ $*" fi "$@" return $?}
EchoError() { echo "$@" 1>&2}
ParseFlutterBuildMode() { # Use FLUTTER_BUILD_MODE if it's set, otherwise use the Xcode build configuration name # This means that if someone wants to use an Xcode build config other than Debug/Profile/Release, # they _must_ set FLUTTER_BUILD_MODE so we know what type of artifact to build. local build_mode="$(echo "${FLUTTER_BUILD_MODE:-${CONFIGURATION}}" | tr "[:upper:]" "[:lower:]")"
case "$build_mode" in *release*) build_mode="release";; *profile*) build_mode="profile";; *debug*) build_mode="debug";; *) EchoError "========================================================================" EchoError "ERROR: Unknown FLUTTER_BUILD_MODE: ${build_mode}." EchoError "Valid values are 'Debug', 'Profile', or 'Release' (case insensitive)." EchoError "This is controlled by the FLUTTER_BUILD_MODE environment variable." EchoError "If that is not set, the CONFIGURATION environment variable is used." EchoError "" EchoError "You can fix this by either adding an appropriately named build" EchoError "configuration, or adding an appropriate value for FLUTTER_BUILD_MODE to the" EchoError ".xcconfig file for the current build configuration (${CONFIGURATION})." EchoError "========================================================================" exit -1;; esac echo "${build_mode}"}
BuildApp() { # Set the working directory to the project root local project_path="${SOURCE_ROOT}/.." RunCommand pushd "${project_path}" > /dev/null
# Set the target file. local target_path="lib/main.dart" if [[ -n "$FLUTTER_TARGET" ]]; then target_path="${FLUTTER_TARGET}" fi
# Use FLUTTER_BUILD_MODE if it's set, otherwise use the Xcode build configuration name # This means that if someone wants to use an Xcode build config other than Debug/Profile/Release, # they _must_ set FLUTTER_BUILD_MODE so we know what type of artifact to build. local build_mode="$(ParseFlutterBuildMode)"
if [[ -n "$LOCAL_ENGINE" ]]; then if [[ $(echo "$LOCAL_ENGINE" | tr "[:upper:]" "[:lower:]") != *"$build_mode"* ]]; then EchoError "========================================================================" EchoError "ERROR: Requested build with Flutter local engine at '${LOCAL_ENGINE}'" EchoError "This engine is not compatible with FLUTTER_BUILD_MODE: '${build_mode}'." EchoError "You can fix this by updating the LOCAL_ENGINE environment variable, or" EchoError "by running:" EchoError " flutter build macos --local-engine=host_${build_mode} --local-engine-host=host_${build_mode}" EchoError "or" EchoError " flutter build macos --local-engine=host_${build_mode}_unopt --local-engine-host=host_${build_mode}_unopt" EchoError "========================================================================" exit -1 fi fi if [[ -n "$LOCAL_ENGINE_HOST" ]]; then if [[ $(echo "$LOCAL_ENGINE_HOST" | tr "[:upper:]" "[:lower:]") != *"$build_mode"* ]]; then EchoError "========================================================================" EchoError "ERROR: Requested build with Flutter local engine at '${LOCAL_ENGINE_HOST}'" EchoError "This engine is not compatible with FLUTTER_BUILD_MODE: '${build_mode}'." EchoError "You can fix this by updating the LOCAL_ENGINE_HOST environment variable, or" EchoError "by running:" EchoError " flutter build macos --local-engine=host_${build_mode} --local-engine-host=host_${build_mode}" EchoError "or" EchoError " flutter build macos --local-engine=host_${build_mode}_unopt --local-engine-host=host_${build_mode}_unopt" EchoError "========================================================================" exit -1 fi fi
# The path where the input/output xcfilelists are stored. These are used by xcode # to conditionally skip this script phase if neither have changed. local ephemeral_dir="${SOURCE_ROOT}/Flutter/ephemeral" local build_inputs_path="${ephemeral_dir}/FlutterInputs.xcfilelist" local build_outputs_path="${ephemeral_dir}/FlutterOutputs.xcfilelist"
# Construct the "flutter assemble" argument array. Arguments should be added # as quoted string elements of the flutter_args array, otherwise an argument # (like a path) with spaces in it might be interpreted as two separate # arguments. local flutter_args=("${FLUTTER_ROOT}/bin/flutter") if [[ -n "$VERBOSE_SCRIPT_LOGGING" ]]; then flutter_args+=('--verbose') fi if [[ -n "$FLUTTER_ENGINE" ]]; then flutter_args+=("--local-engine-src-path=${FLUTTER_ENGINE}") fi if [[ -n "$LOCAL_ENGINE" ]]; then flutter_args+=("--local-engine=${LOCAL_ENGINE}") fi if [[ -n "$LOCAL_ENGINE_HOST" ]]; then flutter_args+=("--local-engine-host=${LOCAL_ENGINE_HOST}") fi flutter_args+=( "assemble" "--no-version-check" "-dTargetPlatform=darwin" "-dDarwinArchs=${ARCHS}" "-dTargetFile=${target_path}" "-dBuildMode=${build_mode}" "-dTreeShakeIcons=${TREE_SHAKE_ICONS}" "-dDartObfuscation=${DART_OBFUSCATION}" "-dSplitDebugInfo=${SPLIT_DEBUG_INFO}" "-dTrackWidgetCreation=${TRACK_WIDGET_CREATION}" "-dAction=${ACTION}" "-dFrontendServerStarterPath=${FRONTEND_SERVER_STARTER_PATH}" "--DartDefines=${DART_DEFINES}" "--ExtraGenSnapshotOptions=${EXTRA_GEN_SNAPSHOT_OPTIONS}" "--ExtraFrontEndOptions=${EXTRA_FRONT_END_OPTIONS}" "--build-inputs=${build_inputs_path}" "--build-outputs=${build_outputs_path}" "--output=${BUILT_PRODUCTS_DIR}" )
if [[ -n "$FLAVOR" ]]; then flutter_args+=("-dFlavor=${FLAVOR}") fi if [[ -n "$PERFORMANCE_MEASUREMENT_FILE" ]]; then flutter_args+=("--performance-measurement-file=${PERFORMANCE_MEASUREMENT_FILE}") fi if [[ -n "$BUNDLE_SKSL_PATH" ]]; then flutter_args+=("-dBundleSkSLPath=${BUNDLE_SKSL_PATH}") fi if [[ -n "$CODE_SIZE_DIRECTORY" ]]; then flutter_args+=("-dCodeSizeDirectory=${CODE_SIZE_DIRECTORY}") fi flutter_args+=("${build_mode}_macos_bundle_flutter_assets")
RunCommand "${flutter_args[@]}"}
# Adds the App.framework as an embedded binary, the flutter_assets as# resources, and the native assets.EmbedFrameworks() { # Embed App.framework from Flutter into the app (after creating the Frameworks directory # if it doesn't already exist). local xcode_frameworks_dir="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" RunCommand mkdir -p -- "${xcode_frameworks_dir}" RunCommand rsync -av --delete --filter "- .DS_Store" "${BUILT_PRODUCTS_DIR}/App.framework" "${xcode_frameworks_dir}"
# Embed the actual FlutterMacOS.framework that the Flutter app expects to run against, # which could be a local build or an arch/type specific build.
# Copy Xcode behavior and don't copy over headers or modules. RunCommand rsync -av --delete --filter "- .DS_Store" --filter "- Headers" --filter "- Modules" "${BUILT_PRODUCTS_DIR}/FlutterMacOS.framework" "${xcode_frameworks_dir}/"
# Sign the binaries we moved. if [[ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" ]]; then RunCommand codesign --force --verbose --sign "${EXPANDED_CODE_SIGN_IDENTITY}" -- "${xcode_frameworks_dir}/App.framework/App" RunCommand codesign --force --verbose --sign "${EXPANDED_CODE_SIGN_IDENTITY}" -- "${xcode_frameworks_dir}/FlutterMacOS.framework/FlutterMacOS" fi
# Copy the native assets. These do not have to be codesigned here because, # they are already codesigned in buildNativeAssetsMacOS. local project_path="${SOURCE_ROOT}/.." if [[ -n "$FLUTTER_APPLICATION_PATH" ]]; then project_path="${FLUTTER_APPLICATION_PATH}" fi local native_assets_path="${project_path}/${FLUTTER_BUILD_DIR}/native_assets/macos/" if [[ -d "$native_assets_path" ]]; then RunCommand rsync -av --filter "- .DS_Store" --filter "- native_assets.yaml" "${native_assets_path}" "${xcode_frameworks_dir}" fi}
# Main entry point.if [[ $# == 0 ]]; then # Unnamed entry point defaults to build. BuildAppelse case $1 in "build") BuildApp ;; "embed") EmbedFrameworks ;; esacfi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359# 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.
require 'json'
# Minimum CocoaPods Ruby version is 2.0.# Don't depend on features newer than that.
# Hook for Podfile setup, installation settings.## @example# flutter_ios_podfile_setup# target 'Runner' do# ...# enddef flutter_ios_podfile_setup; end
# Same as flutter_ios_podfile_setup for macOS.def flutter_macos_podfile_setup; end
# Add iOS build settings to pod targets.## @example# post_install do |installer|# installer.pods_project.targets.each do |target|# flutter_additional_ios_build_settings(target)# end# end# @param [PBXAggregateTarget] target Pod target.def flutter_additional_ios_build_settings(target) return unless target.platform_name == :ios
# [target.deployment_target] is a [String] formatted as "8.0". inherit_deployment_target = target.deployment_target[/\d+/].to_i < 12
# ARC code targeting iOS 8 does not build on Xcode 14.3. force_to_arc_supported_min = target.deployment_target[/\d+/].to_i < 9
# This podhelper script is at $FLUTTER_ROOT/packages/flutter_tools/bin. # Add search paths from $FLUTTER_ROOT/bin/cache/artifacts/engine. artifacts_dir = File.join('..', '..', '..', '..', 'bin', 'cache', 'artifacts', 'engine') debug_framework_dir = File.expand_path(File.join(artifacts_dir, 'ios', 'Flutter.xcframework'), __FILE__)
unless Dir.exist?(debug_framework_dir) # iOS artifacts have not been downloaded. raise "#{debug_framework_dir} must exist. If you're running pod install manually, make sure \"flutter precache --ios\" is executed first" end
release_framework_dir = File.expand_path(File.join(artifacts_dir, 'ios-release', 'Flutter.xcframework'), __FILE__) # Bundles are com.apple.product-type.bundle, frameworks are com.apple.product-type.framework. target_is_resource_bundle = target.respond_to?(:product_type) && target.product_type == 'com.apple.product-type.bundle'
target.build_configurations.each do |build_configuration| # Build both x86_64 and arm64 simulator archs for all dependencies. If a single plugin does not support arm64 simulators, # the app and all frameworks will fall back to x86_64. Unfortunately that case is not detectable in this script. # Therefore all pods must have a x86_64 slice available, or linking a x86_64 app will fail. build_configuration.build_settings['ONLY_ACTIVE_ARCH'] = 'NO' if build_configuration.type == :debug
# Workaround https://github.com/CocoaPods/CocoaPods/issues/11402, do not sign resource bundles. if target_is_resource_bundle build_configuration.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' build_configuration.build_settings['CODE_SIGNING_REQUIRED'] = 'NO' build_configuration.build_settings['CODE_SIGNING_IDENTITY'] = '-' build_configuration.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = '-' end
# ARC code targeting iOS 8 does not build on Xcode 14.3. Force to at least iOS 9. build_configuration.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0' if force_to_arc_supported_min
# Skip other updates if it's not a Flutter plugin (transitive dependency). next unless target.dependencies.any? { |dependency| dependency.name == 'Flutter' }
# Bitcode is deprecated, Flutter.framework bitcode blob will have been stripped. build_configuration.build_settings['ENABLE_BITCODE'] = 'NO'
# Profile can't be derived from the CocoaPods build configuration. Use release framework (for linking only). # TODO(stuartmorgan): Handle local engines here; see https://github.com/flutter/flutter/issues/132228 configuration_engine_dir = build_configuration.type == :debug ? debug_framework_dir : release_framework_dir Dir.new(configuration_engine_dir).each_child do |xcframework_file| next if xcframework_file.start_with?('.') # Hidden file, possibly on external disk. if xcframework_file.end_with?('-simulator') # ios-arm64_x86_64-simulator build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]'] = "\"#{configuration_engine_dir}/#{xcframework_file}\" $(inherited)" elsif xcframework_file.start_with?('ios-') # ios-arm64 build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]'] = "\"#{configuration_engine_dir}/#{xcframework_file}\" $(inherited)" # else Info.plist or another platform. end end build_configuration.build_settings['OTHER_LDFLAGS'] = '$(inherited) -framework Flutter'
build_configuration.build_settings['CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER'] = 'NO' # Suppress warning when pod supports a version lower than the minimum supported by Xcode (Xcode 12 - iOS 9). # This warning is harmless but confusing--it's not a bad thing for dependencies to support a lower version. # When deleted, the deployment version will inherit from the higher version derived from the 'Runner' target. # If the pod only supports a higher version, do not delete to correctly produce an error. build_configuration.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET' if inherit_deployment_target
# Override legacy Xcode 11 style VALID_ARCHS[sdk=iphonesimulator*]=x86_64 and prefer Xcode 12 EXCLUDED_ARCHS. build_configuration.build_settings['VALID_ARCHS[sdk=iphonesimulator*]'] = '$(ARCHS_STANDARD)' build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = '$(inherited) i386' build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphoneos*]'] = '$(inherited) armv7' endend
# Same as flutter_ios_podfile_setup for macOS.def flutter_additional_macos_build_settings(target) return unless target.platform_name == :osx
# [target.deployment_target] is a [String] formatted as "10.8". deployment_target_major, deployment_target_minor = target.deployment_target.match(/(\d+).?(\d*)/).captures
# ARC code targeting macOS 10.10 does not build on Xcode 14.3. force_to_arc_supported_min = !target.deployment_target.blank? && (deployment_target_major.to_i < 10) || (deployment_target_major.to_i == 10 && deployment_target_minor.to_i < 11)
# Suppress warning when pod supports a version lower than the minimum supported by the latest stable version of Xcode (currently 10.14). # This warning is harmless but confusing--it's not a bad thing for dependencies to support a lower version. inherit_deployment_target = !target.deployment_target.blank? && (deployment_target_major.to_i < 10) || (deployment_target_major.to_i == 10 && deployment_target_minor.to_i < 14)
# This podhelper script is at $FLUTTER_ROOT/packages/flutter_tools/bin. # Add search paths from $FLUTTER_ROOT/bin/cache/artifacts/engine. artifacts_dir = File.join('..', '..', '..', '..', 'bin', 'cache', 'artifacts', 'engine') debug_framework_dir = File.expand_path(File.join(artifacts_dir, 'darwin-x64'), __FILE__) release_framework_dir = File.expand_path(File.join(artifacts_dir, 'darwin-x64-release'), __FILE__) application_path = File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file) # Find the local engine path, if any. local_engine = application_path.nil? ? nil : flutter_get_local_engine_dir(File.join(application_path, 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'))
unless Dir.exist?(debug_framework_dir) # macOS artifacts have not been downloaded. raise "#{debug_framework_dir} must exist. If you're running pod install manually, make sure \"flutter precache --macos\" is executed first" end
target.build_configurations.each do |build_configuration| # ARC code targeting macOS 10.10 does not build on Xcode 14.3. Force to at least macOS 10.11. build_configuration.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.11' if force_to_arc_supported_min
# Skip other updates if it's not a Flutter plugin (transitive dependency). next unless target.dependencies.any? { |dependency| dependency.name == 'FlutterMacOS' }
# Profile can't be derived from the CocoaPods build configuration. Use release framework (for linking only). configuration_engine_dir = local_engine || (build_configuration.type == :debug ? debug_framework_dir : release_framework_dir) build_configuration.build_settings['FRAMEWORK_SEARCH_PATHS'] = "\"#{configuration_engine_dir}\" $(inherited)"
# When deleted, the deployment version will inherit from the higher version derived from the 'Runner' target. # If the pod only supports a higher version, do not delete to correctly produce an error. build_configuration.build_settings.delete 'MACOSX_DEPLOYMENT_TARGET' if inherit_deployment_target
# Avoid error about Pods-Runner not supporting provisioning profiles. # Framework signing is handled at the app layer, not per framework, so disallow individual signing. build_configuration.build_settings.delete 'EXPANDED_CODE_SIGN_IDENTITY' build_configuration.build_settings['CODE_SIGNING_REQUIRED'] = 'NO' build_configuration.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' endend
# Install pods needed to embed Flutter iOS engine and plugins.## @example# target 'Runner' do# flutter_install_all_ios_pods# end# @param [String] ios_application_path Path of the iOS directory of the Flutter app.# Optional, defaults to the Podfile directory.def flutter_install_all_ios_pods(ios_application_path = nil) flutter_install_ios_engine_pod(ios_application_path) flutter_install_plugin_pods(ios_application_path, '.symlinks', 'ios')end
# Same as flutter_install_all_ios_pods for macOS.def flutter_install_all_macos_pods(macos_application_path = nil) flutter_install_macos_engine_pod(macos_application_path) flutter_install_plugin_pods(macos_application_path, File.join('Flutter', 'ephemeral', '.symlinks'), 'macos')end
# Install iOS Flutter engine pod.## @example# target 'Runner' do# flutter_install_ios_engine_pod# end# @param [String] ios_application_path Path of the iOS directory of the Flutter app.# Optional, defaults to the Podfile directory.def flutter_install_ios_engine_pod(ios_application_path = nil) # defined_in_file is set by CocoaPods and is a Pathname to the Podfile. ios_application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file) raise 'Could not find iOS application path' unless ios_application_path
podspec_directory = File.join(ios_application_path, 'Flutter') copied_podspec_path = File.expand_path('Flutter.podspec', podspec_directory)
# Generate a fake podspec to represent the Flutter framework. # This is only necessary because plugin podspecs contain `s.dependency 'Flutter'`, and if this Podfile # does not add a `pod 'Flutter'` CocoaPods will try to download it from the CocoaPods trunk. File.open(copied_podspec_path, 'w') do |podspec| podspec.write <<~EOF # # This podspec is NOT to be published. It is only used as a local source! # This is a generated file; do not edit or check into version control. #
Pod::Spec.new do |s| s.name = 'Flutter' s.version = '1.0.0' s.summary = 'A UI toolkit for beautiful and fast apps.' s.homepage = 'https://flutter.dev' s.license = { :type => 'BSD' } s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s } s.ios.deployment_target = '12.0' # Framework linking is handled by Flutter tooling, not CocoaPods. # Add a placeholder to satisfy `s.dependency 'Flutter'` plugin podspecs. s.vendored_frameworks = 'path/to/nothing' end EOF end
# Keep pod path relative so it can be checked into Podfile.lock. pod 'Flutter', path: flutter_relative_path_from_podfile(podspec_directory)end
# Same as flutter_install_ios_engine_pod for macOS.def flutter_install_macos_engine_pod(mac_application_path = nil) # defined_in_file is set by CocoaPods and is a Pathname to the Podfile. mac_application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file) raise 'Could not find macOS application path' unless mac_application_path
copied_podspec_path = File.expand_path('FlutterMacOS.podspec', File.join(mac_application_path, 'Flutter', 'ephemeral'))
# Generate a fake podspec to represent the FlutterMacOS framework. # This is only necessary because plugin podspecs contain `s.dependency 'FlutterMacOS'`, and if this Podfile # does not add a `pod 'FlutterMacOS'` CocoaPods will try to download it from the CocoaPods trunk. File.open(copied_podspec_path, 'w') do |podspec| podspec.write <<~EOF # # This podspec is NOT to be published. It is only used as a local source! # This is a generated file; do not edit or check into version control. #
Pod::Spec.new do |s| s.name = 'FlutterMacOS' s.version = '1.0.0' s.summary = 'A UI toolkit for beautiful and fast apps.' s.homepage = 'https://flutter.dev' s.license = { :type => 'BSD' } s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s } s.osx.deployment_target = '10.14' # Framework linking is handled by Flutter tooling, not CocoaPods. # Add a placeholder to satisfy `s.dependency 'FlutterMacOS'` plugin podspecs. s.vendored_frameworks = 'path/to/nothing' end EOF end
# Keep pod path relative so it can be checked into Podfile.lock. pod 'FlutterMacOS', path: File.join('Flutter', 'ephemeral')end
# Install Flutter plugin pods.## @param [String] application_path Path of the directory of the Flutter app.# Optional, defaults to the Podfile directory.def flutter_install_plugin_pods(application_path = nil, relative_symlink_dir, platform) # defined_in_file is set by CocoaPods and is a Pathname to the Podfile. application_path ||= File.dirname(defined_in_file.realpath) if respond_to?(:defined_in_file) raise 'Could not find application path' unless application_path
# Prepare symlinks folder. We use symlinks to avoid having Podfile.lock # referring to absolute paths on developers' machines.
symlink_dir = File.expand_path(relative_symlink_dir, application_path) system('rm', '-rf', symlink_dir) # Avoid the complication of dependencies like FileUtils.
symlink_plugins_dir = File.expand_path('plugins', symlink_dir) system('mkdir', '-p', symlink_plugins_dir)
plugins_file = File.join(application_path, '..', '.flutter-plugins-dependencies') plugin_pods = flutter_parse_plugins_file(plugins_file, platform) plugin_pods.each do |plugin_hash| plugin_name = plugin_hash['name'] plugin_path = plugin_hash['path'] has_native_build = plugin_hash.fetch('native_build', true)
# iOS and macOS code can be shared in "darwin" directory, otherwise # respectively in "ios" or "macos" directories. shared_darwin_source = plugin_hash.fetch('shared_darwin_source', false) platform_directory = shared_darwin_source ? 'darwin' : platform next unless plugin_name && plugin_path && has_native_build symlink = File.join(symlink_plugins_dir, plugin_name) File.symlink(plugin_path, symlink)
# Keep pod path relative so it can be checked into Podfile.lock. relative = flutter_relative_path_from_podfile(symlink)
pod plugin_name, path: File.join(relative, platform_directory) endend
# .flutter-plugins-dependencies format documented at# https://flutter.dev/go/plugins-list-migrationdef flutter_parse_plugins_file(file, platform) file_path = File.expand_path(file) return [] unless File.exist? file_path
dependencies_file = File.read(file) dependencies_hash = JSON.parse(dependencies_file)
# dependencies_hash.dig('plugins', 'ios') not available until Ruby 2.3 return [] unless dependencies_hash.has_key?('plugins') return [] unless dependencies_hash['plugins'].has_key?(platform) dependencies_hash['plugins'][platform] || []end
def flutter_relative_path_from_podfile(path) # defined_in_file is set by CocoaPods and is a Pathname to the Podfile. project_directory_pathname = defined_in_file.dirname
pathname = Pathname.new File.expand_path(path) relative = pathname.relative_path_from project_directory_pathname relative.to_send
def flutter_parse_xcconfig_file(file) file_abs_path = File.expand_path(file) if !File.exist? file_abs_path return []; end entries = Hash.new skip_line_start_symbols = ["#", "/"] File.foreach(file_abs_path) { |line| next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } key_value_pair = line.split(pattern = '=') if key_value_pair.length == 2 entries[key_value_pair[0].strip()] = key_value_pair[1].strip(); else puts "Invalid key/value pair: #{line}" end } return entriesend
def flutter_get_local_engine_dir(xcconfig_file) file_abs_path = File.expand_path(xcconfig_file) if !File.exist? file_abs_path return nil end config = flutter_parse_xcconfig_file(xcconfig_file) local_engine = config['LOCAL_ENGINE'] base_dir = config['FLUTTER_ENGINE'] if !local_engine.nil? && !base_dir.nil? return File.join(base_dir, 'out', local_engine) end return nilend123456789@ECHO off
REM Copyright 2014 The Flutter Authors. All rights reserved.
REM Use of this source code is governed by a BSD-style license that can be
REM found in the LICENSE file.
set FLUTTER_BIN_DIR=%FLUTTER_ROOT%\bin
set DART_BIN_DIR=%FLUTTER_BIN_DIR%\cache\dart-sdk\bin
"%DART_BIN_DIR%\dart" "%FLUTTER_ROOT%\packages\flutter_tools\bin\tool_backend.dart" %*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137// 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.
// Do not add package imports to this file.import 'dart:convert'; // flutter_ignore: dart_convert_import.import 'dart:io'; // flutter_ignore: dart_io_import.
/// Executes the required Flutter tasks for a desktop build.Future<void> main(List<String> arguments) async { final String targetPlatform = arguments[0]; final String buildMode = arguments[1].toLowerCase();
final String? dartDefines = Platform.environment['DART_DEFINES']; final bool dartObfuscation = Platform.environment['DART_OBFUSCATION'] == 'true'; final String? frontendServerStarterPath = Platform.environment['FRONTEND_SERVER_STARTER_PATH']; final String? extraFrontEndOptions = Platform.environment['EXTRA_FRONT_END_OPTIONS']; final String? extraGenSnapshotOptions = Platform.environment['EXTRA_GEN_SNAPSHOT_OPTIONS']; final String? flutterEngine = Platform.environment['FLUTTER_ENGINE']; final String? flutterRoot = Platform.environment['FLUTTER_ROOT']; final String flutterTarget = Platform.environment['FLUTTER_TARGET'] ?? pathJoin(<String>['lib', 'main.dart']); final String? codeSizeDirectory = Platform.environment['CODE_SIZE_DIRECTORY']; final String? localEngine = Platform.environment['LOCAL_ENGINE']; final String? localEngineHost = Platform.environment['LOCAL_ENGINE_HOST']; final String? projectDirectory = Platform.environment['PROJECT_DIR']; final String? splitDebugInfo = Platform.environment['SPLIT_DEBUG_INFO']; final String? bundleSkSLPath = Platform.environment['BUNDLE_SKSL_PATH']; final bool trackWidgetCreation = Platform.environment['TRACK_WIDGET_CREATION'] == 'true'; final bool treeShakeIcons = Platform.environment['TREE_SHAKE_ICONS'] == 'true'; final bool verbose = Platform.environment['VERBOSE_SCRIPT_LOGGING'] == 'true'; final bool prefixedErrors = Platform.environment['PREFIXED_ERROR_LOGGING'] == 'true';
if (projectDirectory == null) { stderr.write('PROJECT_DIR environment variable must be set to the location of Flutter project to be built.'); exit(1); } if (flutterRoot == null || flutterRoot.isEmpty) { stderr.write('FLUTTER_ROOT environment variable must be set to the location of the Flutter SDK.'); exit(1); }
Directory.current = projectDirectory;
if (localEngine != null && !localEngine.contains(buildMode)) { stderr.write('''ERROR: Requested build with Flutter local engine at '$localEngine'This engine is not compatible with FLUTTER_BUILD_MODE: '$buildMode'.You can fix this by updating the LOCAL_ENGINE environment variable, orby running: flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_$buildModeor flutter build <platform> --local-engine=<platform>_${buildMode}_unopt --local-engine-host=host_${buildMode}_unopt========================================================================'''); exit(1); } if (localEngineHost != null && !localEngineHost.contains(buildMode)) { stderr.write('''ERROR: Requested build with Flutter local engine host at '$localEngineHost'This engine is not compatible with FLUTTER_BUILD_MODE: '$buildMode'.You can fix this by updating the LOCAL_ENGINE_HOST environment variable, orby running: flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_$buildModeor flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_${buildMode}_unopt========================================================================'''); exit(1); } final String flutterExecutable = pathJoin(<String>[ flutterRoot, 'bin', if (Platform.isWindows) 'flutter.bat' else 'flutter', ]); final String bundlePlatform = targetPlatform.startsWith('windows') ? 'windows' : targetPlatform; final String target = '${buildMode}_bundle_${bundlePlatform}_assets'; final Process assembleProcess = await Process.start( flutterExecutable, <String>[ if (verbose) '--verbose', if (prefixedErrors) '--prefixed-errors', if (flutterEngine != null) '--local-engine-src-path=$flutterEngine', if (localEngine != null) '--local-engine=$localEngine', if (localEngineHost != null) '--local-engine-host=$localEngineHost', 'assemble', '--no-version-check', '--output=build', '-dTargetPlatform=$targetPlatform', '-dTrackWidgetCreation=$trackWidgetCreation', '-dBuildMode=$buildMode', '-dTargetFile=$flutterTarget', '-dTreeShakeIcons="$treeShakeIcons"', '-dDartObfuscation=$dartObfuscation', if (bundleSkSLPath != null) '-dBundleSkSLPath=$bundleSkSLPath', if (codeSizeDirectory != null) '-dCodeSizeDirectory=$codeSizeDirectory', if (splitDebugInfo != null) '-dSplitDebugInfo=$splitDebugInfo', if (dartDefines != null) '--DartDefines=$dartDefines', if (extraGenSnapshotOptions != null) '--ExtraGenSnapshotOptions=$extraGenSnapshotOptions', if (frontendServerStarterPath != null) '-dFrontendServerStarterPath=$frontendServerStarterPath', if (extraFrontEndOptions != null) '--ExtraFrontEndOptions=$extraFrontEndOptions', target, ], ); assembleProcess.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen(stdout.writeln); assembleProcess.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(stderr.writeln);
if (await assembleProcess.exitCode != 0) { exit(1); }}
/// Perform a simple path join on the segments based on the current platform.////// Does not normalize paths that have repeated separators.String pathJoin(List<String> segments) { final String separator = Platform.isWindows ? r'\' : '/'; return segments.join(separator);}123456789#!/usr/bin/env bash# 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.
readonly flutter_bin_dir="${FLUTTER_ROOT}/bin"readonly dart_bin_dir="${flutter_bin_dir}/cache/dart-sdk/bin"
exec "${dart_bin_dir}/dart" "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.dart" "${@:1}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455// 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';
void main(List<String> arguments) { File? scriptOutputStreamFile; final String? scriptOutputStreamFileEnv = Platform.environment['SCRIPT_OUTPUT_STREAM_FILE']; if (scriptOutputStreamFileEnv != null && scriptOutputStreamFileEnv.isNotEmpty) { scriptOutputStreamFile = File(scriptOutputStreamFileEnv); } Context( arguments: arguments, environment: Platform.environment, scriptOutputStreamFile: scriptOutputStreamFile, ).run();}
/// Container for script arguments and environment variables.////// All interactions with the platform are broken into individual methods that/// can be overridden in tests.class Context { Context({ required this.arguments, required this.environment, File? scriptOutputStreamFile, }) { if (scriptOutputStreamFile != null) { scriptOutputStream = scriptOutputStreamFile.openSync(mode: FileMode.write); } }
final Map<String, String> environment; final List<String> arguments; RandomAccessFile? scriptOutputStream;
void run() { if (arguments.isEmpty) { // Named entry points were introduced in Flutter v0.0.7. stderr.write( 'error: Your Xcode project is incompatible with this version of Flutter. ' 'Run "rm -rf ios/Runner.xcodeproj" and "flutter create ." to regenerate.\n'); exit(-1); }
final String subCommand = arguments.first; switch (subCommand) { case 'build': buildApp(); case 'thin': // No-op, thinning is handled during the bundle asset assemble build target. break; case 'embed': embedFlutterFrameworks(); case 'embed_and_thin': // Thinning is handled during the bundle asset assemble build target, so just embed. embedFlutterFrameworks(); case 'test_vm_service_bonjour_service': // Exposed for integration testing only. addVmServiceBonjourService(); } }
bool existsFile(String path) { final File file = File(path); return file.existsSync(); }
/// Run given command in a synchronous subprocess. /// /// Will throw [Exception] if the exit code is not 0. ProcessResult runSync( String bin, List<String> args, { bool verbose = false, bool allowFail = false, String? workingDirectory, }) { if (verbose) { print('♦ $bin ${args.join(' ')}'); } final ProcessResult result = Process.runSync( bin, args, workingDirectory: workingDirectory, ); if (verbose) { print((result.stdout as String).trim()); } final String resultStderr = result.stderr.toString().trim(); if (resultStderr.isNotEmpty) { final StringBuffer errorOutput = StringBuffer(); if (result.exitCode != 0) { // "error:" prefix makes this show up as an Xcode compilation error. errorOutput.write('error: '); } errorOutput.write(resultStderr); echoError(errorOutput.toString()); } if (!allowFail && result.exitCode != 0) { throw Exception( 'Command "$bin ${args.join(' ')}" exited with code ${result.exitCode}', ); } return result; }
/// Log message to stderr. void echoError(String message) { stderr.writeln(message); }
/// Log message to stdout. void echo(String message) { stdout.write(message); }
/// Exit the application with the given exit code. /// /// Exists to allow overriding in tests. Never exitApp(int code) { exit(code); }
/// Return value from environment if it exists, else throw [Exception]. String environmentEnsure(String key) { final String? value = environment[key]; if (value == null) { throw Exception( 'Expected the environment variable "$key" to exist, but it was not found', ); } return value; }
// When provided with a pipe by the host Flutter build process, output to the // pipe goes to stdout of the Flutter build process directly. void streamOutput(String output) { scriptOutputStream?.writeStringSync('$output\n'); }
String parseFlutterBuildMode() { // Use FLUTTER_BUILD_MODE if it's set, otherwise use the Xcode build configuration name // This means that if someone wants to use an Xcode build config other than Debug/Profile/Release, // they _must_ set FLUTTER_BUILD_MODE so we know what type of artifact to build. final String? buildMode = (environment['FLUTTER_BUILD_MODE'] ?? environment['CONFIGURATION'])?.toLowerCase();
if (buildMode != null) { if (buildMode.contains('release')) { return 'release'; } if (buildMode.contains('profile')) { return 'profile'; } if (buildMode.contains('debug')) { return 'debug'; } } echoError('========================================================================'); echoError('ERROR: Unknown FLUTTER_BUILD_MODE: $buildMode.'); echoError("Valid values are 'Debug', 'Profile', or 'Release' (case insensitive)."); echoError('This is controlled by the FLUTTER_BUILD_MODE environment variable.'); echoError('If that is not set, the CONFIGURATION environment variable is used.'); echoError(''); echoError('You can fix this by either adding an appropriately named build'); echoError('configuration, or adding an appropriate value for FLUTTER_BUILD_MODE to the'); echoError('.xcconfig file for the current build configuration (${environment['CONFIGURATION']}).'); echoError('========================================================================'); exitApp(-1); }
/// Copies all files from [source] to [destination]. /// /// Does not copy `.DS_Store`. /// /// If [delete], delete extraneous files from [destination]. void runRsync( String source, String destination, { List<String> extraArgs = const <String>[], bool delete = false, }) { runSync( 'rsync', <String>[ '-8', // Avoid mangling filenames with encodings that do not match the current locale. '-av', if (delete) '--delete', '--filter', '- .DS_Store', ...extraArgs, source, destination, ], ); }
// Adds the App.framework as an embedded binary and the flutter_assets as // resources. void embedFlutterFrameworks() { // Embed App.framework from Flutter into the app (after creating the Frameworks directory // if it doesn't already exist). final String xcodeFrameworksDir = '${environment['TARGET_BUILD_DIR']}/${environment['FRAMEWORKS_FOLDER_PATH']}'; runSync( 'mkdir', <String>[ '-p', '--', xcodeFrameworksDir, ] ); runRsync( delete: true, '${environment['BUILT_PRODUCTS_DIR']}/App.framework', xcodeFrameworksDir, );
// Embed the actual Flutter.framework that the Flutter app expects to run against, // which could be a local build or an arch/type specific build. runRsync( delete: true, '${environment['BUILT_PRODUCTS_DIR']}/Flutter.framework', '$xcodeFrameworksDir/', );
// Copy the native assets. These do not have to be codesigned here because, // they are already codesigned in buildNativeAssetsMacOS. final String sourceRoot = environment['SOURCE_ROOT'] ?? ''; String projectPath = '$sourceRoot/..'; if (environment['FLUTTER_APPLICATION_PATH'] != null) { projectPath = environment['FLUTTER_APPLICATION_PATH']!; } final String flutterBuildDir = environment['FLUTTER_BUILD_DIR']!; final String nativeAssetsPath = '$projectPath/$flutterBuildDir/native_assets/ios/'; final bool verbose = (environment['VERBOSE_SCRIPT_LOGGING'] ?? '').isNotEmpty; if (Directory(nativeAssetsPath).existsSync()) { if (verbose) { print('♦ Copying native assets from $nativeAssetsPath.'); } runRsync( extraArgs: <String>[ '--filter', '- native_assets.yaml', ], nativeAssetsPath, xcodeFrameworksDir, ); } else if (verbose) { print("♦ No native assets to bundle. $nativeAssetsPath doesn't exist."); }
addVmServiceBonjourService(); }
// Add the vmService publisher Bonjour service to the produced app bundle Info.plist. void addVmServiceBonjourService() { // Skip adding Bonjour service settings when DISABLE_PORT_PUBLICATION is YES. // These settings are not needed if port publication is disabled. if (environment['DISABLE_PORT_PUBLICATION'] == 'YES') { return; }
final String buildMode = parseFlutterBuildMode();
// Debug and profile only. if (buildMode == 'release') { return; }
final String builtProductsPlist = '${environment['BUILT_PRODUCTS_DIR'] ?? ''}/${environment['INFOPLIST_PATH'] ?? ''}';
if (!existsFile(builtProductsPlist)) { // Very occasionally Xcode hasn't created an Info.plist when this runs. // The file will be present on re-run. echo( '${environment['INFOPLIST_PATH'] ?? ''} does not exist. Skipping ' '_dartVmService._tcp NSBonjourServices insertion. Try re-building to ' 'enable "flutter attach".'); return; }
// If there are already NSBonjourServices specified by the app (uncommon), // insert the vmService service name to the existing list. ProcessResult result = runSync( 'plutil', <String>[ '-extract', 'NSBonjourServices', 'xml1', '-o', '-', builtProductsPlist, ], allowFail: true, ); if (result.exitCode == 0) { runSync( 'plutil', <String>[ '-insert', 'NSBonjourServices.0', '-string', '_dartVmService._tcp', builtProductsPlist, ], ); } else { // Otherwise, add the NSBonjourServices key and vmService service name. runSync( 'plutil', <String>[ '-insert', 'NSBonjourServices', '-json', '["_dartVmService._tcp"]', builtProductsPlist, ], ); //fi }
// Don't override the local network description the Flutter app developer // specified (uncommon). This text will appear below the "Your app would // like to find and connect to devices on your local network" permissions // popup. result = runSync( 'plutil', <String>[ '-extract', 'NSLocalNetworkUsageDescription', 'xml1', '-o', '-', builtProductsPlist, ], allowFail: true, ); if (result.exitCode != 0) { runSync( 'plutil', <String>[ '-insert', 'NSLocalNetworkUsageDescription', '-string', 'Allow Flutter tools on your computer to connect and debug your application. This prompt will not appear on release builds.', builtProductsPlist, ], ); } }
void buildApp() { final bool verbose = environment['VERBOSE_SCRIPT_LOGGING'] != null && environment['VERBOSE_SCRIPT_LOGGING'] != ''; final String sourceRoot = environment['SOURCE_ROOT'] ?? ''; String projectPath = '$sourceRoot/..'; if (environment['FLUTTER_APPLICATION_PATH'] != null) { projectPath = environment['FLUTTER_APPLICATION_PATH']!; }
String targetPath = 'lib/main.dart'; if (environment['FLUTTER_TARGET'] != null) { targetPath = environment['FLUTTER_TARGET']!; }
final String buildMode = parseFlutterBuildMode();
// Warn the user if not archiving (ACTION=install) in release mode. final String? action = environment['ACTION']; if (action == 'install' && buildMode != 'release') { echo( 'warning: Flutter archive not built in Release mode. Ensure ' 'FLUTTER_BUILD_MODE is set to release or run "flutter build ios ' '--release", then re-run Archive from Xcode.', ); }
final List<String> flutterArgs = <String>[];
if (verbose) { flutterArgs.add('--verbose'); }
if (environment['FLUTTER_ENGINE'] != null && environment['FLUTTER_ENGINE']!.isNotEmpty) { flutterArgs.add('--local-engine-src-path=${environment['FLUTTER_ENGINE']}'); }
if (environment['LOCAL_ENGINE'] != null && environment['LOCAL_ENGINE']!.isNotEmpty) { flutterArgs.add('--local-engine=${environment['LOCAL_ENGINE']}'); }
if (environment['LOCAL_ENGINE_HOST'] != null && environment['LOCAL_ENGINE_HOST']!.isNotEmpty) { flutterArgs.add('--local-engine-host=${environment['LOCAL_ENGINE_HOST']}'); }
flutterArgs.addAll(<String>[ 'assemble', '--no-version-check', '--output=${environment['BUILT_PRODUCTS_DIR'] ?? ''}/', '-dTargetPlatform=ios', '-dTargetFile=$targetPath', '-dBuildMode=$buildMode', if (environment['FLAVOR'] != null) '-dFlavor=${environment['FLAVOR']}', '-dIosArchs=${environment['ARCHS'] ?? ''}', '-dSdkRoot=${environment['SDKROOT'] ?? ''}', '-dSplitDebugInfo=${environment['SPLIT_DEBUG_INFO'] ?? ''}', '-dTreeShakeIcons=${environment['TREE_SHAKE_ICONS'] ?? ''}', '-dTrackWidgetCreation=${environment['TRACK_WIDGET_CREATION'] ?? ''}', '-dDartObfuscation=${environment['DART_OBFUSCATION'] ?? ''}', '-dAction=${environment['ACTION'] ?? ''}', '-dFrontendServerStarterPath=${environment['FRONTEND_SERVER_STARTER_PATH'] ?? ''}', '--ExtraGenSnapshotOptions=${environment['EXTRA_GEN_SNAPSHOT_OPTIONS'] ?? ''}', '--DartDefines=${environment['DART_DEFINES'] ?? ''}', '--ExtraFrontEndOptions=${environment['EXTRA_FRONT_END_OPTIONS'] ?? ''}', ]);
if (environment['PERFORMANCE_MEASUREMENT_FILE'] != null && environment['PERFORMANCE_MEASUREMENT_FILE']!.isNotEmpty) { flutterArgs.add('--performance-measurement-file=${environment['PERFORMANCE_MEASUREMENT_FILE']}'); }
final String? expandedCodeSignIdentity = environment['EXPANDED_CODE_SIGN_IDENTITY']; if (expandedCodeSignIdentity != null && expandedCodeSignIdentity.isNotEmpty && environment['CODE_SIGNING_REQUIRED'] != 'NO') { flutterArgs.add('-dCodesignIdentity=$expandedCodeSignIdentity'); }
if (environment['BUNDLE_SKSL_PATH'] != null && environment['BUNDLE_SKSL_PATH']!.isNotEmpty) { flutterArgs.add('-dBundleSkSLPath=${environment['BUNDLE_SKSL_PATH']}'); }
if (environment['CODE_SIZE_DIRECTORY'] != null && environment['CODE_SIZE_DIRECTORY']!.isNotEmpty) { flutterArgs.add('-dCodeSizeDirectory=${environment['CODE_SIZE_DIRECTORY']}'); }
flutterArgs.add('${buildMode}_ios_bundle_flutter_assets');
final ProcessResult result = runSync( '${environmentEnsure('FLUTTER_ROOT')}/bin/flutter', flutterArgs, verbose: verbose, allowFail: true, workingDirectory: projectPath, // equivalent of RunCommand pushd "${project_path}" );
if (result.exitCode != 0) { echoError('Failed to package $projectPath.'); exitApp(-1); }
streamOutput('done'); streamOutput(' └─Compiling, linking and signing...');
echo('Project $projectPath built and packaged successfully.'); }}1234567891011121314151617181920212223242526272829#!/usr/bin/env bash# 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.
# exit on error, or usage of unset varset -euo pipefail
# Needed because if it is set, cd may print the path it changed to.unset CDPATH
function follow_links() ( cd -P "$(dirname -- "$1")" file="$PWD/$(basename -- "$1")" while [[ -h "$file" ]]; do cd -P "$(dirname -- "$file")" file="$(readlink -- "$file")" cd -P "$(dirname -- "$file")" file="$PWD/$(basename -- "$file")" done echo "$file")
PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")"BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"FLUTTER_ROOT="$BIN_DIR/../../.."DART="$FLUTTER_ROOT/bin/dart"
"$DART" "$BIN_DIR/xcode_backend.dart" "$@"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664// 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.
/** * @fileoverview OSA Script to interact with Xcode. Functionality includes * checking if a given project is open in Xcode, starting a debug session for * a given project, and stopping a debug session for a given project. */
'use strict';
/** * OSA Script `run` handler that is called when the script is run. When ran * with `osascript`, arguments are passed from the command line to the direct * parameter of the `run` handler as a list of strings. * * @param {?Array<string>=} args_array * @returns {!RunJsonResponse} The validated command. */function run(args_array = []) { let args; try { args = new CommandArguments(args_array); } catch (e) { return new RunJsonResponse(false, `Failed to parse arguments: ${e}`).stringify(); }
const xcodeResult = getXcode(args); if (xcodeResult.error != null) { return new RunJsonResponse(false, xcodeResult.error).stringify(); } const xcode = xcodeResult.result;
if (args.command === 'check-workspace-opened') { const result = getWorkspaceDocument(xcode, args); return new RunJsonResponse(result.error == null, result.error).stringify(); } else if (args.command === 'debug') { const result = debugApp(xcode, args); return new RunJsonResponse(result.error == null, result.error, result.result).stringify(); } else if (args.command === 'stop') { const result = stopApp(xcode, args); return new RunJsonResponse(result.error == null, result.error).stringify(); } else { return new RunJsonResponse(false, 'Unknown command').stringify(); }}
/** * Parsed and validated arguments passed from the command line. */class CommandArguments { /** * * @param {!Array<string>} args List of arguments passed from the command line. */ constructor(args) { this.command = this.validatedCommand(args[0]);
const parsedArguments = this.parseArguments(args);
this.xcodePath = this.validatedStringArgument('--xcode-path', parsedArguments['--xcode-path']); this.projectPath = this.validatedStringArgument('--project-path', parsedArguments['--project-path']); this.projectName = this.validatedStringArgument('--project-name', parsedArguments['--project-name']); this.expectedConfigurationBuildDir = this.validatedStringArgument( '--expected-configuration-build-dir', parsedArguments['--expected-configuration-build-dir'], ); this.workspacePath = this.validatedStringArgument('--workspace-path', parsedArguments['--workspace-path']); this.targetDestinationId = this.validatedStringArgument('--device-id', parsedArguments['--device-id']); this.targetSchemeName = this.validatedStringArgument('--scheme', parsedArguments['--scheme']); this.skipBuilding = this.validatedBoolArgument('--skip-building', parsedArguments['--skip-building']); this.launchArguments = this.validatedJsonArgument('--launch-args', parsedArguments['--launch-args']); this.closeWindowOnStop = this.validatedBoolArgument('--close-window', parsedArguments['--close-window']); this.promptToSaveBeforeClose = this.validatedBoolArgument('--prompt-to-save', parsedArguments['--prompt-to-save']); this.verbose = this.validatedBoolArgument('--verbose', parsedArguments['--verbose']);
if (this.verbose === true) { console.log(JSON.stringify(this)); } }
/** * Validates the command is available. * * @param {?string} command * @returns {!string} The validated command. * @throws Will throw an error if command is not recognized. */ validatedCommand(command) { const allowedCommands = ['check-workspace-opened', 'debug', 'stop']; if (allowedCommands.includes(command) === false) { throw `Unrecognized Command: ${command}`; }
return command; }
/** * Returns map of commands to map of allowed arguments. For each command, if * an argument flag is a key, than that flag is allowed for that command. If * the value for the key is true, then it is required for the command. * * @returns {!string} Map of commands to allowed and optionally required * arguments. */ argumentSettings() { return { 'check-workspace-opened': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--verbose': false, }, 'debug': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--project-name': true, '--expected-configuration-build-dir': false, '--device-id': true, '--scheme': true, '--skip-building': true, '--launch-args': true, '--verbose': false, }, 'stop': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--close-window': true, '--prompt-to-save': true, '--verbose': false, }, }; }
/** * Validates the flag is allowed for the current command. * * @param {!string} flag * @param {?string} value * @returns {!bool} * @throws Will throw an error if the flag is not allowed for the current * command and the value is not null, undefined, or empty. */ isArgumentAllowed(flag, value) { const isAllowed = this.argumentSettings()[this.command].hasOwnProperty(flag); if (isAllowed === false && (value != null && value !== '')) { throw `The flag ${flag} is not allowed for the command ${this.command}.`; } return isAllowed; }
/** * Validates required flag has a value. * * @param {!string} flag * @param {?string} value * @throws Will throw an error if the flag is required for the current * command and the value is not null, undefined, or empty. */ validateRequiredArgument(flag, value) { const isRequired = this.argumentSettings()[this.command][flag] === true; if (isRequired === true && (value == null || value === '')) { throw `Missing value for ${flag}`; } }
/** * Parses the command line arguments into an object. * * @param {!Array<string>} args List of arguments passed from the command line. * @returns {!Object.<string, string>} Object mapping flag to value. * @throws Will throw an error if flag does not begin with '--'. */ parseArguments(args) { const valuesPerFlag = {}; for (let index = 1; index < args.length; index++) { const entry = args[index]; let flag; let value; const splitIndex = entry.indexOf('='); if (splitIndex === -1) { flag = entry; value = args[index + 1];
// If the flag is allowed for the command, and the next value in the // array is null/undefined or also a flag, treat the flag like a boolean // flag and set the value to 'true'. if (this.isArgumentAllowed(flag) && (value == null || value.startsWith('--'))) { value = 'true'; } else { index++; } } else { flag = entry.substring(0, splitIndex); value = entry.substring(splitIndex + 1, entry.length + 1); } if (flag.startsWith('--') === false) { throw `Unrecognized Flag: ${flag}`; }
valuesPerFlag[flag] = value; } return valuesPerFlag; }
/** * Validates the flag is allowed and `value` is valid. If the flag is not * allowed for the current command, return `null`. * * @param {!string} flag * @param {?string} value * @returns {!string} * @throws Will throw an error if the flag is allowed and `value` is null, * undefined, or empty. */ validatedStringArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } this.validateRequiredArgument(flag, value); return value; }
/** * Validates the flag is allowed, validates `value` is valid, and converts * `value` to a boolean. A `value` of null, undefined, or empty, it will * return true. If the flag is not allowed for the current command, will * return `null`. * * @param {!string} flag * @param {?string} value * @returns {?boolean} * @throws Will throw an error if the flag is allowed and `value` is not * null, undefined, empty, 'true', or 'false'. */ validatedBoolArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } if (value == null || value === '') { return false; } if (value !== 'true' && value !== 'false') { throw `Invalid value for ${flag}`; } return value === 'true'; }
/** * Validates the flag is allowed, `value` is valid, and parses `value` as JSON. * If the flag is not allowed for the current command, will return `null`. * * @param {!string} flag * @param {?string} value * @returns {!Object} * @throws Will throw an error if the flag is allowed and the value is * null, undefined, or empty. Will also throw an error if parsing fails. */ validatedJsonArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } this.validateRequiredArgument(flag, value); try { return JSON.parse(value); } catch (e) { throw `Error parsing ${flag}: ${e}`; } }}
/** * Response to return in `run` function. */class RunJsonResponse { /** * * @param {!bool} success Whether the command was successful. * @param {?string=} errorMessage Defaults to null. * @param {?DebugResult=} debugResult Curated results from Xcode's debug * function. Defaults to null. */ constructor(success, errorMessage = null, debugResult = null) { this.status = success; this.errorMessage = errorMessage; this.debugResult = debugResult; }
/** * Converts this object to a JSON string. * * @returns {!string} * @throws Throws an error if conversion fails. */ stringify() { return JSON.stringify(this); }}
/** * Utility class to return a result along with a potential error. */class FunctionResult { /** * * @param {?Object} result * @param {?string=} error Defaults to null. */ constructor(result, error = null) { this.result = result; this.error = error; }}
/** * Curated results from Xcode's debug function. Mirrors parts of * `scheme action result` from Xcode's Script Editor dictionary. */class DebugResult { /** * * @param {!Object} result */ constructor(result) { this.completed = result.completed(); this.status = result.status(); this.errorMessage = result.errorMessage(); }}
/** * Get the Xcode application from the given path. Since macs can have multiple * Xcode version, we use the path to target the specific Xcode application. * If the Xcode app is not running, return null with an error. * * @param {!CommandArguments} args * @returns {!FunctionResult} Return either an `Application` (Mac Scripting class) * or null as the `result`. */function getXcode(args) { try { const xcode = Application(args.xcodePath); const isXcodeRunning = xcode.running();
if (isXcodeRunning === false) { return new FunctionResult(null, 'Xcode is not running'); }
return new FunctionResult(xcode); } catch (e) { return new FunctionResult(null, `Failed to get Xcode application: ${e}`); }}
/** * After setting the active run destination to the targeted device, uses Xcode * debug function from Mac Scripting for Xcode to install the app on the device * and start a debugging session using the 'run' or 'run without building' scheme * action (depending on `args.skipBuilding`). Waits for the debugging session * to start running. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Return either a `DebugResult` or null as the `result`. */function debugApp(xcode, args) { const workspaceResult = waitForWorkspaceToLoad(xcode, args); if (workspaceResult.error != null) { return new FunctionResult(null, workspaceResult.error); } const targetWorkspace = workspaceResult.result;
const destinationResult = getTargetDestination( targetWorkspace, args.targetDestinationId, args.verbose, ); if (destinationResult.error != null) { return new FunctionResult(null, destinationResult.error) }
// If expectedConfigurationBuildDir is available, ensure that it matches the // build settings. if (args.expectedConfigurationBuildDir != null && args.expectedConfigurationBuildDir !== '') { const updateResult = waitForConfigurationBuildDirToUpdate(targetWorkspace, args); if (updateResult.error != null) { return new FunctionResult(null, updateResult.error); } }
try { // Documentation from the Xcode Script Editor dictionary indicates that the // `debug` function has a parameter called `runDestinationSpecifier` which // is used to specify which device to debug the app on. It also states that // it should be the same as the xcodebuild -destination specifier. It also // states that if not specified, the `activeRunDestination` is used instead. // // Experimentation has shown that the `runDestinationSpecifier` does not work. // It will always use the `activeRunDestination`. To mitigate this, we set // the `activeRunDestination` to the targeted device prior to starting the debug. targetWorkspace.activeRunDestination = destinationResult.result;
const actionResult = targetWorkspace.debug({ scheme: args.targetSchemeName, skipBuilding: args.skipBuilding, commandLineArguments: args.launchArguments, });
// Wait until scheme action has started up to a max of 10 minutes. // This does not wait for app to install, launch, or start debug session. // Potential statuses include: not yet started/running/cancelled/failed/error occurred/succeeded. const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 10 * 60; // 10 minutes const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { if (actionResult.status() !== 'not yet started') { break; } if (args.verbose === true && i % verboseLogInterval === 0) { console.log(`Action result status: ${actionResult.status()}`); } delay(checkFrequencyInSeconds); }
return new FunctionResult(new DebugResult(actionResult)); } catch (e) { return new FunctionResult(null, `Failed to start debugging session: ${e}`); }}
/** * Iterates through available run destinations looking for one with a matching * `deviceId`. If device is not found, return null with an error. * * @param {!WorkspaceDocument} targetWorkspace A `WorkspaceDocument` (Xcode Mac * Scripting class). * @param {!string} deviceId * @param {?bool=} verbose Defaults to false. * @returns {!FunctionResult} Return either a `RunDestination` (Xcode Mac * Scripting class) or null as the `result`. */function getTargetDestination(targetWorkspace, deviceId, verbose = false) { try { for (let destination of targetWorkspace.runDestinations()) { const device = destination.device(); if (verbose === true && device != null) { console.log(`Device: ${device.name()} (${device.deviceIdentifier()})`); } if (device != null && device.deviceIdentifier() === deviceId) { return new FunctionResult(destination); } } return new FunctionResult( null, 'Unable to find target device. Ensure that the device is paired, ' + 'unlocked, connected, and has an iOS version at least as high as the ' + 'Minimum Deployment.', ); } catch (e) { return new FunctionResult(null, `Failed to get target destination: ${e}`); }}
/** * Waits for the workspace to load. If the workspace is not loaded or in the * process of opening, it will wait up to 10 minutes. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Return either a `WorkspaceDocument` (Xcode Mac * Scripting class) or null as the `result`. */function waitForWorkspaceToLoad(xcode, args) { try { const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 10 * 60; // 10 minutes const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { // Every 10 seconds, print the list of workspaces if verbose const verbose = args.verbose && i % verboseLogInterval === 0;
const workspaceResult = getWorkspaceDocument(xcode, args, verbose); if (workspaceResult.error == null) { const document = workspaceResult.result; if (document.loaded() === true) { return new FunctionResult(document, null); } } else if (verbose === true) { console.log(workspaceResult.error); } delay(checkFrequencyInSeconds); } return new FunctionResult(null, 'Timed out waiting for workspace to load'); } catch (e) { return new FunctionResult(null, `Failed to wait for workspace to load: ${e}`); }}
/** * Gets workspace opened in Xcode matching the projectPath or workspacePath * from the command line arguments. If workspace is not found, return null with * an error. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @param {?bool=} verbose Defaults to false. * @returns {!FunctionResult} Return either a `WorkspaceDocument` (Xcode Mac * Scripting class) or null as the `result`. */function getWorkspaceDocument(xcode, args, verbose = false) { const privatePrefix = '/private';
try { const documents = xcode.workspaceDocuments(); for (let document of documents) { const filePath = document.file().toString(); if (verbose === true) { console.log(`Workspace: ${filePath}`); } if (filePath === args.projectPath || filePath === args.workspacePath) { return new FunctionResult(document); } // Sometimes when the project is in a temporary directory, it'll be // prefixed with `/private` but the args will not. Remove the // prefix before matching. if (filePath.startsWith(privatePrefix) === true) { const filePathWithoutPrefix = filePath.slice(privatePrefix.length); if (filePathWithoutPrefix === args.projectPath || filePathWithoutPrefix === args.workspacePath) { return new FunctionResult(document); } } } } catch (e) { return new FunctionResult(null, `Failed to get workspace: ${e}`); } return new FunctionResult(null, `Failed to get workspace.`);}
/** * Stops all debug sessions in the target workspace. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Always returns null as the `result`. */function stopApp(xcode, args) { const workspaceResult = getWorkspaceDocument(xcode, args); if (workspaceResult.error != null) { return new FunctionResult(null, workspaceResult.error); } const targetDocument = workspaceResult.result;
try { targetDocument.stop();
if (args.closeWindowOnStop === true) { // Wait a couple seconds before closing Xcode, otherwise it'll prompt the // user to stop the app. delay(2);
targetDocument.close({ saving: args.promptToSaveBeforeClose === true ? 'ask' : 'no', }); } } catch (e) { return new FunctionResult(null, `Failed to stop app: ${e}`); } return new FunctionResult(null, null);}
/** * Gets resolved build setting for CONFIGURATION_BUILD_DIR and waits until its * value matches the `--expected-configuration-build-dir` argument. Waits up to * 2 minutes. * * @param {!WorkspaceDocument} targetWorkspace A `WorkspaceDocument` (Xcode Mac * Scripting class). * @param {!CommandArguments} args * @returns {!FunctionResult} Always returns null as the `result`. */function waitForConfigurationBuildDirToUpdate(targetWorkspace, args) { // Get the project let project; try { project = targetWorkspace.projects().find(x => x.name() == args.projectName); } catch (e) { return new FunctionResult(null, `Failed to find project ${args.projectName}: ${e}`); } if (project == null) { return new FunctionResult(null, `Failed to find project ${args.projectName}.`); }
// Get the target let target; try { // The target is probably named the same as the project, but if not, just use the first. const targets = project.targets(); target = targets.find(x => x.name() == args.projectName); if (target == null && targets.length > 0) { target = targets[0]; if (args.verbose) { console.log(`Failed to find target named ${args.projectName}, picking first target: ${target.name()}.`); } } } catch (e) { return new FunctionResult(null, `Failed to find target: ${e}`); } if (target == null) { return new FunctionResult(null, `Failed to find target.`); }
try { // Use the first build configuration (Debug). Any should do since they all // include Generated.xcconfig. const buildConfig = target.buildConfigurations()[0]; const buildSettings = buildConfig.resolvedBuildSettings().reverse();
// CONFIGURATION_BUILD_DIR is often at (reverse) index 225 for Xcode // projects, so check there first. If it's not there, search the build // settings (which can be a little slow). const defaultIndex = 225; let configurationBuildDirSettings; if (buildSettings[defaultIndex] != null && buildSettings[defaultIndex].name() === 'CONFIGURATION_BUILD_DIR') { configurationBuildDirSettings = buildSettings[defaultIndex]; } else { configurationBuildDirSettings = buildSettings.find(x => x.name() === 'CONFIGURATION_BUILD_DIR'); }
if (configurationBuildDirSettings == null) { // This should not happen, even if it's not set by Flutter, there should // always be a resolved build setting for CONFIGURATION_BUILD_DIR. return new FunctionResult(null, `Unable to find CONFIGURATION_BUILD_DIR.`); }
// Wait up to 2 minutes for the CONFIGURATION_BUILD_DIR to update to the // expected value. const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 2 * 60; // 2 minutes const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { const verbose = args.verbose && i % verboseLogInterval === 0;
const configurationBuildDir = configurationBuildDirSettings.value(); if (configurationBuildDir === args.expectedConfigurationBuildDir) { console.log(`CONFIGURATION_BUILD_DIR: ${configurationBuildDir}`); return new FunctionResult(null, null); } if (verbose) { console.log(`Current CONFIGURATION_BUILD_DIR: ${configurationBuildDir} while expecting ${args.expectedConfigurationBuildDir}`); } delay(checkFrequencyInSeconds); } return new FunctionResult(null, 'Timed out waiting for CONFIGURATION_BUILD_DIR to update.'); } catch (e) { return new FunctionResult(null, `Failed to get CONFIGURATION_BUILD_DIR: ${e}`); }}1234567891011121314151617181920212223242526# Flutter Attach
## Overview
A Flutter-command that attaches to applications that have been launchedwithout `flutter run` and provides a HotRunner (enabling hot reload/restart).
## Usage
There are three ways for the attach command to discover a running app:
1. If the platform is Fuchsia the module name must be provided, e.g. `$flutter attach --module=mod_name`. This can be called either before or afterthe application is started, attach will poll the device if it cannotimmediately discover the port1. On Android and iOS, just running `flutter attach` suffices. Flutter toolswill search for an already running Flutter app or module if available.Otherwise, the tool will wait for the next Flutter app or module to launchbefore attaching.1. If the app or module is already running and the specific VM Service port isknown, it can be explicitly provided to attach via the command-line, e.g.`$ flutter attach --debug-port 12345`
## Source
See the [source](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/commands/attach.dart) for the attach command.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316# Flutter Daemon
## Overview
The `flutter` command-line tool supports a daemon server mode for use by IDEs and other tools.
```flutter daemon```
It runs a persistent, JSON-RPC based server to communicate with devices. IDEs and other tools can start the flutter tool in this mode and get device addition and removal notifications, as well as being able to programmatically start and stop apps on those devices.
A set of `flutter daemon` commands/events are also exposed via `flutter run --machine` and `flutter attach --machine` which allow IDEs and tools to launch and attach to Flutter applications and interact to send commands like Hot Reload. The command and events that are available in these modes are documented at the bottom of this document.
## Protocol
The daemon speaks [JSON-RPC](http://json-rpc.org/) to clients. It uses stdin and stdout as the transport protocol. To send a command to the server, create your command as a JSON-RPC message, encode it to JSON, surround the encoded text with square brackets, and write it as one line of text to the stdin of the process:
```[{"method":"daemon.version","id":0}]```
The response will come back as a single line from stdout:
```[{"id":0,"result":"0.1.0"}]```
All requests and responses should be wrapped in square brackets. This ensures that the communications are resilient to stray output in the stdout/stdin stream.
`id` is an opaque type to the server, but ids should be unique for the life of the server. A response to a particular command will contain the id that was passed in for that command.
Each command should have a `method` field. This is in the form '`domain.command`'.
Any params for that command should be passed in through a `params` field. Here's an example request/response for the `device.getDevices` method:
```[{"method":"device.getDevices","id":2}]```
```[{"id":2,"result":[{"id":"702ABC1F-5EA5-4F83-84AB-6380CA91D39A","name":"iPhone 6","platform":"ios_x64","available":true}]}]```
Events that come from the server will have an `event` field containing the type of event, along with a `params` field.
```[{"event":"device.added","params":{"id":"1DD6786B-37D4-4355-AA15-B818A87A18B4","name":"iPhone XS Max","platform":"ios","emulator":true,"ephemeral":false,"platformType":"ios","category":"mobile"}}]```
## Domains and Commands
### daemon domain
#### daemon.version
The `version()` command responds with a String with the protocol version.
#### daemon.shutdown
The `shutdown()` command will terminate the flutter daemon. It is not necessary to call this before shutting down the daemon; it is perfectly acceptable to just kill the daemon process.
#### daemon.getSupportedPlatforms
The `getSupportedPlatforms()` command will enumerate all platforms supportedby the project located at the provided `projectRoot`. It returns a Map withthe key 'platformTypes' containing a Map of platform types to a Map with thefollowing entries:
- isSupported (bool) - whether or not the platform type is supported- reasons (List<Map<String, Object>>, only included if isSupported == false) - a list of reasons why the platform is not supported
The schema for each element in `reasons` is:
- reasonText (String) - a description of why the platform is not supported- fixText (String) - human readable instructions of how to fix this reason- fixCode (String) - stringified version of the `_ReasonCode` enum. To be usedby daemon clients who intend to auto-fix.
The possible platform types are the `PlatformType` enumeration in the lib/src/device.dart library.
#### Events
#### daemon.connected
The `daemon.connected` event is sent when the daemon starts. The `params` field will be a map with the following fields:
- `version`: The protocol version. This is the same version returned by the `version()` command.- `pid`: The `pid` of the daemon process.
#### daemon.log
This is sent when user-facing output is received. The `params` field will be a map with the field `log`. The `log` field is a string with the output text. If the output indicates an error, an `error` boolean field will be present, and set to `true`.
#### daemon.showMessage
The `daemon.showMessage` event is sent by the daemon when some if would be useful to show a message to the user. This could be an error notification or a notification that some development tools are not configured or not installed. The JSON message will contain an `event` field with the value `daemon.showMessage`, and a `params` field containing a map with `level`, `title`, and `message` fields. The valid options for `level` are `info`, `warning`, and `error`.
It is up to the client to decide how best to display the message; for some clients, it may map well to a toast style notification. There is an implicit contract that the daemon will not send too many messages over a reasonable period of time.
#### daemon.logMessage
The `daemon.logMessage` event is sent whenever a log message is created - either a status level message or an error. The JSON message will contain an `event` field with the value `daemon.logMessage`, and a `params` field containing a map with `level`, `message`, and (optionally) `stackTrace` fields.
Generally, clients won't display content from `daemon.logMessage` events unless they're set to a more verbose output mode.
### app domain
#### app.restart
The `restart()` restarts the given application. It returns a Map of `{ int code, String message }` to indicate success or failure in restarting the app. A `code` of `0` indicates success, and non-zero indicates a failure.
- `appId`: the id of a previously started app; this is required.- `fullRestart`: optional; whether to do a full (rather than an incremental) restart of the application- `reason`: optional; the reason for the full restart (eg. `save`, `manual`) for reporting purposes- `pause`: optional; when doing a hot restart the isolate should enter a paused mode- `debounce`: optional; whether to automatically debounce multiple requests sent in quick succession (this may introduce a short delay in processing the request)
#### app.reloadMethod (Removed)
This functionality was deprecated and removed after Flutter version 1.23.0
#### app.callServiceExtension
The `callServiceExtension()` allows clients to make arbitrary calls to service protocol extensions. It returns a `Map` - the result returned by the service protocol method.
- `appId`: the id of a previously started app; this is required.- `methodName`: the name of the service protocol extension to invoke; this is required.- `params`: an optional Map of parameters to pass to the service protocol extension.
#### app.detach
The `detach()` command takes one parameter, `appId`. It returns a `bool` to indicate success or failure in detaching from an app without stopping it.
- `appId`: the id of a previously started app; this is required.
#### app.stop
The `stop()` command takes one parameter, `appId`. It returns a `bool` to indicate success or failure in stopping an app.
- `appId`: the id of a previously started app; this is required.
#### Events
#### app.start
This is sent when an app is starting. The `params` field will be a map with the fields `appId`, `directory`, `deviceId`, `launchMode` (`run`/`attach`) and `mode` (`debug`, `profile`, `release`, `jit_release`).
#### app.debugPort
This is sent when a VM service port is available for a started app. The `params` field will be a map with the fields `appId`, `port`, and `wsUri`. Clients should prefer using the `wsUri` field in preference to synthesizing a URI using the `port` field. An optional field, `baseUri`, is populated if a path prefix is required for setting breakpoints on the target device.
#### app.started
This is sent once the application launch process is complete and the app is either paused before main() (if `startPaused` is true) or main() has begun running. When attaching, this even will be fired once attached. The `params` field will be a map containing the field `appId`.
#### app.log
This is sent when output is logged for a running application. The `params` field will be a map with the fields `appId` and `log`. The `log` field is a string with the output text. If the output indicates an error, an `error` boolean field will be present, and set to `true`.
#### app.progress
This is sent when an operation starts and again when it stops. When an operation starts, the event contains the fields `id`, an opaque identifier, and `message` containing text describing the operation. When that same operation ends, the event contains the same `id` field value as when the operation started, along with a `finished` bool field with the value true, but no `message` field.
#### app.stop
This is sent when an app is stopped or detached from. The `params` field will be a map with the field `appId`.
#### app.webLaunchUrl
This is sent once a web application is being served and available for the user to access. The `params` field will be a map with a string `url` field and a boolean `launched` indicating whether the application has already been launched in a browser (this will generally be true for a browser device unless `--no-web-browser-launch` was used, and false for the headless `web-server` device).
### Daemon-to-Editor Requests
These requests come _from_ the Flutter daemon and should be responded to by the client/editor.
#### app.exposeUrl
This request is enabled only if `flutter run` is run with the `--web-allow-expose-url` flag.
This request is sent by the server when it has a local URL that needs to be exposed to the end-user. This is to support running on a remote machine where a URL (for example `http://localhost:1234`) may not be directly accessible to the end-user. With this URL clients can perform tunneling and then provide the tunneled URL back to Flutter so that it can be used in code that will be executed on the end-users machine (for example when a web application needs to be able to connect back to a service like the DWDS debugging service).
This request will only be sent if a web application was run in a mode that requires mapped URLs (such as using `--no-web-browser-launch` for browser devices or the headless `web-server` device when debugging).
The request will contain an `id` field and a `params` field that is a map containing a string `url` field.
The response should be sent using the same `id` as the request with a `result` map containing the mapped `url` (or the same URL in the case where the client does not need to perform any mapping).
### device domain
#### device.getDevices
Return a list of all connected devices. The `params` field will be a List; each item is a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, `emulator` (a boolean) and `emulatorId`.
`category` is a string description of the kind of workflow the device supports. The current categories are "mobile", "web" and "desktop", or null if none.
`platformType` is a string description of the platform sub-folder the devicesupports. The current categories are "android", "ios", "linux", "macos","fuchsia", "windows", and "web". These are kept in sync with the response from `daemon.getSupportedPlatforms`.
`ephemeral` is a boolean which indicates where the device needs to be manually connected to a development machine. For example, a physical Android device is ephemeral, but the "web" device (that is always present) is not.
`emulatorId` is a string ID that matches the ID from `getEmulators` to allow clients to match running devices to the emulators that started them (for example to hide emulators that are already running). This field is not guaranteed to be populated even if a device was spawned from an emulator as it may require a successful connection to the device to retrieve it. In the case of a failed connection or the device is not an emulator, this field will be null.
#### device.enable
Turn on device polling. This will poll for newly connected devices, and fire `device.added` and `device.removed` events.
#### device.disable
Turn off device polling.
#### device.forward
Forward a host port to a device port. This call takes two required arguments, `deviceId` and `devicePort`, and one optional argument, `hostPort`. If `hostPort` is not specified, the host port will be any available port.
This method returns a map with a `hostPort` fieldset.
#### device.unforward
Removed a forwarded port. It takes `deviceId`, `devicePort`, and `hostPort` as required arguments.
#### Events
#### device.added
This is sent when a device is connected (and polling has been enabled via `enable()`). The `params` field will be a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, and `emulator`. For more information on `platform`, `category`, `platformType`, and `ephemeral` see `device.getDevices`.
#### device.removed
This is sent when a device is disconnected (and polling has been enabled via `enable()`). The `params` field will be a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, and `emulator`. For more information on `platform`, `category`, `platformType`, and `ephemeral` see `device.getDevices`.
### emulator domain
#### emulator.getEmulators
Return a list of all available emulators. The `params` field will be a List; each item is a map with the fields `id`, `name`, `category` and `platformType`. `category` and `platformType` values match the values described in `device.getDevices`.
#### emulator.launch
The `launch()` command allows launching an emulator/simulator by its `id`.
- `emulatorId`: the id of an emulator as returned by `getEmulators`.- `coldBoot`: an optional boolean flag which indicates if the emulator should be cold booted. Only supported for android emulators, silently ignored if emulator type is not android.
#### emulator.create
The `create()` command creates a new Android emulator with an optional `name`.
- `name`: an optional name for this emulator
The returned `params` will contain:
- `success` - whether the emulator was successfully created- `emulatorName` - the name of the emulator created; this will have been auto-generated if you did not supply one- `error` - when `success`=`false`, a message explaining why the creation of the emulator failed
### devtools domain
#### devtools.serve
The `serve()` command starts a DevTools server if one isn't already running. The return value will contain:
- `success` - whether the server started.- `host` - the address host if the server successfully started.- `port` - the port if the server successfully started.
## 'flutter run --machine' and 'flutter attach --machine'
When running `flutter run --machine` or `flutter attach --machine` the following subset of the daemon is available:
### daemon domain
The following subset of the daemon domain is available in `flutter run --machine`. Refer to the documentation above for details.
- Commands - [`version`](#daemonversion) - [`shutdown`](#daemonshutdown)- Events - [`connected`](#daemonconnected) - [`log`](#daemonlog) - [`logMessage`](#daemonlogmessage)
### app domain
The following subset of the app domain is available in `flutter run --machine`. Refer to the documentation above for details.
- Commands - [`restart`](#apprestart) - [`callServiceExtension`](#appcallserviceextension) - [`detach`](#appdetach) - [`stop`](#appstop)- Events - [`start`](#appstart) - [`debugPort`](#appdebugport) - [`started`](#appstarted) - [`log`](#applog) - [`progress`](#appprogress) - [`stop`](#appstop)
## Source
See the [source](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/commands/daemon.dart) for the daemon protocol and implementation.
## Changelog
- 0.6.1: Added `coldBoot` option to `emulator.launch` command.- 0.6.0: Added `debounce` option to `app.restart` command.- 0.5.3: Added `emulatorId` field to device.- 0.5.2: Added `platformType` and `category` fields to emulator.- 0.5.1: Added `platformType`, `ephemeral`, and `category` fields to device.- 0.5.0: Added `daemon.getSupportedPlatforms` command- 0.4.2: Added `app.detach` command- 0.4.1: Added `flutter attach --machine`- 0.4.0: Added `emulator.create` command- 0.3.0: Added `daemon.connected` event at startup123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151// This script is used to initialize the build in a module or plugin project.// During this phase, the script applies the Maven plugin and configures the// destination of the local repository.// The local repository will contain the AAR and POM files.
import java.nio.file.Pathsimport org.gradle.api.Projectimport org.gradle.api.artifacts.Configurationimport org.gradle.api.publish.maven.MavenPublication
void configureProject(Project project, String outputDir) { if (!project.hasProperty("android")) { throw new GradleException("Android property not found.") } if (!project.android.hasProperty("libraryVariants")) { throw new GradleException("Can't generate AAR on a non Android library project."); }
// Snapshot versions include the timestamp in the artifact name. // Therefore, remove the snapshot part, so new runs of `flutter build aar` overrides existing artifacts. // This version isn't relevant in Flutter since the pub version is used // to resolve dependencies. project.version = project.version.replace("-SNAPSHOT", "")
if (project.hasProperty("buildNumber")) { project.version = project.property("buildNumber") }
project.components.forEach { component -> if (component.name != "all") { addAarTask(project, component) } }
project.publishing { repositories { maven { url = uri("file://${outputDir}/outputs/repo") } } }
if (!project.property("is-plugin").toBoolean()) { return }
String storageUrl = System.getenv('FLUTTER_STORAGE_BASE_URL') ?: "https://storage.googleapis.com"
String engineRealm = Paths.get(getFlutterRoot(project), "bin", "internal", "engine.realm") .toFile().text.trim() if (engineRealm) { engineRealm = engineRealm + "/" }
// This is a Flutter plugin project. Plugin projects don't apply the Flutter Gradle plugin, // as a result, add the dependency on the embedding. project.repositories { maven { url "$storageUrl/${engineRealm}download.flutter.io" } } String engineVersion = Paths.get(getFlutterRoot(project), "bin", "internal", "engine.version") .toFile().text.trim() project.dependencies { // Add the embedding dependency. compileOnly ("io.flutter:flutter_embedding_release:1.0.0-$engineVersion") { // We only need to expose io.flutter.plugin.* // No need for the embedding transitive dependencies. transitive = false } }}
void configurePlugin(Project project, String outputDir) { if (!project.hasProperty("android")) { // A plugin doesn't support the Android platform when this property isn't defined in the plugin. return } configureProject(project, outputDir)}
String getFlutterRoot(Project project) { if (!project.hasProperty("flutter-root")) { throw new GradleException("The `-Pflutter-root` flag must be specified.") } return project.property("flutter-root")}
void addAarTask(Project project, component) { String variantName = component.name.capitalize() String taskName = "assembleAar$variantName" project.tasks.create(name: taskName) { // This check is required to be able to configure the archives before `publish` runs. if (!project.gradle.startParameter.taskNames.contains(taskName)) { return }
// Create a default MavenPublication for the variant (except "all" since that is used to publish artifacts in the new way) project.publishing.publications.create(component.name, MavenPublication) { pub -> groupId = "${pub.groupId}" artifactId = "${pub.artifactId}_${pub.name}" version = "${pub.version}" from component }
// Generate the Maven artifacts. finalizedBy "publish" }}
// maven-publish has to be applied _before_ the project gets evaluated, but some of the code in// `configureProject` requires the project to be evaluated. Apply the maven plugin to all projects, but// only configure it if it matches the conditions in `projectsEvaluated`
allprojects { apply plugin: "maven-publish"}
projectsEvaluated { assert rootProject.hasProperty("is-plugin") if (rootProject.property("is-plugin").toBoolean()) { assert rootProject.hasProperty("output-dir") // In plugin projects, the root project is the plugin. configureProject(rootProject, rootProject.property("output-dir")) return } // The module project is the `:flutter` subproject. Project moduleProject = rootProject.subprojects.find { it.name == "flutter" } assert moduleProject != null assert moduleProject.hasProperty("output-dir") configureProject(moduleProject, moduleProject.property("output-dir"))
// Gets the plugin subprojects. Set<Project> modulePlugins = rootProject.subprojects.findAll { it.name != "flutter" && it.name != "app" } // When a module is built as a Maven artifacts, plugins must also be built this way // because the module POM's file will include a dependency on the plugin Maven artifact. // This is due to the Android Gradle Plugin expecting all library subprojects to be published // as Maven artifacts. modulePlugins.each { pluginProject -> configurePlugin(pluginProject, moduleProject.property("output-dir")) moduleProject.android.libraryVariants.all { variant -> // Configure the `assembleAar<variantName>` task for each plugin's projects and make // the module's equivalent task depend on the plugin's task. String variantName = variant.name.capitalize() moduleProject.tasks.findByPath("assembleAar$variantName") .dependsOn(pluginProject.tasks.findByPath("assembleAar$variantName")) } }}123456789101112131415// 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.
// This file exists solely for the compatibility with projects that have// not migrated to the declarative apply of the Flutter App Plugin Loader Gradle Plugin.
logger.error("You are applying Flutter's app_plugin_loader Gradle plugin \imperatively using the apply script method, which is deprecated and will be \removed in a future release. Migrate to applying Gradle plugins with the \declarative plugins block: https://flutter.dev/go/flutter-gradle-plugin-apply\n\")
def pathToThisDirectory = buildscript.sourceFile.parentFileapply from: "$pathToThisDirectory/src/main/groovy/app_plugin_loader.groovy"1234567891011121314151617181920212223242526272829303132333435// 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.
plugins { `java-gradle-plugin` `groovy`}
group = "dev.flutter.plugin"version = "1.0.0"
gradlePlugin { plugins { // The "flutterPlugin" name isn't used anywhere. create("flutterPlugin") { id = "dev.flutter.flutter-gradle-plugin" implementationClass = "FlutterPlugin" } // The "flutterAppPluginLoaderPlugin" name isn't used anywhere. create("flutterAppPluginLoaderPlugin") { id = "dev.flutter.flutter-plugin-loader" implementationClass = "FlutterAppPluginLoaderPlugin" } }}
dependencies { // When bumping, also update: // * ndkVersion in FlutterExtension in packages/flutter_tools/gradle/src/main/flutter.groovy // * AGP version constants in packages/flutter_tools/lib/src/android/gradle_utils.dart // * AGP version in buildscript block in packages/flutter_tools/gradle/src/main/flutter.groovy compileOnly("com.android.tools.build:gradle:7.3.0")}1234567891011121314// 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.
// This file exists solely for the compatibility with projects that have// not migrated to the declarative apply of the Flutter Gradle Plugin.
logger.error("You are applying Flutter's main Gradle plugin imperatively using \the apply script method, which is deprecated and will be removed in a future \release. Migrate to applying Gradle plugins with the declarative plugins \block: https://flutter.dev/go/flutter-gradle-plugin-apply\n")
def pathToThisDirectory = buildscript.sourceFile.parentFileapply from: "$pathToThisDirectory/src/main/groovy/flutter.groovy"12345io/flutter/app/FlutterApplication.classio/flutter/app/FlutterMultiDexApplication.classio/flutter/embedding/engine/loader/FlutterLoader.classio/flutter/view/FlutterMain.classio/flutter/util/PathUtils.class1234567# Build the ephemeral app in a module project.# Prevents: Warning: library class <plugin-package> depends on program class io.flutter.plugin.**# This is due to plugins (libraries) depending on the embedding (the program jar)-dontwarn io.flutter.plugin.**
# The android.** package is provided by the OS at runtime.-dontwarn android.**1234567891011121314To manually update `settings.gradle`, follow these steps:
1. Copy `settings.gradle` as `settings_aar.gradle` 2. Remove the following code from `settings_aar.gradle`:
def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties()
assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// 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.
// This file is included from `<module>/.android/include_flutter.groovy`,// so it can be versioned with the Flutter SDK.
import groovy.json.JsonSlurper
def moduleProjectRoot = project(':flutter').projectDir.parentFile.parentFile
def object = null;String flutterModulePath = project(':flutter').projectDir.parentFile.getAbsolutePath()// If this logic is changed, also change the logic in app_plugin_loader.gradle.def pluginsFile = new File(moduleProjectRoot, '.flutter-plugins-dependencies')if (pluginsFile.exists()) { object = new JsonSlurper().parseText(pluginsFile.text) assert object instanceof Map assert object.plugins instanceof Map assert object.plugins.android instanceof List // Includes the Flutter plugins that support the Android platform. object.plugins.android.each { androidPlugin -> assert androidPlugin.name instanceof String assert androidPlugin.path instanceof String // Skip plugins that have no native build (such as a Dart-only // implementation of a federated plugin). def needsBuild = androidPlugin.containsKey('native_build') ? androidPlugin['native_build'] : true if (!needsBuild) { return } def pluginDirectory = new File(androidPlugin.path, 'android') assert pluginDirectory.exists() include ":${androidPlugin.name}" project(":${androidPlugin.name}").projectDir = pluginDirectory }}
gradle.getGradle().projectsLoaded { g -> g.rootProject.beforeEvaluate { p -> p.subprojects { subproject -> if (object != null && object.plugins != null && object.plugins.android != null && object.plugins.android.name.contains(subproject.name)) { File androidPluginBuildOutputDir = new File(flutterModulePath + File.separator + "plugins_build_output" + File.separator + subproject.name); if (!androidPluginBuildOutputDir.exists()) { androidPluginBuildOutputDir.mkdirs() } subproject.buildDir = androidPluginBuildOutputDir } } def _mainModuleName = binding.variables['mainModuleName'] if (_mainModuleName != null && !_mainModuleName.empty) { p.ext.mainModuleName = _mainModuleName } } g.rootProject.afterEvaluate { p -> p.subprojects { sp -> if (sp.name != 'flutter') { sp.evaluationDependsOn(':flutter') } } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667// This script is used to warm the Gradle cache by downloading the Flutter dependencies// used during the build. This script is invoked when `flutter precache` is run.//// Command:// gradle -b <flutter-sdk>packages/flutter_tools/gradle/resolve_dependencies.gradle// resolveDependencies//// This way, Gradle can run with the `--offline` flag later on to eliminate any// network request during the build process.//// This includes:// 1. The embedding// 2. libflutter.so
import java.nio.file.Paths
String storageUrl = System.getenv('FLUTTER_STORAGE_BASE_URL') ?: "https://storage.googleapis.com"
String engineRealm = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.realm") .toFile().text.trim()if (engineRealm) { engineRealm = engineRealm + "/"}
repositories { google() mavenCentral() maven { url "$storageUrl/${engineRealm}download.flutter.io" }}
File flutterRoot = projectDir.parentFile.parentFile.parentFile
assert flutterRoot.isDirectory()String engineVersion = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.version") .toFile().text.trim()
configurations { flutterRelease.extendsFrom releaseImplementation flutterDebug.extendsFrom debugImplementation flutterProfile.extendsFrom debugImplementation}
dependencies { flutterRelease "io.flutter:flutter_embedding_release:1.0.0-$engineVersion" flutterRelease "io.flutter:armeabi_v7a_release:1.0.0-$engineVersion" flutterRelease "io.flutter:arm64_v8a_release:1.0.0-$engineVersion"
flutterProfile "io.flutter:flutter_embedding_profile:1.0.0-$engineVersion" flutterProfile "io.flutter:armeabi_v7a_profile:1.0.0-$engineVersion" flutterProfile "io.flutter:arm64_v8a_profile:1.0.0-$engineVersion"
flutterDebug "io.flutter:flutter_embedding_debug:1.0.0-$engineVersion" flutterDebug "io.flutter:armeabi_v7a_debug:1.0.0-$engineVersion" flutterDebug "io.flutter:arm64_v8a_debug:1.0.0-$engineVersion" flutterDebug "io.flutter:x86_debug:1.0.0-$engineVersion" flutterDebug "io.flutter:x86_64_debug:1.0.0-$engineVersion"}
task resolveDependencies { configurations.each { configuration -> if (configuration.name.startsWith("flutter")) { configuration.resolve() } }}1234567dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')if (pluginsFile.exists()) { pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }}
plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory};EOFinclude ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')if (pluginsFile.exists()) { pluginsFile.withInputStream { stream -> plugins.load(stream) }}
plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory};EOF// 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.
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")def properties = new Properties()
assert localPropertiesFile.exists()localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")assert flutterSdkPath != null, "flutter.sdk not set in local.properties"apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle";EOFinclude ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")def properties = new Properties()
assert localPropertiesFile.exists()localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")assert flutterSdkPath != null, "flutter.sdk not set in local.properties"apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"1include ':app'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308// 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 'runner.dart' as runner;import 'src/artifacts.dart';import 'src/base/context.dart';import 'src/base/io.dart';import 'src/base/logger.dart';import 'src/base/platform.dart';import 'src/base/template.dart';import 'src/base/terminal.dart';import 'src/base/user_messages.dart';import 'src/cache.dart';import 'src/commands/analyze.dart';import 'src/commands/assemble.dart';import 'src/commands/attach.dart';import 'src/commands/build.dart';import 'src/commands/channel.dart';import 'src/commands/clean.dart';import 'src/commands/config.dart';import 'src/commands/create.dart';import 'src/commands/custom_devices.dart';import 'src/commands/daemon.dart';import 'src/commands/debug_adapter.dart';import 'src/commands/devices.dart';import 'src/commands/doctor.dart';import 'src/commands/downgrade.dart';import 'src/commands/drive.dart';import 'src/commands/emulators.dart';import 'src/commands/generate.dart';import 'src/commands/generate_localizations.dart';import 'src/commands/ide_config.dart';import 'src/commands/install.dart';import 'src/commands/logs.dart';import 'src/commands/make_host_app_editable.dart';import 'src/commands/packages.dart';import 'src/commands/precache.dart';import 'src/commands/run.dart';import 'src/commands/screenshot.dart';import 'src/commands/shell_completion.dart';import 'src/commands/symbolize.dart';import 'src/commands/test.dart';import 'src/commands/update_packages.dart';import 'src/commands/upgrade.dart';import 'src/devtools_launcher.dart';import 'src/features.dart';import 'src/globals.dart' as globals;// Files in `isolated` are intentionally excluded from google3 tooling.import 'src/isolated/mustache_template.dart';import 'src/isolated/resident_web_runner.dart';import 'src/pre_run_validator.dart';import 'src/project_validator.dart';import 'src/resident_runner.dart';import 'src/runner/flutter_command.dart';import 'src/web/web_runner.dart';
/// Main entry point for commands.////// This function is intended to be used from the `flutter` command line tool.Future<void> main(List<String> args) async { final bool veryVerbose = args.contains('-vv'); final bool verbose = args.contains('-v') || args.contains('--verbose') || veryVerbose; final bool prefixedErrors = args.contains('--prefixed-errors'); // Support the -? Powershell help idiom. final int powershellHelpIndex = args.indexOf('-?'); if (powershellHelpIndex != -1) { args[powershellHelpIndex] = '-h'; }
final bool doctor = (args.isNotEmpty && args.first == 'doctor') || (args.length == 2 && verbose && args.last == 'doctor'); final bool help = args.contains('-h') || args.contains('--help') || (args.isNotEmpty && args.first == 'help') || (args.length == 1 && verbose); final bool muteCommandLogging = (help || doctor) && !veryVerbose; final bool verboseHelp = help && verbose; final bool daemon = args.contains('daemon'); final bool runMachine = (args.contains('--machine') && args.contains('run')) || (args.contains('--machine') && args.contains('attach'));
// Cache.flutterRoot must be set early because other features use it (e.g. // enginePath's initializer uses it). This can only work with the real // instances of the platform or filesystem, so just use those. Cache.flutterRoot = Cache.defaultFlutterRoot( platform: const LocalPlatform(), fileSystem: globals.localFileSystem, userMessages: UserMessages(), );
await runner.run( args, () => generateCommands( verboseHelp: verboseHelp, verbose: verbose, ), verbose: verbose, muteCommandLogging: muteCommandLogging, verboseHelp: verboseHelp, overrides: <Type, Generator>{ // The web runner is not supported in google3 because it depends // on dwds. WebRunnerFactory: () => DwdsWebRunnerFactory(), // The mustache dependency is different in google3 TemplateRenderer: () => const MustacheTemplateRenderer(), // The devtools launcher is not supported in google3 because it depends on // devtools source code. DevtoolsLauncher: () => DevtoolsServerLauncher( processManager: globals.processManager, dartExecutable: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), logger: globals.logger, botDetector: globals.botDetector, ), Logger: () { final LoggerFactory loggerFactory = LoggerFactory( outputPreferences: globals.outputPreferences, terminal: globals.terminal, stdio: globals.stdio, ); return loggerFactory.createLogger( daemon: daemon, machine: runMachine, verbose: verbose && !muteCommandLogging, prefixedErrors: prefixedErrors, windows: globals.platform.isWindows, ); }, AnsiTerminal: () { return AnsiTerminal( stdio: globals.stdio, platform: globals.platform, now: DateTime.now(), // So that we don't animate anything before calling applyFeatureFlags, default // the animations to disabled in real apps. defaultCliAnimationEnabled: false, ); // runner.run calls "terminal.applyFeatureFlags()" }, PreRunValidator: () => PreRunValidator(fileSystem: globals.fs), }, shutdownHooks: globals.shutdownHooks, );}
List<FlutterCommand> generateCommands({ required bool verboseHelp, required bool verbose,}) => <FlutterCommand>[ AnalyzeCommand( verboseHelp: verboseHelp, fileSystem: globals.fs, platform: globals.platform, processManager: globals.processManager, logger: globals.logger, terminal: globals.terminal, artifacts: globals.artifacts!, // new ProjectValidators should be added here for the --suggestions to run allProjectValidators: <ProjectValidator>[ GeneralInfoProjectValidator(), VariableDumpMachineProjectValidator( logger: globals.logger, fileSystem: globals.fs, platform: globals.platform, ), ], suppressAnalytics: globals.flutterUsage.suppressAnalytics, ), AssembleCommand(verboseHelp: verboseHelp, buildSystem: globals.buildSystem), AttachCommand( verboseHelp: verboseHelp, stdio: globals.stdio, logger: globals.logger, terminal: globals.terminal, signals: globals.signals, platform: globals.platform, processInfo: globals.processInfo, fileSystem: globals.fs, ), BuildCommand( artifacts: globals.artifacts!, fileSystem: globals.fs, buildSystem: globals.buildSystem, osUtils: globals.os, processUtils: globals.processUtils, verboseHelp: verboseHelp, androidSdk: globals.androidSdk, logger: globals.logger, ), ChannelCommand(verboseHelp: verboseHelp), CleanCommand(verbose: verbose), ConfigCommand(verboseHelp: verboseHelp), CustomDevicesCommand( customDevicesConfig: globals.customDevicesConfig, operatingSystemUtils: globals.os, terminal: globals.terminal, platform: globals.platform, featureFlags: featureFlags, processManager: globals.processManager, fileSystem: globals.fs, logger: globals.logger ), CreateCommand(verboseHelp: verboseHelp), DaemonCommand(hidden: !verboseHelp), DebugAdapterCommand(verboseHelp: verboseHelp), DevicesCommand(verboseHelp: verboseHelp), DoctorCommand(verbose: verbose), DowngradeCommand(verboseHelp: verboseHelp, logger: globals.logger), DriveCommand(verboseHelp: verboseHelp, fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, signals: globals.signals, ), EmulatorsCommand(), GenerateCommand(), GenerateLocalizationsCommand( fileSystem: globals.fs, logger: globals.logger, artifacts: globals.artifacts!, processManager: globals.processManager, ), InstallCommand( verboseHelp: verboseHelp, ), LogsCommand( sigint: ProcessSignal.sigint, sigterm: ProcessSignal.sigterm, ), MakeHostAppEditableCommand(), PackagesCommand(), PrecacheCommand( verboseHelp: verboseHelp, cache: globals.cache, logger: globals.logger, platform: globals.platform, featureFlags: featureFlags, ), RunCommand(verboseHelp: verboseHelp), ScreenshotCommand(fs: globals.fs), ShellCompletionCommand(), TestCommand(verboseHelp: verboseHelp, verbose: verbose), UpgradeCommand(verboseHelp: verboseHelp), SymbolizeCommand( stdio: globals.stdio, fileSystem: globals.fs, ), // Development-only commands. These are always hidden, IdeConfigCommand(), UpdatePackagesCommand(),];
/// An abstraction for instantiation of the correct logger type.////// Our logger class hierarchy and runtime requirements are overly complicated.class LoggerFactory { LoggerFactory({ required Terminal terminal, required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), }) : _terminal = terminal, _stdio = stdio, _stopwatchFactory = stopwatchFactory, _outputPreferences = outputPreferences;
final Terminal _terminal; final Stdio _stdio; final StopwatchFactory _stopwatchFactory; final OutputPreferences _outputPreferences;
/// Create the appropriate logger for the current platform and configuration. Logger createLogger({ required bool verbose, required bool prefixedErrors, required bool machine, required bool daemon, required bool windows, }) { Logger logger; if (windows) { logger = WindowsStdoutLogger( terminal: _terminal, stdio: _stdio, outputPreferences: _outputPreferences, stopwatchFactory: _stopwatchFactory, ); } else { logger = StdoutLogger( terminal: _terminal, stdio: _stdio, outputPreferences: _outputPreferences, stopwatchFactory: _stopwatchFactory ); } if (verbose) { logger = VerboseLogger(logger, stopwatchFactory: _stopwatchFactory); } if (prefixedErrors) { logger = PrefixedErrorLogger(logger); } if (daemon) { return NotifyingLogger(verbose: verbose, parent: logger); } if (machine) { return AppRunLogger(parent: logger); } return logger; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292// 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:async';
import 'package:args/command_runner.dart';import 'package:intl/intl.dart' as intl;import 'package:intl/intl_standalone.dart' as intl_standalone;import 'package:unified_analytics/unified_analytics.dart';
import 'src/base/async_guard.dart';import 'src/base/common.dart';import 'src/base/context.dart';import 'src/base/error_handling_io.dart';import 'src/base/file_system.dart';import 'src/base/io.dart';import 'src/base/logger.dart';import 'src/base/process.dart';import 'src/context_runner.dart';import 'src/doctor.dart';import 'src/features.dart';import 'src/globals.dart' as globals;import 'src/reporting/crash_reporting.dart';import 'src/reporting/reporting.dart';import 'src/runner/flutter_command.dart';import 'src/runner/flutter_command_runner.dart';
/// Runs the Flutter tool with support for the specified list of [commands].Future<int> run( List<String> args, List<FlutterCommand> Function() commands, { bool muteCommandLogging = false, bool verbose = false, bool verboseHelp = false, bool? reportCrashes, String? flutterVersion, Map<Type, Generator>? overrides, required ShutdownHooks shutdownHooks, }) async { if (muteCommandLogging) { // Remove the verbose option; for help and doctor, users don't need to see // verbose logs. args = List<String>.of(args); args.removeWhere((String option) => option == '-vv' || option == '-v' || option == '--verbose'); }
return runInContext<int>(() async { globals.terminal.applyFeatureFlags(featureFlags);
reportCrashes ??= !await globals.isRunningOnBot; final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp); commands().forEach(runner.addCommand);
// Initialize the system locale. final String systemLocale = await intl_standalone.findSystemLocale(); intl.Intl.defaultLocale = intl.Intl.verifiedLocale( systemLocale, intl.NumberFormat.localeExists, onFailure: (String _) => 'en_US', );
String getVersion() => flutterVersion ?? globals.flutterVersion.getVersionString(redactUnknownBranches: true); Object? firstError; StackTrace? firstStackTrace; return runZoned<Future<int>>(() async { try { if (args.contains('--disable-analytics') && args.contains('--enable-analytics')) { throwToolExit( 'Both enable and disable analytics commands were detected ' 'when only one can be supplied per invocation.', exitCode: 1); }
// Disable analytics if user passes in the `--disable-analytics` option // "flutter --disable-analytics" // // Same functionality as "flutter config --no-analytics" for disabling // except with the `value` hard coded as false if (args.contains('--disable-analytics')) { // The tool sends the analytics event *before* toggling the flag // intentionally to be sure that opt-out events are sent correctly. AnalyticsConfigEvent(enabled: false).send();
// Normally, the tool waits for the analytics to all send before the // tool exits, but only when analytics are enabled. When reporting that // analytics have been disable, the wait must be done here instead. await globals.flutterUsage.ensureAnalyticsSent();
globals.flutterUsage.enabled = false; globals.printStatus('Analytics reporting disabled.');
// TODO(eliasyishak): Set the telemetry for the unified_analytics // package as well, the above will be removed once we have // fully transitioned to using the new package await globals.analytics.setTelemetry(false); }
// Enable analytics if user passes in the `--enable-analytics` option // `flutter --enable-analytics` // // Same functionality as `flutter config --analytics` for enabling // except with the `value` hard coded as true if (args.contains('--enable-analytics')) { // The tool sends the analytics event *before* toggling the flag // intentionally to be sure that opt-out events are sent correctly. AnalyticsConfigEvent(enabled: true).send();
globals.flutterUsage.enabled = true; globals.printStatus('Analytics reporting enabled.');
// TODO(eliasyishak): Set the telemetry for the unified_analytics // package as well, the above will be removed once we have // fully transitioned to using the new package await globals.analytics.setTelemetry(true); }
await runner.run(args);
// Triggering [runZoned]'s error callback does not necessarily mean that // we stopped executing the body. See https://github.com/dart-lang/sdk/issues/42150. if (firstError == null) { return await exitWithHooks(0, shutdownHooks: shutdownHooks); }
// We already hit some error, so don't return success. The error path // (which should be in progress) is responsible for calling _exit(). return 1; } catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses // This catches all exceptions to send to crash logging, etc. firstError = error; firstStackTrace = stackTrace; return _handleToolError(error, stackTrace, verbose, args, reportCrashes!, getVersion, shutdownHooks); } }, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use // If sending a crash report throws an error into the zone, we don't want // to re-try sending the crash report with *that* error. Rather, we want // to send the original error that triggered the crash report. firstError ??= error; firstStackTrace ??= stackTrace; await _handleToolError(firstError!, firstStackTrace, verbose, args, reportCrashes!, getVersion, shutdownHooks); }); }, overrides: overrides);}
Future<int> _handleToolError( Object error, StackTrace? stackTrace, bool verbose, List<String> args, bool reportCrashes, String Function() getFlutterVersion, ShutdownHooks shutdownHooks,) async { if (error is UsageException) { globals.printError('${error.message}\n'); globals.printError("Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options."); // Argument error exit code. return exitWithHooks(64, shutdownHooks: shutdownHooks); } else if (error is ToolExit) { if (error.message != null) { globals.printError(error.message!); } if (verbose) { globals.printError('\n$stackTrace\n'); } return exitWithHooks(error.exitCode ?? 1, shutdownHooks: shutdownHooks); } else if (error is ProcessExit) { // We've caught an exit code. if (error.immediate) { exit(error.exitCode); return error.exitCode; } else { return exitWithHooks(error.exitCode, shutdownHooks: shutdownHooks); } } else { // We've crashed; emit a log report. globals.stdio.stderrWrite('\n');
if (!reportCrashes) { // Print the stack trace on the bots - don't write a crash report. globals.stdio.stderrWrite('$error\n'); globals.stdio.stderrWrite('$stackTrace\n'); return exitWithHooks(1, shutdownHooks: shutdownHooks); }
// Report to both [Usage] and [CrashReportSender]. globals.flutterUsage.sendException(error); globals.analytics.send(Event.exception(exception: error.runtimeType.toString())); await asyncGuard(() async { final CrashReportSender crashReportSender = CrashReportSender( usage: globals.flutterUsage, platform: globals.platform, logger: globals.logger, operatingSystemUtils: globals.os, ); await crashReportSender.sendReport( error: error, stackTrace: stackTrace!, getFlutterVersion: getFlutterVersion, command: args.join(' '), ); }, onError: (dynamic error) { globals.printError('Error sending crash report: $error'); });
globals.printError('Oops; flutter has exited unexpectedly: "$error".');
try { final BufferLogger logger = BufferLogger( terminal: globals.terminal, outputPreferences: globals.outputPreferences, );
final DoctorText doctorText = DoctorText(logger);
final CrashDetails details = CrashDetails( command: _crashCommand(args), error: error, stackTrace: stackTrace!, doctorText: doctorText, ); final File file = await _createLocalCrashReport(details); await globals.crashReporter!.informUser(details, file);
return exitWithHooks(1, shutdownHooks: shutdownHooks); // This catch catches all exceptions to ensure the message below is printed. } catch (error, st) { // ignore: avoid_catches_without_on_clauses globals.stdio.stderrWrite( 'Unable to generate crash report due to secondary error: $error\n$st\n' '${globals.userMessages.flutterToolBugInstructions}\n', ); // Any exception thrown here (including one thrown by `_exit()`) will // get caught by our zone's `onError` handler. In order to avoid an // infinite error loop, we throw an error that is recognized above // and will trigger an immediate exit. throw ProcessExit(1, immediate: true); } }}
String _crashCommand(List<String> args) => 'flutter ${args.join(' ')}';
String _crashException(dynamic error) => '${error.runtimeType}: $error';
/// Saves the crash report to a local file.Future<File> _createLocalCrashReport(CrashDetails details) async { final StringBuffer buffer = StringBuffer();
buffer.writeln('Flutter crash report.'); buffer.writeln('${globals.userMessages.flutterToolBugInstructions}\n');
buffer.writeln('## command\n'); buffer.writeln('${details.command}\n');
buffer.writeln('## exception\n'); buffer.writeln('${_crashException(details.error)}\n'); buffer.writeln('```\n${details.stackTrace}```\n');
buffer.writeln('## flutter doctor\n'); buffer.writeln('```\n${await details.doctorText.text}```');
late File crashFile; ErrorHandlingFileSystem.noExitOnFailure(() { try { crashFile = globals.fsUtils.getUniqueFile( globals.fs.currentDirectory, 'flutter', 'log', ); crashFile.writeAsStringSync(buffer.toString()); } on FileSystemException catch (_) { // Fallback to the system temporary directory. try { crashFile = globals.fsUtils.getUniqueFile( globals.fs.systemTempDirectory, 'flutter', 'log', ); crashFile.writeAsStringSync(buffer.toString()); } on FileSystemException catch (e) { globals.printError('Could not write crash report to disk: $e'); globals.printError(buffer.toString());
rethrow; } } });
return crashFile;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/flutter/flutter/stable/packages/flutter_tools/static/custom-devices.schema.json", "title": "Flutter Custom Devices", "description": "The schema for the flutter custom devices config file.", "type": "object", "properties": { "custom-devices": { "description": "The actual list of custom devices.", "type": "array", "items": { "description": "A single custom device to be configured.", "type": "object", "properties": { "id": { "description": "A unique, short identification string for this device. Used for example as an argument to the flutter run command.", "type": "string" }, "label": { "description": "A more descriptive, user-friendly label for the device.", "type": "string", "default": "", "required": false }, "sdkNameAndVersion": { "description": "Additional information about the device. For other devices, this is the SDK (for example Android SDK, Windows SDK) name and version.", "type": "string", "default": "", "required": false }, "enabled": { "description": "If false, this device will be ignored completely by the flutter SDK and none of the commands configured will be called. You can use this as a way to comment out device configs you're still working on, for example.", "type": "boolean", "default": true, "required": false }, "platform": { "description": "The platform of the target device.", "enum": ["linux-arm64", "linux-x64"], "default": "linux-arm64", "required": false }, "ping": { "description": "The command to be invoked to ping the device. Used to find out whether its available or not. Every exit code unequal 0 will be treated as \"unavailable\". On Windows, consider providing a \"pingSuccessRegex\" since Windows' ping will also return 0 on failure. Make sure the command times out internally since it's not guaranteed the flutter SDK will enforce a timeout itself.", "type": "array", "items": { "type": "string" }, "minItems": 1, "default": [ "ping", "-w", "500", "-n", "1", "raspberrypi" ] }, "pingSuccessRegex": { "description": "When the output of the ping command matches this regex (and the ping command finished with exit code 0), the ping will be considered successful and the pinged device reachable. If this regex is not provided the ping command will be considered successful when it returned with exit code 0. The regex syntax is the standard dart syntax.", "type": ["string", "null"], "format": "regex", "default": "[<=]\\d+ms", "required": false }, "postBuild": { "description": "The command to be invoked after the build process is done, to do any additional packaging for example.", "type": ["array", "null"], "items": { "type": "string" }, "minItems": 1, "default": null, "required": false }, "install": { "description": "The command to be invoked to install the app on the device. The path to the directory / file to be installed (copied over) to the device is available via the ${localPath} string interpolation and the name of the app to be installed via the ${appName} string interpolation.", "type": "array", "items": { "type": "string" }, "minItems": 1, "default": [ "scp", "-r", "${localPath}", "pi@raspberrypi:/tmp/${appName}" ] }, "uninstall": { "description": "The command to be invoked to remove the app from the device. Invoked before every invocation of the app install command. The name of the app to be removed is available via the ${appName} string interpolation.", "type": "array", "items": { "type": "string" }, "minItems": 1, "default": [ "ssh", "pi@raspberrypi", "rm -rf \"/tmp/${appName}\"" ] }, "runDebug": { "description": "The command to be invoked to run the app in debug mode. The name of the app to be started is available via the ${appName} string interpolation. Make sure the flutter cmdline output is available via this commands stdout/stderr since the SDK needs the \"VM Service is now listening on ...\" message to function. If the forwardPort command is not specified, the VM Service URL will be connected to as-is, without any port forwarding. In that case you need to make sure it is reachable from your host device, possibly via the \"--vm-service-host=<ip>\" engine flag.", "type": "array", "items": { "type": "string" }, "minItems": 1, "default": [ "ssh", "pi@raspberrypi", "flutter-pi /tmp/${appName} --vm-service-host=192.168.178.123" ] }, "forwardPort": { "description": "The command to be invoked to forward a specific device port to a port on the host device. The host port is available via ${hostPort} and the device port via ${devicePort}. On success, the command should stay running for the duration of the forwarding. The command will be terminated using SIGTERM when the forwarding should be stopped. When using ssh, make sure ssh quits when the forwarding fails since that's not the default behaviour.", "type": ["array", "null"], "items": { "type": "string" }, "minItems": 1, "default": [ "ssh", "-o", "ExitOnForwardFailure=yes", "-L", "127.0.0.1:${hostPort}:127.0.0.1:${devicePort}", "pi@raspberrypi" ], "required": false }, "forwardPortSuccessRegex": { "description": "A regular expression to be used to classify a successful port forwarding. As soon as any line of stdout or stderr of the forward port command matches this regex, the port forwarding is considered successful. The regex syntax is the standard dart syntax. This value needs to be present & non-null when \"forwardPort\" specified.", "type": ["string", "null"], "format": "regex", "default": "Linux", "required": false }, "screenshot": { "description": "Take a screenshot of the app as a png image. This command should take the screenshot, convert it to png, then base64 encode it and echo to stdout. Any stderr output will be ignored. If this command is not given, screenshotting will be disabled for this device.", "type": ["array", "null"], "items": { "type": "string" }, "minItems": 1, "default": [ "ssh", "pi@raspberrypi", "fbgrab /tmp/screenshot.png && cat /tmp/screenshot.png | base64 | tr -d ' \\n\\t'" ], "required": false } } } } }}12345678910111213141516171819202122232425262728293031323334<!DOCTYPE HTML><!-- Copyright 2014 The Flutter Authors. All rights reserved.Use of this source code is governed by a BSD-style license that can befound in the LICENSE file. --><html><head> <title>Flutter Test Browser Host</title> <style> /* Configure so that the test application takes up the whole screen */ body { margin: 0; padding: 0; position: fixed; top: 0px; left: 0px; overflow: hidden; }
iframe { border: none; width: 2400px; height: 1800px; position: fixed; top: 0px; left: 0px; overflow: hidden; } </style></head><body> <div id="dark"></div> <script src="host.dart.js"></script></body></html>12345678910111213141516171819202122232425This directory contains templates for `flutter create`.
The `*_shared` subdirectories provide files for multiple templates.
* `app_shared` for `app` and `skeleton`.* `plugin_shared` for (method channel) `plugin` and `plugin_ffi`.
For example, there are two app templates: `app` (the counter app)and `skeleton` (the more advanced list view/detail view app).
```plain ┌────────────┐ │ app_shared │ └──┬──────┬──┘ │ │ │ │ ▼ ▼┌─────┐ ┌──────────┐│ app │ │ skeleton │└─────┘ └──────────┘```
Thanks to `app_shared`, the templates for `app` and `skeleton` can containonly the files that are specific to them alone, and the rest is automaticallykept in sync.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369{ "version": 1.0, "_comment": "A listing of all possible template output files. Files ending in .img.tmpl correspond to files checked in to the flutter_template_images package in the flutter/packages repo, located at the same path, excluding the .img.tmpl suffix.", "files": [ "templates/app/lib/main.dart.tmpl", "templates/app/pubspec.yaml.tmpl", "templates/app/README.md.tmpl",
"templates/app_shared/.gitignore.tmpl", "templates/app_shared/.idea/libraries/Dart_SDK.xml.tmpl", "templates/app_shared/.idea/libraries/KotlinJavaRuntime.xml.tmpl", "templates/app_shared/.idea/modules.xml.tmpl", "templates/app_shared/.idea/runConfigurations/main_dart.xml.tmpl", "templates/app_shared/.idea/workspace.xml.tmpl", "templates/app_shared/.metadata.tmpl", "templates/app_shared/analysis_options.yaml.tmpl", "templates/app_shared/android-java.tmpl/app/build.gradle.tmpl", "templates/app_shared/android-java.tmpl/app/src/main/java/androidIdentifier/MainActivity.java.tmpl", "templates/app_shared/android-java.tmpl/build.gradle.tmpl", "templates/app_shared/android-java.tmpl/projectName_android.iml.tmpl", "templates/app_shared/android-kotlin.tmpl/app/build.gradle.tmpl", "templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl", "templates/app_shared/android-kotlin.tmpl/build.gradle.tmpl", "templates/app_shared/android-kotlin.tmpl/projectName_android.iml.tmpl", "templates/app_shared/android.tmpl/.gitignore", "templates/app_shared/android.tmpl/app/src/debug/AndroidManifest.xml.tmpl", "templates/app_shared/android.tmpl/app/src/main/AndroidManifest.xml.tmpl", "templates/app_shared/android.tmpl/app/src/main/res/drawable-v21/launch_background.xml", "templates/app_shared/android.tmpl/app/src/main/res/drawable/launch_background.xml", "templates/app_shared/android.tmpl/app/src/main/res/mipmap-hdpi/ic_launcher.png", "templates/app_shared/android.tmpl/app/src/main/res/mipmap-mdpi/ic_launcher.png", "templates/app_shared/android.tmpl/app/src/main/res/mipmap-xhdpi/ic_launcher.png", "templates/app_shared/android.tmpl/app/src/main/res/mipmap-xxhdpi/ic_launcher.png", "templates/app_shared/android.tmpl/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png", "templates/app_shared/android.tmpl/app/src/main/res/values-night/styles.xml", "templates/app_shared/android.tmpl/app/src/main/res/values/styles.xml", "templates/app_shared/android.tmpl/app/src/profile/AndroidManifest.xml.tmpl", "templates/app_shared/android.tmpl/gradle.properties.tmpl", "templates/app_shared/android.tmpl/settings.gradle.tmpl", "templates/app_shared/android.tmpl/gradle/wrapper/gradle-wrapper.properties.tmpl", "templates/app_shared/android.tmpl/settings.gradle", "templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/project.pbxproj.tmpl", "templates/app_shared/ios-objc.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme", "templates/app_shared/ios-objc.tmpl/Runner/AppDelegate.h", "templates/app_shared/ios-objc.tmpl/Runner/AppDelegate.m", "templates/app_shared/ios-objc.tmpl/Runner/main.m", "templates/app_shared/ios-objc.tmpl/RunnerTests/RunnerTests.m.tmpl", "templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/project.pbxproj.tmpl", "templates/app_shared/ios-swift.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme", "templates/app_shared/ios-swift.tmpl/Runner/AppDelegate.swift", "templates/app_shared/ios-swift.tmpl/Runner/Runner-Bridging-Header.h", "templates/app_shared/ios-swift.tmpl/RunnerTests/RunnerTests.swift.tmpl", "templates/app_shared/ios.tmpl/.gitignore", "templates/app_shared/ios.tmpl/Flutter/AppFrameworkInfo.plist", "templates/app_shared/ios.tmpl/Flutter/Debug.xcconfig", "templates/app_shared/ios.tmpl/Flutter/Release.xcconfig", "templates/app_shared/ios.tmpl/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata", "templates/app_shared/ios.tmpl/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/app_shared/ios.tmpl/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings", "templates/app_shared/ios.tmpl/Runner.xcworkspace/contents.xcworkspacedata", "templates/app_shared/ios.tmpl/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/app_shared/ios.tmpl/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png.img.tmpl", "templates/app_shared/ios.tmpl/Runner/Assets.xcassets/LaunchImage.imageset/README.md", "templates/app_shared/ios.tmpl/Runner/Base.lproj/LaunchScreen.storyboard", "templates/app_shared/ios.tmpl/Runner/Base.lproj/Main.storyboard", "templates/app_shared/ios.tmpl/Runner/Info.plist.tmpl", "templates/app_shared/linux.tmpl/.gitignore", "templates/app_shared/linux.tmpl/CMakeLists.txt.tmpl", "templates/app_shared/linux.tmpl/flutter/CMakeLists.txt", "templates/app_shared/linux.tmpl/main.cc", "templates/app_shared/linux.tmpl/my_application.cc", "templates/app_shared/linux.tmpl/my_application.cc.tmpl", "templates/app_shared/linux.tmpl/my_application.h", "templates/app_shared/macos.tmpl/.gitignore", "templates/app_shared/macos.tmpl/Flutter/Flutter-Debug.xcconfig", "templates/app_shared/macos.tmpl/Flutter/Flutter-Release.xcconfig", "templates/app_shared/macos.tmpl/Runner.xcodeproj/project.pbxproj.tmpl", "templates/app_shared/macos.tmpl/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/app_shared/macos.tmpl/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme.tmpl", "templates/app_shared/macos.tmpl/Runner.xcworkspace/contents.xcworkspacedata", "templates/app_shared/macos.tmpl/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/app_shared/macos.tmpl/Runner/AppDelegate.swift", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png.img.tmpl", "templates/app_shared/macos.tmpl/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json", "templates/app_shared/macos.tmpl/Runner/Base.lproj/MainMenu.xib", "templates/app_shared/macos.tmpl/Runner/Configs/AppInfo.xcconfig.tmpl", "templates/app_shared/macos.tmpl/Runner/Configs/Debug.xcconfig", "templates/app_shared/macos.tmpl/Runner/Configs/Release.xcconfig", "templates/app_shared/macos.tmpl/Runner/Configs/Warnings.xcconfig", "templates/app_shared/macos.tmpl/Runner/DebugProfile.entitlements", "templates/app_shared/macos.tmpl/Runner/Info.plist", "templates/app_shared/macos.tmpl/Runner/MainFlutterWindow.swift", "templates/app_shared/macos.tmpl/Runner/Release.entitlements", "templates/app_shared/macos.tmpl/RunnerTests/RunnerTests.swift.tmpl", "templates/app_shared/projectName.iml.tmpl", "templates/app_shared/web/favicon.png.copy.tmpl", "templates/app_shared/web/icons/Icon-192.png.copy.tmpl", "templates/app_shared/web/icons/Icon-512.png.copy.tmpl", "templates/app_shared/web/icons/Icon-maskable-192.png.img.tmpl", "templates/app_shared/web/icons/Icon-maskable-512.png.img.tmpl", "templates/app_shared/web/index.html.tmpl", "templates/app_shared/web/manifest.json.tmpl", "templates/app_shared/windows.tmpl/.gitignore", "templates/app_shared/windows.tmpl/CMakeLists.txt.tmpl", "templates/app_shared/windows.tmpl/flutter/CMakeLists.txt", "templates/app_shared/windows.tmpl/runner/CMakeLists.txt", "templates/app_shared/windows.tmpl/runner/flutter_window.cpp", "templates/app_shared/windows.tmpl/runner/flutter_window.h", "templates/app_shared/windows.tmpl/runner/main.cpp.tmpl", "templates/app_shared/windows.tmpl/runner/resource.h", "templates/app_shared/windows.tmpl/runner/resources/app_icon.ico.img.tmpl", "templates/app_shared/windows.tmpl/runner/runner.exe.manifest", "templates/app_shared/windows.tmpl/runner/Runner.rc.tmpl", "templates/app_shared/windows.tmpl/runner/utils.cpp", "templates/app_shared/windows.tmpl/runner/utils.h", "templates/app_shared/windows.tmpl/runner/win32_window.cpp", "templates/app_shared/windows.tmpl/runner/win32_window.h",
"templates/app_test_widget/test/widget_test.dart.tmpl",
"templates/app_integration_test/integration_test/plugin_integration_test.dart.tmpl",
"templates/cocoapods/Podfile-ios-objc", "templates/cocoapods/Podfile-ios-swift", "templates/cocoapods/Podfile-macos",
"templates/module/android/deferred_component/build.gradle.tmpl", "templates/module/android/deferred_component/src/main/AndroidManifest.xml.tmpl", "templates/module/android/gradle/build.gradle.tmpl", "templates/module/android/gradle/gradle.properties.tmpl", "templates/module/android/gradle/settings.gradle.tmpl", "templates/module/android/gradle/src/main/AndroidManifest.xml.tmpl", "templates/module/android/host_app_common/app.tmpl/build.gradle.tmpl", "templates/module/android/host_app_common/app.tmpl/src/main/AndroidManifest.xml.tmpl", "templates/module/android/host_app_common/app.tmpl/src/main/java/androidIdentifier/host/MainActivity.java.tmpl", "templates/module/android/host_app_common/app.tmpl/src/main/res/drawable/launch_background.xml", "templates/module/android/host_app_common/app.tmpl/src/main/res/mipmap-hdpi/ic_launcher.png", "templates/module/android/host_app_common/app.tmpl/src/main/res/values/styles.xml", "templates/module/android/host_app_editable/settings.gradle.copy.tmpl", "templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl", "templates/module/android/library/Flutter.tmpl/build.gradle.tmpl", "templates/module/android/library/Flutter.tmpl/flutter.iml.copy.tmpl", "templates/module/android/library/Flutter.tmpl/src/main/AndroidManifest.xml.tmpl", "templates/module/android/library/Flutter.tmpl/src/main/java/io/flutter/facade/Flutter.java.tmpl", "templates/module/android/library/Flutter.tmpl/src/main/java/io/flutter/facade/FlutterFragment.java.tmpl", "templates/module/android/library/include_flutter.groovy.copy.tmpl", "templates/module/android/library/settings.gradle.copy.tmpl", "templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl", "templates/module/android/library_new_embedding/Flutter.tmpl/flutter.iml.copy.tmpl", "templates/module/android/library_new_embedding/Flutter.tmpl/src/main/AndroidManifest.xml.tmpl", "templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl", "templates/module/android/library_new_embedding/settings.gradle.copy.tmpl", "templates/module/common/.gitignore.tmpl", "templates/module/common/.idea/libraries/Dart_SDK.xml.tmpl", "templates/module/common/.idea/modules.xml.tmpl", "templates/module/common/.idea/workspace.xml.tmpl", "templates/module/common/.metadata.tmpl", "templates/module/common/analysis_options.yaml.tmpl", "templates/module/common/lib/main.dart.tmpl", "templates/module/common/projectName.iml.tmpl", "templates/module/common/projectName_android.iml.tmpl", "templates/module/common/pubspec.yaml.tmpl", "templates/module/common/README.md.tmpl", "templates/module/common/test/widget_test.dart.tmpl", "templates/module/ios/host_app_ephemeral/Config.tmpl/Debug.xcconfig", "templates/module/ios/host_app_ephemeral/Config.tmpl/Flutter.xcconfig", "templates/module/ios/host_app_ephemeral/Config.tmpl/Release.xcconfig", "templates/module/ios/host_app_ephemeral/Runner.tmpl/AppDelegate.h", "templates/module/ios/host_app_ephemeral/Runner.tmpl/AppDelegate.m", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Contents.json", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/LaunchImage.imageset/Contents.json", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/LaunchImage.imageset/LaunchImage.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Assets.xcassets/LaunchImage.imageset/README.md", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Base.lproj/LaunchScreen.storyboard", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Base.lproj/Main.storyboard", "templates/module/ios/host_app_ephemeral/Runner.tmpl/Info.plist.tmpl", "templates/module/ios/host_app_ephemeral/Runner.tmpl/main.m", "templates/module/ios/host_app_ephemeral/Runner.xcodeproj.tmpl/project.pbxproj.tmpl", "templates/module/ios/host_app_ephemeral/Runner.xcodeproj.tmpl/project.xcworkspace/contents.xcworkspacedata", "templates/module/ios/host_app_ephemeral/Runner.xcodeproj.tmpl/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/module/ios/host_app_ephemeral/Runner.xcodeproj.tmpl/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings", "templates/module/ios/host_app_ephemeral/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme", "templates/module/ios/host_app_ephemeral/Runner.xcworkspace.tmpl/contents.xcworkspacedata", "templates/module/ios/host_app_ephemeral/Runner.xcworkspace.tmpl/xcshareddata/IDEWorkspaceChecks.plist", "templates/module/ios/host_app_ephemeral/Runner.xcworkspace.tmpl/xcshareddata/WorkspaceSettings.xcsettings", "templates/module/ios/host_app_ephemeral_cocoapods/Config.tmpl/Debug.xcconfig", "templates/module/ios/host_app_ephemeral_cocoapods/Config.tmpl/Release.xcconfig", "templates/module/ios/host_app_ephemeral_cocoapods/Podfile.copy.tmpl", "templates/module/ios/host_app_ephemeral_cocoapods/Runner.tmpl/AppDelegate.m", "templates/module/ios/library/Flutter.tmpl/AppFrameworkInfo.plist", "templates/module/ios/library/Flutter.tmpl/podhelper.rb.tmpl", "templates/module/ios/library/Flutter.tmpl/README.md", "templates/module/README.md",
"templates/package/.gitignore.tmpl", "templates/package/.idea/libraries/Dart_SDK.xml.tmpl", "templates/package/.idea/modules.xml.tmpl", "templates/package/.idea/workspace.xml.tmpl", "templates/package/.metadata.tmpl", "templates/package/analysis_options.yaml.tmpl", "templates/package/CHANGELOG.md.tmpl", "templates/package/lib/projectName.dart.tmpl", "templates/package/LICENSE.tmpl", "templates/package/projectName.iml.tmpl", "templates/package/pubspec.yaml.tmpl", "templates/package/README.md.tmpl", "templates/package/test/projectName_test.dart.tmpl",
"templates/package_ffi/.gitignore.tmpl", "templates/package_ffi/.metadata.tmpl", "templates/package_ffi/analysis_options.yaml.tmpl", "templates/package_ffi/build.dart.tmpl", "templates/package_ffi/CHANGELOG.md.tmpl", "templates/package_ffi/ffigen.yaml.tmpl", "templates/package_ffi/lib/projectName_bindings_generated.dart.tmpl", "templates/package_ffi/lib/projectName.dart.tmpl", "templates/package_ffi/LICENSE.tmpl", "templates/package_ffi/pubspec.yaml.tmpl", "templates/package_ffi/README.md.tmpl", "templates/package_ffi/src.tmpl/projectName.c.tmpl", "templates/package_ffi/src.tmpl/projectName.h.tmpl", "templates/package_ffi/test/projectName_test.dart.tmpl",
"templates/plugin/android-java.tmpl/build.gradle.tmpl", "templates/plugin/android-java.tmpl/projectName_android.iml.tmpl", "templates/plugin/android-java.tmpl/src/main/java/androidIdentifier/pluginClass.java.tmpl", "templates/plugin/android-java.tmpl/src/test/java/androidIdentifier/pluginClassTest.java.tmpl", "templates/plugin/android-kotlin.tmpl/build.gradle.tmpl", "templates/plugin/android-kotlin.tmpl/projectName_android.iml.tmpl", "templates/plugin/android-kotlin.tmpl/src/main/kotlin/androidIdentifier/pluginClass.kt.tmpl", "templates/plugin/android-kotlin.tmpl/src/test/kotlin/androidIdentifier/pluginClassTest.kt.tmpl", "templates/plugin/android.tmpl/.gitignore", "templates/plugin/android.tmpl/gradle/wrapper/gradle-wrapper.properties", "templates/plugin/android.tmpl/gradle.properties.tmpl", "templates/plugin/android.tmpl/settings.gradle.tmpl", "templates/plugin/android.tmpl/src/main/AndroidManifest.xml.tmpl", "templates/plugin/ios-objc.tmpl/Classes/pluginClass.h.tmpl", "templates/plugin/ios-objc.tmpl/Classes/pluginClass.m.tmpl", "templates/plugin/ios-objc.tmpl/projectName.podspec.tmpl", "templates/plugin/ios-swift.tmpl/Classes/pluginClass.swift.tmpl", "templates/plugin/ios-swift.tmpl/projectName.podspec.tmpl", "templates/plugin/ios.tmpl/.gitignore", "templates/plugin/ios.tmpl/Assets/.gitkeep", "templates/plugin/lib/projectName.dart.tmpl", "templates/plugin/lib/projectName_platform_interface.dart.tmpl", "templates/plugin/lib/projectName_method_channel.dart.tmpl", "templates/plugin/linux.tmpl/CMakeLists.txt.tmpl", "templates/plugin/linux.tmpl/include/projectName.tmpl/pluginClassSnakeCase.h.tmpl", "templates/plugin/linux.tmpl/pluginClassSnakeCase.cc.tmpl", "templates/plugin/linux.tmpl/pluginClassSnakeCase_private.h.tmpl", "templates/plugin/linux.tmpl/test/pluginClassSnakeCase_test.cc.tmpl", "templates/plugin/macos.tmpl/Classes/pluginClass.swift.tmpl", "templates/plugin/README.md.tmpl", "templates/plugin/test/projectName_test.dart.tmpl", "templates/plugin/test/projectName_method_channel_test.dart.tmpl", "templates/plugin/windows.tmpl/CMakeLists.txt.tmpl", "templates/plugin/windows.tmpl/include/projectName.tmpl/pluginClassSnakeCase_c_api.h.tmpl", "templates/plugin/windows.tmpl/test/pluginClassSnakeCase_test.cpp.tmpl", "templates/plugin/windows.tmpl/pluginClassSnakeCase.cpp.tmpl", "templates/plugin/windows.tmpl/pluginClassSnakeCase.h.tmpl", "templates/plugin/windows.tmpl/pluginClassSnakeCase_c_api.cpp.tmpl", "templates/plugin/lib/projectName_web.dart.tmpl",
"templates/plugin_ffi/android.tmpl/build.gradle.tmpl", "templates/plugin_ffi/android.tmpl/projectName_android.iml.tmpl", "templates/plugin_ffi/ffigen.yaml.tmpl", "templates/plugin_ffi/ios.tmpl/.gitignore", "templates/plugin_ffi/ios.tmpl/Classes/projectName.c.tmpl", "templates/plugin_ffi/ios.tmpl/projectName.podspec.tmpl", "templates/plugin_ffi/lib/projectName_bindings_generated.dart.tmpl", "templates/plugin_ffi/lib/projectName.dart.tmpl", "templates/plugin_ffi/linux.tmpl/CMakeLists.txt.tmpl", "templates/plugin_ffi/linux.tmpl/include/projectName.tmpl/plugin_ffiClassSnakeCase.h.tmpl", "templates/plugin_ffi/macos.tmpl/Classes/projectName.c.tmpl", "templates/plugin_ffi/README.md.tmpl", "templates/plugin_ffi/src.tmpl/CMakeLists.txt.tmpl", "templates/plugin_ffi/src.tmpl/projectName.c.tmpl", "templates/plugin_ffi/src.tmpl/projectName.h.tmpl", "templates/plugin_ffi/windows.tmpl/CMakeLists.txt.tmpl",
"templates/plugin_shared/.gitignore.tmpl", "templates/plugin_shared/.idea/libraries/Dart_SDK.xml.tmpl", "templates/plugin_shared/.idea/modules.xml.tmpl", "templates/plugin_shared/.idea/runConfigurations/example_lib_main_dart.xml.tmpl", "templates/plugin_shared/.idea/workspace.xml.tmpl", "templates/plugin_shared/.metadata.tmpl", "templates/plugin_shared/analysis_options.yaml.tmpl", "templates/plugin_shared/android.tmpl/.gitignore", "templates/plugin_shared/android.tmpl/settings.gradle.tmpl", "templates/plugin_shared/android.tmpl/src/main/AndroidManifest.xml.tmpl", "templates/plugin_shared/CHANGELOG.md.tmpl", "templates/plugin_shared/LICENSE.tmpl", "templates/plugin_shared/macos.tmpl/projectName.podspec.tmpl", "templates/plugin_shared/projectName.iml.tmpl", "templates/plugin_shared/pubspec.yaml.tmpl", "templates/plugin_shared/windows.tmpl/.gitignore",
"templates/skeleton/assets/images/2.0x/flutter_logo.png.img.tmpl", "templates/skeleton/assets/images/3.0x/flutter_logo.png.img.tmpl", "templates/skeleton/assets/images/flutter_logo.png.img.tmpl", "templates/skeleton/l10n.yaml.tmpl", "templates/skeleton/lib/main.dart.tmpl", "templates/skeleton/lib/src/app.dart.tmpl", "templates/skeleton/lib/src/sample_feature/sample_item.dart.tmpl", "templates/skeleton/lib/src/sample_feature/sample_item_details_view.dart.tmpl", "templates/skeleton/lib/src/sample_feature/sample_item_list_view.dart.tmpl", "templates/skeleton/lib/src/localization/app_en.arb.tmpl", "templates/skeleton/lib/src/settings/settings_controller.dart.tmpl", "templates/skeleton/lib/src/settings/settings_service.dart.tmpl", "templates/skeleton/lib/src/settings/settings_view.dart.tmpl", "templates/skeleton/pubspec.yaml.tmpl", "templates/skeleton/README.md.tmpl", "templates/skeleton/test/implementation_test.dart.test.tmpl", "templates/skeleton/test/unit_test.dart.tmpl", "templates/skeleton/test/widget_test.dart.tmpl",
"templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/contents.xcworkspacedata", "templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/xcshareddata/IDEWorkspaceChecks.plist", "templates/xcode/ios/custom_application_bundle/Runner.xcworkspace.tmpl/xcshareddata/WorkspaceSettings.xcsettings", "templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/project.pbxproj", "templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/project.xcworkspace/contents.xcworkspacedata", "templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist", "templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings", "templates/xcode/ios/custom_application_bundle/Runner.xcodeproj.tmpl/xcshareddata/xcschemes/Runner.xcscheme.tmpl" ]}12345# Android preview integration tests
This directory contains integration tests which would otherwise live in `integration.shard`,but require a dependency on a CIPD-hosted preview version of Android (and therefore their owntest shard). For additional information see the README in the `../integration.shard` directory.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151// 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';
import 'package:file/src/interface/file_system_entity.dart';
import '../integration.shard/test_utils.dart';import '../src/common.dart';import '../src/context.dart';
const String gradleSettingsFileContent = r'''pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath }()
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories { google() mavenCentral() gradlePluginPortal() }}
plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "AGP_REPLACE_ME" apply false id "org.jetbrains.kotlin.android" version "KGP_REPLACE_ME" apply false}
include ":app"
''';
const String agpReplacementString = 'AGP_REPLACE_ME';const String kgpReplacementString = 'KGP_REPLACE_ME';
const String gradleWrapperPropertiesFileContent = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distszipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-GRADLE_REPLACE_ME-all.zip
''';
const String gradleReplacementString = 'GRADLE_REPLACE_ME';
// This test is currently on the preview shard (but not using the preview// version of Android) because it is the only one using Java 11. This test// requires Java 11 due to the intentionally low version of Gradle.void main() { late Directory tempDir;
setUpAll(() async { tempDir = createResolvedTempDirectorySync('run_test.'); });
tearDownAll(() async { tryToDelete(tempDir as FileSystemEntity); });
Future<ProcessResult> buildFlutterApkWithSpecifiedDependencyVersions({ required String gradleVersion, required String agpVersion, required String kgpVersion}) async { // Create a new flutter project. final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run(<String>[ flutterBin, 'create', 'dependency_checker_app', '--platforms=android', ], workingDirectory: tempDir.path); expect(result, const ProcessResultMatcher());
final Directory app = Directory(fileSystem.path.join(tempDir.path, 'dependency_checker_app'));
// Modify gradle version to passed in version. final File gradleWrapperProperties = File(fileSystem.path.join( app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties')); final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst( gradleReplacementString, gradleVersion, ); await gradleWrapperProperties.writeAsString(propertyContent, flush: true);
final File gradleSettings = File(fileSystem.path.join( app.path, 'android', 'settings.gradle')); final String settingsContent = gradleSettingsFileContent .replaceFirst(agpReplacementString, agpVersion) .replaceFirst(kgpReplacementString, kgpVersion); await gradleSettings.writeAsString(settingsContent, flush: true);
// Ensure that gradle files exists from templates. result = await processManager.run(<String>[ flutterBin, 'build', 'apk', '--debug', ], workingDirectory: app.path); return result; }
testUsingContext( 'AGP version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async {
final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( gradleVersion: '7.5', agpVersion: '7.0.0', kgpVersion: '1.7.10' ); expect(result, const ProcessResultMatcher()); expect(result.stderr, contains('Please upgrade your Android Gradle Plugin version')); });
testUsingContext( 'Gradle version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async { // Create a new flutter project. final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( gradleVersion: '7.0.2', agpVersion: '7.0.0', kgpVersion: '1.7.10' ); expect(result, const ProcessResultMatcher()); expect(result.stderr, contains('Please upgrade your Gradle version')); });
testUsingContext( 'Kotlin version out of "warn" support band but in "error" band builds ' 'successfully and prints warning', () async { final ProcessResult result = await buildFlutterApkWithSpecifiedDependencyVersions( gradleVersion: '7.5', agpVersion: '7.4.0', kgpVersion: '1.7.0' );
expect(result, const ProcessResultMatcher()); expect(result.stderr, contains('Please upgrade your Kotlin version')); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135// 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 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';
import '../integration.shard/test_utils.dart';import '../src/common.dart';
void main() { late Directory tempDir; late String flutterBin; late Directory exampleAppDir; late Directory pluginDir; final RegExp compileSdkVersionMatch = RegExp(r'compileSdk [\w.]+'); final String builtApkPath = <String>['build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk'] .join(platform.pathSeparator);
setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); flutterBin = fileSystem.path.join( getFlutterRoot(), 'bin', 'flutter', ); pluginDir = tempDir.childDirectory('aaa'); exampleAppDir = pluginDir.childDirectory('example');
processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'create', '--template=plugin', '--platforms=android', 'aaa', ], workingDirectory: tempDir.path); });
tearDown(() async { tryToDelete(tempDir); });
test( 'build succeeds targeting string compileSdkVersion', () async { final File buildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkVersion as `android-UpsideDownCake` which is a string preview version buildGradleFile.writeAsStringSync( buildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkVersion "android-UpsideDownCake"'), flush: true ); expect(buildGradleFile.readAsStringSync(), contains('compileSdkVersion "android-UpsideDownCake"'));
final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, );
test( 'build succeeds targeting string compileSdkPreview', () async { final File buildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkPreview as `UpsideDownCake` which is a string preview version buildGradleFile.writeAsStringSync( buildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview "UpsideDownCake"'), flush: true ); expect(buildGradleFile.readAsStringSync(), contains('compileSdkPreview "UpsideDownCake"'));
final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, );
test( 'build succeeds when both example app and plugin target compileSdkPreview', () async { final File appBuildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkPreview as `UpsideDownCake` which is a string preview version appBuildGradleFile.writeAsStringSync( appBuildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview "UpsideDownCake"'), flush: true ); expect(appBuildGradleFile.readAsStringSync(), contains('compileSdkPreview "UpsideDownCake"'));
final File pluginBuildGradleFile = pluginDir.childDirectory('android').childFile('build.gradle'); // change the plugin build.gradle to use a preview compile sdk version pluginBuildGradleFile.writeAsStringSync( pluginBuildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview "UpsideDownCake"'), flush: true ); expect(pluginBuildGradleFile.readAsStringSync(), contains('compileSdkPreview "UpsideDownCake"'));
final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, );}12345678910This directory contains tests for specific `flutter` commands.
Tests that are self-contained unit tests should go in `hermetic/`.
Tests that are more end-to-end, e.g. that involve actually runningsubprocesses, should go in `permeable/`.
The `../../tool/coverage_tool.dart` script (which is used to collectcoverage for the tool) runs only the tests in the `hermetic` directorywhen collecting coverage.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412// 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 'package:args/command_runner.dart';import 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/android_workflow.dart';import 'package:flutter_tools/src/artifacts.dart';import 'package:flutter_tools/src/base/config.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/process.dart';import 'package:flutter_tools/src/base/time.dart';import 'package:flutter_tools/src/build_system/build_system.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/commands/build.dart';import 'package:flutter_tools/src/commands/config.dart';import 'package:flutter_tools/src/commands/doctor.dart';import 'package:flutter_tools/src/doctor.dart';import 'package:flutter_tools/src/doctor_validator.dart';import 'package:flutter_tools/src/features.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/reporting/reporting.dart';import 'package:flutter_tools/src/runner/flutter_command.dart';import 'package:flutter_tools/src/version.dart';import 'package:test/fake.dart';import 'package:usage/usage_io.dart';
import '../src/common.dart';import '../src/context.dart';import '../src/fakes.dart';import '../src/test_build_system.dart';import '../src/test_flutter_command_runner.dart';
void main() { setUpAll(() { Cache.disableLocking(); });
group('analytics', () { late Directory tempDir; late Config testConfig; late FileSystem fs;
const String flutterRoot = '/path/to/flutter';
setUp(() { Cache.flutterRoot = flutterRoot; tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_analytics_test.'); testConfig = Config.test(); fs = MemoryFileSystem.test(); });
tearDown(() { tryToDelete(tempDir); });
// Ensure we don't send anything when analytics is disabled. testUsingContext("doesn't send when disabled", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++);
final FlutterCommand command = FakeFlutterCommand(); final CommandRunner<void>runner = createTestCommandRunner(command);
globals.flutterUsage.enabled = false; await runner.run(<String>['fake']); expect(count, 0);
globals.flutterUsage.enabled = true; await runner.run(<String>['fake']); // LogToFileAnalytics isFirstRun is hardcoded to false // so this usage will never act like the first run // (which would not send usage). expect(count, 4);
count = 0; globals.flutterUsage.enabled = false; await runner.run(<String>['fake']);
expect(count, 0); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Usage: () => Usage( configDirOverride: tempDir.path, logFile: tempDir.childFile('analytics.log').path, runningOnBot: true, ), });
// Ensure we don't send for the 'flutter config' command. testUsingContext("config doesn't send", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++);
globals.flutterUsage.enabled = false; final ConfigCommand command = ConfigCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['config']); expect(count, 0);
globals.flutterUsage.enabled = true; await runner.run(<String>['config']);
expect(count, 0); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Usage: () => Usage( configDirOverride: tempDir.path, logFile: tempDir.childFile('analytics.log').path, runningOnBot: true, ), });
testUsingContext('Usage records one feature in experiment setting', () async { testConfig.setValue(flutterWebFeature.configSetting!, true); final Usage usage = Usage(runningOnBot: true); usage.sendCommand('test');
final String featuresKey = CustomDimensionsEnum.enabledFlutterFeatures.cdKey;
expect(globals.fs.file('test').readAsStringSync(), contains('$featuresKey: enable-web')); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Config: () => testConfig, Platform: () => FakePlatform(environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'test', }), FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Usage records multiple features in experiment setting', () async { testConfig.setValue(flutterWebFeature.configSetting!, true); testConfig.setValue(flutterLinuxDesktopFeature.configSetting!, true); testConfig.setValue(flutterMacOSDesktopFeature.configSetting!, true); final Usage usage = Usage(runningOnBot: true); usage.sendCommand('test');
final String featuresKey = CustomDimensionsEnum.enabledFlutterFeatures.cdKey;
expect( globals.fs.file('test').readAsStringSync(), contains('$featuresKey: enable-web,enable-linux-desktop,enable-macos-desktop'), ); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Config: () => testConfig, Platform: () => FakePlatform(environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'test', }), FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), }); });
group('analytics with fakes', () { late MemoryFileSystem memoryFileSystem; late FakeStdio fakeStdio; late TestUsage testUsage; late FakeClock fakeClock; late FakeDoctor doctor; late FakeAndroidStudio androidStudio; late ProcessManager processManager; late BufferLogger logger; late ProcessUtils processUtils;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); fakeStdio = FakeStdio(); testUsage = TestUsage(); fakeClock = FakeClock(); doctor = FakeDoctor(); androidStudio = FakeAndroidStudio(); processManager = FakeProcessManager.empty(); logger = BufferLogger.test(); processUtils = ProcessUtils(logger: logger, processManager: processManager); });
testUsingContext('flutter commands send timing events', () async { fakeClock.times = <int>[1000, 2000]; doctor.diagnoseSucceeds = true; final DoctorCommand command = DoctorCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['doctor']);
expect(testUsage.timings, contains( const TestTimingEvent( 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'success', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => androidStudio, SystemClock: () => fakeClock, Doctor: () => doctor, Usage: () => testUsage, });
testUsingContext('doctor fail sends warning', () async { fakeClock.times = <int>[1000, 2000]; doctor.diagnoseSucceeds = false; final DoctorCommand command = DoctorCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['doctor']);
expect(testUsage.timings, contains( const TestTimingEvent( 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'warning', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => androidStudio, SystemClock: () => fakeClock, Doctor: () => doctor, Usage: () => testUsage, });
testUsingContext('single command usage path', () async { final FlutterCommand doctorCommand = DoctorCommand();
expect(await doctorCommand.usagePath, 'doctor'); }, overrides: <Type, Generator>{ Usage: () => testUsage, });
testUsingContext('compound command usage path', () async { final BuildCommand buildCommand = BuildCommand( artifacts: Artifacts.test(fileSystem: memoryFileSystem), androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: memoryFileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); final FlutterCommand buildApkCommand = buildCommand.subcommands['apk']! as FlutterCommand;
expect(await buildApkCommand.usagePath, 'build/apk'); });
testUsingContext('command sends localtime', () async { const int kMillis = 1000; fakeClock.times = <int>[kMillis]; // Since FLUTTER_ANALYTICS_LOG_FILE is set in the environment, analytics // will be written to a file. final Usage usage = Usage( versionOverride: 'test', runningOnBot: true, ); usage.suppressAnalytics = false; usage.enabled = true;
usage.sendCommand('test');
final String log = globals.fs.file('analytics.log').readAsStringSync(); final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(kMillis);
expect(log.contains(formatDateTime(dateTime)), isTrue); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => processManager, SystemClock: () => fakeClock, Platform: () => FakePlatform( environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'analytics.log', }, ), Stdio: () => fakeStdio, });
testUsingContext('event sends localtime', () async { const int kMillis = 1000; fakeClock.times = <int>[kMillis]; // Since FLUTTER_ANALYTICS_LOG_FILE is set in the environment, analytics // will be written to a file. final Usage usage = Usage( versionOverride: 'test', runningOnBot: true, ); usage.suppressAnalytics = false; usage.enabled = true;
usage.sendEvent('test', 'test');
final String log = globals.fs.file('analytics.log').readAsStringSync(); final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(kMillis);
expect(log.contains(formatDateTime(dateTime)), isTrue); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => processManager, SystemClock: () => fakeClock, Platform: () => FakePlatform( environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'analytics.log', }, ), Stdio: () => fakeStdio, }); });
group('analytics bots', () { late Directory tempDir;
setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_analytics_bots_test.'); });
tearDown(() { tryToDelete(tempDir); });
testUsingContext("don't send on bots with unknown version", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); await createTestCommandRunner().run(<String>['--version']);
expect(count, 0); }, overrides: <Type, Generator>{ Usage: () => Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', configDirOverride: tempDir.path, runningOnBot: false, ), });
testUsingContext("don't send on bots even when opted in", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); globals.flutterUsage.enabled = true; await createTestCommandRunner().run(<String>['--version']);
expect(count, 0); }, overrides: <Type, Generator>{ Usage: () => Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', configDirOverride: tempDir.path, runningOnBot: false, ), });
testUsingContext('Uses AnalyticsMock when .flutter cannot be created', () async { final Usage usage = Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/known', configDirOverride: tempDir.path, analyticsIOFactory: throwingAnalyticsIOFactory, runningOnBot: false, ); final AnalyticsMock analyticsMock = AnalyticsMock();
expect(usage.clientId, analyticsMock.clientId); expect(usage.suppressAnalytics, isTrue); }); });}
Analytics throwingAnalyticsIOFactory( String trackingId, String applicationName, String applicationVersion, { String? analyticsUrl, Directory? documentDirectory,}) { throw const FileSystemException('Could not create file');}
class FakeFlutterCommand extends FlutterCommand { @override String get description => 'A fake command';
@override String get name => 'fake';
@override Future<FlutterCommandResult> runCommand() async { return FlutterCommandResult.success(); }}
class FakeDoctor extends Fake implements Doctor { bool diagnoseSucceeds = false;
@override Future<bool> diagnose({ bool androidLicenses = false, bool verbose = true, bool showColor = true, AndroidLicenseValidator? androidLicenseValidator, bool showPii = true, List<ValidatorTask>? startedValidatorTasks, bool sendEvent = true, FlutterVersion? version, }) async { return diagnoseSucceeds; }}
class FakeClock extends Fake implements SystemClock { List<int> times = <int>[];
@override DateTime now() { return DateTime.fromMillisecondsSinceEpoch(times.removeAt(0)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249// 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:async';
import 'package:flutter_tools/src/android/android_device.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
const int kLollipopVersionCode = 21;const String kLastLogcatTimestamp = '11-27 15:39:04.506';
/// By default the android log reader accepts lines that match no patterns/// if the previous line was a match. Include an intentionally non-matching/// line as the first input to disable this behavior.const String kDummyLine = 'Contents are not important\n';
void main() { testWithoutContext('AdbLogReader ignores spam from SurfaceSyncer', () async { const int appPid = 1; final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], completer: Completer<void>.sync(), stdout: '$kDummyLine' '05-11 12:54:46.665 W/flutter($appPid): Hello there!\n' '05-11 12:54:46.665 E/SurfaceSyncer($appPid): Failed to find sync for id=9\n' '05-11 12:54:46.665 E/SurfaceSyncer($appPid): Failed to find sync for id=10\n' ), ]); final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, )..appPid = appPid; final Completer<void> onDone = Completer<void>.sync(); final List<String> emittedLines = <String>[]; logReader.logLines.listen((String line) { emittedLines.add(line); }, onDone: onDone.complete); await null; logReader.dispose(); await onDone.future; expect(emittedLines, const <String>['W/flutter($appPid): Hello there!']); });
testWithoutContext('AdbLogReader calls adb logcat with expected flags apiVersion 21', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-T', "'$kLastLogcatTimestamp'", ], ), ]); await AdbLogReader.createLogReader( createFakeDevice(kLollipopVersionCode), processManager, );
expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('AdbLogReader calls adb logcat with expected flags apiVersion < 21', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], ), ]); await AdbLogReader.createLogReader( createFakeDevice(kLollipopVersionCode - 1), processManager, );
expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('AdbLogReader calls adb logcat with expected flags null apiVersion', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], ), ]); await AdbLogReader.createLogReader( createFakeDevice(null), processManager, );
expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('AdbLogReader calls adb logcat with expected flags when requesting past logs', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-s', 'flutter', ], ), ]); await AdbLogReader.createLogReader( createFakeDevice(null), processManager, includePastLogs: true, );
expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('AdbLogReader handles process early exit', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], completer: Completer<void>.sync(), stdout: 'Hello There\n', ), ]); final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, ); final Completer<void> onDone = Completer<void>.sync(); logReader.logLines.listen((String _) { }, onDone: onDone.complete);
logReader.dispose(); await onDone.future; });
testWithoutContext('AdbLogReader does not filter output from AndroidRuntime crashes', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], completer: Completer<void>.sync(), // Example stack trace from an incorrectly named application:name in the AndroidManifest.xml stdout: '$kDummyLine' '05-11 12:54:46.665 E/AndroidRuntime(11787): FATAL EXCEPTION: main\n' '05-11 12:54:46.665 E/AndroidRuntime(11787): Process: com.example.foobar, PID: 11787\n' '05-11 12:54:46.665 java.lang.RuntimeException: Unable to instantiate application ' 'io.flutter.app.FlutterApplication2: java.lang.ClassNotFoundException:\n', ), ]); final AdbLogReader logReader = await AdbLogReader.createLogReader( createFakeDevice(null), processManager, ); await expectLater(logReader.logLines, emitsInOrder(<String>[ 'E/AndroidRuntime(11787): FATAL EXCEPTION: main', 'E/AndroidRuntime(11787): Process: com.example.foobar, PID: 11787', 'java.lang.RuntimeException: Unable to instantiate application io.flutter.app.FlutterApplication2: java.lang.ClassNotFoundException:', ]));
logReader.dispose(); });}
AndroidDevice createFakeDevice(int? sdkLevel) { return FakeAndroidDevice( sdkLevel.toString(), kLastLogcatTimestamp, );}
class FakeAndroidDevice extends Fake implements AndroidDevice { FakeAndroidDevice(this._apiVersion, this._lastLogcatTimestamp);
final String _lastLogcatTimestamp; final String _apiVersion;
@override String get name => 'test-device';
@override Future<String> get apiVersion => Future<String>.value(_apiVersion);
@override Future<String> lastLogcatTimestamp() async => _lastLogcatTimestamp;
@override List<String> adbCommandForDevice(List<String> command) { return <String>[ 'adb', '-s', '1234', ...command, ]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_device_discovery.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/android_workflow.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/user_messages.dart';import 'package:flutter_tools/src/device.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';import '../../src/fakes.dart';
void main() { late AndroidWorkflow androidWorkflow;
setUp(() { androidWorkflow = AndroidWorkflow( androidSdk: FakeAndroidSdk(), featureFlags: TestFeatureFlags(), ); });
testWithoutContext('AndroidDevices returns empty device list and diagnostics on null adb', () async { final AndroidDevices androidDevices = AndroidDevices( androidSdk: FakeAndroidSdk(null), logger: BufferLogger.test(), androidWorkflow: AndroidWorkflow( androidSdk: FakeAndroidSdk(null), featureFlags: TestFeatureFlags(), ), processManager: FakeProcessManager.empty(), fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), userMessages: UserMessages(), );
expect(await androidDevices.pollingGetDevices(), isEmpty); expect(await androidDevices.getDiagnostics(), isEmpty); });
testWithoutContext('AndroidDevices returns empty device list and diagnostics when adb cannot be run', () async { final FakeProcessManager fakeProcessManager = FakeProcessManager.empty(); fakeProcessManager.excludedExecutables.add('adb'); final AndroidDevices androidDevices = AndroidDevices( androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), androidWorkflow: AndroidWorkflow( androidSdk: FakeAndroidSdk(), featureFlags: TestFeatureFlags(), ), processManager: fakeProcessManager, fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), userMessages: UserMessages(), );
expect(await androidDevices.pollingGetDevices(), isEmpty); expect(await androidDevices.getDiagnostics(), isEmpty); expect(fakeProcessManager, hasNoRemainingExpectations); });
testWithoutContext('AndroidDevices returns empty device list and diagnostics on null Android SDK', () async { final AndroidDevices androidDevices = AndroidDevices( logger: BufferLogger.test(), androidWorkflow: AndroidWorkflow( androidSdk: FakeAndroidSdk(null), featureFlags: TestFeatureFlags(), ), processManager: FakeProcessManager.empty(), fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), userMessages: UserMessages(), );
expect(await androidDevices.pollingGetDevices(), isEmpty); expect(await androidDevices.getDiagnostics(), isEmpty); });
testWithoutContext('AndroidDevices throwsToolExit on failing adb', () { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], exitCode: 1, ), ]); final AndroidDevices androidDevices = AndroidDevices( androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), androidWorkflow: androidWorkflow, processManager: processManager, fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), userMessages: UserMessages(), );
expect(androidDevices.pollingGetDevices(), throwsToolExit(message: RegExp('Unable to run "adb"'))); });
testWithoutContext('AndroidDevices is disabled if feature is disabled', () { final AndroidDevices androidDevices = AndroidDevices( androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), androidWorkflow: AndroidWorkflow( androidSdk: FakeAndroidSdk(), featureFlags: TestFeatureFlags( isAndroidEnabled: false, ), ), processManager: FakeProcessManager.any(), fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), userMessages: UserMessages(), );
expect(androidDevices.supportsPlatform, false); });
testWithoutContext('AndroidDevices can parse output for physical attached devices', () async { final AndroidDevices androidDevices = AndroidDevices( userMessages: UserMessages(), androidWorkflow: androidWorkflow, androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], stdout: '''List of devices attached05a02bac device usb:336592896X product:razor model:Nexus_7 device:flo
''', ), ]), platform: FakePlatform(), fileSystem: MemoryFileSystem.test(), );
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1)); expect(devices.first.name, 'Nexus 7'); expect(devices.first.category, Category.mobile); expect(devices.first.connectionInterface, DeviceConnectionInterface.attached); });
testWithoutContext('AndroidDevices can parse output for physical wireless devices', () async { final AndroidDevices androidDevices = AndroidDevices( userMessages: UserMessages(), androidWorkflow: androidWorkflow, androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], stdout: '''List of devices attached05a02bac._adb-tls-connect._tcp. device product:razor model:Nexus_7 device:flo
''', ), ]), platform: FakePlatform(), fileSystem: MemoryFileSystem.test(), );
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1)); expect(devices.first.name, 'Nexus 7'); expect(devices.first.category, Category.mobile); expect(devices.first.connectionInterface, DeviceConnectionInterface.wireless); });
testWithoutContext('AndroidDevices can parse output for emulators and short listings', () async { final AndroidDevices androidDevices = AndroidDevices( userMessages: UserMessages(), androidWorkflow: androidWorkflow, androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], stdout: '''List of devices attachedlocalhost:36790 device0149947A0D01500C device usb:340787200Xemulator-5612 host features:shell_2
''', ), ]), platform: FakePlatform(), fileSystem: MemoryFileSystem.test(), );
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(3)); expect(devices[0].name, 'localhost:36790'); expect(devices[1].name, '0149947A0D01500C'); expect(devices[2].name, 'emulator-5612'); });
testWithoutContext('AndroidDevices can parse output from android n', () async { final AndroidDevices androidDevices = AndroidDevices( userMessages: UserMessages(), androidWorkflow: androidWorkflow, androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], stdout: '''List of devices attachedZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu features:cmd,shell_v2
''', ), ]), platform: FakePlatform(), fileSystem: MemoryFileSystem.test(), );
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1)); expect(devices.first.name, 'Nexus 6'); });
testWithoutContext('AndroidDevices provides adb error message as diagnostics', () async { final AndroidDevices androidDevices = AndroidDevices( userMessages: UserMessages(), androidWorkflow: androidWorkflow, androidSdk: FakeAndroidSdk(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', 'devices', '-l'], stdout: '''It appears you do not have 'Android SDK Platform-tools' installed.Use the 'android' tool to install them: android update sdk --no-ui --filter 'platform-tools'''', ), ]), platform: FakePlatform(), fileSystem: MemoryFileSystem.test(), );
final List<String> diagnostics = await androidDevices.getDiagnostics();
expect(diagnostics, hasLength(1)); expect(diagnostics.first, contains('you do not have')); });}
class FakeAndroidSdk extends Fake implements AndroidSdk { FakeAndroidSdk([this.adbPath = 'adb']);
@override final String? adbPath;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163// 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 'package:flutter_tools/src/android/android_device.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/device_port_forwarder.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
void main() { testWithoutContext('AndroidDevicePortForwarder returns the generated host ' 'port from stdout', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), );
expect(await forwarder.forward(123), 456); });
testWithoutContext('AndroidDevicePortForwarder returns the supplied host ' 'port when stdout is empty', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], ), ]), logger: BufferLogger.test(), );
expect(await forwarder.forward(123, hostPort: 456), 456); });
testWithoutContext('AndroidDevicePortForwarder returns the supplied host port ' 'when stdout is the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), );
expect(await forwarder.forward(123, hostPort: 456), 456); });
testWithoutContext('AndroidDevicePortForwarder throws an exception when stdout ' 'is not blank nor the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '123456', ), ]), logger: BufferLogger.test(), );
expect(forwarder.forward(123, hostPort: 456), throwsProcessException()); });
testWithoutContext('AndroidDevicePortForwarder forwardedPorts returns empty ' 'list when forward failed', () { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], exitCode: 1, ), ]), logger: BufferLogger.test(), );
expect(forwarder.forwardedPorts, isEmpty); });
testWithoutContext('disposing device disposes the portForwarder', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], stdout: '1234 tcp:456 tcp:123', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), );
expect(await forwarder.forward(123), equals(456));
await forwarder.dispose();
expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('failures to unforward port do not throw if the forward is missing', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: "error: listener 'tcp:456' not found", exitCode: 1, ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), );
await forwarder.unforward(ForwardedPort(456, 23)); });
testWithoutContext('failures to unforward port print error but are non-fatal', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: 'error: everything is broken!', exitCode: 1, ), ]); final BufferLogger logger = BufferLogger.test(); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: logger, );
await forwarder.unforward(ForwardedPort(456, 23));
expect(logger.errorText, contains('Failed to unforward port: error: everything is broken!')); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_device.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/application_package.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/device.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
const FakeCommand kAdbVersionCommand = FakeCommand( command: <String>['adb', 'version'], stdout: 'Android Debug Bridge version 1.0.39',);
const FakeCommand kStartServer = FakeCommand( command: <String>['adb', 'start-server'],);
const FakeCommand kShaCommand = FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', 'echo', '-n', '', '>', '/data/local/tmp/sky.FlutterApp.sha1', ],);
void main() { late FileSystem fileSystem; late FakeProcessManager processManager; late AndroidSdk androidSdk;
setUp(() { processManager = FakeProcessManager.empty(); fileSystem = MemoryFileSystem.test(); androidSdk = FakeAndroidSdk(); });
for (final TargetPlatform targetPlatform in <TargetPlatform>[ TargetPlatform.android_arm, TargetPlatform.android_arm64, TargetPlatform.android_x64, ]) { testWithoutContext('AndroidDevice.startApp allows release builds on $targetPlatform', () async { final String arch = getAndroidArchForName(getNameForTargetPlatform(targetPlatform)).archName; final AndroidDevice device = AndroidDevice('1234', modelID: 'TestModel', fileSystem: fileSystem, processManager: processManager, logger: BufferLogger.test(), platform: FakePlatform(), androidSdk: androidSdk, ); final File apkFile = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk apk = AndroidApk( id: 'FlutterApp', applicationPackage: apkFile, launchActivity: 'FlutterActivity', versionCode: 1, );
processManager.addCommand(kAdbVersionCommand); processManager.addCommand(kStartServer);
// This configures the target platform of the device. processManager.addCommand(FakeCommand( command: const <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.product.cpu.abi]: [$arch]', )); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'am', 'force-stop', 'FlutterApp'], )); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', 'FlutterApp'], )); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'install', '-t', '-r', 'app-debug.apk'], )); processManager.addCommand(kShaCommand); processManager.addCommand(const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER', '-f', '0x20000000', '--ez', 'enable-dart-profiling', 'true', 'FlutterActivity', ], ));
final LaunchResult launchResult = await device.startApp( apk, prebuiltApplication: true, debuggingOptions: DebuggingOptions.disabled( BuildInfo.release, ), platformArgs: <String, dynamic>{}, );
expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }); }
testWithoutContext('AndroidDevice.startApp does not allow release builds on x86', () async { final AndroidDevice device = AndroidDevice('1234', modelID: 'TestModel', fileSystem: fileSystem, processManager: processManager, logger: BufferLogger.test(), platform: FakePlatform(), androidSdk: androidSdk, ); final File apkFile = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk apk = AndroidApk( id: 'FlutterApp', applicationPackage: apkFile, launchActivity: 'FlutterActivity', versionCode: 1, );
processManager.addCommand(kAdbVersionCommand); processManager.addCommand(kStartServer);
// This configures the target platform of the device. processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.product.cpu.abi]: [x86]', ));
final LaunchResult launchResult = await device.startApp( apk, prebuiltApplication: true, debuggingOptions: DebuggingOptions.disabled( BuildInfo.release, ), platformArgs: <String, dynamic>{}, );
expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('AndroidDevice.startApp forwards all supported debugging options', () async { final AndroidDevice device = AndroidDevice('1234', modelID: 'TestModel', fileSystem: fileSystem, processManager: processManager, logger: BufferLogger.test(), platform: FakePlatform(), androidSdk: androidSdk, ); final File apkFile = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk apk = AndroidApk( id: 'FlutterApp', applicationPackage: apkFile, launchActivity: 'FlutterActivity', versionCode: 1, );
// These commands are required to install and start the app processManager.addCommand(kAdbVersionCommand); processManager.addCommand(kStartServer); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], )); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'am', 'force-stop', '--user', '10', 'FlutterApp'], )); processManager.addCommand(const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'FlutterApp'], )); processManager.addCommand(const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk', ], stdout: '\n\nThe Dart VM service is listening on http://127.0.0.1:456\n\n', )); processManager.addCommand(kShaCommand); processManager.addCommand(const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', ], ));
// This command contains all launch arguments. processManager.addCommand(const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER', '-f', '0x20000000', // The DebuggingOptions arguments go here. '--ez', 'enable-dart-profiling', 'true', '--ez', 'enable-software-rendering', 'true', '--ez', 'skia-deterministic-rendering', 'true', '--ez', 'trace-skia', 'true', '--es', 'trace-allowlist', 'bar,baz', '--es', 'trace-skia-allowlist', 'skia.a,skia.b', '--ez', 'trace-systrace', 'true', '--es', 'trace-to-file', 'path/to/trace.binpb', '--ez', 'endless-trace-buffer', 'true', '--ez', 'dump-skp-on-shader-compilation', 'true', '--ez', 'cache-sksl', 'true', '--ez', 'purge-persistent-cache', 'true', '--ez', 'enable-impeller', 'true', '--ez', 'enable-checked-mode', 'true', '--ez', 'verify-entry-points', 'true', '--ez', 'start-paused', 'true', '--ez', 'disable-service-auth-codes', 'true', '--es', 'dart-flags', 'foo,--null_assertions', '--ez', 'use-test-fonts', 'true', '--ez', 'verbose-logging', 'true', '--user', '10', 'FlutterActivity', ], ));
final LaunchResult launchResult = await device.startApp( apk, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, startPaused: true, disableServiceAuthCodes: true, dartFlags: 'foo', enableSoftwareRendering: true, skiaDeterministicRendering: true, traceSkia: true, traceAllowlist: 'bar,baz', traceSkiaAllowlist: 'skia.a,skia.b', traceSystrace: true, traceToFile: 'path/to/trace.binpb', endlessTraceBuffer: true, dumpSkpOnShaderCompilation: true, cacheSkSL: true, purgePersistentCache: true, useTestFonts: true, verboseSystemLogs: true, enableImpeller: ImpellerStatus.enabled, nullAssertions: true, ), platformArgs: <String, dynamic>{}, userIdentifier: '10', );
// This fails to start due to VM Service discovery issues. expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); });}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String get adbPath => 'adb';
@override bool get licensesAvailable => false;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717// 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:async';import 'dart:convert';import 'dart:typed_data';
import 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_console.dart';import 'package:flutter_tools/src/android/android_device.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/project.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
void main() { testWithoutContext('AndroidDevice stores the requested id', () { final AndroidDevice device = setUpAndroidDevice();
expect(device.id, '1234'); });
testWithoutContext('parseAdbDeviceProperties parses adb shell output', () { final Map<String, String> properties = parseAdbDeviceProperties(kAdbShellGetprop);
expect(properties, isNotNull); expect(properties['ro.build.characteristics'], 'emulator'); expect(properties['ro.product.cpu.abi'], 'x86_64'); expect(properties['ro.build.version.sdk'], '23'); });
testWithoutContext('adb exiting with heap corruption is only allowed on windows', () async { final List<FakeCommand> commands = <FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]\n[ro.build.characteristics]: [unused]', // Heap corruption exit code. exitCode: -1073740940, ), ];
final AndroidDevice windowsDevice = setUpAndroidDevice( processManager: FakeProcessManager.list(commands.toList()), platform: FakePlatform(operatingSystem: 'windows'), ); final AndroidDevice linuxDevice = setUpAndroidDevice( processManager: FakeProcessManager.list(commands.toList()), platform: FakePlatform(), ); final AndroidDevice macOsDevice = setUpAndroidDevice( processManager: FakeProcessManager.list(commands.toList()), platform: FakePlatform(operatingSystem: 'macos') );
// Parsing succeeds despite the error. expect(await windowsDevice.isLocalEmulator, true);
// Parsing fails and these default to false. expect(await linuxDevice.isLocalEmulator, false); expect(await macOsDevice.isLocalEmulator, false); });
testWithoutContext('AndroidDevice can detect TargetPlatform from property ' 'abi and abiList', () async { // The format is [ABI, ABI list]: expected target platform. final Map<List<String>, TargetPlatform> values = <List<String>, TargetPlatform>{ <String>['x86_64', 'unknown']: TargetPlatform.android_x64, <String>['x86', 'unknown']: TargetPlatform.android_x86, // The default ABI is arm32 <String>['???', 'unknown']: TargetPlatform.android_arm, <String>['arm64-v8a', 'arm64-v8a,']: TargetPlatform.android_arm64, // The Kindle Fire runs 32 bit apps on 64 bit hardware. <String>['arm64-v8a', 'arm']: TargetPlatform.android_arm, };
for (final MapEntry<List<String>, TargetPlatform> entry in values.entries) { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.product.cpu.abi]: [${entry.key.first}]\n' '[ro.product.cpu.abilist]: [${entry.key.last}]', ), ]), );
expect(await device.targetPlatform, entry.value); } });
testWithoutContext('AndroidDevice supports profile/release mode on arm and x64 targets ' 'abi and abiList', () async { // The format is [ABI, ABI list]: expected release mode support. final Map<List<String>, bool> values = <List<String>, bool>{ <String>['x86_64', 'unknown']: true, <String>['x86', 'unknown']: false, // The default ABI is arm32 <String>['???', 'unknown']: true, <String>['arm64-v8a', 'arm64-v8a,']: true, // The Kindle Fire runs 32 bit apps on 64 bit hardware. <String>['arm64-v8a', 'arm']: true, };
for (final MapEntry<List<String>, bool> entry in values.entries) { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.product.cpu.abi]: [${entry.key.first}]\n' '[ro.product.cpu.abilist]: [${entry.key.last}]' ), ]), );
expect(await device.supportsRuntimeMode(BuildMode.release), entry.value); // Debug is always supported. expect(await device.supportsRuntimeMode(BuildMode.debug), true); // jitRelease is never supported. expect(await device.supportsRuntimeMode(BuildMode.jitRelease), false); } });
testWithoutContext('AndroidDevice can detect local emulator for known types', () async { for (final String hardware in kKnownHardware.keys) { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'adb', '-s', '1234', 'shell', 'getprop', ], stdout: '[ro.hardware]: [$hardware]\n' '[ro.build.characteristics]: [unused]' ), ]) );
expect(await device.isLocalEmulator, kKnownHardware[hardware] == HardwareType.emulator); } });
testWithoutContext('AndroidDevice can detect unknown hardware', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', 'getprop', ], stdout: '[ro.hardware]: [unknown]\n' '[ro.build.characteristics]: [att]' ), ]) );
expect(await device.isLocalEmulator, false); });
testWithoutContext('AndroidDevice can detect unknown emulator', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'shell', 'getprop', ], stdout: '[ro.hardware]: [unknown]\n' '[ro.build.characteristics]: [att,emulator]' ), ]) );
expect(await device.isLocalEmulator, true); });
testWithoutContext('isSupportedForProject is true on module project', () async { final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file('pubspec.yaml') ..createSync() ..writeAsStringSync(r'''name: example
flutter: module: {}'''); fileSystem.file('.packages').createSync(); final FlutterProject flutterProject = FlutterProjectFactory( fileSystem: fileSystem, logger: BufferLogger.test(), ).fromDirectory(fileSystem.currentDirectory); final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), true); });
testWithoutContext('isSupportedForProject is true with editable host app', () async { final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); fileSystem.directory('android').createSync(); final FlutterProject flutterProject = FlutterProjectFactory( fileSystem: fileSystem, logger: BufferLogger.test(), ).fromDirectory(fileSystem.currentDirectory);
final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), true); });
testWithoutContext('isSupportedForProject is false with no host app and no module', () async { final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); final FlutterProject flutterProject = FlutterProjectFactory( fileSystem: fileSystem, logger: BufferLogger.test(), ).fromDirectory(fileSystem.currentDirectory);
final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), false); });
testWithoutContext('AndroidDevice returns correct ID for responsive emulator', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', 'emulator-5555', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]' ), ]), id: 'emulator-5555', androidConsoleSocketFactory: (String host, int port) async => FakeWorkingAndroidConsoleSocket('dummyEmulatorId'), );
expect(await device.emulatorId, equals('dummyEmulatorId')); });
testWithoutContext('AndroidDevice does not create socket for non-emulator devices', () async { bool socketWasCreated = false;
// Still use an emulator-looking ID so we can be sure the failure is due // to the isLocalEmulator field and not because the ID doesn't contain a // port. final AndroidDevice device = setUpAndroidDevice( id: 'emulator-5555', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', 'emulator-5555', 'shell', 'getprop'], stdout: '[ro.hardware]: [samsungexynos7420]' ), ]), androidConsoleSocketFactory: (String host, int port) async { socketWasCreated = true; throw Exception('Socket was created for non-emulator'); } );
expect(await device.emulatorId, isNull); expect(socketWasCreated, isFalse); });
testWithoutContext('AndroidDevice does not create socket for emulators with no port', () async { bool socketWasCreated = false; final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]' ), ]), androidConsoleSocketFactory: (String host, int port) async { socketWasCreated = true; throw Exception('Socket was created for emulator without port in ID'); }, );
expect(await device.emulatorId, isNull); expect(socketWasCreated, isFalse); });
testWithoutContext('AndroidDevice.emulatorId is null for connection error', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]' ), ]), androidConsoleSocketFactory: (String host, int port) => throw Exception('Fake socket error'), );
expect(await device.emulatorId, isNull); });
testWithoutContext('AndroidDevice.emulatorId is null for unresponsive device', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]' ), ]), androidConsoleSocketFactory: (String host, int port) async => FakeUnresponsiveAndroidConsoleSocket(), );
expect(await device.emulatorId, isNull); });
testWithoutContext('AndroidDevice.emulatorId is null on early disconnect', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.hardware]: [goldfish]' ), ]), androidConsoleSocketFactory: (String host, int port) async => FakeDisconnectingAndroidConsoleSocket() );
expect(await device.emulatorId, isNull); });
testWithoutContext('AndroidDevice lastLogcatTimestamp returns null if shell command failed', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-t', '1'], exitCode: 1, ), ]) );
expect(await device.lastLogcatTimestamp(), isNull); });
testWithoutContext('AndroidDevice AdbLogReaders for past+future and future logs are not the same', () async { final AndroidDevice device = setUpAndroidDevice( processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [23]', exitCode: 1, ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-s', 'flutter'], ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time'], ), ]) );
final DeviceLogReader pastLogReader = await device.getLogReader(includePastLogs: true); final DeviceLogReader defaultLogReader = await device.getLogReader(); expect(pastLogReader, isNot(equals(defaultLogReader)));
// Getting again is cached. expect(pastLogReader, equals(await device.getLogReader(includePastLogs: true))); expect(defaultLogReader, equals(await device.getLogReader())); });
testWithoutContext('Can parse adb shell dumpsys info', () { const String exampleOutput = r'''Applications Memory Usage (in Kilobytes):Uptime: 441088659 Realtime: 521464097
** MEMINFO in pid 16141 [io.flutter.demo.gallery] ** Pss Private Private SwapPss Heap Heap Heap Total Dirty Clean Dirty Size Alloc Free ------ ------ ------ ------ ------ ------ ------ Native Heap 8648 8620 0 16 20480 12403 8076 Dalvik Heap 547 424 40 18 2628 1092 1536 Dalvik Other 464 464 0 0 Stack 496 496 0 0 Ashmem 2 0 0 0 Gfx dev 212 204 0 0 Other dev 48 0 48 0 .so mmap 10770 708 9372 25 .apk mmap 240 0 0 0 .ttf mmap 35 0 32 0 .dex mmap 2205 4 1172 0 .oat mmap 64 0 0 0 .art mmap 4228 3848 24 2 Other mmap 20713 4 20704 0 GL mtrack 2380 2380 0 0 Unknown 43971 43968 0 1 TOTAL 95085 61120 31392 62 23108 13495 9612
App Summary Pss(KB) ------ Java Heap: 4296 Native Heap: 8620 Code: 11288 Stack: 496 Graphics: 2584 Private Other: 65228 System: 2573
TOTAL: 95085 TOTAL SWAP PSS: 62
Objects Views: 9 ViewRootImpl: 1 AppContexts: 3 Activities: 1 Assets: 4 AssetManagers: 3 Local Binders: 10 Proxy Binders: 18 Parcel memory: 6 Parcel count: 24 Death Recipients: 0 OpenSSL Sockets: 0 WebViews: 0
SQL MEMORY_USED: 0 PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0''';
final AndroidMemoryInfo result = parseMeminfoDump(exampleOutput);
// Parses correctly expect(result.realTime, 521464097); expect(result.javaHeap, 4296); expect(result.nativeHeap, 8620); expect(result.code, 11288); expect(result.stack, 496); expect(result.graphics, 2584); expect(result.privateOther, 65228); expect(result.system, 2573);
// toJson works correctly final Map<String, Object> json = result.toJson();
expect(json, containsPair('Realtime', 521464097)); expect(json, containsPair('Java Heap', 4296)); expect(json, containsPair('Native Heap', 8620)); expect(json, containsPair('Code', 11288)); expect(json, containsPair('Stack', 496)); expect(json, containsPair('Graphics', 2584)); expect(json, containsPair('Private Other', 65228)); expect(json, containsPair('System', 2573));
// computed from summation of other fields. expect(json, containsPair('Total', 95085));
// contains identifier for platform in memory info. expect(json, containsPair('platform', 'Android')); });
testWithoutContext('AndroidDevice stopApp does nothing if app is not passed', () async { final AndroidDevice device = setUpAndroidDevice();
expect(await device.stopApp(null), isFalse); });
}
AndroidDevice setUpAndroidDevice({ String? id, AndroidSdk? androidSdk, FileSystem? fileSystem, ProcessManager? processManager, Platform? platform, AndroidConsoleSocketFactory androidConsoleSocketFactory = kAndroidConsoleSocketFactory,}) { androidSdk ??= FakeAndroidSdk(); return AndroidDevice(id ?? '1234', modelID: 'TestModel', logger: BufferLogger.test(), platform: platform ?? FakePlatform(), androidSdk: androidSdk, fileSystem: fileSystem ?? MemoryFileSystem.test(), processManager: processManager ?? FakeProcessManager.any(), androidConsoleSocketFactory: androidConsoleSocketFactory, );}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String get adbPath => 'adb';}
const String kAdbShellGetprop = '''[dalvik.vm.dex2oat-Xms]: [64m][dalvik.vm.dex2oat-Xmx]: [512m][dalvik.vm.heapsize]: [384m][dalvik.vm.image-dex2oat-Xms]: [64m][dalvik.vm.image-dex2oat-Xmx]: [64m][dalvik.vm.isa.x86.variant]: [dalvik.vm.isa.x86.features=default][dalvik.vm.isa.x86_64.features]: [default][dalvik.vm.isa.x86_64.variant]: [x86_64][dalvik.vm.lockprof.threshold]: [500][dalvik.vm.stack-trace-file]: [/data/anr/traces.txt][debug.atrace.tags.enableflags]: [0][debug.force_rtl]: [0][gsm.current.phone-type]: [1][gsm.network.type]: [Unknown][gsm.nitz.time]: [1473102078793][gsm.operator.alpha]: [][gsm.operator.iso-country]: [][gsm.operator.isroaming]: [false][gsm.operator.numeric]: [][gsm.sim.operator.alpha]: [][gsm.sim.operator.iso-country]: [][gsm.sim.operator.numeric]: [][gsm.sim.state]: [NOT_READY][gsm.version.ril-impl]: [android reference-ril 1.0][init.svc.adbd]: [running][init.svc.bootanim]: [running][init.svc.console]: [running][init.svc.debuggerd]: [running][init.svc.debuggerd64]: [running][init.svc.drm]: [running][init.svc.fingerprintd]: [running][init.svc.gatekeeperd]: [running][init.svc.goldfish-logcat]: [stopped][init.svc.goldfish-setup]: [stopped][init.svc.healthd]: [running][init.svc.installd]: [running][init.svc.keystore]: [running][init.svc.lmkd]: [running][init.svc.logd]: [running][init.svc.logd-reinit]: [stopped][init.svc.media]: [running][init.svc.netd]: [running][init.svc.perfprofd]: [running][init.svc.qemu-props]: [stopped][init.svc.ril-daemon]: [running][init.svc.servicemanager]: [running][init.svc.surfaceflinger]: [running][init.svc.ueventd]: [running][init.svc.vold]: [running][init.svc.zygote]: [running][init.svc.zygote_secondary]: [running][net.bt.name]: [Android][net.change]: [net.qtaguid_enabled][net.eth0.dns1]: [10.0.2.3][net.eth0.gw]: [10.0.2.2][net.gprs.local-ip]: [10.0.2.15][net.hostname]: [android-ccd858aa3d3825ee][net.qtaguid_enabled]: [1][net.tcp.default_init_rwnd]: [60][persist.sys.dalvik.vm.lib.2]: [libart.so][persist.sys.profiler_ms]: [0][persist.sys.timezone]: [America/Los_Angeles][persist.sys.usb.config]: [adb][qemu.gles]: [1][qemu.hw.mainkeys]: [0][qemu.sf.fake_camera]: [none][qemu.sf.lcd_density]: [420][rild.libargs]: [-d /dev/ttyS0][rild.libpath]: [/system/lib/libreference-ril.so][ro.allow.mock.location]: [0][ro.baseband]: [unknown][ro.board.platform]: [][ro.boot.hardware]: [ranchu][ro.bootimage.build.date]: [Wed Jul 20 21:03:09 UTC 2016][ro.bootimage.build.date.utc]: [1469048589][ro.bootimage.build.fingerprint]: [Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/3079352:userdebug/test-keys][ro.bootloader]: [unknown][ro.bootmode]: [unknown][ro.build.characteristics]: [emulator][ro.build.date]: [Wed Jul 20 21:02:14 UTC 2016][ro.build.date.utc]: [1469048534][ro.build.description]: [sdk_google_phone_x86_64-userdebug 6.0 MASTER 3079352 test-keys][ro.build.display.id]: [sdk_google_phone_x86_64-userdebug 6.0 MASTER 3079352 test-keys][ro.build.fingerprint]: [Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/3079352:userdebug/test-keys][ro.build.flavor]: [sdk_google_phone_x86_64-userdebug][ro.build.host]: [vpba14.mtv.corp.google.com][ro.build.id]: [MASTER][ro.build.product]: [generic_x86_64][ro.build.tags]: [test-keys][ro.build.type]: [userdebug][ro.build.user]: [android-build][ro.build.version.all_codenames]: [REL][ro.build.version.base_os]: [][ro.build.version.codename]: [REL][ro.build.version.incremental]: [3079352][ro.build.version.preview_sdk]: [0][ro.build.version.release]: [6.0][ro.build.version.sdk]: [23][ro.build.version.security_patch]: [2015-10-01][ro.com.google.locationfeatures]: [1][ro.config.alarm_alert]: [Alarm_Classic.ogg][ro.config.nocheckin]: [yes][ro.config.notification_sound]: [OnTheHunt.ogg][ro.crypto.state]: [unencrypted][ro.dalvik.vm.native.bridge]: [0][ro.debuggable]: [1][ro.hardware]: [ranchu][ro.hardware.audio.primary]: [goldfish][ro.hwui.drop_shadow_cache_size]: [6][ro.hwui.gradient_cache_size]: [1][ro.hwui.layer_cache_size]: [48][ro.hwui.path_cache_size]: [32][ro.hwui.r_buffer_cache_size]: [8][ro.hwui.text_large_cache_height]: [1024][ro.hwui.text_large_cache_width]: [2048][ro.hwui.text_small_cache_height]: [1024][ro.hwui.text_small_cache_width]: [1024][ro.hwui.texture_cache_flushrate]: [0.4][ro.hwui.texture_cache_size]: [72][ro.kernel.android.checkjni]: [1][ro.kernel.android.qemud]: [1][ro.kernel.androidboot.hardware]: [ranchu][ro.kernel.clocksource]: [pit][ro.kernel.qemu]: [1][ro.kernel.qemu.gles]: [1][ro.opengles.version]: [131072][ro.product.board]: [][ro.product.brand]: [Android][ro.product.cpu.abi]: [x86_64][ro.product.cpu.abilist]: [x86_64,x86][ro.product.cpu.abilist32]: [x86][ro.product.cpu.abilist64]: [x86_64][ro.product.device]: [generic_x86_64][ro.product.locale]: [en-US][ro.product.manufacturer]: [unknown][ro.product.model]: [Android SDK built for x86_64][ro.product.name]: [sdk_google_phone_x86_64][ro.radio.use-ppp]: [no][ro.revision]: [0][ro.secure]: [1][ro.serialno]: [][ro.wifi.channels]: [][ro.zygote]: [zygote64_32][selinux.reload_policy]: [1][service.bootanim.exit]: [0][status.battery.level]: [5][status.battery.level_raw]: [50][status.battery.level_scale]: [9][status.battery.state]: [Slow][sys.sysctl.extra_free_kbytes]: [24300][sys.usb.config]: [adb][sys.usb.state]: [adb][vold.has_adoptable]: [1][wlan.driver.status]: [unloaded][xmpp.auto-presence]: [true]''';
/// A mock Android Console that presents a connection banner and responds to/// "avd name" requests with the supplied name.class FakeWorkingAndroidConsoleSocket extends Fake implements Socket { FakeWorkingAndroidConsoleSocket(this.avdName) { _controller.add('Android Console: Welcome!\n'); // Include OK in the same packet here. In the response to "avd name" // it's sent alone to ensure both are handled. _controller.add('Android Console: Some intro text\nOK\n'); }
final String avdName; final StreamController<String> _controller = StreamController<String>();
@override Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override void add(List<int> data) { final String text = ascii.decode(data); if (text == 'avd name\n') { _controller.add('$avdName\n'); // Include OK in its own packet here. In welcome banner it's included // as part of the previous text to ensure both are handled. _controller.add('OK\n'); } else { throw Exception('Unexpected command $text'); } }
@override void destroy() { }}
/// An Android console socket that drops all input and returns no output.class FakeUnresponsiveAndroidConsoleSocket extends Fake implements Socket { final StreamController<String> _controller = StreamController<String>();
@override Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override void add(List<int> data) {}
@override void destroy() { }}
/// An Android console socket that drops all input and returns no output.class FakeDisconnectingAndroidConsoleSocket extends Fake implements Socket { FakeDisconnectingAndroidConsoleSocket() { _controller.add('Android Console: Welcome!\n'); // Include OK in the same packet here. In the response to "avd name" // it's sent alone to ensure both are handled. _controller.add('Android Console: Some intro text\nOK\n'); }
final StreamController<String> _controller = StreamController<String>();
@override Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override void add(List<int> data) { _controller.close(); }
@override void destroy() { }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225// 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:async';
import 'package:flutter_tools/src/android/android_emulator.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/device.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
const String emulatorID = 'i1234';const String errorText = '[Android emulator test error]';const List<String> kEmulatorLaunchCommand = <String>[ 'emulator', '-avd', emulatorID,];
void main() { group('android_emulator', () { testWithoutContext('flags emulators without config', () { const String emulatorID = '1234';
final AndroidEmulator emulator = AndroidEmulator( emulatorID, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.id, emulatorID); expect(emulator.hasConfig, false); });
testWithoutContext('flags emulators with config', () { const String emulatorID = '1234'; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: const <String, String>{'name': 'test'}, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), );
expect(emulator.id, emulatorID); expect(emulator.hasConfig, true); });
testWithoutContext('reads expected metadata', () { const String emulatorID = '1234'; const String manufacturer = 'Me'; const String displayName = 'The best one'; final Map<String, String> properties = <String, String>{ 'hw.device.manufacturer': manufacturer, 'avd.ini.displayname': displayName, }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), );
expect(emulator.id, emulatorID); expect(emulator.name, displayName); expect(emulator.manufacturer, manufacturer); expect(emulator.category, Category.mobile); expect(emulator.platformType, PlatformType.android); });
testWithoutContext('prefers displayname for name', () { const String emulatorID = '1234'; const String displayName = 'The best one'; final Map<String, String> properties = <String, String>{ 'avd.ini.displayname': displayName, }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), );
expect(emulator.name, displayName); });
testWithoutContext('uses cleaned up ID if no displayname is set', () { // Android Studio uses the ID with underscores replaced with spaces // for the name if displayname is not set so we do the same. const String emulatorID = 'This_is_my_ID'; final Map<String, String> properties = <String, String>{ 'avd.ini.notadisplayname': 'this is not a display name', }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), );
expect(emulator.name, 'This is my ID'); });
testWithoutContext('parses ini files', () { const String iniFile = ''' hw.device.name=My Test Name #hw.device.name=Bad Name
hw.device.manufacturer=Me avd.ini.displayname = dispName '''; final Map<String, String> results = parseIniLines(iniFile.split('\n'));
expect(results['hw.device.name'], 'My Test Name'); expect(results['hw.device.manufacturer'], 'Me'); expect(results['avd.ini.displayname'], 'dispName'); }); });
group('Android emulator launch ', () { late FakeAndroidSdk mockSdk;
setUp(() { mockSdk = FakeAndroidSdk(); mockSdk.emulatorPath = 'emulator'; });
testWithoutContext('succeeds', () async { final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand(command: kEmulatorLaunchCommand), ]), androidSdk: mockSdk, logger: BufferLogger.test(), );
await emulator.launch(startupDuration: Duration.zero); });
testWithoutContext('succeeds with coldboot launch', () async { final List<String> kEmulatorLaunchColdBootCommand = <String>[ ...kEmulatorLaunchCommand, '-no-snapshot-load', ]; final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand(command: kEmulatorLaunchColdBootCommand), ]), androidSdk: mockSdk, logger: BufferLogger.test(), );
await emulator.launch(startupDuration: Duration.zero, coldBoot: true); });
testWithoutContext('prints error on failure', () async { final BufferLogger logger = BufferLogger.test(); final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: kEmulatorLaunchCommand, exitCode: 1, stderr: errorText, stdout: 'dummy text', ), ]), androidSdk: mockSdk, logger: logger, );
await emulator.launch(startupDuration: Duration.zero);
expect(logger.errorText, contains(errorText)); });
testWithoutContext('prints nothing on late failure with empty stderr', () async { final BufferLogger logger = BufferLogger.test(); final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: kEmulatorLaunchCommand, exitCode: 1, stdout: 'dummy text', completer: Completer<void>(), ), ]), androidSdk: mockSdk, logger: logger, ); await emulator.launch(startupDuration: Duration.zero);
expect(logger.errorText, isEmpty); });
testWithoutContext('throws if emulator not found', () async { mockSdk.emulatorPath = null;
final AndroidEmulator emulator = AndroidEmulator( emulatorID, processManager: FakeProcessManager.empty(), androidSdk: mockSdk, logger: BufferLogger.test(), );
await expectLater( () => emulator.launch(startupDuration: Duration.zero), throwsA(isException.having( (Exception exception) => exception.toString(), 'description', contains('Emulator is missing from the Android SDK'), )), ); }); });}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String? emulatorPath;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937// 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 'package:archive/archive.dart';import 'package:file/memory.dart';import 'package:file_testing/file_testing.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/application_package.dart';import 'package:flutter_tools/src/android/gradle.dart';import 'package:flutter_tools/src/android/gradle_errors.dart';import 'package:flutter_tools/src/android/gradle_utils.dart';import 'package:flutter_tools/src/artifacts.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/process.dart';import 'package:flutter_tools/src/base/user_messages.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/reporting/reporting.dart';import 'package:test/fake.dart';import 'package:unified_analytics/unified_analytics.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fake_process_manager.dart';import '../../src/fakes.dart';
void main() { group('gradle build', () { late BufferLogger logger; late TestUsage testUsage; late FakeAnalytics fakeAnalytics; late FileSystem fileSystem; late FakeProcessManager processManager;
setUp(() { processManager = FakeProcessManager.empty(); logger = BufferLogger.test(); testUsage = TestUsage(); fileSystem = MemoryFileSystem.test(); Cache.flutterRoot = '';
fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); });
testUsingContext('Can immediately tool exit on recognized exit code/stderr', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
bool handlerCalled = false; await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { handlerCalled = true; return GradleBuildStatus.exit; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(handlerCalled, isTrue);
expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(2));
expect( fakeAnalytics.sentEvents, containsAll(<Event>[ Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle'), Event.flutterBuildInfo(label: 'gradle-random-event-label-failure', buildType: 'gradle'), ]), );
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'gradle', ), true, );
}, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Verbose mode for APKs includes Gradle stacktrace and sets debug log level', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: BufferLogger.test(verbose: true), processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '--full-stacktrace', '--info', '-Pverbose=true', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[], ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Can retry build on recognized exit code/stderr', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), );
const FakeCommand fakeCmd = FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', );
processManager.addCommand(fakeCmd);
const int maxRetries = 2; for (int i = 0; i < maxRetries; i++) { processManager.addCommand(fakeCmd); }
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
int testFnCalled = 0; await expectLater(() async { await builder.buildGradleApp( maxRetries: maxRetries, project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { if (line.contains('Some gradle message')) { testFnCalled++; return true; } return false; }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { return GradleBuildStatus.retry; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(logger.statusText, contains('Retrying Gradle Build: #1, wait time: 100ms')); expect(logger.statusText, contains('Retrying Gradle Build: #2, wait time: 200ms'));
expect(testFnCalled, equals(maxRetries + 1)); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(4));
expect(fakeAnalytics.sentEvents, hasLength(7)); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'gradle-random-event-label-failure', buildType: 'gradle', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Converts recognized ProcessExceptions into tools exits', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
bool handlerCalled = false; await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { handlerCalled = true; return GradleBuildStatus.exit; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(handlerCalled, isTrue);
expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(2));
expect(fakeAnalytics.sentEvents, hasLength(3)); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'gradle-random-event-label-failure', buildType: 'gradle', ), ));
}, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('rethrows unrecognized ProcessException', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(FakeCommand( command: const <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, onRun: () { throw const ProcessException('', <String>[], 'Unrecognized'); } ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsProcessException()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('logs success event after a successful retry', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nnSome gradle message\n', )); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { return GradleBuildStatus.retry; }, eventLabel: 'random-event-label', ), ], ); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-success', parameters: CustomDimensions(), ), )); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('performs code size analysis and sends analytics', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform( environment: <String, String>{ 'HOME': '/home', }, ), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Pcode-size-directory=foo', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
final Archive archive = Archive() ..addFile(ArchiveFile('AndroidManifest.xml', 100, List<int>.filled(100, 0))) ..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List<int>.filled(10, 0))) ..addFile(ArchiveFile('META-INF/CERT.SF', 10, List<int>.filled(10, 0))) ..addFile(ArchiveFile('lib/arm64-v8a/libapp.so', 50, List<int>.filled(50, 0))) ..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List<int>.filled(50, 0)));
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') ..createSync(recursive: true) ..writeAsBytesSync(ZipEncoder().encode(archive)!);
fileSystem.file('foo/snapshot.arm64-v8a.json') ..createSync(recursive: true) ..writeAsStringSync(r'''[ { "l": "dart:_internal", "c": "SubListIterable", "n": "[Optimized] skip", "s": 2400 }]'''); fileSystem.file('foo/trace.arm64-v8a.json') ..createSync(recursive: true) ..writeAsStringSync('{}');
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, codeSizeDirectory: 'foo', ), targetArchs: <AndroidArch>[AndroidArch.arm64_v8a], ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[], );
expect(testUsage.events, contains( const TestUsageEvent( 'code-size-analysis', 'apk', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('indicates that an APK has been built successfully', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], )); fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], );
expect( logger.statusText, contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'), ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Uses namespace attribute if manifest lacks a package attribute', () async { final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); final AndroidSdk sdk = FakeAndroidSdk();
fileSystem.directory(project.android.hostAppGradleRoot) .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory(project.android.hostAppGradleRoot) .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('''apply from: irrelevant/flutter.gradle
android { namespace 'com.example.foo'}''');
fileSystem.directory(project.android.hostAppGradleRoot) .childDirectory('app') .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml') ..createSync(recursive: true) ..writeAsStringSync(r'''<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:label="namespacetest" android:name="${applicationName}" android:icon="@mipmap/ic_launcher"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>''');
final AndroidApk? androidApk = await AndroidApk.fromAndroidProject( project.android, androidSdk: sdk, fileSystem: fileSystem, logger: logger, processManager: processManager, processUtils: ProcessUtils(processManager: processManager, logger: logger), userMessages: UserMessages(), buildInfo: const BuildInfo(BuildMode.debug, null, treeShakeIcons: false), );
expect(androidApk?.id, 'com.example.foo'); });
testUsingContext('can call custom gradle task getBuildOptions and parse the result', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', 'printBuildVariants', ], stdout: '''BuildVariant: freeDebugBuildVariant: paidDebugBuildVariant: freeReleaseBuildVariant: paidReleaseBuildVariant: freeProfileBuildVariant: paidProfile ''', )); final List<String> actual = await builder.getBuildVariants( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), ); expect(actual, <String>['freeDebug', 'paidDebug', 'freeRelease', 'paidRelease', 'freeProfile', 'paidProfile']);
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'print', variableName: 'android build variants', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), Analytics: () => fakeAnalytics, });
testUsingContext('getBuildOptions returns empty list if gradle returns error', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', 'printBuildVariants', ], stderr: '''Gradle Crashed ''', exitCode: 1, )); final List<String> actual = await builder.getBuildVariants( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), ); expect(actual, const <String>[]); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('can call custom gradle task outputFreeDebugAppLinkSettings and parse the result', () async { final String expectedOutputPath; expectedOutputPath = fileSystem.path.join('/build/deeplink_data', 'app-link-settings-freeDebug.json'); final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(FakeCommand( command: <String>[ 'gradlew', '-q', '-PoutputPath=$expectedOutputPath', 'outputFreeDebugAppLinkSettings', ], )); await builder.outputsAppLinkSettings( 'freeDebug', project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), );
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'outputs', variableName: 'app link settings', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), FileSystem: () => fileSystem, ProcessManager: () => processManager, Analytics: () => fakeAnalytics, });
testUsingContext("doesn't indicate how to consume an AAR when printHowToConsumeAar is false", () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', );
expect( logger.statusText, contains('Built build/outputs/repo'), ); expect( logger.statusText.contains('Consuming the Module'), isFalse, ); expect(processManager, hasNoRemainingExpectations);
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'gradle-aar', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), Analytics: () => fakeAnalytics, });
testUsingContext('Verbose mode for AARs includes Gradle stacktrace and sets debug log level', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: BufferLogger.test(verbose: true), processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '--full-stacktrace', '--info', '-Pverbose=true', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('gradle exit code and stderr is forwarded to tool exit', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], exitCode: 108, stderr: 'Gradle task assembleAarRelease failed with exit code 108.', ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await expectLater(() async => builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', ), throwsToolExit(exitCode: 108, message: 'Gradle task assembleAarRelease failed with exit code 108.')); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with arm32 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_arm/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with arm64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_arm64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with x86 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x86', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x86', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x86', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_x86/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, ));
fileSystem.file('out/android_x64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('honors --no-android-gradle-daemon setting', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand( const FakeCommand(command: <String>[ 'gradlew', '-q', '--no-daemon', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], )); fileSystem.file('android/gradlew').createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, androidGradleDaemon: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with arm32 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm', 'assembleAarRelease', ], ));
fileSystem.file('out/android_arm/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true);
fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm64', 'assembleAarRelease', ], ));
fileSystem.file('out/android_arm64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with x86 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x86', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x86', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x86', 'assembleAarRelease', ], ));
fileSystem.file('out/android_x86/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine on x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x64', 'assembleAarRelease', ], ));
fileSystem.file('out/android_x64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), }); });}
class FakeGradleUtils extends Fake implements GradleUtils { @override String getExecutable(FlutterProject project) { return 'gradlew'; }}
class FakeAndroidStudio extends Fake implements AndroidStudio { @override String get javaPath => '/android-studio/jbr';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_device.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/application_package.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
const FakeCommand kAdbVersionCommand = FakeCommand( command: <String>['adb', 'version'], stdout: 'Android Debug Bridge version 1.0.39',);const FakeCommand kAdbStartServerCommand = FakeCommand( command: <String>['adb', 'start-server']);const FakeCommand kInstallCommand = FakeCommand( command: <String>[ 'adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk', ],);const FakeCommand kStoreShaCommand = FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'echo', '-n', '', '>', '/data/local/tmp/sky.app.sha1']);
void main() { late FileSystem fileSystem; late BufferLogger logger;
setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); });
AndroidDevice setUpAndroidDevice({ AndroidSdk? androidSdk, ProcessManager? processManager, }) { androidSdk ??= FakeAndroidSdk(); return AndroidDevice('1234', modelID: 'TestModel', logger: logger, platform: FakePlatform(), androidSdk: androidSdk, fileSystem: fileSystem, processManager: processManager ?? FakeProcessManager.any(), ); }
testWithoutContext('Cannot install app on API level below 16', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [11]', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk), false); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Cannot install app if APK file is missing', () async { final File apk = fileSystem.file('app-debug.apk'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( );
expect(await androidDevice.installApp(androidApk), false); });
testWithoutContext('Can install app on API level 16 or greater', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), kInstallCommand, kStoreShaCommand, ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Defaults to API level 16 if adb returns a null response', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), kInstallCommand, kStoreShaCommand, ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('displays error if user not found', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], ), // This command is run before the user is checked and is allowed to fail. const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', 'jane', 'app'], stderr: 'Blah blah', exitCode: 1, ), const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'install', '-t', '-r', '--user', 'jane', 'app-debug.apk', ], exitCode: 1, stderr: 'Exception occurred while executing: java.lang.IllegalArgumentException: Bad user number: jane', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: 'jane'), false); expect(logger.errorText, contains('Error: User "jane" not found. Run "adb shell pm list users" to see list of available identifiers.')); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will skip install if the correct version is up to date', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: 'package:app\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], stdout: 'example_sha', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); fileSystem.file('app-debug.apk.sha1').writeAsStringSync('example_sha'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will uninstall if the correct version is not up to date and install fails', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: 'package:app\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], stdout: 'different_example_sha', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], exitCode: 1, stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', ), const FakeCommand(command: <String>['adb', '-s', '1234', 'uninstall', '--user', '10', 'app']), kInstallCommand, const FakeCommand(command: <String>['adb', '-s', '1234', 'shell', 'echo', '-n', 'example_sha', '>', '/data/local/tmp/sky.app.sha1']), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); fileSystem.file('app-debug.apk.sha1').writeAsStringSync('example_sha'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will fail to install if the apk was never installed and it fails the first time', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], exitCode: 1, stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), false); expect(processManager, hasNoRemainingExpectations); });}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String get adbPath => 'adb';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474// 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 'package:file/file.dart';import 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/gradle_utils.dart';import 'package:flutter_tools/src/android/migrations/android_studio_java_gradle_conflict_migration.dart';import 'package:flutter_tools/src/android/migrations/min_sdk_version_migration.dart';import 'package:flutter_tools/src/android/migrations/top_level_gradle_build_file_migration.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/version.dart';import 'package:flutter_tools/src/project.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fakes.dart';
const String otherGradleVersionWrapper = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
const String gradleWrapperToMigrate = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
const String gradleWrapperToMigrateTo = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
String sampleModuleGradleBuildFile(String minSdkVersionString) { return r'''plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin"}
def localProperties = new Properties()def localPropertiesFile = rootProject.file('local.properties')if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) }}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')if (flutterVersionCode == null) { flutterVersionCode = '1'}
def flutterVersionName = localProperties.getProperty('flutter.versionName')if (flutterVersionName == null) { flutterVersionName = '1.0'}
android { namespace "com.example.asset_sample" compileSdk flutter.compileSdkVersion ndkVersion flutter.ndkVersion
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
kotlinOptions { jvmTarget = '1.8' }
sourceSets { main.java.srcDirs += 'src/main/kotlin' }
defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.asset_sample" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. ''' + minSdkVersionString + r'''
targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName }
buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } }}
flutter { source '../..'}
dependencies {}''';}
final Version androidStudioDolphin = Version(2021, 3, 1);
const Version _javaVersion17 = Version.withText(17, 0, 2, 'openjdk 17.0.2');const Version _javaVersion16 = Version.withText(16, 0, 2, 'openjdk 16.0.2');
void main() { group('Android migration', () { group('migrate the Gradle "clean" task to lazy declaration', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File topLevelGradleBuildFile;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); topLevelGradleBuildFile = project.hostAppGradleRoot.childFile('build.gradle'); });
testUsingContext('skipped if files are missing', () { final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); androidProjectMigration.migrate(); expect(topLevelGradleBuildFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains('Top-level Gradle build file not found, skipping migration of task "clean".')); });
testUsingContext('skipped if nothing to upgrade', () { topLevelGradleBuildFile.writeAsStringSync('''tasks.register("clean", Delete) { delete rootProject.buildDir} ''');
final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); final DateTime previousLastModified = topLevelGradleBuildFile.lastModifiedSync(); androidProjectMigration.migrate();
expect(topLevelGradleBuildFile.lastModifiedSync(), previousLastModified); });
testUsingContext('top-level build.gradle is migrated', () { topLevelGradleBuildFile.writeAsStringSync('''task clean(type: Delete) { delete rootProject.buildDir}''');
final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); androidProjectMigration.migrate();
expect(bufferLogger.traceText, contains('Migrating "clean" Gradle task to lazy declaration style.')); expect(topLevelGradleBuildFile.readAsStringSync(), equals('''tasks.register("clean", Delete) { delete rootProject.buildDir}''')); }); });
group('migrate the gradle version to one that does not conflict with the ' 'Android Studio-provided java version', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File gradleWrapperPropertiesFile;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); project.hostAppGradleRoot.childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .createSync(recursive: true); gradleWrapperPropertiesFile = project.hostAppGradleRoot .childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .childFile(gradleWrapperPropertiesFilename); });
testWithoutContext('skipped if files are missing', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); migration.migrate(); expect(gradleWrapperPropertiesFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains(gradleWrapperNotFound)); });
testWithoutContext('skipped if android studio is null', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if android studio version is null', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: null), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if error is encountered in migrate()', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeErroringJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(errorWhileMigrating)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if android studio version is less than flamingo', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(androidStudioVersionBelowFlamingo)); });
testWithoutContext('skipped if bundled java version is less than 17', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion16), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(javaVersionNot17)); });
testWithoutContext('nothing is changed if gradle version not one that was ' 'used by flutter create', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(otherGradleVersionWrapper); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), otherGradleVersionWrapper); expect(bufferLogger.traceText, isEmpty); });
testWithoutContext('change is made with one of the specific gradle versions' ' we migrate for', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrateTo); expect(bufferLogger.statusText, contains('Conflict detected between ' 'Android Studio Java version and Gradle version, upgrading Gradle ' 'version from 6.7 to $gradleVersion7_6_1.')); });
testWithoutContext('change is not made when opt out flag is set', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate + optOutFlag); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate + optOutFlag); expect(bufferLogger.traceText, contains(optOutFlagEnabled)); }); });
group('migrate min sdk versions less than 19 to flutter.minSdkVersion ' 'when in a FlutterProject that is an app', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late MinSdkVersionMigration migration;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); memoryFileSystem.currentDirectory.childDirectory('android').createSync(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), ); project.appGradleFile.parent.createSync(recursive: true); migration = MinSdkVersionMigration( project, bufferLogger ); });
testWithoutContext('do nothing when files missing', () { migration.migrate(); expect(bufferLogger.traceText, contains(appGradleNotFoundWarning)); });
testWithoutContext('replace when api 16', () { const String minSdkVersion16 = 'minSdkVersion 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('replace when api 17', () { const String minSdkVersion17 = 'minSdkVersion 17'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion17)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('replace when api 18', () { const String minSdkVersion18 = 'minSdkVersion 18'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion18)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('do nothing when >=api 19', () { const String minSdkVersion19 = 'minSdkVersion 19'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion19)); });
testWithoutContext('do nothing when already using ' 'flutter.minSdkVersion', () { project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(replacementMinSdkText)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('avoid rewriting comments', () { const String code = '// minSdkVersion 16 // old default\n' ' minSdkVersion 23 // new version'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(code)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(code)); });
testWithoutContext('do nothing when project is a module', () { project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), module: true, ); migration = MinSdkVersionMigration( project, bufferLogger ); const String minSdkVersion16 = 'minSdkVersion 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion16)); });
testWithoutContext('do nothing when minSdkVersion is set ' 'to a constant', () { const String minSdkVersionConstant = 'minSdkVersion kMinSdkversion'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersionConstant)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersionConstant)); });
testWithoutContext('do nothing when minSdkVersion is set ' 'using = syntax', () { const String equalsSyntaxMinSdkVersion16 = 'minSdkVersion = 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16)); }); }); });}
class FakeAndroidProject extends Fake implements AndroidProject { FakeAndroidProject({required Directory root, this.module, this.plugin}) : hostAppGradleRoot = root;
@override Directory hostAppGradleRoot;
final bool? module; final bool? plugin;
@override bool get isPlugin => plugin ?? false;
@override bool get isModule => module ?? false;
@override File get appGradleFile => hostAppGradleRoot.childDirectory('app').childFile('build.gradle');}
class FakeAndroidStudio extends Fake implements AndroidStudio { FakeAndroidStudio({required Version? version}) { _version = version; }
late Version? _version;
@override Version? get version => _version;}
class FakeErroringJava extends FakeJava { @override Version get version { throw Exception('How did this happen?'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/base/config.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/globals.dart' as globals;
import '../../src/common.dart';import '../../src/context.dart';
void main() { late MemoryFileSystem fileSystem; late FakeProcessManager processManager; late Config config;
setUp(() { fileSystem = MemoryFileSystem.test(); processManager = FakeProcessManager.empty(); config = Config.test(); });
group('AndroidSdk', () { testUsingContext('constructing an AndroidSdk handles no matching lines in build.prop', () { final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, withAndroidN: true, // Does not have valid version string buildProp: '\n\n\n', ); config.setValue('android-sdk', sdkDir.path);
try { AndroidSdk.locateAndroidSdk()!; } on StateError catch (err) { fail('sdk.reinitialize() threw a StateError:\n$err'); } }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Config: () => config, });
testUsingContext('parse sdk', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; expect(sdk.latestVersion, isNotNull); expect(sdk.latestVersion!.sdkLevel, 23); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Config: () => config, });
testUsingContext('parse sdk N', () { final Directory sdkDir = createSdkDirectory( withAndroidN: true, fileSystem: fileSystem, ); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; expect(sdk.latestVersion, isNotNull); expect(sdk.latestVersion!.sdkLevel, 24); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Config: () => config, });
testUsingContext('returns sdkmanager path under cmdline tools on Linux/macOS', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'sdkmanager') ).createSync(recursive: true);
expect(sdk.sdkManagerPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'sdkmanager')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext('returns sdkmanager path under cmdline tools (highest version) on Linux/macOS', () { final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, withSdkManager: false, ); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; final List<String> versions = <String>['3.0', '2.1', '1.0']; for (final String version in versions) { fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', version, 'bin', 'sdkmanager') ).createSync(recursive: true); }
expect(sdk.sdkManagerPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', '3.0', 'bin', 'sdkmanager')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext('Does not return sdkmanager under deprecated tools component', () { final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, withSdkManager: false, ); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'tools/bin/sdkmanager') ).createSync(recursive: true);
expect(sdk.sdkManagerPath, null); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext('Can look up cmdline tool from deprecated tools path', () { final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, withSdkManager: false, ); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'tools/bin/foo') ).createSync(recursive: true);
expect(sdk.getCmdlineToolsPath('foo'), '/.tmp_rand0/flutter_mock_android_sdk.rand0/tools/bin/foo'); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext('Caches adb location after first access', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; final File adbFile = fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'adb.exe') )..createSync(recursive: true);
expect(sdk.adbPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'adb.exe'));
adbFile.deleteSync(recursive: true);
expect(sdk.adbPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'adb.exe')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(operatingSystem: 'windows'), Config: () => config, });
testUsingContext('returns sdkmanager.bat path under cmdline tools for windows', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'sdkmanager.bat') ).createSync(recursive: true);
expect(sdk.sdkManagerPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'sdkmanager.bat')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(operatingSystem: 'windows'), Config: () => config, });
testUsingContext('returns sdkmanager version', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path); processManager.addCommand( const FakeCommand( command: <String>[ '/.tmp_rand0/flutter_mock_android_sdk.rand0/cmdline-tools/latest/bin/sdkmanager', '--version', ], stdout: '26.1.1\n', ), ); final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!;
expect(sdk.sdkManagerVersion, '26.1.1'); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Config: () => config, Platform: () => FakePlatform(environment: <String, String>{}), });
testUsingContext('returns validate sdk is well formed', () { final Directory sdkDir = createBrokenSdkDirectory(fileSystem: fileSystem); processManager.addCommand(const FakeCommand(command: <String>[ '/.tmp_rand0/flutter_mock_android_sdk.rand0/cmdline-tools/latest/bin/sdkmanager', '--version', ])); config.setValue('android-sdk', sdkDir.path); final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!;
final List<String> validationIssues = sdk.validateSdkWellFormed(); expect(validationIssues.first, 'No valid Android SDK platforms found in' ' /.tmp_rand0/flutter_mock_android_sdk.rand0/platforms. Candidates were:\n' ' - android-22\n' ' - android-23'); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Config: () => config, Platform: () => FakePlatform(), });
testUsingContext('does not throw on sdkmanager version check failure', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path); processManager.addCommand( const FakeCommand( command: <String>[ '/.tmp_rand0/flutter_mock_android_sdk.rand0/cmdline-tools/latest/bin/sdkmanager', '--version', ], stdout: '\n', stderr: 'Mystery error', exitCode: 1, ), );
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!;
expect(sdk.sdkManagerVersion, isNull); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Config: () => config, Platform: () => FakePlatform(environment: <String, String>{}), });
testUsingContext('throws on sdkmanager version check if sdkmanager not found', () { final Directory sdkDir = createSdkDirectory(withSdkManager: false, fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path); processManager.excludedExecutables.add('/.tmp_rand0/flutter_mock_android_sdk.rand0/cmdline-tools/latest/bin/sdkmanager'); final AndroidSdk? sdk = AndroidSdk.locateAndroidSdk();
expect(() => sdk!.sdkManagerVersion, throwsToolExit()); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Config: () => config, Platform: () => FakePlatform(), });
testUsingContext('returns avdmanager path under cmdline tools', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'avdmanager') ).createSync(recursive: true);
expect(sdk.avdManagerPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'avdmanager')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext('returns avdmanager path under cmdline tools on windows', () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'avdmanager.bat') ).createSync(recursive: true);
expect(sdk.avdManagerPath, fileSystem.path.join(sdk.directory.path, 'cmdline-tools', 'latest', 'bin', 'avdmanager.bat')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(operatingSystem: 'windows'), Config: () => config, });
testUsingContext("returns avdmanager path under tools if cmdline doesn't exist", () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'tools', 'bin', 'avdmanager') ).createSync(recursive: true);
expect(sdk.avdManagerPath, fileSystem.path.join(sdk.directory.path, 'tools', 'bin', 'avdmanager')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(), Config: () => config, });
testUsingContext("returns avdmanager path under tools if cmdline doesn't exist on windows", () { final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk.locateAndroidSdk()!; fileSystem.file( fileSystem.path.join(sdk.directory.path, 'tools', 'bin', 'avdmanager.bat') ).createSync(recursive: true);
expect(sdk.avdManagerPath, fileSystem.path.join(sdk.directory.path, 'tools', 'bin', 'avdmanager.bat')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => FakePlatform(operatingSystem: 'windows'), Config: () => config, }); });
const Map<String, String> llvmHostDirectoryName = <String, String>{ 'macos': 'darwin-x86_64', 'linux': 'linux-x86_64', 'windows': 'windows-x86_64', };
for (final String operatingSystem in <String>['windows', 'linux', 'macos']) { final FileSystem fileSystem; final String extension; if (operatingSystem == 'windows') { fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); extension = '.exe'; } else { fileSystem = MemoryFileSystem.test(); extension = ''; } testWithoutContext('ndk executables $operatingSystem', () { final Platform platform = FakePlatform(operatingSystem: operatingSystem); final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, platform: platform, ); config.setValue('android-sdk', sdkDir.path);
final AndroidSdk sdk = AndroidSdk(sdkDir, fileSystem: fileSystem); late File clang; late File ar; late File ld; const List<String> versions = <String>['22.1.7171670', '24.0.8215888']; for (final String version in versions) { final Directory binDir = sdk.directory .childDirectory('ndk') .childDirectory(version) .childDirectory('toolchains') .childDirectory('llvm') .childDirectory('prebuilt') .childDirectory(llvmHostDirectoryName[operatingSystem]!) .childDirectory('bin') ..createSync(recursive: true); // Save the last version. clang = binDir.childFile('clang$extension')..createSync(); ar = binDir.childFile('llvm-ar$extension')..createSync(); ld = binDir.childFile('ld.lld$extension')..createSync(); } // Check the last NDK version is used. expect( sdk.getNdkClangPath(platform: platform, config: config), clang.path, ); expect( sdk.getNdkArPath(platform: platform, config: config), ar.path, ); expect( sdk.getNdkLdPath(platform: platform, config: config), ld.path, ); });
for (final String envVar in <String>[ kAndroidNdkHome, kAndroidNdkPath, kAndroidNdkRoot, ]) { final Directory ndkDir = fileSystem.systemTempDirectory .createTempSync('flutter_mock_android_ndk.'); testWithoutContext('ndk executables with $operatingSystem $envVar', () { final Platform platform = FakePlatform( operatingSystem: operatingSystem, environment: <String, String>{ envVar: ndkDir.path, }, ); final Directory sdkDir = createSdkDirectory(fileSystem: fileSystem, platform: platform); config.setValue('android-sdk', sdkDir.path);
final Directory binDir = ndkDir .childDirectory('toolchains') .childDirectory('llvm') .childDirectory('prebuilt') .childDirectory(llvmHostDirectoryName[operatingSystem]!) .childDirectory('bin') ..createSync(recursive: true); final File clang = binDir.childFile('clang$extension')..createSync(); final File ar = binDir.childFile('llvm-ar$extension')..createSync(); final File ld = binDir.childFile('ld.lld$extension')..createSync();
final AndroidSdk sdk = AndroidSdk(sdkDir, fileSystem: fileSystem); expect( sdk.getNdkClangPath(platform: platform, config: config), clang.path, ); expect( sdk.getNdkArPath(platform: platform, config: config), ar.path, ); expect( sdk.getNdkLdPath(platform: platform, config: config), ld.path, ); }); }
testWithoutContext('ndk executables with config override $operatingSystem', () { final Platform platform = FakePlatform(operatingSystem: operatingSystem); final Directory sdkDir = createSdkDirectory( fileSystem: fileSystem, platform: platform, ); final Directory ndkDir = fileSystem.systemTempDirectory .createTempSync('flutter_mock_android_ndk.'); config.setValue('android-sdk', sdkDir.path); config.setValue('android-ndk', ndkDir.path);
final Directory binDir = ndkDir .childDirectory('toolchains') .childDirectory('llvm') .childDirectory('prebuilt') .childDirectory(llvmHostDirectoryName[operatingSystem]!) .childDirectory('bin') ..createSync(recursive: true); final File clang = binDir.childFile('clang$extension')..createSync(); final File ar = binDir.childFile('llvm-ar$extension')..createSync(); final File ld = binDir.childFile('ld.lld$extension')..createSync();
final AndroidSdk sdk = AndroidSdk(sdkDir, fileSystem: fileSystem); expect( sdk.getNdkClangPath(platform: platform, config: config), clang.path, ); expect( sdk.getNdkArPath(platform: platform, config: config), ar.path, ); expect( sdk.getNdkLdPath(platform: platform, config: config), ld.path, ); }); }}
/// A broken SDK installation.Directory createBrokenSdkDirectory({ bool withAndroidN = false, bool withSdkManager = true, required FileSystem fileSystem,}) { final Directory dir = fileSystem.systemTempDirectory.createTempSync('flutter_mock_android_sdk.'); _createSdkFile(dir, 'licenses/dummy'); _createSdkFile(dir, 'platform-tools/adb');
_createSdkFile(dir, 'build-tools/sda/aapt'); _createSdkFile(dir, 'build-tools/af/aapt'); _createSdkFile(dir, 'build-tools/ljkasd/aapt');
_createSdkFile(dir, 'platforms/android-22/android.jar'); _createSdkFile(dir, 'platforms/android-23/android.jar');
return dir;}
void _createSdkFile(Directory dir, String filePath, { String? contents }) { final File file = dir.childFile(filePath); file.createSync(recursive: true); if (contents != null) { file.writeAsStringSync(contents, flush: true); }}
Directory createSdkDirectory({ bool withAndroidN = false, bool withSdkManager = true, bool withPlatformTools = true, bool withBuildTools = true, required FileSystem fileSystem, String buildProp = _buildProp, Platform? platform,}) { platform ??= globals.platform; final Directory dir = fileSystem.systemTempDirectory.createTempSync('flutter_mock_android_sdk.'); final String exe = platform.isWindows ? '.exe' : ''; final String bat = platform.isWindows ? '.bat' : '';
void createDir(Directory dir, String path) { final Directory directory = dir.fileSystem.directory(dir.fileSystem.path.join(dir.path, path)); directory.createSync(recursive: true); }
createDir(dir, 'licenses');
if (withPlatformTools) { _createSdkFile(dir, 'platform-tools/adb$exe'); }
if (withBuildTools) { _createSdkFile(dir, 'build-tools/19.1.0/aapt$exe'); _createSdkFile(dir, 'build-tools/22.0.1/aapt$exe'); _createSdkFile(dir, 'build-tools/23.0.2/aapt$exe'); if (withAndroidN) { _createSdkFile(dir, 'build-tools/24.0.0-preview/aapt$exe'); } }
_createSdkFile(dir, 'platforms/android-22/android.jar'); _createSdkFile(dir, 'platforms/android-23/android.jar'); if (withAndroidN) { _createSdkFile(dir, 'platforms/android-N/android.jar'); _createSdkFile(dir, 'platforms/android-N/build.prop', contents: buildProp); }
if (withSdkManager) { _createSdkFile(dir, 'cmdline-tools/latest/bin/sdkmanager$bat'); } return dir;}
const String _buildProp = r'''ro.build.version.incremental=1624448ro.build.version.sdk=24ro.build.version.codename=REL''';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/base/common.dart';import 'package:flutter_tools/src/base/config.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/version.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/ios/plist_parser.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fake_process_manager.dart';
void main() {
group('installation detection on MacOS', () { const String homeMac = '/Users/me';
const Map<String, Object> macStudioInfoPlist3_3 = <String, Object>{ 'CFBundleGetInfoString': 'Android Studio 3.3, build AI-182.5107.16.33.5199772. Copyright JetBrains s.r.o., (c) 2000-2018', 'CFBundleShortVersionString': '3.3', 'CFBundleVersion': 'AI-182.5107.16.33.5199772', 'JVMOptions': <String, Object>{ 'Properties': <String, Object>{ 'idea.paths.selector': 'AndroidStudio3.3', 'idea.platform.prefix': 'AndroidStudio', }, }, };
const Map<String, Object> macStudioInfoPlist4_1 = <String, Object>{ 'CFBundleGetInfoString': 'Android Studio 4.1, build AI-201.8743.12.41.6858069. Copyright JetBrains s.r.o., (c) 2000-2020', 'CFBundleShortVersionString': '4.1', 'CFBundleVersion': 'AI-201.8743.12.41.6858069', 'JVMOptions': <String, Object>{ 'Properties': <String, Object>{ 'idea.vendor.name' : 'Google', 'idea.paths.selector': 'AndroidStudio4.1', 'idea.platform.prefix': 'AndroidStudio', }, }, };
const Map<String, Object> macStudioInfoPlist2020_3 = <String, Object>{ 'CFBundleGetInfoString': 'Android Studio 2020.3, build AI-203.7717.56.2031.7583922. Copyright JetBrains s.r.o., (c) 2000-2021', 'CFBundleShortVersionString': '2020.3', 'CFBundleVersion': 'AI-203.7717.56.2031.7583922', 'JVMOptions': <String, Object>{ 'Properties': <String, Object>{ 'idea.vendor.name' : 'Google', 'idea.paths.selector': 'AndroidStudio2020.3', 'idea.platform.prefix': 'AndroidStudio', }, }, };
const Map<String, Object> macStudioInfoPlist2022_1 = <String, Object>{ 'CFBundleGetInfoString': 'Android Studio 2022.1, build AI-221.6008.13.2211.9477386. Copyright JetBrains s.r.o., (c) 2000-2023', 'CFBundleShortVersionString': '2022.1', 'CFBundleVersion': 'AI-221.6008.13.2211.9477386', 'JVMOptions': <String, Object>{ 'Properties': <String, Object>{ 'idea.vendor.name' : 'Google', 'idea.paths.selector': 'AndroidStudio2022.1', 'idea.platform.prefix': 'AndroidStudio', }, }, };
const Map<String, Object> macStudioInfoPlistEap_2022_3_1_11 = <String, Object>{ 'CFBundleGetInfoString': 'Android Studio EAP AI-223.8836.35.2231.9848316, build AI-223.8836.35.2231.9848316. Copyright JetBrains s.r.o., (c) 2000-2023', 'CFBundleShortVersionString': 'EAP AI-223.8836.35.2231.9848316', 'CFBundleVersion': 'AI-223.8836.35.2231.9848316', 'JVMOptions': <String, Object>{ 'Properties': <String, Object>{ 'idea.vendor.name' : 'Google', 'idea.paths.selector': 'AndroidStudioPreview2022.3', 'idea.platform.prefix': 'AndroidStudio', }, }, };
late Config config; late FileSystem fileSystem; late FileSystemUtils fsUtils; late Platform platform; late FakePlistUtils plistUtils; late FakeProcessManager processManager;
setUp(() { config = Config.test(); fileSystem = MemoryFileSystem.test(); plistUtils = FakePlistUtils(); platform = FakePlatform( operatingSystem: 'macos', environment: <String, String>{'HOME': homeMac}, ); fsUtils = FileSystemUtils( fileSystem: fileSystem, platform: platform, ); processManager = FakeProcessManager.empty(); });
testUsingContext('discovers Android Studio >=4.1 location', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist4_1; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'jdk', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio, isNotNull); expect(studio.pluginsPath, equals(fileSystem.path.join( homeMac, 'Library', 'Application Support', 'Google', 'AndroidStudio4.1', ))); expect(studio.validationMessages, <String>['Java version 123']); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('discovers Android Studio >=2020.3 location', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2020_3; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio, isNotNull); expect(studio.pluginsPath, equals(fileSystem.path.join( homeMac, 'Library', 'Application Support', 'Google', 'AndroidStudio2020.3', ))); expect(studio.validationMessages, <String>['Java version 123']); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('discovers Android Studio <4.1 location', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist3_3; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'jdk', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio, isNotNull); expect(studio.pluginsPath, equals(fileSystem.path.join( homeMac, 'Library', 'Application Support', 'AndroidStudio3.3', ))); expect(studio.validationMessages, <String>['Java version 123']); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('discovers Android Studio EAP location', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio with suffix.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlistEap_2022_3_1_11; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio, isNotNull); expect(studio.pluginsPath, equals(fileSystem.path.join( homeMac, 'Library', 'Application Support', 'AndroidStudioPreview2022.3', ))); expect(studio.validationMessages, <String>['Java version 123']); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('does not discover Android Studio with JetBrainsToolboxApp wrapper', () { final String applicationPlistFolder = fileSystem.path.join( '/', 'Applications', 'Android Studio.app', 'Contents', ); fileSystem.directory(applicationPlistFolder).createSync(recursive: true);
final String applicationsPlistFilePath = fileSystem.path.join(applicationPlistFolder, 'Info.plist'); const Map<String, Object> jetbrainsInfoPlist = <String, Object>{ 'JetBrainsToolboxApp': 'ignored', }; plistUtils.fileContents[applicationsPlistFilePath] = jetbrainsInfoPlist;
final String homeDirectoryPlistFolder = fileSystem.path.join( fsUtils.homeDirPath!, 'Applications', 'Android Studio.app', 'Contents', ); fileSystem.directory(homeDirectoryPlistFolder).createSync(recursive: true);
final String homeDirectoryPlistFilePath = fileSystem.path.join(homeDirectoryPlistFolder, 'Info.plist'); plistUtils.fileContents[homeDirectoryPlistFilePath] = macStudioInfoPlist2020_3;
expect(AndroidStudio.allInstalled().length, 1); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => FakeProcessManager.any(), // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('discovers installation from Spotlight query', () { // One in expected location. final String studioInApplication = fileSystem.path.join( '/', 'Application', 'Android Studio.app', ); final String studioInApplicationPlistFolder = fileSystem.path.join( studioInApplication, 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true); final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist4_1;
// Two in random location only Spotlight knows about. final String randomLocation1 = fileSystem.path.join( '/', 'random', 'Android Studio Preview.app', ); final String randomLocation1PlistFolder = fileSystem.path.join( randomLocation1, 'Contents', ); fileSystem.directory(randomLocation1PlistFolder).createSync(recursive: true); final String randomLocation1PlistPath = fileSystem.path.join(randomLocation1PlistFolder, 'Info.plist'); plistUtils.fileContents[randomLocation1PlistPath] = macStudioInfoPlist4_1;
final String randomLocation2 = fileSystem.path.join( '/', 'random', 'Android Studio with Blaze.app', ); final String randomLocation2PlistFolder = fileSystem.path.join( randomLocation2, 'Contents', ); fileSystem.directory(randomLocation2PlistFolder).createSync(recursive: true); final String randomLocation2PlistPath = fileSystem.path.join(randomLocation2PlistFolder, 'Info.plist'); plistUtils.fileContents[randomLocation2PlistPath] = macStudioInfoPlist4_1; final String javaBin = fileSystem.path.join('jre', 'jdk', 'Contents', 'Home', 'bin', 'java');
// Spotlight finds the one known and two random installations. processManager.addCommands(<FakeCommand>[ FakeCommand( command: const <String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.google.android.studio*"', ], stdout: '$randomLocation1\n$randomLocation2\n$studioInApplication', ), FakeCommand( command: <String>[ fileSystem.path.join(randomLocation1, 'Contents', javaBin), '-version', ], ), FakeCommand( command: <String>[ fileSystem.path.join(randomLocation2, 'Contents', javaBin), '-version', ], ), FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, javaBin), '-version', ], ), ]);
// Results are de-duplicated, only 3 installed. expect(AndroidStudio.allInstalled().length, 3); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('finds latest valid install', () { final String applicationPlistFolder = fileSystem.path.join( '/', 'Applications', 'Android Studio.app', 'Contents', ); fileSystem.directory(applicationPlistFolder).createSync(recursive: true);
final String applicationsPlistFilePath = fileSystem.path.join(applicationPlistFolder, 'Info.plist'); plistUtils.fileContents[applicationsPlistFilePath] = macStudioInfoPlist3_3;
final String homeDirectoryPlistFolder = fileSystem.path.join( fsUtils.homeDirPath!, 'Applications', 'Android Studio.app', 'Contents', ); fileSystem.directory(homeDirectoryPlistFolder).createSync(recursive: true);
final String homeDirectoryPlistFilePath = fileSystem.path.join(homeDirectoryPlistFolder, 'Info.plist'); plistUtils.fileContents[homeDirectoryPlistFilePath] = macStudioInfoPlist4_1;
expect(AndroidStudio.allInstalled().length, 2); expect(AndroidStudio.latestValid()!.version, Version(4, 1, 0)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => FakeProcessManager.any(), Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('extracts custom paths for directly downloaded Android Studio', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist3_3; final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!; expect(studio, isNotNull); expect(studio.pluginsPath, equals(fileSystem.path.join( homeMac, 'Library', 'Application Support', 'AndroidStudio3.3', ))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => FakeProcessManager.any(), // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('finds Android Studio 2020.3 bundled Java version', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2020_3; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jre', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio.javaPath, equals(fileSystem.path.join( studioInApplicationPlistFolder, 'jre', 'Contents', 'Home', ))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('finds Android Studio 2022.1 bundled Java version', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2022_1; processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home', 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio.javaPath, equals(fileSystem.path.join( studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home', ))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); final Map<String, Object> plistWithoutVersion = Map<String, Object>.from(macStudioInfoPlist2022_1); plistWithoutVersion['CFBundleShortVersionString'] = ''; plistUtils.fileContents[plistFilePath] = plistWithoutVersion;
final String jdkPath = fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home');
processManager.addCommand(FakeCommand( command: <String>[ fileSystem.path.join(jdkPath, 'bin', 'java'), '-version', ], stderr: '123', ) ); final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio.version, null); expect(studio.javaPath, jdkPath); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () { final String studioInApplicationPlistFolder = fileSystem.path.join( '/', 'Application', 'Android Studio.app', 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true);
final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); final Map<String, Object> plistWithoutVersion = Map<String, Object>.from(macStudioInfoPlist2022_1); plistWithoutVersion['CFBundleShortVersionString'] = '99999.99.99'; plistUtils.fileContents[plistFilePath] = plistWithoutVersion;
final String jdkPathFor2022 = fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home');
final AndroidStudio studio = AndroidStudio.fromMacOSBundle( fileSystem.directory(studioInApplicationPlistFolder).parent.path, )!;
expect(studio.version, equals(Version(99999, 99, 99))); expect(studio.javaPath, jdkPathFor2022); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => FakeProcessManager.any(), Platform: () => platform, PlistParser: () => plistUtils, });
testUsingContext('discovers explicitly configured Android Studio', () { final String extractedDownloadZip = fileSystem.path.join( '/', 'Users', 'Dash', 'Desktop', 'android-studio' ); config.setValue('android-studio-dir', extractedDownloadZip); final String studioInApplicationPlistFolder = fileSystem.path.join( extractedDownloadZip, 'Contents', ); fileSystem.directory(studioInApplicationPlistFolder).createSync(recursive: true); final String plistFilePath = fileSystem.path.join(studioInApplicationPlistFolder, 'Info.plist'); plistUtils.fileContents[plistFilePath] = macStudioInfoPlist2022_1;
final String studioInApplicationJavaBinary = fileSystem.path.join( extractedDownloadZip, 'Contents', 'jbr', 'Contents', 'Home', 'bin', 'java', );
processManager.addCommands(<FakeCommand>[ FakeCommand( command: const <String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.google.android.studio*"', ], stdout: extractedDownloadZip, ), FakeCommand( command: <String>[ studioInApplicationJavaBinary, '-version', ], ), ]);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.configuredPath, extractedDownloadZip); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ Config:() => config, FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, ProcessManager: () => processManager, Platform: () => platform, PlistParser: () => plistUtils, }); });
group('installation detection on Windows', () { late Config config; late Platform platform; late FileSystem fileSystem;
setUp(() { config = Config.test(); platform = FakePlatform( operatingSystem: 'windows', environment: <String, String>{ 'LOCALAPPDATA': r'C:\Users\Dash\AppData\Local', } ); fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); });
testUsingContext('discovers Android Studio 4.1 location', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.1\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0)); expect(studio.studioAppName, 'Android Studio'); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('discovers Android Studio 4.2 location', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.2\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 2, 0)); expect(studio.studioAppName, 'Android Studio'); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('discovers Android Studio 2020.3 location', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(2020, 3, 0)); expect(studio.studioAppName, 'Android Studio'); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('does not discover Android Studio 4.1 location if LOCALAPPDATA is null', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.1\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty); }, overrides: <Type, Generator>{ Platform: () => FakePlatform( operatingSystem: 'windows', environment: <String, String>{}, // Does not include LOCALAPPDATA ), FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('does not discover Android Studio 4.2 location if LOCALAPPDATA is null', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.2\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty); }, overrides: <Type, Generator>{ Platform: () => FakePlatform( operatingSystem: 'windows', environment: <String, String>{}, // Does not include LOCALAPPDATA ), FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('does not discover Android Studio 2020.3 location if LOCALAPPDATA is null', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
expect(AndroidStudio.allInstalled(), isEmpty); }, overrides: <Type, Generator>{ Platform: () => FakePlatform( operatingSystem: 'windows', environment: <String, String>{}, // Does not include LOCALAPPDATA ), FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds Android Studio 2020.3 bundled Java version', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2020.3\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jre')); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds Android Studio 2022.1 bundled Java version', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2022.1\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jbr')); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
fileSystem.file(r'C:\Program Files\AndroidStudio\jbr\bin\java').createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, null); expect(studio.javaPath, equals(r'C:\Program Files\AndroidStudio\jbr')); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio99999.99.99\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio'); fileSystem.directory(r'C:\Program Files\AndroidStudio') .createSync(recursive: true);
fileSystem.file(r'C:\Program Files\AndroidStudio\jbr\bin\java').createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
const String expectedJdkLocationFor2022 = r'C:\Program Files\AndroidStudio\jbr'; expect(studio.version, equals(Version(99999, 99, 99))); expect(studio.javaPath, equals(expectedJdkLocationFor2022)); }, overrides: <Type, Generator>{ Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('discovers explicitly configured Android Studio', () { const String androidStudioDir = r'C:\Users\Dash\Desktop\android-studio'; config.setValue('android-studio-dir', androidStudioDir); fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio2022.1\.home') ..createSync(recursive: true) ..writeAsStringSync(androidStudioDir); fileSystem.directory(androidStudioDir) .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(2022, 1, null))); expect(studio.configuredPath, androidStudioDir); expect(studio.javaPath, fileSystem.path.join(androidStudioDir, 'jbr')); }, overrides: <Type, Generator>{ Config: () => config, Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), }); });
group('installation detection on Linux', () { const String homeLinux = '/home/me';
late Config config; late FileSystem fileSystem; late FileSystemUtils fsUtils; late Platform platform;
setUp(() { config = Config.test(); platform = FakePlatform( environment: <String, String>{'HOME': homeLinux}, ); fileSystem = MemoryFileSystem.test(); fsUtils = FileSystemUtils( fileSystem: fileSystem, platform: platform, ); });
testUsingContext('discovers Android Studio <4.1', () { const String studioHomeFilePath = '$homeLinux/.AndroidStudio4.0/system/.home'; const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 0, 0)); expect(studio.studioAppName, 'AndroidStudio'); expect( studio.pluginsPath, '/home/me/.AndroidStudio4.0/config/plugins', ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('discovers Android Studio >=4.1', () { const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio4.1/.home'; const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0)); expect(studio.studioAppName, 'AndroidStudio'); expect( studio.pluginsPath, '/home/me/.local/share/Google/AndroidStudio4.1', ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('discovers when installed with Toolbox', () { const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio4.1/.home'; const String studioInstallPath = '$homeLinux/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/201.7042882'; const String pluginsInstallPath = '$studioInstallPath.plugins';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync(recursive: true); fileSystem.directory(pluginsInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, Version(4, 1, 0)); expect(studio.studioAppName, 'AndroidStudio'); expect( studio.pluginsPath, pluginsInstallPath, ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds Android Studio 2020.3 bundled Java version', () { const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio2020.3/.home'; const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals('$studioInstallPath/jre')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds Android Studio 2022.1 bundled Java version', () { const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio2022.1/.home'; const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.javaPath, equals('$studioInstallPath/jbr')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('finds bundled Java version when Android Studio version is unknown by assuming the latest version', () { const String configuredStudioInstallPath = '$homeLinux/AndroidStudio'; config.setValue('android-studio-dir', configuredStudioInstallPath);
fileSystem.directory(configuredStudioInstallPath).createSync(recursive: true);
fileSystem.directory(configuredStudioInstallPath).createSync();
fileSystem.file(fileSystem.path.join(configuredStudioInstallPath, 'jbr', 'bin', 'java')).createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, null); expect(studio.javaPath, equals('$configuredStudioInstallPath/jbr')); }, overrides: <Type, Generator>{ Config: () => config, FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('when given an Android Studio newer than any known version, finds Java version by assuming latest known Android Studio version', () { const String studioHomeFilePath = '$homeLinux/.cache/Google/AndroidStudio99999.99.99/.home'; const String studioInstallPath = '$homeLinux/AndroidStudio';
fileSystem.file(studioHomeFilePath) ..createSync(recursive: true) ..writeAsStringSync(studioInstallPath);
fileSystem.directory(studioInstallPath).createSync();
final String expectedJdkLocationFor2022 = fileSystem.path.join(studioInstallPath, 'jbr', 'bin', 'java'); fileSystem.file(expectedJdkLocationFor2022).createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(99999, 99, 99))); expect(studio.javaPath, equals('$studioInstallPath/jbr')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, FileSystemUtils: () => fsUtils, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('pluginsPath extracts custom paths from home dir', () { const String installPath = '/opt/android-studio-with-cheese-5.0'; const String studioHome = '$homeLinux/.AndroidStudioWithCheese5.0'; const String homeFile = '$studioHome/system/.home'; fileSystem.directory(installPath).createSync(recursive: true); fileSystem.file(homeFile).createSync(recursive: true); fileSystem.file(homeFile).writeAsStringSync(installPath);
final AndroidStudio studio = AndroidStudio.fromHomeDot(fileSystem.directory(studioHome))!; expect(studio, isNotNull); expect(studio.pluginsPath, equals('/home/me/.AndroidStudioWithCheese5.0/config/plugins')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), // Custom home paths are not supported on macOS nor Windows yet, // so we force the platform to fake Linux here. Platform: () => platform, FileSystemUtils: () => FileSystemUtils( fileSystem: fileSystem, platform: platform, ), });
testUsingContext('discovers explicitly configured Android Studio', () { const String androidStudioDir = '/Users/Dash/Desktop/android-studio'; config.setValue('android-studio-dir', androidStudioDir); const String studioHome = '$homeLinux/.cache/Google/AndroidStudio2022.3/.home'; fileSystem.file(studioHome) ..createSync(recursive: true) ..writeAsStringSync(androidStudioDir); fileSystem.directory(androidStudioDir) .createSync(recursive: true);
final AndroidStudio studio = AndroidStudio.allInstalled().single;
expect(studio.version, equals(Version(2022, 3, null))); expect(studio.configuredPath, androidStudioDir); expect(studio.javaPath, fileSystem.path.join(androidStudioDir, 'jbr')); }, overrides: <Type, Generator>{ Config: () => config, Platform: () => platform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), }); });
group('latestValid', () { late Config config; late Platform platform; late FileSystem fileSystem;
setUp(() { config = Config.test(); platform = FakePlatform( operatingSystem: 'windows', environment: <String, String>{ 'LOCALAPPDATA': r'C:\Users\Dash\AppData\Local', } ); fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); });
testUsingContext('choses the install with the latest version', () { const List<String> versions = <String> [ '4.0', '2022.0', '3.1', ];
for (final String version in versions) { fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home') ..createSync(recursive: true) ..writeAsStringSync('C:\\Program Files\\AndroidStudio$version'); fileSystem.directory('C:\\Program Files\\AndroidStudio$version') .createSync(recursive: true); }
expect(AndroidStudio.allInstalled().length, 3); expect(AndroidStudio.latestValid()!.version, Version(2022, 0, 0)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('prefers installs with known versions over installs with unknown versions', () { const List<String> versions = <String> [ '3.0', 'unknown', ];
for (final String version in versions) { fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home') ..createSync(recursive: true) ..writeAsStringSync('C:\\Program Files\\AndroidStudio$version'); fileSystem.directory('C:\\Program Files\\AndroidStudio$version') .createSync(recursive: true); }
expect(AndroidStudio.allInstalled().length, 2); expect(AndroidStudio.latestValid()!.version, Version(3, 0, 0)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('choses install with lexicographically greatest directory if no installs have known versions', () { const List<String> versions = <String> [ 'Apple', 'Zucchini', 'Banana', ];
for (final String version in versions) { fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home') ..createSync(recursive: true) ..writeAsStringSync('C:\\Program Files\\AndroidStudio$version'); fileSystem.directory('C:\\Program Files\\AndroidStudio$version') .createSync(recursive: true); }
expect(AndroidStudio.allInstalled().length, 3); expect(AndroidStudio.latestValid()!.directory, r'C:\Program Files\AndroidStudioZucchini'); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('choses install with lexicographically greatest directory if all installs have the same version', () { fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudioPreview4.0\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudioPreview4.0'); fileSystem.directory(r'C:\Program Files\AndroidStudioPreview4.0') .createSync(recursive: true);
fileSystem.file(r'C:\Users\Dash\AppData\Local\Google\AndroidStudio4.0\.home') ..createSync(recursive: true) ..writeAsStringSync(r'C:\Program Files\AndroidStudio4.0'); fileSystem.directory(r'C:\Program Files\AndroidStudio4.0') .createSync(recursive: true);
expect(AndroidStudio.allInstalled().length, 2); expect(AndroidStudio.latestValid()!.directory, contains('Preview')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('always chooses the install configured by --android-studio-dir, even if the install is invalid', () { const String configuredAndroidStudioDir = r'C:\Users\Dash\Desktop\android-studio'; config.setValue('android-studio-dir', configuredAndroidStudioDir);
// The directory exists, but nothing is inside. fileSystem.directory(configuredAndroidStudioDir).createSync(recursive: true); (globals.processManager as FakeProcessManager).excludedExecutables.add( fileSystem.path.join(configuredAndroidStudioDir, 'jbr', 'bin', 'java'), );
const List<String> validVersions = <String> [ '4.0', '2.0', '3.1', ];
for (final String version in validVersions) { fileSystem.file('C:\\Users\\Dash\\AppData\\Local\\Google\\AndroidStudio$version\\.home') ..createSync(recursive: true) ..writeAsStringSync('C:\\Program Files\\AndroidStudio$version'); fileSystem.directory('C:\\Program Files\\AndroidStudio$version') .createSync(recursive: true); }
const List<String> validJavaPaths = <String>[ r'C:\Program Files\AndroidStudio4.0\jre\bin\java', r'C:\Program Files\AndroidStudio2.0\jre\bin\java', r'C:\Program Files\AndroidStudio3.1\jre\bin\java', ];
for (final String javaPath in validJavaPaths) { (globals.processManager as FakeProcessManager).addCommand(FakeCommand( command: <String>[ fileSystem.path.join(javaPath), '-version', ], )); }
expect(AndroidStudio.allInstalled().length, 4);
for (final String javaPath in validJavaPaths) { (globals.processManager as FakeProcessManager).addCommand(FakeCommand( command: <String>[ fileSystem.path.join(javaPath), '-version', ], )); }
final AndroidStudio chosenInstall = AndroidStudio.latestValid()!; expect(chosenInstall.directory, configuredAndroidStudioDir); expect(chosenInstall.isValid, false); }, overrides: <Type, Generator>{ Config: () => config, FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.empty(), });
testUsingContext('throws a ToolExit if --android-studio-dir is configured but the directory does not exist', () async { const String configuredAndroidStudioDir = r'C:\Users\Dash\Desktop\android-studio'; config.setValue('android-studio-dir', configuredAndroidStudioDir);
expect(fileSystem.directory(configuredAndroidStudioDir).existsSync(), false); expect(() => AndroidStudio.latestValid(), throwsA( (dynamic e) => e is ToolExit && e.message!.startsWith('Could not find the Android Studio installation at the manually configured path') ) ); }, overrides: <Type, Generator>{ Config: () => config, FileSystem: () => fileSystem, Platform: () => platform, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('handles file system exception when checking for explicitly configured Android Studio install', () { const String androidStudioDir = '/Users/Dash/Desktop/android-studio'; config.setValue('android-studio-dir', androidStudioDir);
expect(() => AndroidStudio.latestValid(), throwsToolExit(message: RegExp(r'[.\s\S]*Could not find[.\s\S]*FileSystemException[.\s\S]*'))); }, overrides: <Type, Generator>{ Config: () => config, Platform: () => platform, FileSystem: () => _FakeFileSystem(), FileSystemUtils: () => _FakeFsUtils(), ProcessManager: () => FakeProcessManager.any(), }); });}
class FakePlistUtils extends Fake implements PlistParser { final Map<String, Map<String, Object>> fileContents = <String, Map<String, Object>>{};
@override Map<String, Object> parseFile(String plistFilePath) { return fileContents[plistFilePath]!; }}
class _FakeFileSystem extends Fake implements FileSystem { @override Directory directory(dynamic path) { return _NonExistentDirectory(); }
@override Context get path { return MemoryFileSystem.test().path; }}
class _NonExistentDirectory extends Fake implements Directory { @override bool existsSync() { throw const FileSystemException('OS Error: Filename, directory name, or volume label syntax is incorrect.'); }
@override String get path => '';
@override Directory get parent => _NonExistentDirectory();}
class _FakeFsUtils extends Fake implements FileSystemUtils { @override String get homeDirPath => '/home/';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110// 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 'package:file/memory.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/android_studio_validator.dart';import 'package:flutter_tools/src/base/config.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/user_messages.dart';import 'package:flutter_tools/src/base/version.dart';import 'package:flutter_tools/src/doctor_validator.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fake_process_manager.dart';
const String home = '/home/me';
final Platform linuxPlatform = FakePlatform( environment: <String, String>{'HOME': home});
void main() {
late FileSystem fileSystem; late FakeProcessManager fakeProcessManager;
setUp(() { fileSystem = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); });
group(NoAndroidStudioValidator, () { testWithoutContext('shows Android Studio as "not available" when not available.', () async { final Config config = Config.test(); final NoAndroidStudioValidator validator = NoAndroidStudioValidator( config: config, platform: linuxPlatform, userMessages: UserMessages(), );
expect((await validator.validate()).type, equals(ValidationType.notAvailable)); }); });
group(AndroidStudioValidator, () { testUsingContext('gives doctor error on java crash', () async { fakeProcessManager.addCommand(const FakeCommand( command: <String>[ '/opt/android-studio-with-cheese-5.0/jre/bin/java', '-version', ], exception: ProcessException('java', <String>['-version']), )); const String installPath = '/opt/android-studio-with-cheese-5.0'; const String studioHome = '$home/.AndroidStudioWithCheese5.0'; const String homeFile = '$studioHome/system/.home'; globals.fs.directory(installPath).createSync(recursive: true); globals.fs.file(homeFile).createSync(recursive: true); globals.fs.file(homeFile).writeAsStringSync(installPath);
// This checks that running the validator doesn't throw an unhandled // exception and that the ProcessException makes it into the error // message list. for (final DoctorValidator validator in AndroidStudioValidator.allValidators(globals.config, globals.platform, globals.fs, globals.userMessages)) { final ValidationResult result = await validator.validate(); expect(result.messages.where((ValidationMessage message) { return message.isError && message.message.contains('ProcessException'); }).isNotEmpty, true); } expect(fakeProcessManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => fakeProcessManager, Platform: () => linuxPlatform, FileSystemUtils: () => FileSystemUtils( fileSystem: fileSystem, platform: linuxPlatform, ), });
testWithoutContext('warns if version of Android Studio could not be determined', () async { final AndroidStudio studio = _FakeAndroidStudio(); final AndroidStudioValidator validator = AndroidStudioValidator(studio, fileSystem: fileSystem, userMessages: UserMessages()); final ValidationResult result = await validator.validate(); expect(result.messages, contains(const ValidationMessage.error('Unable to determine Android Studio version.'))); expect(result.statusInfo, 'version unknown'); }); });}
class _FakeAndroidStudio extends Fake implements AndroidStudio { @override List<String> get validationMessages => <String>[]; @override bool get isValid => true; @override String? get pluginsPath => null; @override String get directory => 'android-studio'; @override Version? get version => null; @override String get javaPath => 'android-studio/jbr/bin/java';}novelforge-project/flutter/packages/flutter_tools/bin/analysis_options.yamlAdded+5
novelforge-project/flutter/packages/flutter_tools/bin/flutter_tools.dartAdded+9
novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dartAdded+117
novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_tester.dartAdded+177
novelforge-project/flutter/packages/flutter_tools/bin/macos_assemble.shAdded+196
novelforge-project/flutter/packages/flutter_tools/bin/podhelper.rbAdded+359
novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.batAdded+9
novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.dartAdded+137
novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.shAdded+9
novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.dartAdded+455
novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.shAdded+29
novelforge-project/flutter/packages/flutter_tools/bin/xcode_debug.jsAdded+664
novelforge-project/flutter/packages/flutter_tools/doc/attach.mdAdded+26
novelforge-project/flutter/packages/flutter_tools/doc/daemon.mdAdded+316
novelforge-project/flutter/packages/flutter_tools/gradle/aar_init_script.gradleAdded+151
novelforge-project/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradleAdded+15
novelforge-project/flutter/packages/flutter_tools/gradle/build.gradle.ktsAdded+35
novelforge-project/flutter/packages/flutter_tools/gradle/flutter.gradleAdded+14
novelforge-project/flutter/packages/flutter_tools/gradle/flutter_multidex_keepfile.txtAdded+5
novelforge-project/flutter/packages/flutter_tools/gradle/flutter_proguard_rules.proAdded+7
novelforge-project/flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.mdAdded+14
novelforge-project/flutter/packages/flutter_tools/gradle/module_plugin_loader.gradleAdded+63
novelforge-project/flutter/packages/flutter_tools/gradle/resolve_dependencies.gradleAdded+67
novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.ktsAdded+7
novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versionsAdded+59
novelforge-project/flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmplAdded+1
novelforge-project/flutter/packages/flutter_tools/lib/executable.dartAdded+308
novelforge-project/flutter/packages/flutter_tools/lib/runner.dartAdded+292
novelforge-project/flutter/packages/flutter_tools/static/Ahem.ttfAdded
novelforge-project/flutter/packages/flutter_tools/static/custom-devices.schema.jsonAdded+139
novelforge-project/flutter/packages/flutter_tools/static/index.htmlAdded+34
novelforge-project/flutter/packages/flutter_tools/templates/README.mdAdded+25
novelforge-project/flutter/packages/flutter_tools/templates/template_manifest.jsonAdded+369
novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/README.mdAdded+5
novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dartAdded+151
novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dartAdded+135
novelforge-project/flutter/packages/flutter_tools/test/commands.shard/README.mdAdded+10
novelforge-project/flutter/packages/flutter_tools/test/general.shard/analytics_test.dartAdded+412
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dartAdded+249
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dartAdded+269
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dartAdded+163
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_start_test.dartAdded+301
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dartAdded+717
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dartAdded+225
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dartAdded+1937
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dartAdded+318
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dartAdded+474
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_sdk_test.dartAdded+569
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dartAdded+1344
novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dartAdded+110