diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/analysis_options.yaml b/novelforge-project/flutter/packages/flutter_tools/bin/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19391e33ff98ea4a261294fd5d0e7f03cddf926d --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/analysis_options.yaml @@ -0,0 +1,5 @@ +include: ../analysis_options.yaml + +linter: + rules: + avoid_print: false # These are CLI tools which print as a matter of course. diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/flutter_tools.dart b/novelforge-project/flutter/packages/flutter_tools/bin/flutter_tools.dart new file mode 100644 index 0000000000000000000000000000000000000000..2caa134a35154137bf0db8742c5b3721fca3735a --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/flutter_tools.dart @@ -0,0 +1,9 @@ +// 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 args) { + executable.main(args); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dart b/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dart new file mode 100644 index 0000000000000000000000000000000000000000..b7ddd47b4661a06fa434fe6b4cf8cd846843230f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dart @@ -0,0 +1,117 @@ +// 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 _kRequiredOptions = [ + _kOptionPackages, + _kOptionAsset, + _kOptionAssetManifestOut, + _kOptionComponentName, +]; + +Future main(List args) { + return runInContext(() => run(args), overrides: { + Usage: () => DisabledUsage(), + }); +} + +Future writeFile(libfs.File outputFile, DevFSContent content) async { + outputFile.createSync(recursive: true); + final List data = await content.contentsAsBytes(); + outputFile.writeAsBytesSync(data); +} + +Future run(List 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> calls = >[]; + 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(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 writeDepfile(AssetBundle assets, String outputManifest, String depfilePath) async { + final Depfile depfileContent = Depfile( + assets.inputFiles, + [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 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(); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_tester.dart b/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_tester.dart new file mode 100644 index 0000000000000000000000000000000000000000..c0017d25a5f210d80579947b6e8b069b1e9e341f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/fuchsia_tester.dart @@ -0,0 +1,177 @@ +// 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 _kRequiredOptions = [ + _kOptionPackages, + _kOptionShell, + _kOptionSdkRoot, + _kOptionIcudtl, + _kOptionTests, +]; +const String _kOptionCoverage = 'coverage'; +const String _kOptionCoveragePath = 'coverage-path'; + +void main(List args) { + runInContext(() => run(args), overrides: { + Usage: () => DisabledUsage(), + }); +} + +Future run(List 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? libraryNames = coverageDirectory != null ? null : + {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 tests = {}; + final List> jsonList = List>.from( + (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List).cast>()); + for (final Map 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); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/macos_assemble.sh b/novelforge-project/flutter/packages/flutter_tools/bin/macos_assemble.sh new file mode 100644 index 0000000000000000000000000000000000000000..71f69ef22e15fc1e64fdf5539a611538789a40af --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/macos_assemble.sh @@ -0,0 +1,196 @@ +#!/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. + BuildApp +else + case $1 in + "build") + BuildApp ;; + "embed") + EmbedFrameworks ;; + esac +fi diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/podhelper.rb b/novelforge-project/flutter/packages/flutter_tools/bin/podhelper.rb new file mode 100644 index 0000000000000000000000000000000000000000..2ec1e82e428e7624534d9f801beeb5281961e648 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/podhelper.rb @@ -0,0 +1,359 @@ +# 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 +# ... +# end +def 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' + end +end + +# 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' + end +end + +# 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) + end +end + +# .flutter-plugins-dependencies format documented at +# https://flutter.dev/go/plugins-list-migration +def 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_s +end + +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 entries +end + +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 nil +end diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.bat b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.bat new file mode 100644 index 0000000000000000000000000000000000000000..23a402d9b85751fbc6522f0ff55a73b668fa22ef --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.bat @@ -0,0 +1,9 @@ +@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" %* diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.dart b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.dart new file mode 100644 index 0000000000000000000000000000000000000000..d98c7055477dbb60d34ccd8e55f45b4762efb904 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.dart @@ -0,0 +1,137 @@ +// 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 main(List 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(['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, or +by running: + flutter build --local-engine=_$buildMode --local-engine-host=host_$buildMode +or + flutter build --local-engine=_${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, or +by running: + flutter build --local-engine=_$buildMode --local-engine-host=host_$buildMode +or + flutter build --local-engine=_$buildMode --local-engine-host=host_${buildMode}_unopt +======================================================================== +'''); + exit(1); + } + final String flutterExecutable = pathJoin([ + 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, + [ + 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 segments) { + final String separator = Platform.isWindows ? r'\' : '/'; + return segments.join(separator); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.sh b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae4000e37db6a05a746b7ebb1b9208900748e25d --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/tool_backend.sh @@ -0,0 +1,9 @@ +#!/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}" diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.dart b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.dart new file mode 100644 index 0000000000000000000000000000000000000000..dca13dad5f74d834a9758a943b7db42c0f7329d6 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.dart @@ -0,0 +1,455 @@ +// 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 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 environment; + final List 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 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 extraArgs = const [], + bool delete = false, + }) { + runSync( + 'rsync', + [ + '-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', + [ + '-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: [ + '--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', + [ + '-extract', + 'NSBonjourServices', + 'xml1', + '-o', + '-', + builtProductsPlist, + ], + allowFail: true, + ); + if (result.exitCode == 0) { + runSync( + 'plutil', + [ + '-insert', + 'NSBonjourServices.0', + '-string', + '_dartVmService._tcp', + builtProductsPlist, + ], + ); + } else { + // Otherwise, add the NSBonjourServices key and vmService service name. + runSync( + 'plutil', + [ + '-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', + [ + '-extract', + 'NSLocalNetworkUsageDescription', + 'xml1', + '-o', + '-', + builtProductsPlist, + ], + allowFail: true, + ); + if (result.exitCode != 0) { + runSync( + 'plutil', + [ + '-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 flutterArgs = []; + + 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([ + '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.'); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.sh b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.sh new file mode 100644 index 0000000000000000000000000000000000000000..2889d7c8e4e29bcc7a4c54e1e90a6b9a9c66b7e3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_backend.sh @@ -0,0 +1,29 @@ +#!/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 var +set -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" "$@" diff --git a/novelforge-project/flutter/packages/flutter_tools/bin/xcode_debug.js b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_debug.js new file mode 100644 index 0000000000000000000000000000000000000000..35c39b88b5ae74245f6cfa098703cbce407a27a3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/bin/xcode_debug.js @@ -0,0 +1,664 @@ +// 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=} 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} 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} args List of arguments passed from the command line. + * @returns {!Object.} 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}`); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/doc/attach.md b/novelforge-project/flutter/packages/flutter_tools/doc/attach.md new file mode 100644 index 0000000000000000000000000000000000000000..565115ded3f56fe3803410b415806bf4f0876279 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/doc/attach.md @@ -0,0 +1,26 @@ +# Flutter Attach + +## Overview + +A Flutter-command that attaches to applications that have been launched +without `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 after +the application is started, attach will poll the device if it cannot +immediately discover the port +1. On Android and iOS, just running `flutter attach` suffices. Flutter tools +will search for an already running Flutter app or module if available. +Otherwise, the tool will wait for the next Flutter app or module to launch +before attaching. +1. If the app or module is already running and the specific VM Service port is +known, 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. diff --git a/novelforge-project/flutter/packages/flutter_tools/doc/daemon.md b/novelforge-project/flutter/packages/flutter_tools/doc/daemon.md new file mode 100644 index 0000000000000000000000000000000000000000..f570949064decbe8e4b3c13c428b785f46ffbd80 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/doc/daemon.md @@ -0,0 +1,316 @@ +# 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 supported +by the project located at the provided `projectRoot`. It returns a Map with +the key 'platformTypes' containing a Map of platform types to a Map with the +following entries: + +- isSupported (bool) - whether or not the platform type is supported +- reasons (List>, 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 used +by 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 device +supports. 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 startup diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/aar_init_script.gradle b/novelforge-project/flutter/packages/flutter_tools/gradle/aar_init_script.gradle new file mode 100644 index 0000000000000000000000000000000000000000..e6fa84cc17fd864f27aa088f4702cb45db02be67 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/aar_init_script.gradle @@ -0,0 +1,151 @@ +// 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.Paths +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import 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 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` 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")) + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradle b/novelforge-project/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradle new file mode 100644 index 0000000000000000000000000000000000000000..0d1f001e861eb42f14aed013de8cf79cf3418e8c --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/app_plugin_loader.gradle @@ -0,0 +1,15 @@ +// 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.parentFile +apply from: "$pathToThisDirectory/src/main/groovy/app_plugin_loader.groovy" diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/build.gradle.kts b/novelforge-project/flutter/packages/flutter_tools/gradle/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..e14f1c37e16701c07813e126e38a6742c3df55cc --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/build.gradle.kts @@ -0,0 +1,35 @@ +// 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") +} diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/flutter.gradle b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter.gradle new file mode 100644 index 0000000000000000000000000000000000000000..7d06e32d3168c57cc0b0ed0f5f9ebdcf6378d650 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter.gradle @@ -0,0 +1,14 @@ +// 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.parentFile +apply from: "$pathToThisDirectory/src/main/groovy/flutter.groovy" diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_multidex_keepfile.txt b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_multidex_keepfile.txt new file mode 100644 index 0000000000000000000000000000000000000000..34984e6fa50aa9aadaba3c3a7819808c4e9c124f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_multidex_keepfile.txt @@ -0,0 +1,5 @@ +io/flutter/app/FlutterApplication.class +io/flutter/app/FlutterMultiDexApplication.class +io/flutter/embedding/engine/loader/FlutterLoader.class +io/flutter/view/FlutterMain.class +io/flutter/util/PathUtils.class diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_proguard_rules.pro b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_proguard_rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..10390efaa8a5978d846d2811d50547db25553894 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/flutter_proguard_rules.pro @@ -0,0 +1,7 @@ +# Build the ephemeral app in a module project. +# Prevents: Warning: library class 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.** diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.md b/novelforge-project/flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.md new file mode 100644 index 0000000000000000000000000000000000000000..b8e062f43b7adfc97d7e7fc176391c81b9b62221 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/manual_migration_settings.gradle.md @@ -0,0 +1,14 @@ +To 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" diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/module_plugin_loader.gradle b/novelforge-project/flutter/packages/flutter_tools/gradle/module_plugin_loader.gradle new file mode 100644 index 0000000000000000000000000000000000000000..2e3a80091499dd21aedeb6fda3e96b3e7b420b4a --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/module_plugin_loader.gradle @@ -0,0 +1,63 @@ +// 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 `/.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') + } + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/resolve_dependencies.gradle b/novelforge-project/flutter/packages/flutter_tools/gradle/resolve_dependencies.gradle new file mode 100644 index 0000000000000000000000000000000000000000..6355654f2edfbc40d01b0d9ef80b694b881e1233 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/resolve_dependencies.gradle @@ -0,0 +1,67 @@ +// 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 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() + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.kts b/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..f8d3e87ffa2d7eb205b4befba4685e0b167f1032 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.kts @@ -0,0 +1,7 @@ +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versions b/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versions new file mode 100644 index 0000000000000000000000000000000000000000..fc40e6d933cd2be82bfb46f69dfce340bb4c1c33 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/settings.gradle.legacy_versions @@ -0,0 +1,59 @@ +include ':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 +} +;EOF +include ':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" +;EOF +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" diff --git a/novelforge-project/flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmpl b/novelforge-project/flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmpl new file mode 100644 index 0000000000000000000000000000000000000000..e7b4def49cb53d9aa04228dd3edb14c9e635e003 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmpl @@ -0,0 +1 @@ +include ':app' diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/executable.dart b/novelforge-project/flutter/packages/flutter_tools/lib/executable.dart new file mode 100644 index 0000000000000000000000000000000000000000..9927cf906b3598000878f543a6a9a425c1c08c88 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/executable.dart @@ -0,0 +1,308 @@ +// 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 main(List 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: { + // 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 generateCommands({ + required bool verboseHelp, + required bool verbose, +}) => [ + 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: [ + 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; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/lib/runner.dart b/novelforge-project/flutter/packages/flutter_tools/lib/runner.dart new file mode 100644 index 0000000000000000000000000000000000000000..7ec36bfd0d8573ce1f874fe08d63bc119c421c57 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/lib/runner.dart @@ -0,0 +1,292 @@ +// 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 run( + List args, + List Function() commands, { + bool muteCommandLogging = false, + bool verbose = false, + bool verboseHelp = false, + bool? reportCrashes, + String? flutterVersion, + Map? 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.of(args); + args.removeWhere((String option) => option == '-vv' || option == '-v' || option == '--verbose'); + } + + return runInContext(() 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>(() 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 _handleToolError( + Object error, + StackTrace? stackTrace, + bool verbose, + List 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 -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 args) => 'flutter ${args.join(' ')}'; + +String _crashException(dynamic error) => '${error.runtimeType}: $error'; + +/// Saves the crash report to a local file. +Future _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; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/static/Ahem.ttf b/novelforge-project/flutter/packages/flutter_tools/static/Ahem.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ac81cb03165ab831a36abb59145ff7a2f5675fb9 Binary files /dev/null and b/novelforge-project/flutter/packages/flutter_tools/static/Ahem.ttf differ diff --git a/novelforge-project/flutter/packages/flutter_tools/static/custom-devices.schema.json b/novelforge-project/flutter/packages/flutter_tools/static/custom-devices.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..da0a78400d96db185ac6a7b72d6f0f5ed40c11b0 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/static/custom-devices.schema.json @@ -0,0 +1,139 @@ +{ + "$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=\" 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 + } + } + } + } + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/static/index.html b/novelforge-project/flutter/packages/flutter_tools/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..85ebd46c4c602128adaac9b230d85eaec2283b21 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/static/index.html @@ -0,0 +1,34 @@ + + + + + Flutter Test Browser Host + + + +
+ + + diff --git a/novelforge-project/flutter/packages/flutter_tools/templates/README.md b/novelforge-project/flutter/packages/flutter_tools/templates/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f3e5f6d98b5632bf55858812be5e079919392a40 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/templates/README.md @@ -0,0 +1,25 @@ +This 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 contain +only the files that are specific to them alone, and the rest is automatically +kept in sync. diff --git a/novelforge-project/flutter/packages/flutter_tools/templates/template_manifest.json b/novelforge-project/flutter/packages/flutter_tools/templates/template_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..b43e75d4228e69064e5a9fbad856aedf1ab146d7 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/templates/template_manifest.json @@ -0,0 +1,369 @@ +{ + "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" + ] +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/README.md b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/README.md new file mode 100644 index 0000000000000000000000000000000000000000..26274ba49d2f029840363f3109ea62599c2524b8 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/README.md @@ -0,0 +1,5 @@ +# 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 own +test shard). For additional information see the README in the `../integration.shard` directory. \ No newline at end of file diff --git a/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..96e3f6353d35c294d2ba1a21f34c7a15c502d659 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dart @@ -0,0 +1,151 @@ +// 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_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=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 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([ + 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([ + 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')); + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ebb49b43658bb68efcc920857d4baad7c1a25303 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart @@ -0,0 +1,135 @@ +// 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 = ['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([ + 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([ + 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([ + 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([ + 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')); + }, + ); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/commands.shard/README.md b/novelforge-project/flutter/packages/flutter_tools/test/commands.shard/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9564f0f4840c0347ee70a29ab6841446a4620077 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/commands.shard/README.md @@ -0,0 +1,10 @@ +This 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 running +subprocesses, should go in `permeable/`. + +The `../../tool/coverage_tool.dart` script (which is used to collect +coverage for the tool) runs only the tests in the `hermetic` directory +when collecting coverage. diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/analytics_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/analytics_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a3d23bf6d416984babe78cb003bbde162b5963e3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/analytics_test.dart @@ -0,0 +1,412 @@ +// 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 data) => count++); + + final FlutterCommand command = FakeFlutterCommand(); + final CommandRunnerrunner = createTestCommandRunner(command); + + globals.flutterUsage.enabled = false; + await runner.run(['fake']); + expect(count, 0); + + globals.flutterUsage.enabled = true; + await runner.run(['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(['fake']); + + expect(count, 0); + }, overrides: { + 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 data) => count++); + + globals.flutterUsage.enabled = false; + final ConfigCommand command = ConfigCommand(); + final CommandRunner runner = createTestCommandRunner(command); + await runner.run(['config']); + expect(count, 0); + + globals.flutterUsage.enabled = true; + await runner.run(['config']); + + expect(count, 0); + }, overrides: { + 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: { + FlutterVersion: () => FakeFlutterVersion(), + Config: () => testConfig, + Platform: () => FakePlatform(environment: { + '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: { + FlutterVersion: () => FakeFlutterVersion(), + Config: () => testConfig, + Platform: () => FakePlatform(environment: { + '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 = [1000, 2000]; + doctor.diagnoseSucceeds = true; + final DoctorCommand command = DoctorCommand(); + final CommandRunner runner = createTestCommandRunner(command); + await runner.run(['doctor']); + + expect(testUsage.timings, contains( + const TestTimingEvent( + 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'success', + ), + )); + }, overrides: { + AndroidStudio: () => androidStudio, + SystemClock: () => fakeClock, + Doctor: () => doctor, + Usage: () => testUsage, + }); + + testUsingContext('doctor fail sends warning', () async { + fakeClock.times = [1000, 2000]; + doctor.diagnoseSucceeds = false; + final DoctorCommand command = DoctorCommand(); + final CommandRunner runner = createTestCommandRunner(command); + await runner.run(['doctor']); + + + expect(testUsage.timings, contains( + const TestTimingEvent( + 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'warning', + ), + )); + }, overrides: { + AndroidStudio: () => androidStudio, + SystemClock: () => fakeClock, + Doctor: () => doctor, + Usage: () => testUsage, + }); + + testUsingContext('single command usage path', () async { + final FlutterCommand doctorCommand = DoctorCommand(); + + expect(await doctorCommand.usagePath, 'doctor'); + }, overrides: { + 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 = [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: { + FileSystem: () => memoryFileSystem, + ProcessManager: () => processManager, + SystemClock: () => fakeClock, + Platform: () => FakePlatform( + environment: { + 'FLUTTER_ANALYTICS_LOG_FILE': 'analytics.log', + }, + ), + Stdio: () => fakeStdio, + }); + + testUsingContext('event sends localtime', () async { + const int kMillis = 1000; + fakeClock.times = [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: { + FileSystem: () => memoryFileSystem, + ProcessManager: () => processManager, + SystemClock: () => fakeClock, + Platform: () => FakePlatform( + environment: { + '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 data) => count++); + await createTestCommandRunner().run(['--version']); + + expect(count, 0); + }, overrides: { + 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 data) => count++); + globals.flutterUsage.enabled = true; + await createTestCommandRunner().run(['--version']); + + expect(count, 0); + }, overrides: { + 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 runCommand() async { + return FlutterCommandResult.success(); + } +} + +class FakeDoctor extends Fake implements Doctor { + bool diagnoseSucceeds = false; + + @override + Future diagnose({ + bool androidLicenses = false, + bool verbose = true, + bool showColor = true, + AndroidLicenseValidator? androidLicenseValidator, + bool showPii = true, + List? startedValidatorTasks, + bool sendEvent = true, + FlutterVersion? version, + }) async { + return diagnoseSucceeds; + } +} + +class FakeClock extends Fake implements SystemClock { + List times = []; + + @override + DateTime now() { + return DateTime.fromMillisecondsSinceEpoch(times.removeAt(0)); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..543aff1c7ca2b8d077d2ee4b24e65633e849ae32 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/adb_log_reader_test.dart @@ -0,0 +1,249 @@ +// 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( + command: const [ + 'adb', + '-s', + '1234', + 'shell', + '-x', + 'logcat', + '-v', + 'time', + ], + completer: Completer.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 onDone = Completer.sync(); + final List emittedLines = []; + logReader.logLines.listen((String line) { + emittedLines.add(line); + }, onDone: onDone.complete); + await null; + logReader.dispose(); + await onDone.future; + expect(emittedLines, const ['W/flutter($appPid): Hello there!']); + }); + + testWithoutContext('AdbLogReader calls adb logcat with expected flags apiVersion 21', () async { + final FakeProcessManager processManager = FakeProcessManager.list([ + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: [ + '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( + command: const [ + 'adb', + '-s', + '1234', + 'shell', + '-x', + 'logcat', + '-v', + 'time', + ], + completer: Completer.sync(), + stdout: 'Hello There\n', + ), + ]); + final AdbLogReader logReader = await AdbLogReader.createLogReader( + createFakeDevice(null), + processManager, + ); + final Completer onDone = Completer.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( + command: const [ + 'adb', + '-s', + '1234', + 'shell', + '-x', + 'logcat', + '-v', + 'time', + ], + completer: Completer.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([ + '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 get apiVersion => Future.value(_apiVersion); + + @override + Future lastLogcatTimestamp() async => _lastLogcatTimestamp; + + @override + List adbCommandForDevice(List command) { + return [ + 'adb', '-s', '1234', ...command, + ]; + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2f2135df0eddbd7208756cfa0b1e5cf4dbcebe42 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart @@ -0,0 +1,269 @@ +// 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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['adb', 'devices', '-l'], + stdout: ''' +List of devices attached +05a02bac device usb:336592896X product:razor model:Nexus_7 device:flo + + ''', + ), + ]), + platform: FakePlatform(), + fileSystem: MemoryFileSystem.test(), + ); + + final List 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([ + const FakeCommand( + command: ['adb', 'devices', '-l'], + stdout: ''' +List of devices attached +05a02bac._adb-tls-connect._tcp. device product:razor model:Nexus_7 device:flo + + ''', + ), + ]), + platform: FakePlatform(), + fileSystem: MemoryFileSystem.test(), + ); + + final List 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([ + const FakeCommand( + command: ['adb', 'devices', '-l'], + stdout: ''' +List of devices attached +localhost:36790 device +0149947A0D01500C device usb:340787200X +emulator-5612 host features:shell_2 + + ''', + ), + ]), + platform: FakePlatform(), + fileSystem: MemoryFileSystem.test(), + ); + + final List 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([ + const FakeCommand( + command: ['adb', 'devices', '-l'], + stdout: ''' +List of devices attached +ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu features:cmd,shell_v2 + +''', + ), + ]), + platform: FakePlatform(), + fileSystem: MemoryFileSystem.test(), + ); + + final List 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([ + const FakeCommand( + command: ['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 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; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..410a02c93d320a84d0185b070d2f908110e33fed --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart @@ -0,0 +1,163 @@ +// 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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], + stdout: '456', + ), + const FakeCommand( + command: ['adb', '-s', '1', 'forward', '--list'], + stdout: '1234 tcp:456 tcp:123', + ), + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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!')); + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_start_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_start_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..186f507195e6ba4c7fbc7088e229d5b094c2ce3b --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_start_test.dart @@ -0,0 +1,301 @@ +// 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: ['adb', 'version'], + stdout: 'Android Debug Bridge version 1.0.39', +); + +const FakeCommand kStartServer = FakeCommand( + command: ['adb', 'start-server'], +); + +const FakeCommand kShaCommand = FakeCommand( + command: [ + '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.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 ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.product.cpu.abi]: [$arch]', + )); + processManager.addCommand(const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'am', 'force-stop', 'FlutterApp'], + )); + processManager.addCommand(const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', 'FlutterApp'], + )); + processManager.addCommand(const FakeCommand( + command: ['adb', '-s', '1234', 'install', '-t', '-r', 'app-debug.apk'], + )); + processManager.addCommand(kShaCommand); + processManager.addCommand(const FakeCommand( + command: [ + '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: {}, + ); + + 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: ['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: {}, + ); + + 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: ['adb', '-s', '1234', 'shell', 'getprop'], + )); + processManager.addCommand(const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'am', 'force-stop', '--user', '10', 'FlutterApp'], + )); + processManager.addCommand(const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'FlutterApp'], + )); + processManager.addCommand(const FakeCommand( + command: [ + '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: [ + 'adb', + '-s', + '1234', + 'shell', + '-x', + 'logcat', + '-v', + 'time', + ], + )); + + // This command contains all launch arguments. + processManager.addCommand(const FakeCommand( + command: [ + '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: {}, + 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; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6746dde0099638606a1a6ac022ab1b62e74d3ed6 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dart @@ -0,0 +1,717 @@ +// 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 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 commands = [ + const FakeCommand( + command: ['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, TargetPlatform> values = , TargetPlatform>{ + ['x86_64', 'unknown']: TargetPlatform.android_x64, + ['x86', 'unknown']: TargetPlatform.android_x86, + // The default ABI is arm32 + ['???', 'unknown']: TargetPlatform.android_arm, + ['arm64-v8a', 'arm64-v8a,']: TargetPlatform.android_arm64, + // The Kindle Fire runs 32 bit apps on 64 bit hardware. + ['arm64-v8a', 'arm']: TargetPlatform.android_arm, + }; + + for (final MapEntry, TargetPlatform> entry in values.entries) { + final AndroidDevice device = setUpAndroidDevice( + processManager: FakeProcessManager.list([ + FakeCommand( + command: const ['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, bool> values = , bool>{ + ['x86_64', 'unknown']: true, + ['x86', 'unknown']: false, + // The default ABI is arm32 + ['???', 'unknown']: true, + ['arm64-v8a', 'arm64-v8a,']: true, + // The Kindle Fire runs 32 bit apps on 64 bit hardware. + ['arm64-v8a', 'arm']: true, + }; + + for (final MapEntry, bool> entry in values.entries) { + final AndroidDevice device = setUpAndroidDevice( + processManager: FakeProcessManager.list([ + FakeCommand( + command: const ['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( + command: const [ + '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([ + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [23]', + exitCode: 1, + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-s', 'flutter'], + ), + const FakeCommand( + command: ['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 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 _controller = StreamController(); + + @override + Stream asyncMap(FutureOr Function(Uint8List event) convert) => _controller.stream as Stream; + + @override + void add(List 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 _controller = StreamController(); + + @override + Stream asyncMap(FutureOr Function(Uint8List event) convert) => _controller.stream as Stream; + + @override + void add(List 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 _controller = StreamController(); + + @override + Stream asyncMap(FutureOr Function(Uint8List event) convert) => _controller.stream as Stream; + + @override + void add(List data) { + _controller.close(); + } + + @override + void destroy() { } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..027164dcc3d7a69a0f657ebc94c3d9972a458768 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dart @@ -0,0 +1,225 @@ +// 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 kEmulatorLaunchCommand = [ + '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 {'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 properties = { + '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 properties = { + '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 properties = { + '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 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([ + const FakeCommand(command: kEmulatorLaunchCommand), + ]), + androidSdk: mockSdk, + logger: BufferLogger.test(), + ); + + await emulator.launch(startupDuration: Duration.zero); + }); + + testWithoutContext('succeeds with coldboot launch', () async { + final List kEmulatorLaunchColdBootCommand = [ + ...kEmulatorLaunchCommand, + '-no-snapshot-load', + ]; + final AndroidEmulator emulator = AndroidEmulator(emulatorID, + processManager: FakeProcessManager.list([ + 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([ + 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( + command: kEmulatorLaunchCommand, + exitCode: 1, + stdout: 'dummy text', + completer: Completer(), + ), + ]), + 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; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..dee0bd409454519198f9c4d7a8ac084d842591b2 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart @@ -0,0 +1,1937 @@ +// 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: [ + '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( + 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.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: { + 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: [ + '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: [], + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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( + 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: { + 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: [ + '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( + 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: { + 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 [ + '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('', [], '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 [], + ); + }, throwsProcessException()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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: [ + '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( + 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: { + 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: { + 'HOME': '/home', + }, + ), + androidStudio: FakeAndroidStudio(), + ); + processManager.addCommand(const FakeCommand( + command: [ + '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.filled(100, 0))) + ..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List.filled(10, 0))) + ..addFile(ArchiveFile('META-INF/CERT.SF', 10, List.filled(10, 0))) + ..addFile(ArchiveFile('lib/arm64-v8a/libapp.so', 50, List.filled(50, 0))) + ..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List.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.arm64_v8a], + ), + target: 'lib/main.dart', + isBuildingBundle: false, + configOnly: false, + localGradleErrors: [], + ); + + expect(testUsage.events, contains( + const TestUsageEvent( + 'code-size-analysis', + 'apk', + ), + )); + }, overrides: { + 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: [ + '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 [], + ); + + expect( + logger.statusText, + contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'), + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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''' + + + + + + + + + + +'''); + + 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: [ + 'gradlew', + '-q', + 'printBuildVariants', + ], + stdout: ''' +BuildVariant: freeDebug +BuildVariant: paidDebug +BuildVariant: freeRelease +BuildVariant: paidRelease +BuildVariant: freeProfile +BuildVariant: paidProfile + ''', + )); + final List actual = await builder.getBuildVariants( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + expect(actual, ['freeDebug', 'paidDebug', 'freeRelease', 'paidRelease', 'freeProfile', 'paidProfile']); + + expect( + analyticsTimingEventExists( + sentEvents: fakeAnalytics.sentEvents, + workflow: 'print', + variableName: 'android build variants', + ), + true, + ); + }, overrides: { + 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: [ + 'gradlew', + '-q', + 'printBuildVariants', + ], + stderr: ''' +Gradle Crashed + ''', + exitCode: 1, + )); + final List actual = await builder.getBuildVariants( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + expect(actual, const []); + }, overrides: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..21b653f53c23e832a66352218cad0406dd642a7a --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart @@ -0,0 +1,318 @@ +// 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: ['adb', 'version'], + stdout: 'Android Debug Bridge version 1.0.39', +); +const FakeCommand kAdbStartServerCommand = FakeCommand( + command: ['adb', 'start-server'] +); +const FakeCommand kInstallCommand = FakeCommand( + command: [ + 'adb', + '-s', + '1234', + 'install', + '-t', + '-r', + '--user', + '10', + 'app-debug.apk', + ], +); +const FakeCommand kStoreShaCommand = FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + ), + // This command is run before the user is checked and is allowed to fail. + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', 'jane', 'app'], + stderr: 'Blah blah', + exitCode: 1, + ), + const FakeCommand( + command: [ + '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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: 'package:app\n' + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: 'package:app\n' + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], + stdout: 'different_example_sha', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], + exitCode: 1, + stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', + ), + const FakeCommand(command: ['adb', '-s', '1234', 'uninstall', '--user', '10', 'app']), + kInstallCommand, + const FakeCommand(command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: '\n' + ), + const FakeCommand( + command: ['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'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2d28c6bd2d2f782573430665c70ebf49b715e650 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart @@ -0,0 +1,474 @@ +// 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_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +'''; + +const String gradleWrapperToMigrate = r''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +'''; + +const String gradleWrapperToMigrateTo = r''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=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?'); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..13ca380a6f4e5d9ccd15b4e9d1d0f5c8b2328290 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart @@ -0,0 +1,569 @@ +// 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: { + 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: { + 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: { + 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: { + 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 versions = ['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: { + 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: { + 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: { + 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: { + 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: { + 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: [ + '/.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: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + Config: () => config, + Platform: () => FakePlatform(environment: {}), + }); + + testUsingContext('returns validate sdk is well formed', () { + final Directory sdkDir = createBrokenSdkDirectory(fileSystem: fileSystem); + processManager.addCommand(const FakeCommand(command: [ + '/.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 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: { + 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: [ + '/.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: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + Config: () => config, + Platform: () => FakePlatform(environment: {}), + }); + + 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: { + 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: { + 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: { + 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: { + 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: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + Platform: () => FakePlatform(operatingSystem: 'windows'), + Config: () => config, + }); + }); + + const Map llvmHostDirectoryName = { + 'macos': 'darwin-x86_64', + 'linux': 'linux-x86_64', + 'windows': 'windows-x86_64', + }; + + for (final String operatingSystem in ['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 versions = ['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 [ + 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: { + 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=1624448 +ro.build.version.sdk=24 +ro.build.version.codename=REL +'''; diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2fca60b3de957a5f0faddb5605503a08cfaa816e --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_test.dart @@ -0,0 +1,1344 @@ +// 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 macStudioInfoPlist3_3 = { + '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': { + 'Properties': { + 'idea.paths.selector': 'AndroidStudio3.3', + 'idea.platform.prefix': 'AndroidStudio', + }, + }, + }; + + const Map macStudioInfoPlist4_1 = { + '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': { + 'Properties': { + 'idea.vendor.name' : 'Google', + 'idea.paths.selector': 'AndroidStudio4.1', + 'idea.platform.prefix': 'AndroidStudio', + }, + }, + }; + + const Map macStudioInfoPlist2020_3 = { + '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': { + 'Properties': { + 'idea.vendor.name' : 'Google', + 'idea.paths.selector': 'AndroidStudio2020.3', + 'idea.platform.prefix': 'AndroidStudio', + }, + }, + }; + + const Map macStudioInfoPlist2022_1 = { + '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': { + 'Properties': { + 'idea.vendor.name' : 'Google', + 'idea.paths.selector': 'AndroidStudio2022.1', + 'idea.platform.prefix': 'AndroidStudio', + }, + }, + }; + + const Map macStudioInfoPlistEap_2022_3_1_11 = { + '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': { + 'Properties': { + '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: {'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: [ + 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, ['Java version 123']); + }, overrides: { + 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: [ + 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, ['Java version 123']); + }, overrides: { + 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: [ + 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, ['Java version 123']); + }, overrides: { + 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: [ + 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, ['Java version 123']); + }, overrides: { + 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 jetbrainsInfoPlist = { + '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: { + 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( + command: const [ + 'mdfind', + 'kMDItemCFBundleIdentifier="com.google.android.studio*"', + ], + stdout: '$randomLocation1\n$randomLocation2\n$studioInApplication', + ), + FakeCommand( + command: [ + fileSystem.path.join(randomLocation1, 'Contents', javaBin), + '-version', + ], + ), + FakeCommand( + command: [ + fileSystem.path.join(randomLocation2, 'Contents', javaBin), + '-version', + ], + ), + FakeCommand( + command: [ + fileSystem.path.join(studioInApplicationPlistFolder, javaBin), + '-version', + ], + ), + ]); + + // Results are de-duplicated, only 3 installed. + expect(AndroidStudio.allInstalled().length, 3); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: { + 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: { + 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: [ + 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: { + 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: [ + 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: { + 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 plistWithoutVersion = Map.from(macStudioInfoPlist2022_1); + plistWithoutVersion['CFBundleShortVersionString'] = ''; + plistUtils.fileContents[plistFilePath] = plistWithoutVersion; + + final String jdkPath = fileSystem.path.join(studioInApplicationPlistFolder, 'jbr', 'Contents', 'Home'); + + processManager.addCommand(FakeCommand( + command: [ + 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: { + 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 plistWithoutVersion = Map.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: { + 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( + command: const [ + 'mdfind', + 'kMDItemCFBundleIdentifier="com.google.android.studio*"', + ], + stdout: extractedDownloadZip, + ), + FakeCommand( + command: [ + studioInApplicationJavaBinary, + '-version', + ], + ), + ]); + + final AndroidStudio studio = AndroidStudio.allInstalled().single; + + expect(studio.configuredPath, extractedDownloadZip); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: { + '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: { + 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: { + 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: { + 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: { + Platform: () => FakePlatform( + operatingSystem: 'windows', + environment: {}, // 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: { + Platform: () => FakePlatform( + operatingSystem: 'windows', + environment: {}, // 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: { + Platform: () => FakePlatform( + operatingSystem: 'windows', + environment: {}, // 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: { + 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: { + 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: { + 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: { + 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: { + 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: {'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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 'LOCALAPPDATA': r'C:\Users\Dash\AppData\Local', + } + ); + fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); + }); + + testUsingContext('choses the install with the latest version', () { + const List versions = [ + '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: { + FileSystem: () => fileSystem, + Platform: () => platform, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('prefers installs with known versions over installs with unknown versions', () { + const List versions = [ + '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: { + FileSystem: () => fileSystem, + Platform: () => platform, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('choses install with lexicographically greatest directory if no installs have known versions', () { + const List versions = [ + '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: { + 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: { + 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 validVersions = [ + '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 validJavaPaths = [ + 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: [ + fileSystem.path.join(javaPath), + '-version', + ], + )); + } + + expect(AndroidStudio.allInstalled().length, 4); + + for (final String javaPath in validJavaPaths) { + (globals.processManager as FakeProcessManager).addCommand(FakeCommand( + command: [ + fileSystem.path.join(javaPath), + '-version', + ], + )); + } + + final AndroidStudio chosenInstall = AndroidStudio.latestValid()!; + expect(chosenInstall.directory, configuredAndroidStudioDir); + expect(chosenInstall.isValid, false); + }, overrides: { + 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: { + 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: { + Config: () => config, + Platform: () => platform, + FileSystem: () => _FakeFileSystem(), + FileSystemUtils: () => _FakeFsUtils(), + ProcessManager: () => FakeProcessManager.any(), + }); + }); +} + +class FakePlistUtils extends Fake implements PlistParser { + final Map> fileContents = >{}; + + @override + Map 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/'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a969081d3833cf6b04018e2a9f5e1d24946900a4 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_studio_validator_test.dart @@ -0,0 +1,110 @@ +// 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: {'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: [ + '/opt/android-studio-with-cheese-5.0/jre/bin/java', + '-version', + ], + exception: ProcessException('java', ['-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: { + 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 get validationMessages => []; + @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'; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..eb6ec04e8067f032caf2a7311b2ad437b287aba3 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/android_workflow_test.dart @@ -0,0 +1,674 @@ +// 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/android/android_workflow.dart'; +import 'package:flutter_tools/src/android/java.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/user_messages.dart'; +import 'package:flutter_tools/src/base/version.dart'; +import 'package:flutter_tools/src/doctor_validator.dart'; +import 'package:test/fake.dart'; + +import '../../src/common.dart'; +import '../../src/context.dart'; +import '../../src/fake_process_manager.dart'; +import '../../src/fakes.dart'; + +void main() { + late FakeAndroidSdk sdk; + late Logger logger; + late MemoryFileSystem fileSystem; + late FakeProcessManager processManager; + late FakeStdio stdio; + + setUp(() { + sdk = FakeAndroidSdk(); + fileSystem = MemoryFileSystem.test(); + fileSystem.directory('/home/me').createSync(recursive: true); + logger = BufferLogger.test(); + processManager = FakeProcessManager.empty(); + stdio = FakeStdio(); + }); + + testWithoutContext('AndroidWorkflow handles a null AndroidSDK', () { + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(), + androidSdk: null, + ); + + expect(androidWorkflow.canLaunchDevices, false); + expect(androidWorkflow.canListDevices, false); + expect(androidWorkflow.canListEmulators, false); + }); + + testWithoutContext('AndroidWorkflow handles a null adb', () { + final FakeAndroidSdk androidSdk = FakeAndroidSdk(); + androidSdk.adbPath = null; + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(), + androidSdk: androidSdk, + ); + + expect(androidWorkflow.canLaunchDevices, false); + expect(androidWorkflow.canListDevices, false); + expect(androidWorkflow.canListEmulators, false); + }); + + // Android SDK is actually supported on Linux Arm64 hosts. + testWithoutContext('Support for Android SDK on Linux Arm Hosts', () { + final FakeAndroidSdk androidSdk = FakeAndroidSdk(); + androidSdk.adbPath = null; + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(), + androidSdk: androidSdk, + ); + + expect(androidWorkflow.appliesToHostPlatform, isTrue); + expect(androidWorkflow.canLaunchDevices, isFalse); + expect(androidWorkflow.canListDevices, isFalse); + expect(androidWorkflow.canListEmulators, isFalse); + }); + + testWithoutContext('AndroidWorkflow is disabled if feature is disabled', () { + final FakeAndroidSdk androidSdk = FakeAndroidSdk(); + androidSdk.adbPath = 'path/to/adb'; + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(isAndroidEnabled: false), + androidSdk: androidSdk, + ); + + expect(androidWorkflow.appliesToHostPlatform, false); + expect(androidWorkflow.canLaunchDevices, false); + expect(androidWorkflow.canListDevices, false); + expect(androidWorkflow.canListEmulators, false); + }); + + testWithoutContext('AndroidWorkflow cannot list emulators if emulatorPath is null', () { + final FakeAndroidSdk androidSdk = FakeAndroidSdk(); + androidSdk.adbPath = 'path/to/adb'; + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(), + androidSdk: androidSdk, + ); + + expect(androidWorkflow.appliesToHostPlatform, true); + expect(androidWorkflow.canLaunchDevices, true); + expect(androidWorkflow.canListDevices, true); + expect(androidWorkflow.canListEmulators, false); + }); + + testWithoutContext('AndroidWorkflow can list emulators', () { + final FakeAndroidSdk androidSdk = FakeAndroidSdk(); + androidSdk.adbPath = 'path/to/adb'; + androidSdk.emulatorPath = 'path/to/emulator'; + final AndroidWorkflow androidWorkflow = AndroidWorkflow( + featureFlags: TestFeatureFlags(), + androidSdk: androidSdk, + ); + + expect(androidWorkflow.appliesToHostPlatform, true); + expect(androidWorkflow.canLaunchDevices, true); + expect(androidWorkflow.canListDevices, true); + expect(androidWorkflow.canListEmulators, true); + }); + + testWithoutContext('licensesAccepted returns LicensesAccepted.unknown if cannot find sdkmanager', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.excludedExecutables.add('/foo/bar/sdkmanager'); + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted licenseStatus = await licenseValidator.licensesAccepted; + + expect(licenseStatus, LicensesAccepted.unknown); + }); + + testWithoutContext('licensesAccepted returns LicensesAccepted.unknown if cannot run sdkmanager', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.excludedExecutables.add('/foo/bar/sdkmanager'); + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted licenseStatus = await licenseValidator.licensesAccepted; + + expect(licenseStatus, LicensesAccepted.unknown); + }); + + testWithoutContext('licensesAccepted handles garbage/no output', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.addCommand(const FakeCommand( + command: [ + '/foo/bar/sdkmanager', + '--licenses', + ], stdout: 'asdasassad', + )); + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted result = await licenseValidator.licensesAccepted; + + expect(result, LicensesAccepted.unknown); + }); + + testWithoutContext('licensesAccepted works for all licenses accepted', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + const String output = ''' +[=======================================] 100% Computing updates... +All SDK package licenses accepted. +'''; + processManager.addCommand(const FakeCommand( + command: [ + '/foo/bar/sdkmanager', + '--licenses', + ], stdout: output, + )); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted result = await licenseValidator.licensesAccepted; + + expect(result, LicensesAccepted.all); + }); + + testWithoutContext('licensesAccepted sets environment for finding java', () async { + final Java java = FakeJava(); + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.addCommand( + FakeCommand( + command: [sdk.sdkManagerPath!, '--licenses'], + stdout: 'All SDK package licenses accepted.', + environment: { + 'JAVA_HOME': java.javaHome!, + 'PATH': fileSystem.path.join(java.javaHome!, 'bin'), + } + ) + ); + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: java, + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted licenseStatus = await licenseValidator.licensesAccepted; + + expect(licenseStatus, LicensesAccepted.all); + }); + + testWithoutContext('licensesAccepted works for some licenses accepted', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + const String output = ''' +[=======================================] 100% Computing updates... +2 of 5 SDK package licenses not accepted. +Review licenses that have not been accepted (y/N)? +'''; + processManager.addCommand(const FakeCommand( + command: [ + '/foo/bar/sdkmanager', + '--licenses', + ], stdout: output, + )); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted result = await licenseValidator.licensesAccepted; + + expect(result, LicensesAccepted.some); + }); + + testWithoutContext('licensesAccepted works for no licenses accepted', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + const String output = ''' +[=======================================] 100% Computing updates... +5 of 5 SDK package licenses not accepted. +Review licenses that have not been accepted (y/N)? +'''; + processManager.addCommand(const FakeCommand( + command: [ + '/foo/bar/sdkmanager', + '--licenses', + ], stdout: output, + )); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + final LicensesAccepted result = await licenseValidator.licensesAccepted; + + expect(result, LicensesAccepted.none); + }); + + testWithoutContext('runLicenseManager succeeds for version >= 26', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + sdk.sdkManagerVersion = '26.0.0'; + processManager.addCommand(const FakeCommand( + command: [ + '/foo/bar/sdkmanager', + '--licenses', + ], + )); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + + expect(await licenseValidator.runLicenseManager(), isTrue); + }); + + testWithoutContext('runLicenseManager errors when sdkmanager is not found', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.excludedExecutables.add('/foo/bar/sdkmanager'); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + + expect(licenseValidator.runLicenseManager(), throwsToolExit()); + }); + + testWithoutContext('runLicenseManager handles broken pipe without ArgumentError', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + const String exceptionMessage = 'Write failed (OS Error: Broken pipe, errno = 32), port = 0'; + const SocketException exception = SocketException(exceptionMessage); + // By using a `Socket` generic parameter, the stdin.addStream will return a `Future` + // We are testing that our error handling properly handles futures of this type + final ThrowingStdin fakeStdin = ThrowingStdin(exception); + final FakeCommand licenseCommand = FakeCommand( + command: [sdk.sdkManagerPath!, '--licenses'], + stdin: fakeStdin, + ); + processManager.addCommand(licenseCommand); + final BufferLogger logger = BufferLogger.test(); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: logger, + userMessages: UserMessages(), + ); + + await licenseValidator.runLicenseManager(); + expect(logger.traceText, contains(exceptionMessage)); + expect(processManager, hasNoRemainingExpectations); + }); + + testWithoutContext('runLicenseManager errors when sdkmanager fails to run', () async { + sdk.sdkManagerPath = '/foo/bar/sdkmanager'; + processManager.excludedExecutables.add('/foo/bar/sdkmanager'); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: BufferLogger.test(), + userMessages: UserMessages(), + ); + + expect(licenseValidator.runLicenseManager(), throwsToolExit()); + }); + + testWithoutContext('runLicenseManager errors when sdkmanager exits non-zero', () async { + const String sdkManagerPath = '/foo/bar/sdkmanager'; + sdk.sdkManagerPath = sdkManagerPath; + final BufferLogger logger = BufferLogger.test(); + processManager.addCommand( + const FakeCommand( + command: [sdkManagerPath, '--licenses'], + exitCode: 1, + stderr: 'sdkmanager crash', + ), + ); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: logger, + userMessages: UserMessages(), + ); + + await expectLater( + licenseValidator.runLicenseManager(), + throwsToolExit( + message: 'Android sdkmanager tool was found, but failed to run ($sdkManagerPath): "exited code 1"', + ), + ); + expect(processManager, hasNoRemainingExpectations); + expect(logger.traceText, isEmpty); + expect(stdio.writtenToStdout, isEmpty); + expect(stdio.writtenToStderr, contains('sdkmanager crash')); + }); + + testWithoutContext('detects license-only SDK installation with cmdline-tools', () async { + sdk + ..licensesAvailable = true + ..platformToolsAvailable = false + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar'); + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(), + androidSdk: sdk, + logger: logger, + platform: FakePlatform()..environment = {'HOME': '/home/me'}, + userMessages: UserMessages(), + ).validate(); + + expect(validationResult.type, ValidationType.partial); + + final ValidationMessage sdkMessage = validationResult.messages.first; + expect(sdkMessage.type, ValidationMessageType.information); + expect(sdkMessage.message, 'Android SDK at /foo/bar'); + + final ValidationMessage licenseMessage = validationResult.messages.last; + expect(licenseMessage.type, ValidationMessageType.hint); + expect(licenseMessage.message, UserMessages().androidSdkLicenseOnly(kAndroidHome)); + }); + + testUsingContext('detects minimum required SDK and buildtools', () async { + final FakeAndroidSdkVersion sdkVersion = FakeAndroidSdkVersion() + ..sdkLevel = 28 + ..buildToolsVersion = Version(26, 0, 3); + + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + // Test with invalid SDK and build tools + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager' + ..latestVersion = sdkVersion; + + final String errorMessage = UserMessages().androidSdkBuildToolsOutdated( + kAndroidSdkMinVersion, + kAndroidSdkBuildToolsMinVersion.toString(), + FakePlatform(), + ); + + final AndroidValidator androidValidator = AndroidValidator( + java: null, + androidSdk: sdk, + logger: logger, + platform: FakePlatform()..environment = {'HOME': '/home/me'}, + userMessages: UserMessages(), + ); + + + ValidationResult validationResult = await androidValidator.validate(); + expect(validationResult.type, ValidationType.missing); + expect( + validationResult.messages.last.message, + errorMessage, + ); + + // Test with valid SDK but invalid build tools + sdkVersion.sdkLevel = 29; + sdkVersion.buildToolsVersion = Version(28, 0, 2); + + validationResult = await androidValidator.validate(); + expect(validationResult.type, ValidationType.missing); + expect( + validationResult.messages.last.message, + errorMessage, + ); + + // Test with valid SDK and valid build tools + // Will still be partial because AndroidSdk.findJavaBinary is static :( + sdkVersion.sdkLevel = kAndroidSdkMinVersion; + sdkVersion.buildToolsVersion = kAndroidSdkBuildToolsMinVersion; + + validationResult = await androidValidator.validate(); + expect(validationResult.type, ValidationType.partial); // No Java binary + expect( + validationResult.messages.any((ValidationMessage message) => message.message == errorMessage), + isFalse, + ); + }); + + testWithoutContext('detects missing cmdline tools', () async { + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = false + ..directory = fileSystem.directory('/foo/bar'); + + final AndroidValidator androidValidator = AndroidValidator( + java: FakeJava(), + androidSdk: sdk, + logger: logger, + platform: FakePlatform()..environment = {'HOME': '/home/me'}, + userMessages: UserMessages(), + ); + + + final String errorMessage = UserMessages().androidMissingCmdTools; + + final ValidationResult validationResult = await androidValidator.validate(); + expect(validationResult.type, ValidationType.missing); + + final ValidationMessage sdkMessage = validationResult.messages.first; + expect(sdkMessage.type, ValidationMessageType.information); + expect(sdkMessage.message, 'Android SDK at /foo/bar'); + + final ValidationMessage cmdlineMessage = validationResult.messages.last; + expect(cmdlineMessage.type, ValidationMessageType.error); + expect(cmdlineMessage.message, errorMessage); + }); + + testUsingContext('detects minimum required java version', () async { + // Test with older version of JDK + final Platform platform = FakePlatform()..environment = { + 'HOME': '/home/me', + Java.javaHomeEnvironmentVariable: 'home/java', + 'PATH': '', + }; + final FakeAndroidSdkVersion sdkVersion = FakeAndroidSdkVersion() + ..sdkLevel = 29 + ..buildToolsVersion = Version(28, 0, 3); + + // Mock a pass through scenario to reach _checkJavaVersion() + sdk + ..licensesAvailable = true + ..platformToolsAvailable = true + ..cmdlineToolsAvailable = true + ..directory = fileSystem.directory('/foo/bar') + ..sdkManagerPath = '/foo/bar/sdkmanager'; + sdk.latestVersion = sdkVersion; + + const String javaVersionText = 'openjdk version "1.7.0_212"'; + final String errorMessage = UserMessages().androidJavaMinimumVersion(javaVersionText); + + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(version: const Version.withText(1, 7, 0, javaVersionText)), + androidSdk: sdk, + logger: logger, + platform: platform, + userMessages: UserMessages(), + ).validate(); + expect(validationResult.type, ValidationType.partial); + expect( + validationResult.messages.last.message, + errorMessage, + ); + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains('Unable to locate Android SDK') + ), + false, + ); + }); + + testWithoutContext('Mentions `flutter config --android-sdk if user has no AndroidSdk`', () async { + final ValidationResult validationResult = await AndroidValidator( + java: FakeJava(), + androidSdk: null, + logger: logger, + platform: FakePlatform()..environment = {'HOME': '/home/me', Java.javaHomeEnvironmentVariable: 'home/java'}, + userMessages: UserMessages(), + ).validate(); + + expect( + validationResult.messages.any( + (ValidationMessage message) => message.message.contains('flutter config --android-sdk') + ), + true, + ); + }); + + testWithoutContext('Asks user to upgrade Android Studio when it is too far behind the Android SDK', () async { + const String sdkManagerPath = '/foo/bar/sdkmanager'; + sdk.sdkManagerPath = sdkManagerPath; + final BufferLogger logger = BufferLogger.test(); + processManager.addCommand( + const FakeCommand( + command: [sdkManagerPath, '--licenses'], + exitCode: 1, + stderr: ''' +Error: LinkageError occurred while loading main class com.android.sdklib.tool.sdkmanager.SdkManagerCli + java.lang.UnsupportedClassVersionError: com/android/sdklib/tool/sdkmanager/SdkManagerCli has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0 +Android sdkmanager tool was found, but failed to run +''', + ), + ); + + final AndroidLicenseValidator licenseValidator = AndroidLicenseValidator( + java: FakeJava(), + androidSdk: sdk, + processManager: processManager, + platform: FakePlatform(environment: {'HOME': '/home/me'}), + stdio: stdio, + logger: logger, + userMessages: UserMessages(), + ); + + await expectLater( + licenseValidator.runLicenseManager(), + throwsToolExit( + message: RegExp('.*consider updating your installation of Android studio. Alternatively, you.*'), + ), + ); + expect(processManager, hasNoRemainingExpectations); + expect(stdio.stderr.getAndClear(), contains('UnsupportedClassVersionError')); + }); +} + +class FakeAndroidSdk extends Fake implements AndroidSdk { + @override + String? sdkManagerPath; + + @override + String? sdkManagerVersion; + + @override + String? adbPath; + + @override + bool licensesAvailable = false; + + @override + bool platformToolsAvailable = false; + + @override + bool cmdlineToolsAvailable = false; + + @override + Directory directory = MemoryFileSystem.test().directory('/foo/bar'); + + @override + AndroidSdkVersion? latestVersion; + + @override + String? emulatorPath; + + @override + List validateSdkWellFormed() => []; +} + +class FakeAndroidSdkVersion extends Fake implements AndroidSdkVersion { + @override + int sdkLevel = 0; + + @override + Version buildToolsVersion = Version(0, 0, 0); + + @override + String get buildToolsVersionName => ''; + + @override + String get platformName => ''; +} + +class ThrowingStdin extends Fake implements IOSink { + ThrowingStdin(this.exception); + + final Exception exception; + + @override + Future addStream(Stream> stream) { + return Future.error(exception); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/build_validation_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/build_validation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..886662379f38be8ede23c9c6f1d15da99de93ea7 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/build_validation_test.dart @@ -0,0 +1,64 @@ +// 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/build_validation.dart'; +import 'package:flutter_tools/src/build_info.dart'; + +import '../../src/common.dart'; + +void main() { + testWithoutContext('validateBuild throws if attempting to build release/profile on x86', () { + expect(() => validateBuild( + const AndroidBuildInfo( + BuildInfo.release, + targetArchs: [AndroidArch.x86], + ), + ), throwsToolExit(message: 'Cannot build release mode for x86 ABI.')); + }); + + testWithoutContext('validateBuild does not throw on AOT supported architectures', () { + expect(() => validateBuild( + const AndroidBuildInfo( + BuildInfo.release, + targetArchs: [AndroidArch.x86_64, AndroidArch.armeabi_v7a, AndroidArch.arm64_v8a], + ), + ), returnsNormally); + }); + + testWithoutContext('validateBuild throws if an invalid build number is specified', () { + expect(() => validateBuild( + const AndroidBuildInfo( + // Invalid number + BuildInfo(BuildMode.debug, '', treeShakeIcons: false, buildNumber: 'a'), + targetArchs: [AndroidArch.x86], + ), + ), throwsToolExit(message: 'buildNumber: a was not a valid integer value.')); + + expect(() => validateBuild( + const AndroidBuildInfo( + // Negative number + BuildInfo(BuildMode.debug, '', treeShakeIcons: false, buildNumber: '-1'), + targetArchs: [AndroidArch.x86], + ), + ), throwsToolExit(message: 'buildNumber: -1 must be a positive integer value.')); + + expect(() => validateBuild( + const AndroidBuildInfo( + // bigger than maximum supported play store value + BuildInfo(BuildMode.debug, '', treeShakeIcons: false, buildNumber: '2100000001'), + targetArchs: [AndroidArch.x86], + ), + ), throwsToolExit(message: 'buildNumber: 2100000001 is greater than the maximum ' + 'allowed value of 2100000000.')); + }); + + testWithoutContext('validateBuild does not throw on positive number', () { + expect(() => validateBuild( + const AndroidBuildInfo( + BuildInfo(BuildMode.debug, '', treeShakeIcons: false, buildNumber: '2'), + targetArchs: [AndroidArch.x86], + ), + ), returnsNormally); + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/deferred_components_gen_snapshot_validator_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/deferred_components_gen_snapshot_validator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6962b50a6aaead2de74ec51dc300ce0c3e2e5471 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/deferred_components_gen_snapshot_validator_test.dart @@ -0,0 +1,702 @@ +// 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/deferred_components_gen_snapshot_validator.dart'; +import 'package:flutter_tools/src/android/deferred_components_validator.dart'; +import 'package:flutter_tools/src/artifacts.dart'; +import 'package:flutter_tools/src/base/deferred_component.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/build_system/build_system.dart'; + +import '../../src/common.dart'; +import '../../src/fake_process_manager.dart'; + +void main() { + late FileSystem fileSystem; + late BufferLogger logger; + late Environment env; + + Environment createEnvironment() { + final Map defines = { kDeferredComponents: 'true' }; + final Environment result = Environment.test( + fileSystem.directory('/project'), + defines: defines, + artifacts: Artifacts.test(), + fileSystem: fileSystem, + logger: logger, + processManager: FakeProcessManager.any(), + ); + return result; + } + + setUp(() { + fileSystem = MemoryFileSystem.test(); + logger = BufferLogger.test(); + env = createEnvironment(); + }); + + testWithoutContext('No checks passes', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + validator.displayResults(); + validator.attemptToolExit(); + expect(logger.statusText, 'test check passed.\n'); + }); + + testWithoutContext('writeCache passes', () async { + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + if (cacheFile.existsSync()) { + cacheFile.deleteSync(); + } + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + validator.writeLoadingUnitsCache( + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, 'test check passed.\n'); + + final File expectedFile = env.projectDir.childFile('deferred_components_loading_units.yaml'); + + expect(expectedFile.existsSync(), true); + const String expectedContents = +''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: + - lib2 + - lib3 +'''; + expect(expectedFile.readAsStringSync(), contains(expectedContents)); + }); + + testWithoutContext('loadingUnitCache identical passes', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: + - lib2 + - lib3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ] + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, 'test check passed.\n'); + }); + + testWithoutContext('loadingUnitCache finds new loading units', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 3 + libraries: + - lib2 + - lib3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('New loading units were found:\n\n LoadingUnit 2\n Libraries:\n - lib1\n')); + }); + + testWithoutContext('loadingUnitCache finds missing loading units', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: + - lib2 + - lib3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Previously existing loading units no longer exist:\n\n LoadingUnit 2\n Libraries:\n - lib1\n')); + }); + + testWithoutContext('missing cache file counts as all new loading units', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 2, libraries: ['lib1']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('New loading units were found:\n\n LoadingUnit 2\n Libraries:\n - lib1\n')); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: missing main entry', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units-spelled-wrong: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: + - lib2 + - lib3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, 'loading-units' entry did not exist.")); + + expect(logger.statusText.contains('Previously existing loading units no longer exist:\n\n LoadingUnit 2\n Libraries:\n - lib1\n'), false); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: not a list', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: hello +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, 'loading-units' is not a list.")); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: not a list', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - 2 + - 3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, 'loading-units' is not a list of maps.")); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: missing id', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - libraries: + - lib2 + - lib3 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, all loading units must have an 'id'")); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: libraries is list', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: hello +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, 'libraries' is not a list.")); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: libraries is list of strings', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: + - blah: hello + blah2: hello2 +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Errors checking the following files:')); + expect(logger.statusText, contains("Invalid loading units yaml file, 'libraries' is not a list of strings.")); + }); + + testWithoutContext('loadingUnitCache validator detects malformed file: empty libraries allowed', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); + cacheFile.createSync(recursive: true); + cacheFile.writeAsStringSync(''' +loading-units: + - id: 2 + libraries: + - lib1 + - id: 3 + libraries: +'''); + validator.checkAgainstLoadingUnitsCache( + [ + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText.contains('Errors checking the following files:'), false); + }); + + testWithoutContext('androidStringMapping modifies strings file', () async { + final DeferredComponentsGenSnapshotValidator validator = DeferredComponentsGenSnapshotValidator( + env, + exitOnFail: false, + title: 'test check', + ); + final Directory baseModuleDir = env.projectDir.childDirectory('android').childDirectory('app'); + final File manifest = baseModuleDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); + if (manifest.existsSync()) { + manifest.deleteSync(); + } + manifest.createSync(recursive: true); + manifest.writeAsStringSync(''' + + + + + + + + + +'''); + validator.checkAppAndroidManifestComponentLoadingUnitMapping( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + LoadingUnit(id: 4, libraries: ['lib4', 'lib5']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Modified android files:\n')); + expect(logger.statusText, contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/AndroidManifest.xml\n')); + + final File manifestOutput = env.projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + expect(manifestOutput.existsSync(), true); + expect(manifestOutput.readAsStringSync().contains(''), true); + expect(manifestOutput.readAsStringSync().contains('android:value="invalidmapping"'), false); + expect(manifestOutput.readAsStringSync().contains(" + + + +'''); + validator.checkAppAndroidManifestComponentLoadingUnitMapping( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + LoadingUnit(id: 4, libraries: ['lib4', 'lib5']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Modified android files:\n')); + expect(logger.statusText, contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/AndroidManifest.xml\n')); + + final File manifestOutput = env.projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + expect(manifestOutput.existsSync(), true); + expect(manifestOutput.readAsStringSync(), contains('')); + expect(manifestOutput.readAsStringSync(), contains(" + + + +'''); + validator.checkAppAndroidManifestComponentLoadingUnitMapping( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + LoadingUnit(id: 4, libraries: ['lib4', 'lib5']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Modified android files:\n')); + expect(logger.statusText, contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/AndroidManifest.xml\n')); + + final File manifestOutput = env.projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + expect(manifestOutput.existsSync(), true); + expect(manifestOutput.readAsStringSync(), contains('')); + expect(manifestOutput.readAsStringSync(), contains(" + + + +'''); + validator.checkAppAndroidManifestComponentLoadingUnitMapping( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + LoadingUnit(id: 4, libraries: ['lib4', 'lib5']), + // Loading units 6 and 7 are in base module + LoadingUnit(id: 5, libraries: ['lib6', 'lib7']), + LoadingUnit(id: 6, libraries: ['lib8', 'lib9']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Modified android files:\n')); + expect(logger.statusText, contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/AndroidManifest.xml\n')); + + final File manifestOutput = env.projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + expect(manifestOutput.existsSync(), true); + expect(manifestOutput.readAsStringSync(), contains('')); + expect(manifestOutput.readAsStringSync(), contains(" + + + + +'''); + validator.checkAppAndroidManifestComponentLoadingUnitMapping( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + [ + LoadingUnit(id: 2, libraries: ['lib1']), + LoadingUnit(id: 3, libraries: ['lib2', 'lib3']), + LoadingUnit(id: 4, libraries: ['lib4', 'lib5']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText, contains('Modified android files:\n')); + expect(logger.statusText, contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/AndroidManifest.xml\n')); + + final File manifestOutput = env.projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + expect(manifestOutput.existsSync(), true); + expect(manifestOutput.readAsStringSync().contains(''), true); + expect(manifestOutput.readAsStringSync().contains(RegExp(r'android:value[\s\n]*=[\s\n]*"invalidmapping"')), false); + expect(manifestOutput.readAsStringSync().contains(" + + + + +''', flush: true, mode: FileMode.append); + validator.checkAndroidResourcesStrings( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText.contains('Modified android files:\n'), false); + expect(logger.statusText.contains('Newly generated android files:\n'), true); + expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/res/values/strings.xml\n'), true); + + final File stringsOutput = projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('res') + .childDirectory('values') + .childFile('strings.xml'); + expect(stringsOutput.existsSync(), true); + expect(stringsOutput.readAsStringSync().contains('component1'), true); + expect(stringsOutput.readAsStringSync().contains('component2'), true); + }); + + testWithoutContext('androidStringMapping modifies strings file', () async { + final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( + projectDir, + logger, + platform, + exitOnFail: false, + title: 'test check', + ); + final Directory baseModuleDir = projectDir.childDirectory('android').childDirectory('app'); + final File stringRes = baseModuleDir.childDirectory('src').childDirectory('main').childDirectory('res').childDirectory('values').childFile('strings.xml'); + if (stringRes.existsSync()) { + stringRes.deleteSync(); + } + stringRes.createSync(recursive: true); + stringRes.writeAsStringSync(''' + + + component1 + + +''', flush: true, mode: FileMode.append); + validator.checkAndroidResourcesStrings( + [ + DeferredComponent(name: 'component1', libraries: ['lib2']), + DeferredComponent(name: 'component2', libraries: ['lib1', 'lib4']), + ], + ); + validator.displayResults(); + validator.attemptToolExit(); + + expect(logger.statusText.contains('Newly generated android files:\n'), false); + expect(logger.statusText.contains('Modified android files:\n'), true); + expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/res/values/strings.xml\n'), true); + + final File stringsOutput = projectDir + .childDirectory('build') + .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('res') + .childDirectory('values') + .childFile('strings.xml'); + expect(stringsOutput.existsSync(), true); + expect(stringsOutput.readAsStringSync().contains('component1'), true); + expect(stringsOutput.readAsStringSync().contains('component2'), true); + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_errors_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_errors_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..307224d11a44bda414fe2233db02c58540645456 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_errors_test.dart @@ -0,0 +1,1497 @@ +// 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:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/android/gradle_errors.dart'; +import 'package:flutter_tools/src/android/gradle_utils.dart'; +import 'package:flutter_tools/src/android/java.dart'; +import 'package:flutter_tools/src/base/bot_detector.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/base/terminal.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:test/fake.dart'; + +import '../../src/common.dart'; +import '../../src/context.dart'; +import '../../src/fake_process_manager.dart'; +import '../../src/fakes.dart'; + +void main() { + late FileSystem fileSystem; + late FakeProcessManager processManager; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + processManager = FakeProcessManager.empty(); + }); + + group('gradleErrors', () { + testWithoutContext('list of errors', () { + // If you added a new Gradle error, please update this test. + expect(gradleErrors, + equals([ + licenseNotAcceptedHandler, + networkErrorHandler, + permissionDeniedErrorHandler, + flavorUndefinedHandler, + r8FailureHandler, + minSdkVersionHandler, + transformInputIssueHandler, + lockFileDepMissingHandler, + multidexErrorHandler, + incompatibleKotlinVersionHandler, + minCompileSdkVersionHandler, + jvm11RequiredHandler, + outdatedGradleHandler, + sslExceptionHandler, + zipExceptionHandler, + incompatibleJavaAndGradleVersionsHandler, + remoteTerminatedHandshakeHandler, + couldNotOpenCacheDirectoryHandler, + ]) + ); + }); + }); + + group('network errors', () { + testUsingContext('retries if gradle fails while downloading', () async { + const String errorMessage = r''' +Exception in thread "main" java.io.FileNotFoundException: https://downloads.gradle.org/distributions/gradle-4.1.1-all.zip +at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872) +at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) +at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) +at org.gradle.wrapper.Download.downloadInternal(Download.java:58) +at org.gradle.wrapper.Download.download(Download.java:44) +at org.gradle.wrapper.Install$1.call(Install.java:61) +at org.gradle.wrapper.Install$1.call(Install.java:48) +at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) +at org.gradle.wrapper.Install.createDist(Install.java:48) +at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) +at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if remote host terminated ssl handshake', () async { + const String errorMessage = r''' +Exception in thread "main" javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake + at java.base/sun.security.ssl.SSLSocketImpl.handleEOF(SSLSocketImpl.java:1696) + at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1514) + at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1416) + at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:456) + at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:427) + at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:572) + at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) + at java.base/sun.net.www.protocol.http.HttpURLConnection.followRedirect0(HttpURLConnection.java:2783) + at java.base/sun.net.www.protocol.http.HttpURLConnection.followRedirect(HttpURLConnection.java:2695) + at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1854) + at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520) + at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250) + at org.gradle.wrapper.Download.downloadInternal(Download.java:58) + at org.gradle.wrapper.Download.download(Download.java:44) + at org.gradle.wrapper.Install$1.call(Install.java:61) + at org.gradle.wrapper.Install$1.call(Install.java:48) + at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) + at org.gradle.wrapper.Install.createDist(Install.java:48) + at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) + at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) +Caused by: java.io.EOFException: SSL peer shut down incorrectly + at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:483) + at java.base/sun.security.ssl.SSLSocketInputRecord.readHeader(SSLSocketInputRecord.java:472) + at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:160) + at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:111) + at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1506)'''; + + expect(formatTestErrorMessage(errorMessage, remoteTerminatedHandshakeHandler), isTrue); + expect(await remoteTerminatedHandshakeHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }); + + testUsingContext('retries if gradle fails downloading with proxy error', () async { + const String errorMessage = r''' +Exception in thread "main" java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request" +at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:2124) +at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:183) +at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1546) +at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) +at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) +at org.gradle.wrapper.Download.downloadInternal(Download.java:58) +at org.gradle.wrapper.Download.download(Download.java:44) +at org.gradle.wrapper.Install$1.call(Install.java:61) +at org.gradle.wrapper.Install$1.call(Install.java:48) +at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) +at org.gradle.wrapper.Install.createDist(Install.java:48) +at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) +at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if gradle fails downloading with bad gateway error', () async { + const String errorMessage = r''' +Exception in thread "main" java.io.IOException: Server returned HTTP response code: 502 for URL: https://objects.githubusercontent.com/github-production-release-asset-2e65be/696192900/1e77bbfb-4cde-4376-92ea-fc4ff57b8362?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=FFFF%2F20231220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20231220T160553Z&X-Amz-Expires=300&X-Amz-Signature=ffff&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=696192900&response-content-disposition=attachment%3B%20filename%3Dgradle-8.2.1-all.zip&response-content-type=application%2Foctet-stream +at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997) +at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589) +at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224) +at org.gradle.wrapper.Download.downloadInternal(Download.java:58) +at org.gradle.wrapper.Download.download(Download.java:44) +at org.gradle.wrapper.Install$1.call(Install.java:61) +at org.gradle.wrapper.Install$1.call(Install.java:48) +at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) +at org.gradle.wrapper.Install.createDist(Install.java:48) +at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) +at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if gradle times out waiting for exclusive access to zip', () async { + const String errorMessage = ''' +Exception in thread "main" java.lang.RuntimeException: Timeout of 120000 reached waiting for exclusive access to file: /User/documents/gradle-5.6.2-all.zip + at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:61) + at org.gradle.wrapper.Install.createDist(Install.java:48) + at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) + at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if remote host closes connection', () async { + const String errorMessage = r''' +Downloading https://services.gradle.org/distributions/gradle-5.6.2-all.zip +Exception in thread "main" javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake + at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:994) + at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367) + at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395) + at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379) + at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) + at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) + at sun.net.www.protocol.http.HttpURLConnection.followRedirect0(HttpURLConnection.java:2729) + at sun.net.www.protocol.http.HttpURLConnection.followRedirect(HttpURLConnection.java:2641) + at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1824) + at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) + at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263) + at org.gradle.wrapper.Download.downloadInternal(Download.java:58) + at org.gradle.wrapper.Download.download(Download.java:44) + at org.gradle.wrapper.Install$1.call(Install.java:61) + at org.gradle.wrapper.Install$1.call(Install.java:48) + at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) + at org.gradle.wrapper.Install.createDist(Install.java:48) + at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) + at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if file opening fails', () async { + const String errorMessage = r''' +Downloading https://services.gradle.org/distributions/gradle-3.5.0-all.zip +Exception in thread "main" java.io.FileNotFoundException: https://downloads.gradle-dn.com/distributions/gradle-3.5.0-all.zip + at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890) + at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) + at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263) + at org.gradle.wrapper.Download.downloadInternal(Download.java:58) + at org.gradle.wrapper.Download.download(Download.java:44) + at org.gradle.wrapper.Install$1.call(Install.java:61) + at org.gradle.wrapper.Install$1.call(Install.java:48) + at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) + at org.gradle.wrapper.Install.createDist(Install.java:48) + at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) + at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if the connection is reset', () async { + const String errorMessage = r''' +Downloading https://services.gradle.org/distributions/gradle-5.6.2-all.zip +Exception in thread "main" java.net.SocketException: Connection reset + at java.net.SocketInputStream.read(SocketInputStream.java:210) + at java.net.SocketInputStream.read(SocketInputStream.java:141) + at sun.security.ssl.InputRecord.readFully(InputRecord.java:465) + at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:593) + at sun.security.ssl.InputRecord.read(InputRecord.java:532) + at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975) + at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367) + at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395) + at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379) + at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) + at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) + at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564) + at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) + at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263) + at org.gradle.wrapper.Download.downloadInternal(Download.java:58) + at org.gradle.wrapper.Download.download(Download.java:44) + at org.gradle.wrapper.Install$1.call(Install.java:61) + at org.gradle.wrapper.Install$1.call(Install.java:48) + at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) + at org.gradle.wrapper.Install.createDist(Install.java:48) + at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) + at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if Gradle could not get a resource', () async { + const String errorMessage = ''' +A problem occurred configuring root project 'android'. +> Could not resolve all artifacts for configuration ':classpath'. + > Could not resolve net.sf.proguard:proguard-gradle:6.0.3. + Required by: + project : > com.android.tools.build:gradle:3.3.0 + > Could not resolve net.sf.proguard:proguard-gradle:6.0.3. + > Could not parse POM https://jcenter.bintray.com/net/sf/proguard/proguard-gradle/6.0.3/proguard-gradle-6.0.3.pom + > Could not resolve net.sf.proguard:proguard-parent:6.0.3. + > Could not resolve net.sf.proguard:proguard-parent:6.0.3. + > Could not get resource 'https://jcenter.bintray.com/net/sf/proguard/proguard-parent/6.0.3/proguard-parent-6.0.3.pom'. + > Could not GET 'https://jcenter.bintray.com/net/sf/proguard/proguard-parent/6.0.3/proguard-parent-6.0.3.pom'. Received status code 504 from server: Gateway Time-out'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('retries if Gradle could not get a resource (non-Gateway)', () async { + const String errorMessage = ''' +* Error running Gradle: +Exit code 1 from: /home/travis/build/flutter/flutter sdk/examples/flutter_gallery/android/gradlew app:properties: +Starting a Gradle Daemon (subsequent builds will be faster) +Picked up _JAVA_OPTIONS: -Xmx2048m -Xms512m +FAILURE: Build failed with an exception. +* What went wrong: +A problem occurred configuring root project 'android'. +> Could not resolve all files for configuration ':classpath'. + > Could not resolve com.android.tools.build:gradle:3.1.2. + Required by: + project : + > Could not resolve com.android.tools.build:gradle:3.1.2. + > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'. + > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'. + > Remote host closed connection during handshake'''; + + expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue); + expect(await networkErrorHandler.handler( + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + usesAndroidX: true, + ), equals(GradleBuildStatus.retry)); + + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('multidex errors', () { + testUsingContext('exits if multidex AndroidManifest not detected', () async { + const String errorMessage = r''' +Caused by: com.android.tools.r8.utils.b: Cannot fit requested classes in a single dex file (# methods: 85091 > 65536) + at com.android.tools.r8.utils.T0.error(SourceFile:1) + at com.android.tools.r8.utils.T0.a(SourceFile:2) + at com.android.tools.r8.dex.P.a(SourceFile:740) + at com.android.tools.r8.dex.P$h.a(SourceFile:7) + at com.android.tools.r8.dex.b.a(SourceFile:14) + at com.android.tools.r8.dex.b.b(SourceFile:25) + at com.android.tools.r8.D8.d(D8.java:133) + at com.android.tools.r8.D8.b(D8.java:1) + at com.android.tools.r8.utils.Y.a(SourceFile:36) + ... 38 more + + +FAILURE: Build failed with an exception. + +* What went wrong: +Execution failed for task ':app:mergeDexDebug'. +> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade + > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: + The number of method references in a .dex file cannot exceed 64K. + Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html'''; + + expect(formatTestErrorMessage(errorMessage, multidexErrorHandler), isTrue); + expect(await multidexErrorHandler.handler(project: FlutterProject.fromDirectory(fileSystem.currentDirectory), multidexEnabled: true, usesAndroidX: true, line: ''), equals(GradleBuildStatus.exit)); + + expect(testLogger.statusText, + contains( + 'Multidex support is required for your android app to build since the number of methods has exceeded 64k.' + ) + ); + expect(testLogger.statusText, + contains( + 'See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information.' + ) + ); + expect(testLogger.statusText, + contains( + 'Your `android/app/src/main/AndroidManifest.xml` does not contain' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + testUsingContext('retries if multidex support enabled', () async { + const String errorMessage = r''' +Caused by: com.android.tools.r8.utils.b: Cannot fit requested classes in a single dex file (# methods: 85091 > 65536) + at com.android.tools.r8.utils.T0.error(SourceFile:1) + at com.android.tools.r8.utils.T0.a(SourceFile:2) + at com.android.tools.r8.dex.P.a(SourceFile:740) + at com.android.tools.r8.dex.P$h.a(SourceFile:7) + at com.android.tools.r8.dex.b.a(SourceFile:14) + at com.android.tools.r8.dex.b.b(SourceFile:25) + at com.android.tools.r8.D8.d(D8.java:133) + at com.android.tools.r8.D8.b(D8.java:1) + at com.android.tools.r8.utils.Y.a(SourceFile:36) + ... 38 more + + +FAILURE: Build failed with an exception. + +* What went wrong: +Execution failed for task ':app:mergeDexDebug'. +> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade + > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: + The number of method references in a .dex file cannot exceed 64K. + Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html'''; + + final File manifest = fileSystem.currentDirectory + .childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + manifest.createSync(recursive: true); + manifest.writeAsStringSync(r''' + + + + +''', flush: true); + + expect(formatTestErrorMessage(errorMessage, multidexErrorHandler), isTrue); + expect(await multidexErrorHandler.handler(project: FlutterProject.fromDirectory(fileSystem.currentDirectory), multidexEnabled: true, line: '', usesAndroidX: true), equals(GradleBuildStatus.retry)); + + expect(testLogger.statusText, + contains( + 'Multidex support is required for your android app to build since the number of methods has exceeded 64k.' + ) + ); + expect(testLogger.statusText, + contains( + 'android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + AnsiTerminal: () => _TestPromptTerminal('y'), + }); + + testUsingContext('exits if multidex support skipped', () async { + const String errorMessage = r''' +Caused by: com.android.tools.r8.utils.b: Cannot fit requested classes in a single dex file (# methods: 85091 > 65536) + at com.android.tools.r8.utils.T0.error(SourceFile:1) + at com.android.tools.r8.utils.T0.a(SourceFile:2) + at com.android.tools.r8.dex.P.a(SourceFile:740) + at com.android.tools.r8.dex.P$h.a(SourceFile:7) + at com.android.tools.r8.dex.b.a(SourceFile:14) + at com.android.tools.r8.dex.b.b(SourceFile:25) + at com.android.tools.r8.D8.d(D8.java:133) + at com.android.tools.r8.D8.b(D8.java:1) + at com.android.tools.r8.utils.Y.a(SourceFile:36) + ... 38 more + + +FAILURE: Build failed with an exception. + +* What went wrong: +Execution failed for task ':app:mergeDexDebug'. +> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade + > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: + The number of method references in a .dex file cannot exceed 64K. + Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html'''; + + final File manifest = fileSystem.currentDirectory + .childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + manifest.createSync(recursive: true); + manifest.writeAsStringSync(r''' + + + + +''', flush: true); + + expect(formatTestErrorMessage(errorMessage, multidexErrorHandler), isTrue); + expect(await multidexErrorHandler.handler(project: FlutterProject.fromDirectory(fileSystem.currentDirectory), multidexEnabled: true, line: '', usesAndroidX: true), equals(GradleBuildStatus.exit)); + + expect(testLogger.statusText, + contains( + 'Multidex support is required for your android app to build since the number of methods has exceeded 64k.' + ) + ); + expect(testLogger.statusText, + contains( + 'Flutter tool can add multidex support. The following file will be added by flutter:' + ) + ); + expect(testLogger.statusText, + contains( + 'android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + AnsiTerminal: () => _TestPromptTerminal('n'), + }); + + testUsingContext('exits if multidex support disabled', () async { + const String errorMessage = r''' +Caused by: com.android.tools.r8.utils.b: Cannot fit requested classes in a single dex file (# methods: 85091 > 65536) + at com.android.tools.r8.utils.T0.error(SourceFile:1) + at com.android.tools.r8.utils.T0.a(SourceFile:2) + at com.android.tools.r8.dex.P.a(SourceFile:740) + at com.android.tools.r8.dex.P$h.a(SourceFile:7) + at com.android.tools.r8.dex.b.a(SourceFile:14) + at com.android.tools.r8.dex.b.b(SourceFile:25) + at com.android.tools.r8.D8.d(D8.java:133) + at com.android.tools.r8.D8.b(D8.java:1) + at com.android.tools.r8.utils.Y.a(SourceFile:36) + ... 38 more + + +FAILURE: Build failed with an exception. + +* What went wrong: +Execution failed for task ':app:mergeDexDebug'. +> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade + > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: + The number of method references in a .dex file cannot exceed 64K. + Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html'''; + + expect(formatTestErrorMessage(errorMessage, multidexErrorHandler), isTrue); + expect(await multidexErrorHandler.handler(project: FlutterProject.fromDirectory(fileSystem.currentDirectory), multidexEnabled: false, line: '', usesAndroidX: true), equals(GradleBuildStatus.exit)); + + expect(testLogger.statusText, + contains( + 'Flutter multidex handling is disabled.' + ) + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('permission errors', () { + testUsingContext('throws toolExit if gradle is missing execute permissions', () async { + const String errorMessage = ''' +Permission denied +Command: /home/android/gradlew assembleRelease +'''; + expect(formatTestErrorMessage(errorMessage, permissionDeniedErrorHandler), isTrue); + expect(await permissionDeniedErrorHandler.handler( + usesAndroidX: true, + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + ), equals(GradleBuildStatus.exit)); + + expect( + testLogger.statusText, + contains('Gradle does not have execution permission.'), + ); + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Gradle does not have execution permission. │\n' + '│ You should change the ownership of the project directory to your user, or move the project to a │\n' + '│ directory with execute permissions. │\n' + '└─────────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }); + + testUsingContext('pattern', () async { + const String errorMessage = ''' +Permission denied +Command: /home/android/gradlew assembleRelease +'''; + expect(formatTestErrorMessage(errorMessage, permissionDeniedErrorHandler), isTrue); + }); + + testUsingContext('handler', () async { + expect(await permissionDeniedErrorHandler.handler( + usesAndroidX: true, + line: '', + multidexEnabled: true, + project: FakeFlutterProject(), + ), equals(GradleBuildStatus.exit)); + + expect( + testLogger.statusText, + contains('Gradle does not have execution permission.'), + ); + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Gradle does not have execution permission. │\n' + '│ You should change the ownership of the project directory to your user, or move the project to a │\n' + '│ directory with execute permissions. │\n' + '└─────────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }); + }); + + group('license not accepted', () { + testWithoutContext('pattern', () { + expect( + licenseNotAcceptedHandler.test( + 'You have not accepted the license agreements of the following SDK components' + ), + isTrue, + ); + }); + + testUsingContext('handler', () async { + await licenseNotAcceptedHandler.handler( + line: 'You have not accepted the license agreements of the following SDK components: [foo, bar]', + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ─────────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Unable to download needed Android SDK components, as the following licenses have not been │\n' + '│ accepted: foo, bar │\n' + '│ │\n' + '│ To resolve this, please run the following command in a Terminal: │\n' + '│ flutter doctor --android-licenses │\n' + '└───────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }); + }); + + group('flavor undefined', () { + testWithoutContext('pattern', () { + expect( + flavorUndefinedHandler.test( + 'Task assembleFooRelease not found in root project.' + ), + isTrue, + ); + expect( + flavorUndefinedHandler.test( + 'Task assembleBarRelease not found in root project.' + ), + isTrue, + ); + expect( + flavorUndefinedHandler.test( + 'Task assembleBar not found in root project.' + ), + isTrue, + ); + expect( + flavorUndefinedHandler.test( + 'Task assembleBar_foo not found in root project.' + ), + isTrue, + ); + }); + + testUsingContext('handler - with flavor', () async { + processManager.addCommand(const FakeCommand( + command: [ + 'gradlew', + 'app:tasks' , + '--all', + '--console=auto', + ], + stdout: ''' +assembleRelease +assembleFlavor1 +assembleFlavor1Release +assembleFlavor_2 +assembleFlavor_2Release +assembleDebug +assembleProfile +assembles +assembleFooTest + ''', + )); + + await flavorUndefinedHandler.handler( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + 'Gradle project does not define a task suitable ' + 'for the requested build.' + ) + ); + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Gradle project does not define a task suitable for the requested build. │\n' + '│ │\n' + '│ The /android/app/build.gradle file defines product flavors: flavor1, flavor_2. You must specify │\n' + '│ a --flavor option to select one of them. │\n' + '└─────────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + Java: () => FakeJava(), + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('handler - without flavor', () async { + processManager.addCommand(const FakeCommand( + command: [ + 'gradlew', + 'app:tasks' , + '--all', + '--console=auto', + ], + stdout: ''' +assembleRelease +assembleDebug +assembleProfile + ''', + )); + + await flavorUndefinedHandler.handler( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ─────────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Gradle project does not define a task suitable for the requested build. │\n' + '│ │\n' + '│ The /android/app/build.gradle file does not define any custom product flavors. You cannot use │\n' + '│ the --flavor option. │\n' + '└───────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + Java: () => FakeJava(), + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('higher minSdkVersion', () { + const String stdoutLine = 'uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:webview_flutter] /tmp/cirrus-ci-build/all_plugins/build/webview_flutter/intermediates/library_manifest/release/AndroidManifest.xml as the library might be using APIs not available in 16'; + + testWithoutContext('pattern', () { + expect( + minSdkVersionHandler.test(stdoutLine), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await minSdkVersionHandler.handler( + line: stdoutLine, + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ─────────────────────────────────────────────────────────────────────────────────┐\n' + '│ The plugin webview_flutter requires a higher Android SDK version. │\n' + '│ Fix this issue by adding the following to the file /android/app/build.gradle: │\n' + '│ android { │\n' + '│ defaultConfig { │\n' + '│ minSdkVersion 19 │\n' + '│ } │\n' + '│ } │\n' + '│ │\n' + '│ Following this change, your app will not be available to users running Android SDKs below 19. │\n' + '│ Consider searching for a version of this plugin that supports these lower versions of the │\n' + '│ Android SDK instead. │\n' + '│ For more information, see: │\n' + '│ https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration │\n' + '└───────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + // https://issuetracker.google.com/issues/141126614 + group('transform input issue', () { + testWithoutContext('pattern', () { + expect( + transformInputIssueHandler.test( + 'https://issuetracker.google.com/issues/158753935' + ), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await transformInputIssueHandler.handler( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ─────────────────────────────────────────────────────────────────┐\n' + '│ This issue appears to be https://github.com/flutter/flutter/issues/58247. │\n' + '│ Fix this issue by adding the following to the file /android/app/build.gradle: │\n' + '│ android { │\n' + '│ lintOptions { │\n' + '│ checkReleaseBuilds false │\n' + '│ } │\n' + '│ } │\n' + '└───────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Dependency mismatch', () { + testWithoutContext('pattern', () { + expect( + lockFileDepMissingHandler.test(''' +* What went wrong: +Execution failed for task ':app:generateDebugFeatureTransitiveDeps'. +> Could not resolve all artifacts for configuration ':app:debugRuntimeClasspath'. + > Resolved 'androidx.lifecycle:lifecycle-common:2.2.0' which is not part of the dependency lock state + > Resolved 'androidx.customview:customview:1.0.0' which is not part of the dependency lock state''' + ), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await lockFileDepMissingHandler.handler( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ────────────────────────────────────────────────────────────────────────────┐\n' + '│ You need to update the lockfile, or disable Gradle dependency locking. │\n' + '│ To regenerate the lockfiles run: `./gradlew :generateLockfiles` in /android/build.gradle │\n' + '│ To remove dependency locking, remove the `dependencyLocking` from /android/build.gradle │\n' + '└──────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Incompatible Kotlin version', () { + testWithoutContext('pattern', () { + expect( + incompatibleKotlinVersionHandler.test('Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.'), + isTrue, + ); + expect( + incompatibleKotlinVersionHandler.test("class 'kotlin.Unit' was compiled with an incompatible version of Kotlin."), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await incompatibleKotlinVersionHandler.handler( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ──────────────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Your project requires a newer version of the Kotlin Gradle plugin. │\n' + '│ Find the latest version on https://kotlinlang.org/docs/releases.html#release-details, then │\n' + '│ update /android/build.gradle: │\n' + "│ ext.kotlin_version = '' │\n" + '└────────────────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Bump Gradle', () { + const String errorMessage = ''' +A problem occurred evaluating project ':app'. +> Failed to apply plugin [id 'kotlin-android'] + > The current Gradle version 4.10.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 6.1.1 or newer, or the previous version of the Kotlin plugin. +'''; + + testWithoutContext('pattern', () { + expect( + outdatedGradleHandler.test(errorMessage), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await outdatedGradleHandler.handler( + line: errorMessage, + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ────────────────────────────────────────────────────────────────────┐\n' + '│ [!] Your project needs to upgrade Gradle and the Android Gradle plugin. │\n' + '│ │\n' + '│ To fix this issue, replace the following content: │\n' + '│ /android/build.gradle: │\n' + "│ - classpath 'com.android.tools.build:gradle:' │\n" + "│ + classpath 'com.android.tools.build:gradle:7.3.0' │\n" + '│ /android/gradle/wrapper/gradle-wrapper.properties: │\n' + '│ - https://services.gradle.org/distributions/gradle--all.zip │\n' + '│ + https://services.gradle.org/distributions/gradle-7.6.3-all.zip │\n' + '└──────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Required compileSdkVersion', () { + const String errorMessage = ''' +Execution failed for task ':app:checkDebugAarMetadata'. +> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction + > One or more issues found when checking AAR metadata values: + + The minCompileSdk (31) specified in a + dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) + is greater than this module's compileSdkVersion (android-30). + Dependency: androidx.window:window-java:1.0.0-beta04. + AAR metadata file: ~/.gradle/caches/transforms-3/2adc32c5b3f24bed763d33fbfb203338/transformed/jetified-window-java-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties. + + The minCompileSdk (31) specified in a + dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) + is greater than this module's compileSdkVersion (android-30). + Dependency: androidx.window:window:1.0.0-beta04. + AAR metadata file: ~/.gradle/caches/transforms-3/88f7e476ef68cecca729426edff955b5/transformed/jetified-window-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties. +'''; + + testWithoutContext('pattern', () { + expect( + minCompileSdkVersionHandler.test(errorMessage), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await minCompileSdkVersionHandler.handler( + line: errorMessage, + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ──────────────────────────────────────────────────────────────────┐\n' + '│ [!] Your project requires a higher compileSdk version. │\n' + '│ Fix this issue by bumping the compileSdk version in /android/app/build.gradle: │\n' + '│ android { │\n' + '│ compileSdk 31 │\n' + '│ } │\n' + '└────────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Java 11 requirement', () { + testWithoutContext('pattern', () { + expect( + jvm11RequiredHandler.test(''' +* What went wrong: +A problem occurred evaluating project ':flutter'. +> Failed to apply plugin 'com.android.internal.library'. + > Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8. + You can try some of the following options: + - changing the IDE settings. + - changing the JAVA_HOME environment variable. + - changing `org.gradle.java.home` in `gradle.properties`.''' + ), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await jvm11RequiredHandler.handler( + project: FakeFlutterProject(), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect( + testLogger.statusText, + contains( + '\n' + '┌─ Flutter Fix ─────────────────────────────────────────────────────────────────┐\n' + '│ [!] You need Java 11 or higher to build your app with this version of Gradle. │\n' + '│ │\n' + '│ To get Java 11, update to the latest version of Android Studio on │\n' + '│ https://developer.android.com/studio/install. │\n' + '│ │\n' + '│ To check the Java version used by Flutter, run `flutter doctor -v`. │\n' + '└───────────────────────────────────────────────────────────────────────────────┘\n' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('SSLException', () { + testWithoutContext('pattern', () { + expect( + sslExceptionHandler.test(r''' +Exception in thread "main" javax.net.ssl.SSLException: Tag mismatch! +at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:129) +at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321) +at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264) +at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:259) +at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:129) +at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1155) +at java.base/sun.security.ssl.SSLSocketImpl.readApplicationRecord(SSLSocketImpl.java:1125) +at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:823) +at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:290) +at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:351) +at java.base/sun.net.www.MeteredStream.read(MeteredStream.java:134) +at java.base/java.io.FilterInputStream.read(FilterInputStream.java:133) +at java.base/sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3444) +at java.base/sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3437) +at org.gradle.wrapper.Download.downloadInternal(Download.java:62) +at org.gradle.wrapper.Download.download(Download.java:44) +at org.gradle.wrapper.Install$1.call(Install.java:61) +at org.gradle.wrapper.Install$1.call(Install.java:48) +at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) +at org.gradle.wrapper.Install.createDist(Install.java:48) +at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) +at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''' + ), + isTrue, + ); + + expect( + sslExceptionHandler.test(r''' +Caused by: javax.crypto.AEADBadTagException: Tag mismatch! +at java.base/com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:580) +at java.base/com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1049) +at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:985) +at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:491) +at java.base/javax.crypto.CipherSpi.bufferCrypt(CipherSpi.java:779) +at java.base/javax.crypto.CipherSpi.engineDoFinal(CipherSpi.java:730) +at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2497) +at java.base/sun.security.ssl.SSLCipher$T12GcmReadCipherGenerator$GcmReadCipher.decrypt(SSLCipher.java:1613) +at java.base/sun.security.ssl.SSLSocketInputRecord.decodeInputRecord(SSLSocketInputRecord.java:262) +at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:190) +at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:108)''' + ), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + final GradleBuildStatus status = await sslExceptionHandler.handler( + project: FakeFlutterProject(), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect(status, GradleBuildStatus.retry); + expect(testLogger.errorText, + contains( + 'Gradle threw an error while downloading artifacts from the network.' + ) + ); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + group('Zip exception', () { + testWithoutContext('pattern', () { + expect( + zipExceptionHandler.test(r''' +Exception in thread "main" java.util.zip.ZipException: error in opening zip file +at java.util.zip.ZipFile.open(Native Method) +at java.util.zip.ZipFile.(ZipFile.java:225) +at java.util.zip.ZipFile.(ZipFile.java:155) +at java.util.zip.ZipFile.(ZipFile.java:169) +at org.gradle.wrapper.Install.unzip(Install.java:214) +at org.gradle.wrapper.Install.access$600(Install.java:27) +at org.gradle.wrapper.Install$1.call(Install.java:74) +at org.gradle.wrapper.Install$1.call(Install.java:48) +at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) +at org.gradle.wrapper.Install.createDist(Install.java:48) +at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) +at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''' + ), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + fileSystem.file('foo/.gradle/fizz.zip').createSync(recursive: true); + + final GradleBuildStatus result = await zipExceptionHandler.handler( + project: FakeFlutterProject(), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect(result, equals(GradleBuildStatus.retry)); + expect(fileSystem.file('foo/.gradle/fizz.zip'), exists); + expect( + testLogger.errorText, + contains( + '[!] Your .gradle directory under the home directory might be corrupted.\n' + ) + ); + expect(testLogger.statusText, ''); + }, overrides: { + Platform: () => FakePlatform(environment: {'HOME': 'foo/'}), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + BotDetector: () => const FakeBotDetector(false), + }); + + testUsingContext('suggestion if running as bot', () async { + fileSystem.file('foo/.gradle/fizz.zip').createSync(recursive: true); + + final GradleBuildStatus result = await zipExceptionHandler.handler( + project: FakeFlutterProject(), + usesAndroidX: true, + line: '', + multidexEnabled: true, + ); + + expect(result, equals(GradleBuildStatus.retry)); + expect(fileSystem.file('foo/.gradle/fizz.zip'), isNot(exists)); + + expect( + testLogger.errorText, + contains( + '[!] Your .gradle directory under the home directory might be corrupted.\n' + ) + ); + expect( + testLogger.statusText, + contains('Deleting foo/.gradle\n'), + ); + }, overrides: { + Platform: () => FakePlatform(environment: {'HOME': 'foo/'}), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + BotDetector: () => const FakeBotDetector(true), + }); + + testUsingContext('suggestion if stdin has terminal and user entered y', () async { + fileSystem.file('foo/.gradle/fizz.zip').createSync(recursive: true); + + final GradleBuildStatus result = await zipExceptionHandler.handler( + line: '', + usesAndroidX: true, + multidexEnabled: true, + project: FakeFlutterProject(), + ); + + expect(result, equals(GradleBuildStatus.retry)); + expect(fileSystem.file('foo/.gradle/fizz.zip'), isNot(exists)); + expect( + testLogger.errorText, + contains( + '[!] Your .gradle directory under the home directory might be corrupted.\n' + ) + ); + expect( + testLogger.statusText, + contains('Deleting foo/.gradle\n'), + ); + }, overrides: { + Platform: () => FakePlatform(environment: {'HOME': 'foo/'}), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + AnsiTerminal: () => _TestPromptTerminal('y'), + BotDetector: () => const FakeBotDetector(false), + }); + + testUsingContext('suggestion if stdin has terminal and user entered n', () async { + fileSystem.file('foo/.gradle/fizz.zip').createSync(recursive: true); + + final GradleBuildStatus result = await zipExceptionHandler.handler( + line: '', + usesAndroidX: true, + multidexEnabled: true, + project: FakeFlutterProject(), + ); + + expect(result, equals(GradleBuildStatus.retry)); + expect(fileSystem.file('foo/.gradle/fizz.zip'), exists); + expect( + testLogger.errorText, + contains( + '[!] Your .gradle directory under the home directory might be corrupted.\n' + ) + ); + expect(testLogger.statusText, ''); + }, overrides: { + Platform: () => FakePlatform(environment: {'HOME': 'foo/'}), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + AnsiTerminal: () => _TestPromptTerminal('n'), + BotDetector: () => const FakeBotDetector(false), + }); + }); + + group('incompatible java and gradle versions error', () { + const String errorMessage = ''' +Could not compile build file '…/example/android/build.gradle'. +> startup failed: + General error during conversion: Unsupported class file major version 61 + java.lang.IllegalArgumentException: Unsupported class file major version 61 +'''; + + testWithoutContext('pattern', () { + expect( + incompatibleJavaAndGradleVersionsHandler.test(errorMessage), + isTrue, + ); + }); + + testUsingContext('suggestion', () async { + await incompatibleJavaAndGradleVersionsHandler.handler( + line: errorMessage, + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + + // Ensure the error notes the incompatible Gradle/AGP/Java versions, links to related resources, + // and a portion of the path to where to change their gradle version. + expect(testLogger.statusText, contains('Gradle version is incompatible with the Java version')); + expect(testLogger.statusText, contains('docs.flutter.dev/go/android-java-gradle-error')); + expect(testLogger.statusText, contains('gradle-wrapper.properties')); + expect(testLogger.statusText, contains('https://docs.gradle.org/current/userguide/compatibility.html#java')); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + }); + + testUsingContext('couldNotOpenCacheDirectoryHandler', () async { + final GradleBuildStatus status = await couldNotOpenCacheDirectoryHandler.handler( + line: ''' +FAILURE: Build failed with an exception. + +* Where: +Script '/Volumes/Work/s/w/ir/x/w/flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy' line: 276 + +* What went wrong: +A problem occurred evaluating script. +> Failed to apply plugin class 'FlutterPlugin'. + > Could not open cache directory 41rl0ui7kgmsyfwn97o2jypl6 (/Volumes/Work/s/w/ir/cache/gradle/caches/6.7/gradle-kotlin-dsl/41rl0ui7kgmsyfwn97o2jypl6). + > Failed to create Jar file /Volumes/Work/s/w/ir/cache/gradle/caches/6.7/generated-gradle-jars/gradle-api-6.7.jar.''', + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + usesAndroidX: true, + multidexEnabled: true, + ); + expect(testLogger.errorText, contains('Gradle threw an error while resolving dependencies')); + expect(status, GradleBuildStatus.retry); + }, overrides: { + GradleUtils: () => FakeGradleUtils(), + Platform: () => fakePlatform('android'), + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); +} + +bool formatTestErrorMessage(String errorMessage, GradleHandledError error) { + return errorMessage + .split('\n') + .any((String line) => error.test(line)); +} + +Platform fakePlatform(String name) { + return FakePlatform( + environment: { + 'HOME': '/', + }, + operatingSystem: name, + ); +} + +class FakeGradleUtils extends Fake implements GradleUtils { + @override + String getExecutable(FlutterProject project) { + return 'gradlew'; + } +} + +/// Simple terminal that returns the specified string when +/// promptForCharInput is called. +class _TestPromptTerminal extends Fake implements AnsiTerminal { + _TestPromptTerminal(this.promptResult); + + final String promptResult; + + @override + bool get stdinHasTerminal => true; + + @override + Future promptForCharInput( + List acceptedCharacters, { + required Logger logger, + String? prompt, + int? defaultChoiceIndex, + bool displayAcceptedCharacters = true, + }) { + return Future.value(promptResult); + } +} + +class FakeFlutterProject extends Fake implements FlutterProject {} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4c1f80af0cdd548b40aaca68f0b6d9bdfdc9d1bc --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart @@ -0,0 +1,466 @@ +// 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/gradle.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/reporting/reporting.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import '../../src/common.dart'; +import '../../src/fakes.dart'; + +void main() { + late FileSystem fileSystem; + late FakeAnalytics fakeAnalytics; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + fakeAnalytics = getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ); + }); + + testWithoutContext('Finds app bundle when flavor contains multiple dimensions in release mode', () { + final FlutterProject project = generateFakeAppBundle('fooBarRelease', 'app-foo-bar-release.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'fooBar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooBarRelease/app-foo-bar-release.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores in release mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in release mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores in release mode", () { + final FlutterProject project = generateFakeAppBundle('fooRelease', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'foo', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooRelease/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in release mode", () { + final FlutterProject project = generateFakeAppBundle('fooaRelease', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'fooA', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooaRelease/app.aab'); + }); + + testWithoutContext('Finds app bundle when no flavor is used in release mode', () { + final FlutterProject project = generateFakeAppBundle('release', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, null, treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/release/app.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains multiple dimensions in debug mode', () { + final FlutterProject project = generateFakeAppBundle('fooBarDebug', 'app-foo-bar-debug.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'fooBar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooBarDebug/app-foo-bar-debug.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores in debug mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in debug mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores in debug mode", () { + final FlutterProject project = generateFakeAppBundle('fooDebug', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'foo', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooDebug/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in debug mode", () { + final FlutterProject project = generateFakeAppBundle('fooaDebug', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'fooA', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooaDebug/app.aab'); + }); + + testWithoutContext('Finds app bundle when no flavor is used in debug mode', () { + final FlutterProject project = generateFakeAppBundle('debug', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + BuildInfo.debug, + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/debug/app.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains multiple dimensions in profile mode', () { + final FlutterProject project = generateFakeAppBundle('fooBarProfile', 'app-foo-bar-profile.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'fooBar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooBarProfile/app-foo-bar-profile.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores in profile mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in profile mode', () { + final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores in profile mode", () { + final FlutterProject project = generateFakeAppBundle('fooProfile', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'foo', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooProfile/app.aab'); + }); + + testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in profile mode", () { + final FlutterProject project = generateFakeAppBundle('fooaProfile', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'fooA', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/fooaProfile/app.aab'); + }); + + testWithoutContext('Finds app bundle when no flavor is used in profile mode', () { + final FlutterProject project = generateFakeAppBundle('profile', 'app.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, null, treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/profile/app.aab'); + }); + + testWithoutContext('Finds app bundle in release mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('release', 'app-release.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, null, treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/release/app-release.aab'); + }); + + testWithoutContext('Finds app bundle in profile mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('profile', 'app-profile.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, null, treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/profile/app-profile.aab'); + }); + + testWithoutContext('Finds app bundle in debug mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('debug', 'app-debug.aab', fileSystem); + final File bundle = findBundleFile( + project, + BuildInfo.debug, + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/debug/app-debug.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores in release mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app-foo_bar-release.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app-foo_bar-release.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in release mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app-foo_bar-release.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app-foo_bar-release.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores in profile mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app-foo_bar-profile.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app-foo_bar-profile.aab'); + }); + + testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in debug mode - Gradle 3.5', () { + final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app-foo_bar-debug.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app-foo_bar-debug.aab'); + }); + + testWithoutContext( + 'Finds app bundle when flavor contains underscores and uppercase letters in release mode - Gradle 4.1', () { + final FlutterProject project = generateFakeAppBundle('foo_BarRelease', 'app-foo_Bar-release.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.release, 'Foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_BarRelease/app-foo_Bar-release.aab'); + }); + + testWithoutContext( + 'Finds app bundle when flavor contains underscores and uppercase letters in debug mode - Gradle 4.1', () { + final FlutterProject project = generateFakeAppBundle('foo_BarDebug', 'app-foo_Bar-debug.aab', fileSystem); + final File bundle = findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'Foo_Bar', treeShakeIcons: false), + BufferLogger.test(), + TestUsage(), + fakeAnalytics, + ); + + expect(bundle, isNotNull); + expect(bundle.path, '/build/app/outputs/bundle/foo_BarDebug/app-foo_Bar-debug.aab'); + }); + + testWithoutContext('AAB not found', () { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final TestUsage testUsage = TestUsage(); + expect( + () { + findBundleFile( + project, + const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false), + BufferLogger.test(), + testUsage, + fakeAnalytics, + ); + }, + throwsToolExit( + message: + "Gradle build failed to produce an .aab file. It's likely that this file " + "was generated under ${project.android.buildDirectory.path}, but the tool couldn't find it." + ) + ); + expect(testUsage.events, contains( + TestUsageEvent( + 'build', + 'gradle', + label: 'gradle-expected-file-not-found', + parameters: CustomDimensions.fromMap( { + 'cd37': 'androidGradlePluginVersion: 7.6.3, fileExtension: .aab', + }), + ), + )); + expect(fakeAnalytics.sentEvents, hasLength(1)); + expect( + fakeAnalytics.sentEvents, + contains( + Event.flutterBuildInfo( + label: 'gradle-expected-file-not-found', + buildType: 'gradle', + settings: 'androidGradlePluginVersion: 7.6.3, fileExtension: .aab', + ), + ), + ); + }); +} + +/// Generates a fake app bundle at the location [directoryName]/[fileName]. +FlutterProject generateFakeAppBundle(String directoryName, String fileName, FileSystem fileSystem) { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + final Directory bundleDirectory = getBundleDirectory(project); + bundleDirectory + .childDirectory(directoryName) + .createSync(recursive: true); + + bundleDirectory + .childDirectory(directoryName) + .childFile(fileName) + .createSync(); + return project; +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a6a19a48945021ec8096d1305a6d7417b8248f07 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_test.dart @@ -0,0 +1,719 @@ +// 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/android/gradle.dart'; +import 'package:flutter_tools/src/android/gradle_utils.dart' as gradle_utils; +import 'package:flutter_tools/src/artifacts.dart'; +import 'package:flutter_tools/src/base/common.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/cache.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/project.dart'; + +import '../../src/common.dart'; +import '../../src/context.dart'; + +const String kModulePubspec = ''' +name: test +flutter: + module: + androidPackage: com.example + androidX: true +'''; + +void main() { + Cache.flutterRoot = getFlutterRoot(); + + group('build artifacts', () { + late FileSystem fileSystem; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + }); + + testWithoutContext('getApkDirectory in app projects', () { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + expect( + getApkDirectory(project).path, '/build/app/outputs/flutter-apk', + ); + }); + + testWithoutContext('getApkDirectory in module projects', () { + fileSystem.currentDirectory + .childFile('pubspec.yaml') + .writeAsStringSync(kModulePubspec); + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + expect(project.isModule, true); + expect( + getApkDirectory(project).path, '/build/host/outputs/apk', + ); + }); + + testWithoutContext('getBundleDirectory in app projects', () { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + expect( + getBundleDirectory(project).path, '/build/app/outputs/bundle', + ); + }); + + testWithoutContext('getBundleDirectory in module projects', () { + fileSystem.currentDirectory + .childFile('pubspec.yaml') + .writeAsStringSync(kModulePubspec); + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + expect(project.isModule, true); + expect( + getBundleDirectory(project).path, '/build/host/outputs/bundle', + ); + }); + + testWithoutContext('getRepoDirectory', () { + expect( + getRepoDirectory(fileSystem.directory('foo')).path, + equals(fileSystem.path.join('foo','outputs', 'repo')), + ); + }); + }); + + group('gradle tasks', () { + testWithoutContext('assemble release', () { + expect( + getAssembleTaskFor(const BuildInfo(BuildMode.release, null, treeShakeIcons: false)), + equals('assembleRelease'), + ); + expect( + getAssembleTaskFor(const BuildInfo(BuildMode.release, 'flavorFoo', treeShakeIcons: false)), + equals('assembleFlavorFooRelease'), + ); + }); + + testWithoutContext('assemble debug', () { + expect( + getAssembleTaskFor(BuildInfo.debug), + equals('assembleDebug'), + ); + expect( + getAssembleTaskFor(const BuildInfo(BuildMode.debug, 'flavorFoo', treeShakeIcons: false)), + equals('assembleFlavorFooDebug'), + ); + }); + + testWithoutContext('assemble profile', () { + expect( + getAssembleTaskFor(const BuildInfo(BuildMode.profile, null, treeShakeIcons: false)), + equals('assembleProfile'), + ); + expect( + getAssembleTaskFor(const BuildInfo(BuildMode.profile, 'flavorFoo', treeShakeIcons: false)), + equals('assembleFlavorFooProfile'), + ); + }); + }); + + group('listApkPaths', () { + testWithoutContext('Finds APK without flavor in debug', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.debug, '', treeShakeIcons: false)), + ); + expect(apks, ['app-debug.apk']); + }); + + testWithoutContext('Finds APK with flavor in debug', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.debug, 'flavor1', treeShakeIcons: false)), + ); + expect(apks, ['app-flavor1-debug.apk']); + }); + + testWithoutContext('Finds APK without flavor in release', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, '', treeShakeIcons: false)), + ); + + expect(apks, ['app-release.apk']); + }); + + testWithoutContext('Finds APK with flavor in release mode', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false)), + ); + + expect(apks, ['app-flavor1-release.apk']); + }); + + testWithoutContext('Finds APK with flavor in release mode', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavorA', treeShakeIcons: false)), + ); + + expect(apks, ['app-flavora-release.apk']); + }); + + testWithoutContext('Finds APK with flavor in release mode - AGP v3', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false)), + ); + + expect(apks, ['app-flavor1-release.apk']); + }); + + testWithoutContext('Finds APK with split-per-abi', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false), splitPerAbi: true), + ); + + expect(apks, unorderedEquals([ + 'app-armeabi-v7a-flavor1-release.apk', + 'app-arm64-v8a-flavor1-release.apk', + 'app-x86_64-flavor1-release.apk', + ])); + }); + + testWithoutContext('Finds APK with split-per-abi when flavor contains uppercase letters', () { + final Iterable apks = listApkPaths( + const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavorA', treeShakeIcons: false), splitPerAbi: true), + ); + + expect(apks, unorderedEquals([ + 'app-armeabi-v7a-flavora-release.apk', + 'app-arm64-v8a-flavora-release.apk', + 'app-x86_64-flavora-release.apk', + ])); + }); + + }); + + group('gradle build', () { + testUsingContext('do not crash if there is no Android SDK', () async { + expect(() { + gradle_utils.updateLocalProperties(project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory)); + }, throwsToolExit( + message: '${globals.logger.terminal.warningMark} No Android SDK found. Try setting the ANDROID_HOME environment variable.', + )); + }, overrides: { + AndroidSdk: () => null, + }); + }); + + group('Gradle local.properties', () { + late Artifacts localEngineArtifacts; + late FileSystem fs; + + setUp(() { + fs = MemoryFileSystem.test(); + localEngineArtifacts = Artifacts.testLocalEngine(localEngine: 'out/android_arm', localEngineHost: 'out/host_release'); + }); + + void testUsingAndroidContext(String description, dynamic Function() testMethod) { + testUsingContext(description, testMethod, overrides: { + Artifacts: () => localEngineArtifacts, + Platform: () => FakePlatform(), + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + } + + String? propertyFor(String key, File file) { + final Iterable result = file.readAsLinesSync() + .where((String line) => line.startsWith('$key=')) + .map((String line) => line.split('=')[1]); + return result.isEmpty ? null : result.first; + } + + Future checkBuildVersion({ + required String manifest, + BuildInfo? buildInfo, + String? expectedBuildName, + String? expectedBuildNumber, + }) async { + final File manifestFile = globals.fs.file('path/to/project/pubspec.yaml'); + manifestFile.createSync(recursive: true); + manifestFile.writeAsStringSync(manifest); + + + gradle_utils.updateLocalProperties( + project: FlutterProject.fromDirectoryTest(globals.fs.directory('path/to/project')), + buildInfo: buildInfo, + requireAndroidSdk: false, + ); + + final File localPropertiesFile = globals.fs.file('path/to/project/android/local.properties'); + expect(propertyFor('flutter.versionName', localPropertiesFile), expectedBuildName); + expect(propertyFor('flutter.versionCode', localPropertiesFile), expectedBuildNumber); + } + + testUsingAndroidContext('extract build name and number from pubspec.yaml', () async { + const String manifest = ''' +name: test +version: 1.0.0+1 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.0', + expectedBuildNumber: '1', + ); + }); + + testUsingAndroidContext('extract build name from pubspec.yaml', () async { + const String manifest = ''' +name: test +version: 1.0.0 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.0', + ); + }); + + testUsingAndroidContext('allow build info to override build name', () async { + const String manifest = ''' +name: test +version: 1.0.0+1 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.2', + expectedBuildNumber: '1', + ); + }); + + testUsingAndroidContext('allow build info to override build number', () async { + const String manifest = ''' +name: test +version: 1.0.0+1 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildNumber: '3', treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.0', + expectedBuildNumber: '3', + ); + }); + + testUsingAndroidContext('allow build info to override build name and number', () async { + const String manifest = ''' +name: test +version: 1.0.0+1 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.2', + expectedBuildNumber: '3', + ); + }); + + testUsingAndroidContext('allow build info to override build name and set number', () async { + const String manifest = ''' +name: test +version: 1.0.0 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.2', + expectedBuildNumber: '3', + ); + }); + + testUsingAndroidContext('allow build info to set build name and number', () async { + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false); + await checkBuildVersion( + manifest: manifest, + buildInfo: buildInfo, + expectedBuildName: '1.0.2', + expectedBuildNumber: '3', + ); + }); + + testUsingAndroidContext('allow build info to unset build name and number', () async { + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + await checkBuildVersion( + manifest: manifest, + buildInfo: const BuildInfo(BuildMode.release, null, treeShakeIcons: false), + ); + await checkBuildVersion( + manifest: manifest, + buildInfo: const BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false), + expectedBuildName: '1.0.2', + expectedBuildNumber: '3', + ); + await checkBuildVersion( + manifest: manifest, + buildInfo: const BuildInfo(BuildMode.release, null, buildName: '1.0.3', buildNumber: '4', treeShakeIcons: false), + expectedBuildName: '1.0.3', + expectedBuildNumber: '4', + ); + // Values don't get unset. + await checkBuildVersion( + manifest: manifest, + expectedBuildName: '1.0.3', + expectedBuildNumber: '4', + ); + // Values get unset. + await checkBuildVersion( + manifest: manifest, + buildInfo: const BuildInfo(BuildMode.release, null, treeShakeIcons: false), + ); + }); + }); + + group('gradgradle_utils.le version', () { + testWithoutContext('should be compatible with the Android plugin version', () { + // Grangradle_utils.ular versions. + expect(gradle_utils.getGradleVersionFor('1.0.0'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.0.1'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.0.2'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.0.4'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.0.8'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.1.0'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.1.2'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.1.2'), '2.3'); + expect(gradle_utils.getGradleVersionFor('1.1.3'), '2.3'); + // Versgradle_utils.ion Ranges. + expect(gradle_utils.getGradleVersionFor('1.2.0'), '2.9'); + expect(gradle_utils.getGradleVersionFor('1.3.1'), '2.9'); + + expect(gradle_utils.getGradleVersionFor('1.5.0'), '2.2.1'); + + expect(gradle_utils.getGradleVersionFor('2.0.0'), '2.13'); + expect(gradle_utils.getGradleVersionFor('2.1.2'), '2.13'); + + expect(gradle_utils.getGradleVersionFor('2.1.3'), '2.14.1'); + expect(gradle_utils.getGradleVersionFor('2.2.3'), '2.14.1'); + + expect(gradle_utils.getGradleVersionFor('2.3.0'), '3.3'); + + expect(gradle_utils.getGradleVersionFor('3.0.0'), '4.1'); + + expect(gradle_utils.getGradleVersionFor('3.1.0'), '4.4'); + + expect(gradle_utils.getGradleVersionFor('3.2.0'), '4.6'); + expect(gradle_utils.getGradleVersionFor('3.2.1'), '4.6'); + + expect(gradle_utils.getGradleVersionFor('3.3.0'), '4.10.2'); + expect(gradle_utils.getGradleVersionFor('3.3.2'), '4.10.2'); + + expect(gradle_utils.getGradleVersionFor('3.4.0'), '5.6.2'); + expect(gradle_utils.getGradleVersionFor('3.5.0'), '5.6.2'); + + expect(gradle_utils.getGradleVersionFor('4.0.0'), '6.7'); + expect(gradle_utils.getGradleVersionFor('4.1.0'), '6.7'); + + expect(gradle_utils.getGradleVersionFor('7.0'), '7.5'); + expect(gradle_utils.getGradleVersionFor('7.1.2'), '7.5'); + expect(gradle_utils.getGradleVersionFor('7.2'), '7.5'); + expect(gradle_utils.getGradleVersionFor('8.0'), '8.0'); + expect(gradle_utils.getGradleVersionFor(gradle_utils.maxKnownAgpVersion), '8.0'); + }); + + testWithoutContext('throws on unsupported versions', () { + expect(() => gradle_utils.getGradleVersionFor('3.6.0'), + throwsA(predicate((Exception e) => e is ToolExit))); + }); + }); + + group('isAppUsingAndroidX', () { + late FileSystem fs; + + setUp(() { + fs = MemoryFileSystem.test(); + }); + + testUsingContext('returns true when the project is using AndroidX', () async { + final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.'); + + androidDirectory + .childFile('gradle.properties') + .writeAsStringSync('android.useAndroidX=true'); + + expect(isAppUsingAndroidX(androidDirectory), isTrue); + + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('returns false when the project is not using AndroidX', () async { + final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.'); + + androidDirectory + .childFile('gradle.properties') + .writeAsStringSync('android.useAndroidX=false'); + + expect(isAppUsingAndroidX(androidDirectory), isFalse); + + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('returns false when gradle.properties does not exist', () async { + final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.'); + + expect(isAppUsingAndroidX(androidDirectory), isFalse); + + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + }); + + group('printHowToConsumeAar', () { + late BufferLogger logger; + late FileSystem fileSystem; + + setUp(() { + logger = BufferLogger.test(); + fileSystem = MemoryFileSystem.test(); + }); + + testWithoutContext('stdout contains release, debug and profile', () async { + printHowToConsumeAar( + buildModes: const {'release', 'debug', 'profile'}, + androidPackage: 'com.mycompany', + repoDirectory: fileSystem.directory('build/'), + buildNumber: '2.2', + logger: logger, + fileSystem: fileSystem, + ); + + expect( + logger.statusText, + contains( + '\n' + 'Consuming the Module\n' + ' 1. Open /app/build.gradle\n' + ' 2. Ensure you have the repositories configured, otherwise add them:\n' + '\n' + ' String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n' + ' repositories {\n' + ' maven {\n' + " url 'build/'\n" + ' }\n' + ' maven {\n' + ' url "\$storageUrl/download.flutter.io"\n' + ' }\n' + ' }\n' + '\n' + ' 3. Make the host app depend on the Flutter module:\n' + '\n' + ' dependencies {\n' + " releaseImplementation 'com.mycompany:flutter_release:2.2'\n" + " debugImplementation 'com.mycompany:flutter_debug:2.2'\n" + " profileImplementation 'com.mycompany:flutter_profile:2.2'\n" + ' }\n' + '\n' + '\n' + ' 4. Add the `profile` build type:\n' + '\n' + ' android {\n' + ' buildTypes {\n' + ' profile {\n' + ' initWith debug\n' + ' }\n' + ' }\n' + ' }\n' + '\n' + 'To learn more, visit https://flutter.dev/go/build-aar\n' + ) + ); + }); + + testWithoutContext('stdout contains release', () async { + printHowToConsumeAar( + buildModes: const {'release'}, + androidPackage: 'com.mycompany', + repoDirectory: fileSystem.directory('build/'), + logger: logger, + fileSystem: fileSystem, + ); + + expect( + logger.statusText, + contains( + '\n' + 'Consuming the Module\n' + ' 1. Open /app/build.gradle\n' + ' 2. Ensure you have the repositories configured, otherwise add them:\n' + '\n' + ' String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n' + ' repositories {\n' + ' maven {\n' + " url 'build/'\n" + ' }\n' + ' maven {\n' + ' url "\$storageUrl/download.flutter.io"\n' + ' }\n' + ' }\n' + '\n' + ' 3. Make the host app depend on the Flutter module:\n' + '\n' + ' dependencies {\n' + " releaseImplementation 'com.mycompany:flutter_release:1.0'\n" + ' }\n' + '\n' + 'To learn more, visit https://flutter.dev/go/build-aar\n' + ) + ); + }); + + testWithoutContext('stdout contains debug', () async { + printHowToConsumeAar( + buildModes: const {'debug'}, + androidPackage: 'com.mycompany', + repoDirectory: fileSystem.directory('build/'), + logger: logger, + fileSystem: fileSystem, + ); + + expect( + logger.statusText, + contains( + '\n' + 'Consuming the Module\n' + ' 1. Open /app/build.gradle\n' + ' 2. Ensure you have the repositories configured, otherwise add them:\n' + '\n' + ' String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n' + ' repositories {\n' + ' maven {\n' + " url 'build/'\n" + ' }\n' + ' maven {\n' + ' url "\$storageUrl/download.flutter.io"\n' + ' }\n' + ' }\n' + '\n' + ' 3. Make the host app depend on the Flutter module:\n' + '\n' + ' dependencies {\n' + " debugImplementation 'com.mycompany:flutter_debug:1.0'\n" + ' }\n' + '\n' + 'To learn more, visit https://flutter.dev/go/build-aar\n' + ) + ); + }); + + testWithoutContext('stdout contains profile', () async { + printHowToConsumeAar( + buildModes: const {'profile'}, + androidPackage: 'com.mycompany', + repoDirectory: fileSystem.directory('build/'), + buildNumber: '1.0', + logger: logger, + fileSystem: fileSystem, + ); + + expect( + logger.statusText, + contains( + '\n' + 'Consuming the Module\n' + ' 1. Open /app/build.gradle\n' + ' 2. Ensure you have the repositories configured, otherwise add them:\n' + '\n' + ' String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n' + ' repositories {\n' + ' maven {\n' + " url 'build/'\n" + ' }\n' + ' maven {\n' + ' url "\$storageUrl/download.flutter.io"\n' + ' }\n' + ' }\n' + '\n' + ' 3. Make the host app depend on the Flutter module:\n' + '\n' + ' dependencies {\n' + " profileImplementation 'com.mycompany:flutter_profile:1.0'\n" + ' }\n' + '\n' + '\n' + ' 4. Add the `profile` build type:\n' + '\n' + ' android {\n' + ' buildTypes {\n' + ' profile {\n' + ' initWith debug\n' + ' }\n' + ' }\n' + ' }\n' + '\n' + 'To learn more, visit https://flutter.dev/go/build-aar\n' + ) + ); + }); + }); + + test('Current settings.gradle is in our legacy settings.gradle file set', () { + // If this test fails, you probably edited templates/app/android.tmpl. + // That's fine, but you now need to add a copy of that file to gradle/settings.gradle.legacy_versions, separated + // from the previous versions by a line that just says ";EOF". + final File templateSettingsDotGradle = globals.fs.file(globals.fs.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools', 'templates', 'app', 'android.tmpl', 'settings.gradle')); + final File legacySettingsDotGradleFiles = globals.fs.file(globals.fs.path.join(Cache.flutterRoot!, 'packages','flutter_tools', 'gradle', 'settings.gradle.legacy_versions')); + expect( + legacySettingsDotGradleFiles.readAsStringSync().split(';EOF').map((String body) => body.trim()), + contains(templateSettingsDotGradle.readAsStringSync().trim()), + ); + // TODO(zanderso): This is an integration test and should be moved to the integration shard. + }, skip: true); // https://github.com/flutter/flutter/issues/87922 +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_utils_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_utils_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8da3336121a424c0b41333a9d90dd8ed1e0e2c0c --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/gradle_utils_test.dart @@ -0,0 +1,1048 @@ +// 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/gradle_utils.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/base/version_range.dart'; +import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/project.dart'; +import '../../src/common.dart'; +import '../../src/fake_process_manager.dart'; +import '../../src/fakes.dart'; + +void main() { + group('injectGradleWrapperIfNeeded', () { + late MemoryFileSystem fileSystem; + late Directory gradleWrapperDirectory; + late GradleUtils gradleUtils; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + gradleWrapperDirectory = + fileSystem.directory('cache/bin/cache/artifacts/gradle_wrapper'); + gradleWrapperDirectory.createSync(recursive: true); + gradleWrapperDirectory + .childFile('gradlew') + .writeAsStringSync('irrelevant'); + gradleWrapperDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + .createSync(recursive: true); + gradleWrapperDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.jar') + .writeAsStringSync('irrelevant'); + gradleUtils = GradleUtils( + cache: Cache.test( + processManager: FakeProcessManager.any(), fileSystem: fileSystem), + platform: FakePlatform(environment: {}), + logger: BufferLogger.test(), + operatingSystemUtils: FakeOperatingSystemUtils(), + ); + }); + + testWithoutContext('injects the wrapper when all files are missing', () { + final Directory sampleAppAndroid = + fileSystem.directory('/sample-app/android'); + sampleAppAndroid.createSync(recursive: true); + + gradleUtils.injectGradleWrapperIfNeeded(sampleAppAndroid); + + expect(sampleAppAndroid.childFile('gradlew').existsSync(), isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.jar') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .readAsStringSync(), + 'distributionBase=GRADLE_USER_HOME\n' + 'distributionPath=wrapper/dists\n' + 'zipStoreBase=GRADLE_USER_HOME\n' + 'zipStorePath=wrapper/dists\n' + 'distributionUrl=https\\://services.gradle.org/distributions/gradle-7.6.3-all.zip\n'); + }); + + testWithoutContext('injects the wrapper when some files are missing', () { + final Directory sampleAppAndroid = + fileSystem.directory('/sample-app/android'); + sampleAppAndroid.createSync(recursive: true); + + // There's an existing gradlew + sampleAppAndroid + .childFile('gradlew') + .writeAsStringSync('existing gradlew'); + + gradleUtils.injectGradleWrapperIfNeeded(sampleAppAndroid); + + expect(sampleAppAndroid.childFile('gradlew').existsSync(), isTrue); + expect(sampleAppAndroid.childFile('gradlew').readAsStringSync(), + equals('existing gradlew')); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.jar') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .readAsStringSync(), + 'distributionBase=GRADLE_USER_HOME\n' + 'distributionPath=wrapper/dists\n' + 'zipStoreBase=GRADLE_USER_HOME\n' + 'zipStorePath=wrapper/dists\n' + 'distributionUrl=https\\://services.gradle.org/distributions/gradle-7.6.3-all.zip\n'); + }); + + testWithoutContext( + 'injects the wrapper and the Gradle version is derivated from the AGP version', + () { + const Map testCases = { + // AGP version : Gradle version + '1.0.0': '2.3', + '3.3.1': '4.10.2', + '3.0.0': '4.1', + '3.0.5': '4.1', + '3.0.9': '4.1', + '3.1.0': '4.4', + '3.2.0': '4.6', + '3.3.0': '4.10.2', + '3.4.0': '5.6.2', + '3.5.0': '5.6.2', + '4.0.0': '6.7', + '4.0.5': '6.7', + '4.1.0': '6.7', + }; + + for (final MapEntry entry in testCases.entries) { + final Directory sampleAppAndroid = + fileSystem.systemTempDirectory.createTempSync('flutter_android.'); + sampleAppAndroid.childFile('build.gradle').writeAsStringSync(''' + buildscript { + dependencies { + classpath 'com.android.tools.build:gradle:${entry.key}' + } + } + '''); + gradleUtils.injectGradleWrapperIfNeeded(sampleAppAndroid); + + expect(sampleAppAndroid.childFile('gradlew').existsSync(), isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.jar') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .existsSync(), + isTrue); + + expect( + sampleAppAndroid + .childDirectory('gradle') + .childDirectory('wrapper') + .childFile('gradle-wrapper.properties') + .readAsStringSync(), + 'distributionBase=GRADLE_USER_HOME\n' + 'distributionPath=wrapper/dists\n' + 'zipStoreBase=GRADLE_USER_HOME\n' + 'zipStorePath=wrapper/dists\n' + 'distributionUrl=https\\://services.gradle.org/distributions/gradle-${entry.value}-all.zip\n'); + } + }); + + testWithoutContext('returns the gradlew path', () { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + androidDirectory.childFile('gradlew').createSync(); + androidDirectory.childFile('gradlew.bat').createSync(); + androidDirectory.childFile('gradle.properties').createSync(); + + final FlutterProject flutterProject = FlutterProjectFactory( + logger: BufferLogger.test(), + fileSystem: fileSystem, + ).fromDirectory(fileSystem.currentDirectory); + + expect( + gradleUtils.getExecutable(flutterProject), + androidDirectory.childFile('gradlew').path, + ); + }); + testWithoutContext('getGradleFileName for notWindows', () { + expect(getGradlewFileName(notWindowsPlatform), 'gradlew'); + }); + testWithoutContext('getGradleFileName for windows', () { + expect(getGradlewFileName(windowsPlatform), 'gradlew.bat'); + }); + + testWithoutContext('returns the gradle properties file', () async { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final Directory wrapperDirectory = androidDirectory + .childDirectory(gradleDirectoryName) + .childDirectory(gradleWrapperDirectoryName) + ..createSync(recursive: true); + final File expectedFile = await wrapperDirectory + .childFile(gradleWrapperPropertiesFilename) + .create(); + final File gradleWrapperFile = getGradleWrapperFile(androidDirectory); + expect(gradleWrapperFile.path, expectedFile.path); + }); + + testWithoutContext('returns the gradle wrapper version', () async { + const String expectedVersion = '7.4.2'; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final Directory wrapperDirectory = androidDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + ..createSync(recursive: true); + wrapperDirectory + .childFile('gradle-wrapper.properties') + .writeAsStringSync(''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\\://services.gradle.org/distributions/gradle-$expectedVersion-all.zip +'''); + + expect( + await getGradleVersion( + androidDirectory, BufferLogger.test(), FakeProcessManager.empty()), + expectedVersion, + ); + }); + + testWithoutContext('ignores gradle comments', () async { + const String expectedVersion = '7.4.2'; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final Directory wrapperDirectory = androidDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + ..createSync(recursive: true); + wrapperDirectory + .childFile('gradle-wrapper.properties') + .writeAsStringSync(''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +# distributionUrl=https\\://services.gradle.org/distributions/gradle-8.0.2-all.zip +distributionUrl=https\\://services.gradle.org/distributions/gradle-$expectedVersion-all.zip +# distributionUrl=https\\://services.gradle.org/distributions/gradle-8.0.2-all.zip +'''); + + expect( + await getGradleVersion( + androidDirectory, BufferLogger.test(), FakeProcessManager.empty()), + expectedVersion, + ); + }); + + testWithoutContext('returns gradlew version, whitespace, location', () async { + const String expectedVersion = '7.4.2'; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final Directory wrapperDirectory = androidDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + ..createSync(recursive: true); + // Distribution url is not the last line. + // Whitespace around distribution url. + wrapperDirectory + .childFile('gradle-wrapper.properties') + .writeAsStringSync(''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl = https\\://services.gradle.org/distributions/gradle-$expectedVersion-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +'''); + + expect( + await getGradleVersion( + androidDirectory, BufferLogger.test(), FakeProcessManager.empty()), + expectedVersion, + ); + }); + + testWithoutContext('does not crash on hypothetical new format', () async { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final Directory wrapperDirectory = androidDirectory + .childDirectory('gradle') + .childDirectory('wrapper') + ..createSync(recursive: true); + // Distribution url is not the last line. + // Whitespace around distribution url. + wrapperDirectory + .childFile('gradle-wrapper.properties') + .writeAsStringSync(r'distributionUrl=https\://services.gradle.org/distributions/gradle_7.4.2_all.zip'); + + // FakeProcessManager.any is used here and not in other getGradleVersion + // tests because this test does not care about process fallback logic. + expect( + await getGradleVersion( + androidDirectory, BufferLogger.test(), FakeProcessManager.any()), + isNull, + ); + }); + + testWithoutContext('returns the installed gradle version', () async { + const String expectedVersion = '7.4.2'; + const String gradleOutput = ''' + +------------------------------------------------------------ +Gradle $expectedVersion +------------------------------------------------------------ + +Build time: 2022-03-31 15:25:29 UTC +Revision: 540473b8118064efcc264694cbcaa4b677f61041 + +Kotlin: 1.5.31 +Groovy: 3.0.9 +Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021 +JVM: 11.0.18 (Azul Systems, Inc. 11.0.18+10-LTS) +OS: Mac OS X 13.2.1 aarch64 +'''; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final ProcessManager processManager = FakeProcessManager.empty() + ..addCommand(const FakeCommand( + command: ['gradle', gradleVersionFlag], + stdout: gradleOutput)); + + expect( + await getGradleVersion( + androidDirectory, + BufferLogger.test(), + processManager, + ), + expectedVersion, + ); + }); + + testWithoutContext('returns the installed gradle with whitespace formatting', () async { + const String expectedVersion = '7.4.2'; + const String gradleOutput = 'Gradle $expectedVersion'; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + final ProcessManager processManager = FakeProcessManager.empty() + ..addCommand(const FakeCommand( + command: ['gradle', gradleVersionFlag], + stdout: gradleOutput)); + + expect( + await getGradleVersion( + androidDirectory, + BufferLogger.test(), + processManager, + ), + expectedVersion, + ); + }); + + testWithoutContext('returns the AGP version when set', () async { + const String expectedVersion = '7.3.0'; + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + androidDirectory.childFile('build.gradle').writeAsStringSync(''' +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:$expectedVersion' + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} +'''); + + expect( + getAgpVersion(androidDirectory, BufferLogger.test()), + expectedVersion, + ); + }); + testWithoutContext('returns null when AGP version not set', () async { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + androidDirectory.childFile('build.gradle').writeAsStringSync(''' +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + } +} +allprojects { + repositories { + google() + mavenCentral() + } +} +'''); + + expect( + getAgpVersion(androidDirectory, BufferLogger.test()), + null, + ); + }); + testWithoutContext('returns the AGP version when beta', () async { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + androidDirectory.childFile('build.gradle').writeAsStringSync(r''' +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.3.0-beta03' + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} +'''); + + expect( + getAgpVersion(androidDirectory, BufferLogger.test()), + '7.3.0', + ); + }); + + testWithoutContext('returns the AGP version when in settings', () async { + final Directory androidDirectory = fileSystem.directory('/android') + ..createSync(); + // File must exist and can not have agp defined. + androidDirectory.childFile('build.gradle').writeAsStringSync(r''); + androidDirectory.childFile('settings.gradle').writeAsStringSync(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 + } + settings.ext.flutterSdkPath = flutterSdkPath() + + includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } + + plugins { + id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + // Decoy value to ensure we ignore commented out lines. + // id "com.android.application" version "6.1.0" apply false + id "com.android.application" version "7.3.0" apply false +} + +include ":app" +'''); + + expect( + getAgpVersion(androidDirectory, BufferLogger.test()), + '7.3.0', + ); + }); + + group('validates gradle/agp versions', () { + final List testData = [ + // Values too new *these need to be updated* when + // max known gradle and max known agp versions are updated: + // Newer tools version supports max gradle version. + GradleAgpTestData(true, agpVersion: '8.2', gradleVersion: '8.0'), + // Newer tools version does not even meet current gradle version requirements. + GradleAgpTestData(false, agpVersion: '8.2', gradleVersion: '7.3'), + // Newer tools version requires newer gradle version. + GradleAgpTestData(true, agpVersion: '8.3', gradleVersion: '8.1'), + + // Template versions of Gradle/AGP. + GradleAgpTestData(true, agpVersion: templateAndroidGradlePluginVersion, gradleVersion: templateDefaultGradleVersion), + GradleAgpTestData(true, agpVersion: templateAndroidGradlePluginVersionForModule, gradleVersion: templateDefaultGradleVersion), + + // Minimums as defined in + // https://developer.android.com/studio/releases/gradle-plugin#updating-gradle + GradleAgpTestData(true, agpVersion: '8.1', gradleVersion: '8.0'), + GradleAgpTestData(true, agpVersion: '8.0', gradleVersion: '8.0'), + GradleAgpTestData(true, agpVersion: '7.4', gradleVersion: '7.5'), + GradleAgpTestData(true, agpVersion: '7.3', gradleVersion: '7.4'), + GradleAgpTestData(true, agpVersion: '7.2', gradleVersion: '7.3.3'), + GradleAgpTestData(true, agpVersion: '7.1', gradleVersion: '7.2'), + GradleAgpTestData(true, agpVersion: '7.0', gradleVersion: '7.0'), + GradleAgpTestData(true, agpVersion: '4.2.0', gradleVersion: '6.7.1'), + GradleAgpTestData(true, agpVersion: '4.1.0', gradleVersion: '6.5'), + GradleAgpTestData(true, agpVersion: '4.0.0', gradleVersion: '6.1.1'), + GradleAgpTestData(true, agpVersion: '3.6.0', gradleVersion: '5.6.4'), + GradleAgpTestData(true, agpVersion: '3.5.0', gradleVersion: '5.4.1'), + GradleAgpTestData(true, agpVersion: '3.4.0', gradleVersion: '5.1.1'), + GradleAgpTestData(true, agpVersion: '3.3.0', gradleVersion: '4.10.1'), + // Values too old: + GradleAgpTestData(false, agpVersion: '3.3.0', gradleVersion: '4.9'), + GradleAgpTestData(false, agpVersion: '7.3', gradleVersion: '7.2'), + GradleAgpTestData(false, agpVersion: '3.0.0', gradleVersion: '7.2'), + // Null values: + // ignore: avoid_redundant_argument_values + GradleAgpTestData(false, agpVersion: null, gradleVersion: '7.2'), + // ignore: avoid_redundant_argument_values + GradleAgpTestData(false, agpVersion: '3.0.0', gradleVersion: null), + // ignore: avoid_redundant_argument_values + GradleAgpTestData(false, agpVersion: null, gradleVersion: null), + // Middle AGP cases: + GradleAgpTestData(true, agpVersion: '8.0.1', gradleVersion: '8.0'), + GradleAgpTestData(true, agpVersion: '7.4.1', gradleVersion: '7.5'), + GradleAgpTestData(true, agpVersion: '7.3.1', gradleVersion: '7.4'), + GradleAgpTestData(true, agpVersion: '7.2.1', gradleVersion: '7.3.3'), + GradleAgpTestData(true, agpVersion: '7.1.1', gradleVersion: '7.2'), + GradleAgpTestData(true, agpVersion: '7.0.1', gradleVersion: '7.0'), + GradleAgpTestData(true, agpVersion: '4.2.1', gradleVersion: '6.7.1'), + GradleAgpTestData(true, agpVersion: '4.1.1', gradleVersion: '6.5'), + GradleAgpTestData(true, agpVersion: '4.0.1', gradleVersion: '6.1.1'), + GradleAgpTestData(true, agpVersion: '3.6.1', gradleVersion: '5.6.4'), + GradleAgpTestData(true, agpVersion: '3.5.1', gradleVersion: '5.4.1'), + GradleAgpTestData(true, agpVersion: '3.4.1', gradleVersion: '5.1.1'), + GradleAgpTestData(true, agpVersion: '3.3.1', gradleVersion: '4.10.1'), + + // Higher gradle cases: + GradleAgpTestData(true, agpVersion: '7.4', gradleVersion: '8.0'), + GradleAgpTestData(true, agpVersion: '7.3', gradleVersion: '7.5'), + GradleAgpTestData(true, agpVersion: '7.2', gradleVersion: '7.4'), + GradleAgpTestData(true, agpVersion: '7.1', gradleVersion: '7.3.3'), + GradleAgpTestData(true, agpVersion: '7.0', gradleVersion: '7.2'), + GradleAgpTestData(true, agpVersion: '4.2.0', gradleVersion: '7.0'), + GradleAgpTestData(true, agpVersion: '4.1.0', gradleVersion: '6.7.1'), + GradleAgpTestData(true, agpVersion: '4.0.0', gradleVersion: '6.5'), + GradleAgpTestData(true, agpVersion: '3.6.0', gradleVersion: '6.1.1'), + GradleAgpTestData(true, agpVersion: '3.5.0', gradleVersion: '5.6.4'), + GradleAgpTestData(true, agpVersion: '3.4.0', gradleVersion: '5.4.1'), + GradleAgpTestData(true, agpVersion: '3.3.0', gradleVersion: '5.1.1'), + ]; + for (final GradleAgpTestData data in testData) { + test('(gradle, agp): (${data.gradleVersion}, ${data.agpVersion})', () { + expect( + validateGradleAndAgp( + BufferLogger.test(), + gradleV: data.gradleVersion, + agpV: data.agpVersion, + ), + data.validPair ? isTrue : isFalse, + reason: 'G: ${data.gradleVersion}, AGP: ${data.agpVersion}'); + }); + } + }); + + group('Parse gradle version from distribution url', () { + testWithoutContext('null distribution url returns null version', () { + expect(parseGradleVersionFromDistributionUrl(null), null); + }); + + testWithoutContext('unparseable format returns null', () { + const String distributionUrl = 'aString'; + expect(parseGradleVersionFromDistributionUrl(distributionUrl), null); + }); + + testWithoutContext("recognizable 'all' format returns correct version", () { + const String distributionUrl = r'distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip'; + expect(parseGradleVersionFromDistributionUrl(distributionUrl), '6.7'); + }); + + testWithoutContext("recognizable 'bin' format returns correct version", () { + const String distributionUrl = r'distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip'; + expect(parseGradleVersionFromDistributionUrl(distributionUrl), '6.7'); + }); + + testWithoutContext("recognizable 'rc' format returns correct version", () { + const String distributionUrl = r'distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-rc-3-all.zip'; + expect(parseGradleVersionFromDistributionUrl(distributionUrl), '8.1'); + }); + }); + + group('validates java/gradle versions', () { + final List testData = [ + // Values too new *these need to be updated* when + // max supported java and max known gradle versions are updated: + // Newer tools version does not even meet current gradle version requiremnts. + JavaGradleTestData(false, javaVersion: '20', gradleVersion: '7.5'), + // Newer tools version requires newer gradle version. + JavaGradleTestData(true, javaVersion: '20', gradleVersion: '8.1'), + // Max known unsupported Java version. + JavaGradleTestData(true, javaVersion: '24', gradleVersion: maxKnownAndSupportedGradleVersion), + // Minimums as defined in + // https://docs.gradle.org/current/userguide/compatibility.html#java + JavaGradleTestData(true, javaVersion: '19', gradleVersion: '7.6'), + JavaGradleTestData(true, javaVersion: '18', gradleVersion: '7.5'), + JavaGradleTestData(true, javaVersion: '17', gradleVersion: '7.3'), + JavaGradleTestData(true, javaVersion: '16', gradleVersion: '7.0'), + JavaGradleTestData(true, javaVersion: '15', gradleVersion: '6.7'), + JavaGradleTestData(true, javaVersion: '14', gradleVersion: '6.3'), + JavaGradleTestData(true, javaVersion: '13', gradleVersion: '6.0'), + JavaGradleTestData(true, javaVersion: '12', gradleVersion: '5.4'), + JavaGradleTestData(true, javaVersion: '11', gradleVersion: '5.0'), + JavaGradleTestData(true, javaVersion: '1.10', gradleVersion: '4.7'), + JavaGradleTestData(true, javaVersion: '1.9', gradleVersion: '4.3'), + JavaGradleTestData(true, javaVersion: '1.8', gradleVersion: '2.0'), + // Gradle too old for Java version. + JavaGradleTestData(false, javaVersion: '19', gradleVersion: '6.7'), + JavaGradleTestData(false, javaVersion: '11', gradleVersion: '4.10.1'), + JavaGradleTestData(false, javaVersion: '1.9', gradleVersion: '4.1'), + // Null values: + // ignore: avoid_redundant_argument_values + JavaGradleTestData(false, javaVersion: null, gradleVersion: '7.2'), + // ignore: avoid_redundant_argument_values + JavaGradleTestData(false, javaVersion: '11', gradleVersion: null), + // ignore: avoid_redundant_argument_values + JavaGradleTestData(false, javaVersion: null, gradleVersion: null), + // Middle Java cases: + // https://www.java.com/releases/ + JavaGradleTestData(true, javaVersion: '19.0.2', gradleVersion: '8.0.2'), + JavaGradleTestData(true, javaVersion: '19.0.2', gradleVersion: '8.0.0'), + JavaGradleTestData(true, javaVersion: '18.0.2', gradleVersion: '8.0.2'), + JavaGradleTestData(true, javaVersion: '17.0.3', gradleVersion: '7.5'), + JavaGradleTestData(true, javaVersion: '16.0.1', gradleVersion: '7.3'), + JavaGradleTestData(true, javaVersion: '15.0.2', gradleVersion: '7.3'), + JavaGradleTestData(true, javaVersion: '14.0.1', gradleVersion: '7.0'), + JavaGradleTestData(true, javaVersion: '13.0.2', gradleVersion: '6.7'), + JavaGradleTestData(true, javaVersion: '12.0.2', gradleVersion: '6.3'), + JavaGradleTestData(true, javaVersion: '11.0.18', gradleVersion: '6.0'), + // Higher gradle cases: + JavaGradleTestData(true, javaVersion: '19', gradleVersion: '8.0'), + JavaGradleTestData(true, javaVersion: '18', gradleVersion: '8.0'), + JavaGradleTestData(true, javaVersion: '17', gradleVersion: '7.5'), + JavaGradleTestData(true, javaVersion: '16', gradleVersion: '7.3'), + JavaGradleTestData(true, javaVersion: '15', gradleVersion: '7.3'), + JavaGradleTestData(true, javaVersion: '14', gradleVersion: '7.0'), + JavaGradleTestData(true, javaVersion: '13', gradleVersion: '6.7'), + JavaGradleTestData(true, javaVersion: '12', gradleVersion: '6.3'), + JavaGradleTestData(true, javaVersion: '11', gradleVersion: '6.0'), + JavaGradleTestData(true, javaVersion: '1.10', gradleVersion: '5.4'), + JavaGradleTestData(true, javaVersion: '1.9', gradleVersion: '5.0'), + JavaGradleTestData(true, javaVersion: '1.8', gradleVersion: '4.3'), + ]; + + for (final JavaGradleTestData data in testData) { + testWithoutContext( + '(Java, gradle): (${data.javaVersion}, ${data.gradleVersion})', () { + expect( + validateJavaAndGradle( + BufferLogger.test(), + javaV: data.javaVersion, + gradleV: data.gradleVersion, + ), + data.validPair ? isTrue : isFalse, + reason: 'J: ${data.javaVersion}, G: ${data.gradleVersion}'); + }); + } + }); + }); + + group('validates java/AGP versions', () { + final List testData = [ + // Strictly too old Java versions for known AGP versions. + JavaAgpTestData(false, javaVersion: '1.6', agpVersion: maxKnownAgpVersion), + JavaAgpTestData(false, javaVersion: '1.6', agpVersion: maxKnownAndSupportedAgpVersion), + JavaAgpTestData(false, javaVersion: '1.6', agpVersion: '4.2'), + // Strictly too old AGP versions. + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: '1.0'), + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: '4.1'), + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: '2.3'), + // Strictly too new Java versions for defined AGP versions. + JavaAgpTestData(true, javaVersion: '18', agpVersion: '8.1'), + JavaAgpTestData(true, javaVersion: '18', agpVersion: '7.4'), + JavaAgpTestData(true, javaVersion: '18', agpVersion: '4.2'), + // Strictly too new AGP versions. + // *The tests that follow need to be updated* when max supported AGP versions are updated: + JavaAgpTestData(false, javaVersion: '24', agpVersion: '8.3'), + JavaAgpTestData(false, javaVersion: '20', agpVersion: '8.3'), + JavaAgpTestData(false, javaVersion: '17', agpVersion: '8.3'), + // Java 17 & patch versions compatibility cases + // *The tests that follow need to be updated* when maxKnownAndSupportedAgpVersion is + // updated: + JavaAgpTestData(false, javaVersion: '17', agpVersion: '8.2'), + JavaAgpTestData(true, javaVersion: '17', agpVersion: maxKnownAndSupportedAgpVersion), + JavaAgpTestData(true, javaVersion: '17', agpVersion: '8.1'), + JavaAgpTestData(true, javaVersion: '17', agpVersion: '8.0'), + JavaAgpTestData(true, javaVersion: '17', agpVersion: '7.4'), + JavaAgpTestData(false, javaVersion: '17.0.3', agpVersion: '8.2'), + JavaAgpTestData(true, javaVersion: '17.0.3', agpVersion: maxKnownAndSupportedAgpVersion), + JavaAgpTestData(true, javaVersion: '17.0.3', agpVersion: '8.1'), + JavaAgpTestData(true, javaVersion: '17.0.3', agpVersion: '8.0'), + JavaAgpTestData(true, javaVersion: '17.0.3', agpVersion: '7.4'), + // Java 11 & patch versions compatibility cases + JavaAgpTestData(false, javaVersion: '11', agpVersion: '8.0'), + JavaAgpTestData(true, javaVersion: '11', agpVersion: '7.4'), + JavaAgpTestData(true, javaVersion: '11', agpVersion: '7.2'), + JavaAgpTestData(true, javaVersion: '11', agpVersion: '7.0'), + JavaAgpTestData(true, javaVersion: '11', agpVersion: '4.2'), + JavaAgpTestData(false, javaVersion: '11.0.18', agpVersion: '8.0'), + JavaAgpTestData(true, javaVersion: '11.0.18', agpVersion: '7.4'), + JavaAgpTestData(true, javaVersion: '11.0.18', agpVersion: '7.2'), + JavaAgpTestData(true, javaVersion: '11.0.18', agpVersion: '7.0'), + JavaAgpTestData(true, javaVersion: '11.0.18', agpVersion: '4.2'), + // Java 8 compatibility cases + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: '7.0'), + JavaAgpTestData(true, javaVersion: '1.8', agpVersion: oldestDocumentedJavaAgpCompatibilityVersion), // agpVersion = 4.2 + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: '4.1'), + // Null value cases + // ignore: avoid_redundant_argument_values + JavaAgpTestData(false, javaVersion: null, agpVersion: '4.2'), + // ignore: avoid_redundant_argument_values + JavaAgpTestData(false, javaVersion: '1.8', agpVersion: null), + // ignore: avoid_redundant_argument_values + JavaAgpTestData(false, javaVersion: null, agpVersion: null), + ]; + + for (final JavaAgpTestData data in testData) { + testWithoutContext( + '(Java, agp): (${data.javaVersion}, ${data.agpVersion})', () { + expect( + validateJavaAndAgp( + BufferLogger.test(), + javaV: data.javaVersion, + agpV: data.agpVersion, + ), + data.validPair ? isTrue : isFalse, + reason: 'J: ${data.javaVersion}, G: ${data.agpVersion}'); + }); + } + }); + + group('detecting valid Gradle/AGP versions for given Java version and vice versa', () { + testWithoutContext('getValidGradleVersionRangeForJavaVersion returns valid Gradle version range for Java version', () { + final Logger testLogger = BufferLogger.test(); + // Java version too high. + expect(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: oneMajorVersionHigherJavaVersion), isNull); + // Maximum known Java version. + // *The test case that follows needs to be updated* when higher versions of Java are supported: + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '20'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '20.0.2')), + isNull)); + // Known supported Java versions. + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '19'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '19.0.2')), + equals( + const JavaGradleCompat( + javaMin: '19', + javaMax: '20', + gradleMin: '7.6', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '18'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '18.0.2')), + equals( + const JavaGradleCompat( + javaMin: '18', + javaMax: '19', + gradleMin: '7.5', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '17'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '17.0.2')), + equals( + const JavaGradleCompat( + javaMin: '17', + javaMax: '18', + gradleMin: '7.3', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '16'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '16.0.2')), + equals( + const JavaGradleCompat( + javaMin: '16', + javaMax: '17', + gradleMin: '7.0', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '15'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '15.0.2')), + equals( + const JavaGradleCompat( + javaMin: '15', + javaMax: '16', + gradleMin: '6.7', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '14'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '14.0.2')), + equals( + const JavaGradleCompat( + javaMin: '14', + javaMax: '15', + gradleMin: '6.3', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '13'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '13.0.2')), + equals( + const JavaGradleCompat( + javaMin: '13', + javaMax: '14', + gradleMin: '6.0', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '12'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '12.0.2')), + equals( + const JavaGradleCompat( + javaMin: '12', + javaMax: '13', + gradleMin: '5.4', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '11'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '11.0.2')), + equals( + const JavaGradleCompat( + javaMin: '11', + javaMax: '12', + gradleMin: '5.0', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.10'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.10.2')), + equals( + const JavaGradleCompat( + javaMin: '1.10', + javaMax: '1.11', + gradleMin: '4.7', + gradleMax: maxKnownAndSupportedGradleVersion)))); + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.9'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.9.2')), + equals( + const JavaGradleCompat( + javaMin: '1.9', + javaMax: '1.10', + gradleMin: '4.3', + gradleMax: maxKnownAndSupportedGradleVersion)))); + // Java 1.8 -- return oldest documented compatibility info + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.8'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.8.2')), + equals( + const JavaGradleCompat( + javaMin: '1.8', + javaMax: '1.9', + gradleMin: '2.0', + gradleMax: maxKnownAndSupportedGradleVersion)))); + // Java version too low. + expect( + getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.7'), + allOf( + equals(getValidGradleVersionRangeForJavaVersion(testLogger, javaV: '1.7.2')), + isNull)); + }); + + testWithoutContext('getMinimumAgpVersionForJavaVersion returns minimum AGP version for Java version', () { + final Logger testLogger = BufferLogger.test(); + // Maximum known Java version. + // *The test case that follows needs to be updated* as higher versions of AGP are supported: + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: oneMajorVersionHigherJavaVersion), + equals( + const JavaAgpCompat( + javaMin: '17', + javaDefault: '17', + agpMin: '8.0', + agpMax: '8.1'))); + // Known Java versions. + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '17'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '17.0.2')), + equals( + const JavaAgpCompat( + javaMin: '17', + javaDefault: '17', + agpMin: '8.0', + agpMax: '8.1')))); + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '15'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '15.0.2')), + equals( + const JavaAgpCompat( + javaMin: '11', + javaDefault: '11', + agpMin: '7.0', + agpMax: '7.4')))); + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '11'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '11.0.2')), + equals( + const JavaAgpCompat( + javaMin: '11', + javaDefault: '11', + agpMin: '7.0', + agpMax: '7.4')))); + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.9'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.9.2')), + equals( + const JavaAgpCompat( + javaMin: '1.8', + javaDefault: '1.8', + agpMin: '4.2', + agpMax: '4.2')))); + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.8'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.8.2')), + equals( + const JavaAgpCompat( + javaMin: '1.8', + javaDefault: '1.8', + agpMin: '4.2', + agpMax: '4.2')))); + // Java version too low. + expect( + getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.7'), + allOf( + equals(getMinimumAgpVersionForJavaVersion(testLogger, javaV: '1.7.2')), + isNull)); + }); + + testWithoutContext('getJavaVersionFor returns expected Java version range', () { + // Strictly too old Gradle and AGP versions. + expect(getJavaVersionFor(gradleV: '1.9', agpV: '4.1'), equals(const VersionRange(null, null))); + // Strictly too old Gradle or AGP version. + expect(getJavaVersionFor(gradleV: '1.9', agpV: '4.2'), equals(const VersionRange('1.8', null))); + expect(getJavaVersionFor(gradleV: '2.0', agpV: '4.1'), equals(const VersionRange(null, '1.9'))); + // Strictly too new Gradle and AGP versions. + expect(getJavaVersionFor(gradleV: '8.1', agpV: '8.2'), equals(const VersionRange(null, null))); + // Strictly too new Gradle version and maximum version of AGP. + //*This test case will need its expected Java range updated when a new version of AGP is supported.* + expect(getJavaVersionFor(gradleV: '8.1', agpV: maxKnownAndSupportedAgpVersion), equals(const VersionRange('17', null))); + // Strictly too new AGP version and maximum version of Gradle. + //*This test case will need its expected Java range updated when a new version of Gradle is supported.* + expect(getJavaVersionFor(gradleV: maxKnownAndSupportedGradleVersion, agpV: '8.2'), equals(const VersionRange(null, '20'))); + // Tests with a known compatible Gradle/AGP version pair. + expect(getJavaVersionFor(gradleV: '7.0', agpV: '7.2'), equals(const VersionRange('11', '17'))); + expect(getJavaVersionFor(gradleV: '7.1', agpV: '7.2'), equals(const VersionRange('11', '17'))); + expect(getJavaVersionFor(gradleV: '7.2.2', agpV: '7.2'), equals(const VersionRange('11', '17'))); + expect(getJavaVersionFor(gradleV: '7.1', agpV: '7.0'), equals(const VersionRange('11', '17'))); + expect(getJavaVersionFor(gradleV: '7.1', agpV: '7.2'), equals(const VersionRange('11', '17'))); + expect(getJavaVersionFor(gradleV: '7.1', agpV: '7.4'), equals(const VersionRange('11', '17'))); + }); + }); +} + +class GradleAgpTestData { + GradleAgpTestData(this.validPair, {this.gradleVersion, this.agpVersion}); + final String? gradleVersion; + final String? agpVersion; + final bool validPair; +} + +class JavaGradleTestData { + JavaGradleTestData(this.validPair, {this.javaVersion, this.gradleVersion}); + final String? gradleVersion; + final String? javaVersion; + final bool validPair; +} + +class JavaAgpTestData { + JavaAgpTestData(this.validPair, {this.javaVersion, this.agpVersion}); + final String? agpVersion; + final String? javaVersion; + final bool validPair; +} + +final Platform windowsPlatform = FakePlatform( + operatingSystem: 'windows', + environment: { + 'PROGRAMFILES(X86)': r'C:\Program Files (x86)\', + 'FLUTTER_ROOT': r'C:\flutter', + 'USERPROFILE': '/', + } +); +final Platform notWindowsPlatform = FakePlatform( + environment: { + 'FLUTTER_ROOT': r'/users/someuser/flutter', + } +); diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/java_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/java_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..66d8dd9fc10ddf522683246e8b757ba45a7db770 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/java_test.dart @@ -0,0 +1,354 @@ +// 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/java.dart'; +import 'package:flutter_tools/src/base/config.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/os.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/base/version.dart'; +import 'package:test/fake.dart'; +import 'package:webdriver/async_io.dart'; + +import '../../integration.shard/test_utils.dart'; +import '../../src/common.dart'; +import '../../src/context.dart'; +import '../../src/fakes.dart'; + +void main() { + + late Config config; + late Logger logger; + late FileSystem fs; + late Platform platform; + late FakeProcessManager processManager; + + setUp(() { + config = Config.test(); + logger = BufferLogger.test(); + fs = MemoryFileSystem.test(); + platform = FakePlatform(environment: { + 'PATH': '', + }); + processManager = FakeProcessManager.empty(); + }); + + group(Java, () { + + group('find', () { + testWithoutContext('finds the JDK bundled with Android Studio, if it exists', () { + final AndroidStudio androidStudio = _FakeAndroidStudioWithJdk(); + final String androidStudioBundledJdkHome = androidStudio.javaPath!; + final String expectedJavaBinaryPath = fs.path.join(androidStudioBundledJdkHome, 'bin', 'java'); + + processManager.addCommand(FakeCommand( + command: [ + expectedJavaBinaryPath, + '--version', + ], + stdout: ''' +openjdk 19.0.2 2023-01-17 +OpenJDK Runtime Environment Zulu19.32+15-CA (build 19.0.2+7) +OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing) +''' + )); + final Java java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: platform, + processManager: processManager, + )!; + + expect(java.javaHome, androidStudioBundledJdkHome); + expect(java.binaryPath, expectedJavaBinaryPath); + + expect(java.version!.toString(), 'OpenJDK Runtime Environment Zulu19.32+15-CA (build 19.0.2+7)'); + expect(java.version, equals(Version(19, 0, 2))); + }); + + testWithoutContext('finds JAVA_HOME if it is set and the JDK bundled with Android Studio could not be found', () { + final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk(); + const String javaHome = '/java/home'; + final String expectedJavaBinaryPath = fs.path.join(javaHome, 'bin', 'java'); + + final Java java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: FakePlatform(environment: { + Java.javaHomeEnvironmentVariable: javaHome, + }), + processManager: processManager, + )!; + + expect(java.javaHome, javaHome); + expect(java.binaryPath, expectedJavaBinaryPath); + }); + + testWithoutContext('returns the java binary found on PATH if no other can be found', () { + final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk(); + final OperatingSystemUtils os = _FakeOperatingSystemUtilsWithJava(fileSystem); + + processManager.addCommand( + const FakeCommand( + command: ['which', 'java'], + stdout: '/fake/which/java/path', + ), + ); + + final Java java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: platform, + processManager: processManager, + )!; + + expect(java.javaHome, isNull); + expect(java.binaryPath, os.which('java')!.path); + }); + + testWithoutContext('returns null if no java could be found', () { + final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk(); + processManager.addCommand( + const FakeCommand( + command: ['which', 'java'], + exitCode: 1, + ), + ); + final Java? java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: platform, + processManager: processManager, + ); + expect(java, isNull); + }); + + testWithoutContext('finds and prefers JDK found at config item "jdk-dir" if it is set', () { + const String configuredJdkPath = '/jdk'; + config.setValue('jdk-dir', configuredJdkPath); + + processManager.addCommand( + const FakeCommand( + command: ['which', 'java'], + stdout: '/fake/which/java/path', + ), + ); + + final _FakeAndroidStudioWithJdk androidStudio = _FakeAndroidStudioWithJdk(); + final FakePlatform platformWithJavaHome = FakePlatform( + environment: { + 'JAVA_HOME': '/old/jdk' + }, + ); + Java? java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: platformWithJavaHome, + processManager: processManager, + ); + + expect(java, isNotNull); + expect(java!.javaHome, configuredJdkPath); + expect(java.binaryPath, fs.path.join(configuredJdkPath, 'bin', 'java')); + + config.removeValue('jdk-dir'); + + java = Java.find( + config: config, + androidStudio: androidStudio, + logger: logger, + fileSystem: fs, + platform: platformWithJavaHome, + processManager: processManager, + ); + + expect(java, isNotNull); + assert(androidStudio.javaPath != configuredJdkPath); + expect(java!.javaHome, androidStudio.javaPath); + expect(java.binaryPath, fs.path.join(androidStudio.javaPath!, 'bin', 'java')); + }); + }); + + group('version', () { + late Java java; + + setUp(() { + processManager = FakeProcessManager.empty(); + java = Java( + fileSystem: fs, + logger: logger, + os: FakeOperatingSystemUtils(), + platform: platform, + processManager: processManager, + binaryPath: 'javaHome/bin/java', + javaHome: 'javaHome', + ); + }); + + void addJavaVersionCommand(String output) { + processManager.addCommand( + FakeCommand( + command: [java.binaryPath, '--version'], + stdout: output, + ), + ); + } + + testWithoutContext('is null when java binary cannot be run', () async { + addJavaVersionCommand(''); + processManager.excludedExecutables.add('java'); + + expect(java.version, null); + }); + + testWithoutContext('is null when java --version returns a non-zero exit code', () async { + processManager.addCommand( + FakeCommand( + command: [java.binaryPath, '--version'], + exitCode: 1, + ), + ); + expect(java.version, null); + }); + + testWithoutContext('parses jdk 8', () { + addJavaVersionCommand(''' +java version "1.8.0_202" +Java(TM) SE Runtime Environment (build 1.8.0_202-b10) +Java HotSpot(TM) 64-Bit Server VM (build 25.202-b10, mixed mode) +'''); + final Version version = java.version!; + expect(version.toString(), 'Java(TM) SE Runtime Environment (build 1.8.0_202-b10)'); + expect(version, equals(Version(1, 8, 0))); + }); + testWithoutContext('parses jdk 11 windows', () { + addJavaVersionCommand(''' +java version "11.0.14" +Java(TM) SE Runtime Environment (build 11.0.14+10-b13) +Java HotSpot(TM) 64-Bit Server VM (build 11.0.14+10-b13, mixed mode) +'''); + final Version version = java.version!; + expect(version.toString(), 'Java(TM) SE Runtime Environment (build 11.0.14+10-b13)'); + expect(version, equals(Version(11, 0, 14))); + }); + + testWithoutContext('parses jdk 11 mac/linux', () { + addJavaVersionCommand(''' +openjdk version "11.0.18" 2023-01-17 LTS +OpenJDK Runtime Environment Zulu11.62+17-CA (build 11.0.18+10-LTS) +OpenJDK 64-Bit Server VM Zulu11.62+17-CA (build 11.0.18+10-LTS, mixed mode) +'''); + final Version version = java.version!; + expect(version.toString(), 'OpenJDK Runtime Environment Zulu11.62+17-CA (build 11.0.18+10-LTS)'); + expect(version, equals(Version(11, 0, 18))); + }); + + testWithoutContext('parses jdk 17', () { + addJavaVersionCommand(''' +openjdk 17.0.6 2023-01-17 +OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694) +OpenJDK 64-Bit Server VM (build 17.0.6+0-17.0.6b802.4-9586694, mixed mode) +'''); + final Version version = java.version!; + expect(version.toString(), 'OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)'); + expect(version, equals(Version(17, 0, 6))); + }); + + testWithoutContext('parses jdk 19', () { + addJavaVersionCommand(''' +openjdk 19.0.2 2023-01-17 +OpenJDK Runtime Environment Homebrew (build 19.0.2) +OpenJDK 64-Bit Server VM Homebrew (build 19.0.2, mixed mode, sharing) +'''); + final Version version = java.version!; + expect(version.toString(), 'OpenJDK Runtime Environment Homebrew (build 19.0.2)'); + expect(version, equals(Version(19, 0, 2))); + }); + + // https://chrome-infra-packages.appspot.com/p/flutter/java/openjdk/ + testWithoutContext('parses jdk output from ci', () { + addJavaVersionCommand(''' +openjdk 11.0.2 2019-01-15 +OpenJDK Runtime Environment 18.9 (build 11.0.2+9) +OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode) +'''); + final Version version = java.version!; + expect(version.toString(), 'OpenJDK Runtime Environment 18.9 (build 11.0.2+9)'); + expect(version, equals(Version(11, 0, 2))); + }); + + testWithoutContext('parses jdk two number versions', () { + addJavaVersionCommand('openjdk 19.0 2023-01-17'); + final Version version = java.version!; + expect(version.toString(), 'openjdk 19.0 2023-01-17'); + expect(version, equals(Version(19, 0, null))); + }); + + testWithoutContext('parses jdk 21 with patch numbers', () { + addJavaVersionCommand(''' +java 21.0.1 2023-09-19 LTS +Java(TM) SE Runtime Environment (build 21+35-LTS-2513) +Java HotSpot(TM) 64-Bit Server VM (build 21+35-LTS-2513, mixed mode, sharing) +'''); + final Version? version = java.version; + expect(version, equals(Version(21, 0, 1))); + }); + + testWithoutContext('parses jdk 21 with no patch numbers', () { + addJavaVersionCommand(''' +java 21 2023-09-19 LTS +Java(TM) SE Runtime Environment (build 21+35-LTS-2513) +Java HotSpot(TM) 64-Bit Server VM (build 21+35-LTS-2513, mixed mode, sharing) +'''); + final Version? version = java.version; + expect(version, equals(Version(21, 0, 0))); + }); + testWithoutContext('parses openjdk 21 with no patch numbers', () { + addJavaVersionCommand(''' +openjdk version "21" 2023-09-19 +OpenJDK Runtime Environment (build 21+35) +OpenJDK 64-Bit Server VM (build 21+35, mixed mode, sharing) +'''); + final Version? version = java.version; + expect(version, equals(Version(21, 0, 0))); + }); + }); + }); +} + +class _FakeAndroidStudioWithJdk extends Fake implements AndroidStudio { + @override + String? get javaPath => '/fake/android_studio/java/path/'; +} + +class _FakeAndroidStudioWithoutJdk extends Fake implements AndroidStudio { + @override + String? get javaPath => null; +} + +class _FakeOperatingSystemUtilsWithJava extends FakeOperatingSystemUtils { + _FakeOperatingSystemUtilsWithJava(this._fileSystem); + + final FileSystem _fileSystem; + @override + File? which(String execName) { + if (execName == 'java') { + return _fileSystem.file('/fake/which/java/path'); + } + throw const InvalidArgumentException(null, null); + } +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/multidex_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/multidex_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..11cf2027256984fb8f40a135c56bbab5a907ac54 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/multidex_test.dart @@ -0,0 +1,213 @@ +// 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/multidex.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; + +import '../../src/common.dart'; +import '../../src/context.dart'; + +void main() { + testUsingContext('ensureMultidexUtilsExists patches file when invalid', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('java') + .childDirectory('io') + .childDirectory('flutter') + .childDirectory('app') + .childFile('FlutterMultiDexApplication.java'); + applicationFile.createSync(recursive: true); + applicationFile.writeAsStringSync('hello', flush: true); + expect(applicationFile.readAsStringSync(), 'hello'); + + ensureMultiDexApplicationExists(directory); + + // File should remain untouched + expect(applicationFile.readAsStringSync(), ''' +// Generated file. +// +// If you wish to remove Flutter's multidex support, delete this entire file. +// +// Modifications to this file should be done in a copy under a different name +// as this file may be regenerated. + +package io.flutter.app; + +import android.app.Application; +import android.content.Context; +import androidx.annotation.CallSuper; +import androidx.multidex.MultiDex; + +/** + * Extension of {@link android.app.Application}, adding multidex support. + */ +public class FlutterMultiDexApplication extends Application { + @Override + @CallSuper + protected void attachBaseContext(Context base) { + super.attachBaseContext(base); + MultiDex.install(this); + } +} +'''); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('ensureMultiDexApplicationExists generates when does not exist', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('java') + .childDirectory('io') + .childDirectory('flutter') + .childDirectory('app') + .childFile('FlutterMultiDexApplication.java'); + + ensureMultiDexApplicationExists(directory); + + final String contents = applicationFile.readAsStringSync(); + expect(contents.contains('FlutterMultiDexApplication'), true); + expect(contents.contains('MultiDex.install(this);'), true); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('multiDexApplicationExists false when does not exist', () async { + final Directory directory = globals.fs.currentDirectory; + expect(multiDexApplicationExists(directory), false); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('multiDexApplicationExists true when does exist', () async { + final Directory directory = globals.fs.currentDirectory; + final File utilsFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('java') + .childDirectory('io') + .childDirectory('flutter') + .childDirectory('app') + .childFile('FlutterMultiDexApplication.java'); + utilsFile.createSync(recursive: true); + + expect(multiDexApplicationExists(directory), true); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('androidManifestHasNameVariable true with valid manifest', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + applicationFile.createSync(recursive: true); + applicationFile.writeAsStringSync(r''' + + + + +''', flush: true); + expect(androidManifestHasNameVariable(directory), true); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('androidManifestHasNameVariable false with no android:name attribute', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + applicationFile.createSync(recursive: true); + applicationFile.writeAsStringSync(r''' + + + +''', flush: true); + expect(androidManifestHasNameVariable(directory), false); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('androidManifestHasNameVariable false with incorrect android:name attribute', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + applicationFile.createSync(recursive: true); + applicationFile.writeAsStringSync(r''' + + + +''', flush: true); + expect(androidManifestHasNameVariable(directory), false); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('androidManifestHasNameVariable false with invalid xml manifest', () async { + final Directory directory = globals.fs.currentDirectory; + final File applicationFile = directory.childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childFile('AndroidManifest.xml'); + applicationFile.createSync(recursive: true); + applicationFile.writeAsStringSync(r''' + + + +''', flush: true); + expect(androidManifestHasNameVariable(directory), false); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('androidManifestHasNameVariable false with no manifest file', () async { + final Directory directory = globals.fs.currentDirectory; + expect(androidManifestHasNameVariable(directory), false); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/native_assets_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/native_assets_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0b7f610abbf5277b1499c5f5d0b0aa261a276b4f --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/native_assets_test.dart @@ -0,0 +1,385 @@ +// 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:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/android/native_assets.dart'; +import 'package:flutter_tools/src/artifacts.dart'; +import 'package:flutter_tools/src/base/common.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/build_system/build_system.dart'; +import 'package:flutter_tools/src/features.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli; +import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode, Target; +import 'package:package_config/package_config_types.dart'; + +import '../../src/common.dart'; +import '../../src/context.dart'; +import '../../src/fakes.dart'; +import '../fake_native_assets_build_runner.dart'; + +void main() { + late FakeProcessManager processManager; + late Environment environment; + late Artifacts artifacts; + late FileSystem fileSystem; + late BufferLogger logger; + late Uri projectUri; + + setUp(() { + processManager = FakeProcessManager.empty(); + logger = BufferLogger.test(); + artifacts = Artifacts.test(); + fileSystem = MemoryFileSystem.test(); + environment = Environment.test( + fileSystem.currentDirectory, + inputs: {}, + artifacts: artifacts, + processManager: processManager, + fileSystem: fileSystem, + logger: logger, + ); + environment.buildDir.createSync(recursive: true); + projectUri = environment.projectDir.uri; + }); + + testUsingContext('dry run with no package config', overrides: { + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + expect( + await dryRunNativeAssetsAndroid( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: FakeNativeAssetsBuildRunner( + hasPackageConfigResult: false, + ), + ), + null, + ); + expect( + (globals.logger as BufferLogger).traceText, + contains('No package config found. Skipping native assets compilation.'), + ); + }); + + testUsingContext('build with no package config', overrides: { + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + await buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: FakeNativeAssetsBuildRunner( + hasPackageConfigResult: false, + ), + ); + expect( + (globals.logger as BufferLogger).traceText, + contains('No package config found. Skipping native assets compilation.'), + ); + }); + + testUsingContext('dry run with assets but not enabled', overrides: { + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + expect( + () => dryRunNativeAssetsAndroid( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + ), + ), + throwsToolExit( + message: 'Package(s) bar require the native assets feature to be enabled. ' + 'Enable using `flutter config --enable-native-assets`.', + ), + ); + }); + + testUsingContext('dry run with assets', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + final Uri? nativeAssetsYaml = await dryRunNativeAssetsAndroid( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + dryRunResult: FakeNativeAssetsBuilderResult( + assets: [ + Asset( + id: 'package:bar/bar.dart', + linkMode: LinkMode.dynamic, + target: native_assets_cli.Target.macOSArm64, + path: AssetAbsolutePath(Uri.file('libbar.so')), + ), + Asset( + id: 'package:bar/bar.dart', + linkMode: LinkMode.dynamic, + target: native_assets_cli.Target.macOSX64, + path: AssetAbsolutePath(Uri.file('libbar.so')), + ), + ], + ), + ), + ); + expect( + (globals.logger as BufferLogger).traceText, + stringContainsInOrder([ + 'Dry running native assets for android.', + 'Dry running native assets for android done.', + ]), + ); + expect( + nativeAssetsYaml, + projectUri.resolve('build/native_assets/android/native_assets.yaml'), + ); + expect( + await fileSystem.file(nativeAssetsYaml).readAsString(), + contains('package:bar/bar.dart'), + ); + }); + + testUsingContext('build with assets but not enabled', () async { + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + expect( + () => buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + ), + ), + throwsToolExit( + message: 'Package(s) bar require the native assets feature to be enabled. ' + 'Enable using `flutter config --enable-native-assets`.', + ), + ); + }); + + testUsingContext('build no assets', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + await buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + ), + ); + expect( + environment.buildDir.childFile('native_assets.yaml'), + exists, + ); + }); + + testUsingContext('build with assets', + skip: const LocalPlatform().isWindows, // [intended] Backslashes in commands, but we will never run these commands on Windows. + overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + final File dylibAfterCompiling = fileSystem.file('libbar.so'); + // The mock doesn't create the file, so create it here. + await dylibAfterCompiling.create(); + await buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + buildResult: FakeNativeAssetsBuilderResult( + assets: [ + Asset( + id: 'package:bar/bar.dart', + linkMode: LinkMode.dynamic, + target: native_assets_cli.Target.androidArm64, + path: AssetAbsolutePath(Uri.file('libbar.so')), + ), + ], + ), + ), + ); + expect( + (globals.logger as BufferLogger).traceText, + stringContainsInOrder([ + 'Building native assets for [android_arm64] debug.', + 'Building native assets for [android_arm64] done.', + ]), + ); + expect( + environment.buildDir.childFile('native_assets.yaml'), + exists, + ); + }); + + // Ensure no exceptions for a non installed NDK are thrown if no native + // assets have to be build. + testUsingContext( + 'does not throw if NDK not present but no native assets present', + overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.create(recursive: true); + await buildNativeAssetsAndroid( + androidArchs: [AndroidArch.x86_64], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + buildRunner: _BuildRunnerWithoutNdk(), + ); + expect( + (globals.logger as BufferLogger).traceText, + isNot(contains('Building native assets for ')), + ); + }); + + testUsingContext('throw if NDK not present and there are native assets', + overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + expect( + () => buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: _BuildRunnerWithoutNdk( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + ), + ), + throwsToolExit( + message: 'Android NDK Clang could not be found.', + ), + ); + }); + + + testUsingContext('Native assets dry run error', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + expect( + () => dryRunNativeAssetsAndroid( + projectUri: projectUri, + fileSystem: fileSystem, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + dryRunResult: const FakeNativeAssetsBuilderResult( + success: false, + ), + ), + ), + throwsToolExit( + message: + 'Building native assets failed. See the logs for more details.', + ), + ); + }); + + testUsingContext('Native assets build error', overrides: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + ProcessManager: () => FakeProcessManager.empty(), + }, () async { + final File packageConfig = + environment.projectDir.childFile('.dart_tool/package_config.json'); + await packageConfig.parent.create(); + await packageConfig.create(); + expect( + () => buildNativeAssetsAndroid( + androidArchs: [AndroidArch.arm64_v8a], + targetAndroidNdkApi: 21, + projectUri: projectUri, + buildMode: BuildMode.debug, + fileSystem: fileSystem, + yamlParentDirectory: environment.buildDir.uri, + buildRunner: FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + buildResult: const FakeNativeAssetsBuilderResult( + success: false, + ), + ), + ), + throwsToolExit( + message: + 'Building native assets failed. See the logs for more details.', + ), + ); + }); +} + +class _BuildRunnerWithoutNdk extends FakeNativeAssetsBuildRunner { + _BuildRunnerWithoutNdk({ + super.packagesWithNativeAssetsResult = const [], + }); + + @override + Future get ndkCCompilerConfig async => + throwToolExit('Android NDK Clang could not be found.'); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/template_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/template_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..5a915e5931225b2100338ffea1327eb89ec467c7 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android/template_test.dart @@ -0,0 +1,47 @@ +// 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/base/logger.dart'; +import 'package:flutter_tools/src/isolated/mustache_template.dart'; +import 'package:flutter_tools/src/template.dart'; + +import '../../src/common.dart'; + +void main() { + + testWithoutContext('kotlin reserved keywords', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final BufferLogger logger = BufferLogger.test(); + final Directory rootDir = fileSystem.currentDirectory; + final Directory templateSource = rootDir.childDirectory('src'); + final Directory imageSourceDir = templateSource; + final Directory destination = rootDir.childDirectory('dest'); + + const String outputClass = 'SomeClass.kt'; + + final File sourceFile = templateSource.childFile('$outputClass.tmpl'); + + templateSource.createSync(); + sourceFile.writeAsStringSync('package {{androidIdentifier}};'); + + final Template template = Template( + templateSource, + imageSourceDir, + fileSystem: fileSystem, + logger: logger, + templateRenderer: const MustacheTemplateRenderer(), + ); + + final Map context = { + 'androidIdentifier': 'is.in.when.there', + }; + template.render(destination, context); + + final File destinationFile = destination.childFile(outputClass); + expect(destinationFile.readAsStringSync(), equals('package `is`.`in`.`when`.there;')); + }); + +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android_plugin_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android_plugin_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8a42e97b393e9e373a5db1a1e8e18e5f4c58189e --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/android_plugin_test.dart @@ -0,0 +1,154 @@ +// 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/platform_plugins.dart'; + +import '../src/common.dart'; + +void main() { + testWithoutContext('AndroidPlugin throws tool exit if the plugin main class can not be found', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + package: 'com.company', + pluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + expect(() => androidPlugin.toMap(), throwsToolExit( + message: "The plugin `pluginA` doesn't have a main class defined in " + '.pub_cache/plugin_a/android/src/main/java/com/company/PluginA.java ' + 'or .pub_cache/plugin_a/android/src/main/kotlin/com/company/PluginA.kt' + )); + }); + + testWithoutContext('AndroidPlugin does not validate the main class for Dart-only plugins', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + dartPluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'dartPluginClass': 'PluginA', + 'supportsEmbeddingV1': false, + 'supportsEmbeddingV2': false, + }); + }); + + testWithoutContext('AndroidPlugin does not validate the main class for default_package', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + defaultPackage: 'plugin_a_android', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'default_package': 'plugin_a_android', + 'supportsEmbeddingV1': false, + 'supportsEmbeddingV2': false, + }); + }); + + testWithoutContext('AndroidPlugin parses embedding version 2 from the Java search path', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + package: 'com.company', + pluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + fileSystem.file('.pub_cache/plugin_a/android/src/main/java/com/company/PluginA.java') + ..createSync(recursive: true) + ..writeAsStringSync('io.flutter.embedding.engine.plugins.FlutterPlugin'); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'package': 'com.company', + 'class': 'PluginA', + 'supportsEmbeddingV1': false, + 'supportsEmbeddingV2': true, + }); + }); + + testWithoutContext('AndroidPlugin parses embedding version 1 from the Java search path', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + package: 'com.company', + pluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + fileSystem.file('.pub_cache/plugin_a/android/src/main/java/com/company/PluginA.java') + ..createSync(recursive: true) + ..writeAsStringSync('some.other.string'); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'package': 'com.company', + 'class': 'PluginA', + 'supportsEmbeddingV1': true, + 'supportsEmbeddingV2': false, + }); + }); + + testWithoutContext('AndroidPlugin parses embedding version 2 from the Kotlin search path', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + package: 'com.company', + pluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + fileSystem.file('.pub_cache/plugin_a/android/src/main/kotlin/com/company/PluginA.kt') + ..createSync(recursive: true) + ..writeAsStringSync('io.flutter.embedding.engine.plugins.FlutterPlugin'); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'package': 'com.company', + 'class': 'PluginA', + 'supportsEmbeddingV1': false, + 'supportsEmbeddingV2': true, + }); + }); + + testWithoutContext('AndroidPlugin parses embedding version 1 from the Kotlin search path', () { + final FileSystem fileSystem = MemoryFileSystem.test(); + final AndroidPlugin androidPlugin = AndroidPlugin( + name: 'pluginA', + package: 'com.company', + pluginClass: 'PluginA', + pluginPath: '.pub_cache/plugin_a', + fileSystem: fileSystem, + ); + + fileSystem.file('.pub_cache/plugin_a/android/src/main/kotlin/com/company/PluginA.kt') + ..createSync(recursive: true) + ..writeAsStringSync('some.other.string'); + + expect(androidPlugin.toMap(), { + 'name': 'pluginA', + 'package': 'com.company', + 'class': 'PluginA', + 'supportsEmbeddingV1': true, + 'supportsEmbeddingV2': false, + }); + }); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/application_package_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/application_package_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e7e04cdfc6d12f40cff1ee9aa71c085c5f753179 --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/application_package_test.dart @@ -0,0 +1,980 @@ +// 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_sdk.dart'; +import 'package:flutter_tools/src/android/application_package.dart'; +import 'package:flutter_tools/src/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/os.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/fuchsia/application_package.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/ios/application_package.dart'; +import 'package:flutter_tools/src/ios/plist_parser.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/fake_process_manager.dart'; +import '../src/fakes.dart'; + +void main() { + group('Apk with partial Android SDK works', () { + late FakeAndroidSdk sdk; + late FakeProcessManager fakeProcessManager; + late MemoryFileSystem fs; + late Cache cache; + + final Map overrides = { + AndroidSdk: () => sdk, + ProcessManager: () => fakeProcessManager, + FileSystem: () => fs, + Cache: () => cache, + }; + + setUp(() async { + sdk = FakeAndroidSdk(); + fakeProcessManager = FakeProcessManager.empty(); + fs = MemoryFileSystem.test(); + cache = Cache.test( + processManager: FakeProcessManager.any(), + ); + Cache.flutterRoot = '../..'; + sdk.licensesAvailable = true; + final FlutterProject project = FlutterProject.fromDirectoryTest(fs.currentDirectory); + fs.file(project.android.hostAppGradleRoot.childFile( + globals.platform.isWindows ? 'gradlew.bat' : 'gradlew', + ).path).createSync(recursive: true); + }); + + testUsingContext('correct debug filename in module projects', () async { + const String aaptPath = 'aaptPath'; + final File apkFile = globals.fs.file('app-debug.apk'); + final FakeAndroidSdkVersion sdkVersion = FakeAndroidSdkVersion(); + sdkVersion.aaptPath = aaptPath; + sdk.latestVersion = sdkVersion; + sdk.platformToolsAvailable = true; + sdk.licensesAvailable = false; + + fakeProcessManager.addCommand( + FakeCommand( + command: [ + aaptPath, + 'dump', + 'xmltree', + apkFile.path, + 'AndroidManifest.xml', + ], + stdout: _aaptDataWithDefaultEnabledAndMainLauncherActivity + ) + ); + + fakeProcessManager.addCommand( + FakeCommand( + command: [ + aaptPath, + 'dump', + 'xmltree', + fs.path.join('module_project', 'build', 'host', 'outputs', 'apk', 'debug', 'app-debug.apk'), + 'AndroidManifest.xml', + ], + stdout: _aaptDataWithDefaultEnabledAndMainLauncherActivity + ) + ); + + await ApplicationPackageFactory.instance!.getPackageForPlatform( + TargetPlatform.android_arm, + applicationBinary: apkFile, + ); + final BufferLogger logger = BufferLogger.test(); + final FlutterProject project = await aModuleProject(); + project.android.hostAppGradleRoot.childFile('build.gradle').createSync(recursive: true); + final File appGradle = project.android.hostAppGradleRoot.childFile( + fs.path.join('app', 'build.gradle')); + appGradle.createSync(recursive: true); + appGradle.writeAsStringSync("def flutterPluginVersion = 'managed'"); + final File apkDebugFile = project.directory + .childDirectory('build') + .childDirectory('host') + .childDirectory('outputs') + .childDirectory('apk') + .childDirectory('debug') + .childFile('app-debug.apk'); + apkDebugFile.createSync(recursive: true); + final AndroidApk? androidApk = await AndroidApk.fromAndroidProject( + project.android, + androidSdk: sdk, + processManager: fakeProcessManager, + userMessages: UserMessages(), + processUtils: ProcessUtils(processManager: fakeProcessManager, logger: logger), + logger: logger, + fileSystem: fs, + buildInfo: const BuildInfo(BuildMode.debug, null, treeShakeIcons: false), + ); + expect(androidApk, isNotNull); + }, overrides: overrides); + + testUsingContext('Licenses not available, platform and buildtools available, apk exists', () async { + const String aaptPath = 'aaptPath'; + final File apkFile = globals.fs.file('app-debug.apk'); + final FakeAndroidSdkVersion sdkVersion = FakeAndroidSdkVersion(); + sdkVersion.aaptPath = aaptPath; + sdk.latestVersion = sdkVersion; + sdk.platformToolsAvailable = true; + sdk.licensesAvailable = false; + + fakeProcessManager.addCommand( + FakeCommand( + command: [ + aaptPath, + 'dump', + 'xmltree', + apkFile.path, + 'AndroidManifest.xml', + ], + stdout: _aaptDataWithDefaultEnabledAndMainLauncherActivity + ) + ); + + final ApplicationPackage applicationPackage = (await ApplicationPackageFactory.instance!.getPackageForPlatform( + TargetPlatform.android_arm, + applicationBinary: apkFile, + ))!; + expect(applicationPackage.name, 'app-debug.apk'); + expect(applicationPackage, isA()); + expect((applicationPackage as PrebuiltApplicationPackage).applicationPackage.path, apkFile.path); + expect(fakeProcessManager, hasNoRemainingExpectations); + }, overrides: overrides); + + testUsingContext('Licenses available, build tools not, apk exists', () async { + sdk.latestVersion = null; + final FlutterProject project = FlutterProject.fromDirectoryTest(fs.currentDirectory); + project.android.hostAppGradleRoot + .childFile('gradle.properties') + .writeAsStringSync('irrelevant'); + + final Directory gradleWrapperDir = cache.getArtifactDirectory('gradle_wrapper'); + + gradleWrapperDir.fileSystem.directory(gradleWrapperDir.childDirectory('gradle').childDirectory('wrapper')) + .createSync(recursive: true); + gradleWrapperDir.childFile('gradlew').writeAsStringSync('irrelevant'); + gradleWrapperDir.childFile('gradlew.bat').writeAsStringSync('irrelevant'); + + await ApplicationPackageFactory.instance!.getPackageForPlatform( + TargetPlatform.android_arm, + applicationBinary: globals.fs.file('app-debug.apk'), + ); + expect(fakeProcessManager, hasNoRemainingExpectations); + }, overrides: overrides); + + testUsingContext('Licenses available, build tools available, does not call gradle dependencies', () async { + final AndroidSdkVersion sdkVersion = FakeAndroidSdkVersion(); + sdk.latestVersion = sdkVersion; + + await ApplicationPackageFactory.instance!.getPackageForPlatform( + TargetPlatform.android_arm, + ); + expect(fakeProcessManager, hasNoRemainingExpectations); + }, overrides: overrides); + + testWithoutContext('returns null when failed to extract manifest', () async { + final Logger logger = BufferLogger.test(); + final AndroidApk? androidApk = AndroidApk.fromApk( + fs.file(''), + processManager: fakeProcessManager, + logger: logger, + userMessages: UserMessages(), + androidSdk: sdk, + processUtils: ProcessUtils(processManager: fakeProcessManager, logger: logger), + ); + + expect(androidApk, isNull); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); + }); + + group('ApkManifestData', () { + testWithoutContext('Parses manifest with an Activity that has enabled set to true, action set to android.intent.action.MAIN and category set to android.intent.category.LAUNCHER', () { + final ApkManifestData data = ApkManifestData.parseFromXmlDump( + _aaptDataWithExplicitEnabledAndMainLauncherActivity, + BufferLogger.test(), + )!; + + expect(data, isNotNull); + expect(data.packageName, 'io.flutter.examples.hello_world'); + expect(data.launchableActivityName, 'io.flutter.examples.hello_world.MainActivity2'); + }); + + testWithoutContext('Parses manifest with an Activity that has no value for its enabled field, action set to android.intent.action.MAIN and category set to android.intent.category.LAUNCHER', () { + final ApkManifestData data = ApkManifestData.parseFromXmlDump( + _aaptDataWithDefaultEnabledAndMainLauncherActivity, + BufferLogger.test(), + )!; + + expect(data, isNotNull); + expect(data.packageName, 'io.flutter.examples.hello_world'); + expect(data.launchableActivityName, 'io.flutter.examples.hello_world.MainActivity2'); + }); + + testWithoutContext('Parses manifest with a dist namespace', () { + final ApkManifestData data = ApkManifestData.parseFromXmlDump( + _aaptDataWithDistNamespace, + BufferLogger.test(), + )!; + + expect(data, isNotNull); + expect(data.packageName, 'io.flutter.examples.hello_world'); + expect(data.launchableActivityName, 'io.flutter.examples.hello_world.MainActivity'); + }); + + testWithoutContext('Error when parsing manifest with no Activity that has enabled set to true nor has no value for its enabled field', () { + final BufferLogger logger = BufferLogger.test(); + final ApkManifestData? data = ApkManifestData.parseFromXmlDump( + _aaptDataWithNoEnabledActivity, + logger, + ); + + expect(data, isNull); + expect( + logger.errorText, + 'Error running io.flutter.examples.hello_world. Default activity not found\n', + ); + }); + + testWithoutContext('Error when parsing manifest with no Activity that has action set to android.intent.action.MAIN', () { + final BufferLogger logger = BufferLogger.test(); + final ApkManifestData? data = ApkManifestData.parseFromXmlDump( + _aaptDataWithNoMainActivity, + logger, + ); + + expect(data, isNull); + expect( + logger.errorText, + 'Error running io.flutter.examples.hello_world. Default activity not found\n', + ); + }); + + testWithoutContext('Error when parsing manifest with no Activity that has category set to android.intent.category.LAUNCHER', () { + final BufferLogger logger = BufferLogger.test(); + final ApkManifestData? data = ApkManifestData.parseFromXmlDump( + _aaptDataWithNoLauncherActivity, + logger, + ); + + expect(data, isNull); + expect( + logger.errorText, + 'Error running io.flutter.examples.hello_world. Default activity not found\n', + ); + }); + + testWithoutContext('Parsing manifest with Activity that has multiple category, android.intent.category.LAUNCHER and android.intent.category.DEFAULT', () { + final ApkManifestData data = ApkManifestData.parseFromXmlDump( + _aaptDataWithLauncherAndDefaultActivity, + BufferLogger.test(), + )!; + + expect(data, isNotNull); + expect(data.packageName, 'io.flutter.examples.hello_world'); + expect(data.launchableActivityName, 'io.flutter.examples.hello_world.MainActivity'); + }); + + testWithoutContext('Parses manifest with missing application tag', () async { + final ApkManifestData? data = ApkManifestData.parseFromXmlDump( + _aaptDataWithoutApplication, + BufferLogger.test(), + ); + + expect(data, isNull); + }); + }); + + group('PrebuiltIOSApp', () { + late FakeOperatingSystemUtils os; + late FakePlistParser testPlistParser; + + final Map overrides = { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + PlistParser: () => testPlistParser, + OperatingSystemUtils: () => os, + }; + + setUp(() { + os = FakeOperatingSystemUtils(); + testPlistParser = FakePlistParser(); + }); + + testUsingContext('Error on non-existing file', () { + final PrebuiltIOSApp? iosApp = + IOSApp.fromPrebuiltApp(globals.fs.file('not_existing.ipa')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect( + testLogger.errorText, + 'File "not_existing.ipa" does not exist. Use an app bundle or an ipa.\n', + ); + }, overrides: overrides); + + testUsingContext('Error on non-app-bundle folder', () { + globals.fs.directory('regular_folder').createSync(); + final PrebuiltIOSApp? iosApp = + IOSApp.fromPrebuiltApp(globals.fs.file('regular_folder')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect( + testLogger.errorText, 'Folder "regular_folder" is not an app bundle.\n'); + }, overrides: overrides); + + testUsingContext('Error on no info.plist', () { + globals.fs.directory('bundle.app').createSync(); + final PrebuiltIOSApp? iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('bundle.app')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect( + testLogger.errorText, + 'Invalid prebuilt iOS app. Does not contain Info.plist.\n', + ); + }, overrides: overrides); + + testUsingContext('Error on bad info.plist', () { + globals.fs.directory('bundle.app').createSync(); + globals.fs.file('bundle.app/Info.plist').createSync(); + final PrebuiltIOSApp? iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('bundle.app')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect( + testLogger.errorText, + contains( + 'Invalid prebuilt iOS app. Info.plist does not contain bundle identifier\n'), + ); + }, overrides: overrides); + + testUsingContext('Success with app bundle', () { + globals.fs.directory('bundle.app').createSync(); + globals.fs.file('bundle.app/Info.plist').createSync(); + testPlistParser.setProperty('CFBundleIdentifier', 'fooBundleId'); + final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('bundle.app'))! as PrebuiltIOSApp; + expect(testLogger.errorText, isEmpty); + expect(iosApp.uncompressedBundle.path, 'bundle.app'); + expect(iosApp.id, 'fooBundleId'); + expect(iosApp.bundleName, 'bundle.app'); + expect(iosApp.applicationPackage.path, globals.fs.directory('bundle.app').path); + }, overrides: overrides); + + testUsingContext('Bad ipa zip-file, no payload dir', () { + globals.fs.file('app.ipa').createSync(); + final PrebuiltIOSApp? iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('app.ipa')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect( + testLogger.errorText, + 'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.\n', + ); + }, overrides: overrides); + + testUsingContext('Bad ipa zip-file, two app bundles', () { + globals.fs.file('app.ipa').createSync(); + os.onUnzip = (File zipFile, Directory targetDirectory) { + if (zipFile.path != 'app.ipa') { + return; + } + final String bundlePath1 = + globals.fs.path.join(targetDirectory.path, 'Payload', 'bundle1.app'); + final String bundlePath2 = + globals.fs.path.join(targetDirectory.path, 'Payload', 'bundle2.app'); + globals.fs.directory(bundlePath1).createSync(recursive: true); + globals.fs.directory(bundlePath2).createSync(recursive: true); + }; + final PrebuiltIOSApp? iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('app.ipa')) as PrebuiltIOSApp?; + expect(iosApp, isNull); + expect(testLogger.errorText, + 'Invalid prebuilt iOS ipa. Does not contain a single app bundle.\n'); + }, overrides: overrides); + + testUsingContext('Success with ipa', () { + globals.fs.file('app.ipa').createSync(); + os.onUnzip = (File zipFile, Directory targetDirectory) { + if (zipFile.path != 'app.ipa') { + return; + } + final Directory bundleAppDir = globals.fs.directory( + globals.fs.path.join(targetDirectory.path, 'Payload', 'bundle.app')); + bundleAppDir.createSync(recursive: true); + testPlistParser.setProperty('CFBundleIdentifier', 'fooBundleId'); + globals.fs + .file(globals.fs.path.join(bundleAppDir.path, 'Info.plist')) + .createSync(); + }; + final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(globals.fs.file('app.ipa'))! as PrebuiltIOSApp; + expect(testLogger.errorText, isEmpty); + expect(iosApp.uncompressedBundle.path, endsWith('bundle.app')); + expect(iosApp.id, 'fooBundleId'); + expect(iosApp.bundleName, 'bundle.app'); + expect(iosApp.applicationPackage.path, globals.fs.file('app.ipa').path); + }, overrides: overrides); + + testUsingContext('returns null when there is no ios or .ios directory', () async { + globals.fs.file('pubspec.yaml').createSync(); + globals.fs.file('.packages').createSync(); + final BuildableIOSApp? iosApp = await IOSApp.fromIosProject( + FlutterProject.fromDirectory(globals.fs.currentDirectory).ios, null) as BuildableIOSApp?; + + expect(iosApp, null); + }, overrides: overrides); + + testUsingContext('returns null when there is no Runner.xcodeproj', () async { + globals.fs.file('pubspec.yaml').createSync(); + globals.fs.file('.packages').createSync(); + globals.fs.file('ios/FooBar.xcodeproj').createSync(recursive: true); + final BuildableIOSApp? iosApp = await IOSApp.fromIosProject( + FlutterProject.fromDirectory(globals.fs.currentDirectory).ios, null) as BuildableIOSApp?; + + expect(iosApp, null); + }, overrides: overrides); + + testUsingContext('returns null when there is no Runner.xcodeproj/project.pbxproj', () async { + globals.fs.file('pubspec.yaml').createSync(); + globals.fs.file('.packages').createSync(); + globals.fs.file('ios/Runner.xcodeproj').createSync(recursive: true); + final BuildableIOSApp? iosApp = await IOSApp.fromIosProject( + FlutterProject.fromDirectory(globals.fs.currentDirectory).ios, null) as BuildableIOSApp?; + + expect(iosApp, null); + }, overrides: overrides); + + testUsingContext('returns null when there with no product identifier', () async { + globals.fs.file('pubspec.yaml').createSync(); + globals.fs.file('.packages').createSync(); + final Directory project = globals.fs.directory('ios/Runner.xcodeproj')..createSync(recursive: true); + project.childFile('project.pbxproj').createSync(); + final BuildableIOSApp? iosApp = await IOSApp.fromIosProject( + FlutterProject.fromDirectory(globals.fs.currentDirectory).ios, null) as BuildableIOSApp?; + + expect(iosApp, null); + }, overrides: overrides); + + testUsingContext('returns project app icon dirname', () async { + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner', + ); + final String iconDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'AppIcon.appiconset', + ); + expect(iosApp.projectAppIconDirName, globals.fs.path.join('ios', iconDirSuffix)); + }, overrides: overrides); + + testUsingContext('returns template app icon dirname for Contents.json', () async { + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner', + ); + final String iconDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'AppIcon.appiconset', + ); + expect( + iosApp.templateAppIconDirNameForContentsJson, + globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + 'templates', + 'app_shared', + 'ios.tmpl', + iconDirSuffix, + ), + ); + }, overrides: overrides); + + testUsingContext('returns template app icon dirname for images', () async { + final String toolsDir = globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + ); + final String packageConfigPath = globals.fs.path.join( + toolsDir, + '.dart_tool', + 'package_config.json' + ); + globals.fs.file(packageConfigPath) + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "flutter_template_images", + "rootUri": "/flutter_template_images", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner'); + final String iconDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'AppIcon.appiconset', + ); + expect( + await iosApp.templateAppIconDirNameForImages, + globals.fs.path.absolute( + 'flutter_template_images', + 'templates', + 'app_shared', + 'ios.tmpl', + iconDirSuffix, + ), + ); + }, overrides: overrides); + + testUsingContext('returns project launch image dirname', () async { + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner', + ); + final String launchImageDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'LaunchImage.imageset', + ); + expect(iosApp.projectLaunchImageDirName, globals.fs.path.join('ios', launchImageDirSuffix)); + }, overrides: overrides); + + testUsingContext('returns template launch image dirname for Contents.json', () async { + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner', + ); + final String launchImageDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'LaunchImage.imageset', + ); + expect( + iosApp.templateLaunchImageDirNameForContentsJson, + globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + 'templates', + 'app_shared', + 'ios.tmpl', + launchImageDirSuffix, + ), + ); + }, overrides: overrides); + + testUsingContext('returns template launch image dirname for images', () async { + final String toolsDir = globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + ); + final String packageConfigPath = globals.fs.path.join( + toolsDir, + '.dart_tool', + 'package_config.json' + ); + globals.fs.file(packageConfigPath) + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "flutter_template_images", + "rootUri": "/flutter_template_images", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + final BuildableIOSApp iosApp = BuildableIOSApp( + IosProject.fromFlutter(FlutterProject.fromDirectory(globals.fs.currentDirectory)), + 'com.foo.bar', + 'Runner'); + final String launchImageDirSuffix = globals.fs.path.join( + 'Runner', + 'Assets.xcassets', + 'LaunchImage.imageset', + ); + expect( + await iosApp.templateLaunchImageDirNameForImages, + globals.fs.path.absolute( + 'flutter_template_images', + 'templates', + 'app_shared', + 'ios.tmpl', + launchImageDirSuffix, + ), + ); + }, overrides: overrides); + }); + + group('FuchsiaApp', () { + final Map overrides = { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + OperatingSystemUtils: () => FakeOperatingSystemUtils(), + }; + + testUsingContext('Error on non-existing file', () { + final PrebuiltFuchsiaApp? fuchsiaApp = + FuchsiaApp.fromPrebuiltApp(globals.fs.file('not_existing.far')) as PrebuiltFuchsiaApp?; + expect(fuchsiaApp, isNull); + expect( + testLogger.errorText, + 'File "not_existing.far" does not exist or is not a .far file. Use far archive.\n', + ); + }, overrides: overrides); + + testUsingContext('Error on non-far file', () { + globals.fs.directory('regular_folder').createSync(); + final PrebuiltFuchsiaApp? fuchsiaApp = + FuchsiaApp.fromPrebuiltApp(globals.fs.file('regular_folder')) as PrebuiltFuchsiaApp?; + expect(fuchsiaApp, isNull); + expect( + testLogger.errorText, + 'File "regular_folder" does not exist or is not a .far file. Use far archive.\n', + ); + }, overrides: overrides); + + testUsingContext('Success with far file', () { + globals.fs.file('bundle.far').createSync(); + final PrebuiltFuchsiaApp fuchsiaApp = FuchsiaApp.fromPrebuiltApp(globals.fs.file('bundle.far'))! as PrebuiltFuchsiaApp; + expect(testLogger.errorText, isEmpty); + expect(fuchsiaApp.id, 'bundle.far'); + expect(fuchsiaApp.applicationPackage.path, globals.fs.file('bundle.far').path); + }, overrides: overrides); + + testUsingContext('returns null when there is no fuchsia', () async { + globals.fs.file('pubspec.yaml').createSync(); + globals.fs.file('.packages').createSync(); + final BuildableFuchsiaApp? fuchsiaApp = FuchsiaApp.fromFuchsiaProject(FlutterProject.fromDirectory(globals.fs.currentDirectory).fuchsia) as BuildableFuchsiaApp?; + + expect(fuchsiaApp, null); + }, overrides: overrides); + }); +} + +const String _aaptDataWithExplicitEnabledAndMainLauncherActivity = ''' +N: android=http://schemas.android.com/apk/res/android + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + E: uses-sdk (line=12) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1b + E: uses-permission (line=21) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=29) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff + E: activity (line=34) + A: android:theme(0x01010000)=@0x1030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:enabled(0x0101000e)=(type 0x12)0x0 + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400035b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=42) + E: action (line=43) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=45) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER") + E: activity (line=48) + A: android:theme(0x01010000)=@0x1030009 + A: android:label(0x01010001)="app2" (Raw: "app2") + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity2" (Raw: "io.flutter.examples.hello_world.MainActivity2") + A: android:enabled(0x0101000e)=(type 0x12)0xffffffff + E: intent-filter (line=53) + E: action (line=54) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=56) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")'''; + + +const String _aaptDataWithDefaultEnabledAndMainLauncherActivity = ''' +N: android=http://schemas.android.com/apk/res/android + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + E: uses-sdk (line=12) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1b + E: uses-permission (line=21) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=29) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff + E: activity (line=34) + A: android:theme(0x01010000)=@0x1030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:enabled(0x0101000e)=(type 0x12)0x0 + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400035b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=42) + E: action (line=43) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=45) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER") + E: activity (line=48) + A: android:theme(0x01010000)=@0x1030009 + A: android:label(0x01010001)="app2" (Raw: "app2") + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity2" (Raw: "io.flutter.examples.hello_world.MainActivity2") + E: intent-filter (line=53) + E: action (line=54) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=56) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")'''; + + +const String _aaptDataWithNoEnabledActivity = ''' +N: android=http://schemas.android.com/apk/res/android + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + E: uses-sdk (line=12) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1b + E: uses-permission (line=21) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=29) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff + E: activity (line=34) + A: android:theme(0x01010000)=@0x1030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:enabled(0x0101000e)=(type 0x12)0x0 + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400035b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=42) + E: action (line=43) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=45) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")'''; + +const String _aaptDataWithNoMainActivity = ''' +N: android=http://schemas.android.com/apk/res/android + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + E: uses-sdk (line=12) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1b + E: uses-permission (line=21) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=29) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff + E: activity (line=34) + A: android:theme(0x01010000)=@0x1030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:enabled(0x0101000e)=(type 0x12)0xffffffff + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400035b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=42) + E: category (line=43) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")'''; + +const String _aaptDataWithNoLauncherActivity = ''' +N: android=http://schemas.android.com/apk/res/android + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="0.0.1" (Raw: "0.0.1") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + E: uses-sdk (line=12) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1b + E: uses-permission (line=21) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=29) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff + E: activity (line=34) + A: android:theme(0x01010000)=@0x1030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:enabled(0x0101000e)=(type 0x12)0xffffffff + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400035b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=42) + E: action (line=43) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN")'''; + +const String _aaptDataWithLauncherAndDefaultActivity = ''' +N: android=http://schemas.android.com/apk/res/android + N: dist=http://schemas.android.com/apk/distribution + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="1.0" (Raw: "1.0") + A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1c + A: android:compileSdkVersionCodename(0x01010573)="9" (Raw: "9") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + A: platformBuildVersionCode=(type 0x10)0x1 + A: platformBuildVersionName=(type 0x4)0x3f800000 + E: uses-sdk (line=13) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1c + E: dist:module (line=17) + A: dist:instant=(type 0x12)0xffffffff + E: uses-permission (line=24) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=32) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + E: activity (line=36) + A: android:theme(0x01010000)=@0x01030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400037b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=43) + E: action (line=44) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=46) + A: android:name(0x01010003)="android.intent.category.DEFAULT" (Raw: "android.intent.category.DEFAULT") + E: category (line=47) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER") +'''; + +const String _aaptDataWithDistNamespace = ''' +N: android=http://schemas.android.com/apk/res/android + N: dist=http://schemas.android.com/apk/distribution + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="1.0" (Raw: "1.0") + A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1c + A: android:compileSdkVersionCodename(0x01010573)="9" (Raw: "9") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + A: platformBuildVersionCode=(type 0x10)0x1 + A: platformBuildVersionName=(type 0x4)0x3f800000 + E: uses-sdk (line=13) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1c + E: dist:module (line=17) + A: dist:instant=(type 0x12)0xffffffff + E: uses-permission (line=24) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") + E: application (line=32) + A: android:label(0x01010001)="hello_world" (Raw: "hello_world") + A: android:icon(0x01010002)=@0x7f010000 + A: android:name(0x01010003)="io.flutter.app.FlutterApplication" (Raw: "io.flutter.app.FlutterApplication") + E: activity (line=36) + A: android:theme(0x01010000)=@0x01030009 + A: android:name(0x01010003)="io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") + A: android:launchMode(0x0101001d)=(type 0x10)0x1 + A: android:configChanges(0x0101001f)=(type 0x11)0x400037b4 + A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10 + A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff + E: intent-filter (line=43) + E: action (line=44) + A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN") + E: category (line=46) + A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER") +'''; + +const String _aaptDataWithoutApplication = ''' +N: android=http://schemas.android.com/apk/res/android + N: dist=http://schemas.android.com/apk/distribution + E: manifest (line=7) + A: android:versionCode(0x0101021b)=(type 0x10)0x1 + A: android:versionName(0x0101021c)="1.0" (Raw: "1.0") + A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1c + A: android:compileSdkVersionCodename(0x01010573)="9" (Raw: "9") + A: package="io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") + A: platformBuildVersionCode=(type 0x10)0x1 + A: platformBuildVersionName=(type 0x4)0x3f800000 + E: uses-sdk (line=13) + A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10 + A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1c + E: dist:module (line=17) + A: dist:instant=(type 0x12)0xffffffff + E: uses-permission (line=24) + A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET") +'''; + +class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { + void Function(File, Directory)? onUnzip; + + @override + void unzip(File file, Directory targetDirectory) { + onUnzip?.call(file, targetDirectory); + } +} + +class FakeAndroidSdk extends Fake implements AndroidSdk { + @override + late bool platformToolsAvailable; + + @override + late bool licensesAvailable; + + @override + AndroidSdkVersion? latestVersion; +} + +class FakeAndroidSdkVersion extends Fake implements AndroidSdkVersion { + @override + late String aaptPath; +} + +Future aModuleProject() async { + final Directory directory = globals.fs.directory('module_project'); + directory + .childDirectory('.dart_tool') + .childFile('package_config.json') + ..createSync(recursive: true) + ..writeAsStringSync('{"configVersion":2,"packages":[]}'); + directory.childFile('pubspec.yaml').writeAsStringSync(''' +name: my_module +flutter: + module: + androidPackage: com.example +'''); + return FlutterProject.fromDirectory(directory); +} diff --git a/novelforge-project/flutter/packages/flutter_tools/test/general.shard/args_test.dart b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/args_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bb04cc8a86ffda0979bca11ed2fa912395065d8e --- /dev/null +++ b/novelforge-project/flutter/packages/flutter_tools/test/general.shard/args_test.dart @@ -0,0 +1,271 @@ +// 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:args/command_runner.dart'; +import 'package:flutter_tools/executable.dart' as executable; +import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/commands/analyze.dart'; +import 'package:flutter_tools/src/runner/flutter_command.dart'; +import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/testbed.dart'; +import 'runner/utils.dart'; + +void main() { + setUpAll(() { + Cache.disableLocking(); + }); + + tearDownAll(() { + Cache.enableLocking(); + }); + + test('Help for command line arguments is consistently styled and complete', () => Testbed().run(() { + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + executable.generateCommands( + verboseHelp: true, + verbose: true, + ).forEach(runner.addCommand); + verifyCommandRunner(runner); + for (final Command command in runner.commands.values) { + if (command.name == 'analyze') { + final AnalyzeCommand analyze = command as AnalyzeCommand; + expect(analyze.allProjectValidators().length, 2); + } + } + })); + + testUsingContext('Global arg results are available in FlutterCommands', () async { + final DummyFlutterCommand command = DummyFlutterCommand( + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + + runner.addCommand(command); + await runner.run(['dummy', '--${FlutterGlobalOptions.kContinuousIntegrationFlag}']); + + expect(command.globalResults, isNotNull); + expect(command.boolArg(FlutterGlobalOptions.kContinuousIntegrationFlag, global: true), true); + }); + + testUsingContext('Global arg results are available in FlutterCommands sub commands', () async { + final DummyFlutterCommand command = DummyFlutterCommand( + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + + final DummyFlutterCommand subcommand = DummyFlutterCommand( + name: 'sub', + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + + command.addSubcommand(subcommand); + + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + + runner.addCommand(command); + runner.addCommand(subcommand); + await runner.run(['dummy', 'sub', '--${FlutterGlobalOptions.kContinuousIntegrationFlag}']); + + expect(subcommand.globalResults, isNotNull); + expect(subcommand.boolArg(FlutterGlobalOptions.kContinuousIntegrationFlag, global: true), true); + }); + + testUsingContext('bool? safe argResults', () async { + final DummyFlutterCommand command = DummyFlutterCommand( + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + command.argParser.addFlag('key'); + command.argParser.addFlag('key-false'); + // argResults will be null at this point, if attempt to read them is made, + // exception `Null check operator used on a null value` would be thrown. + expect(() => command.boolArg('key'), throwsA(const TypeMatcher())); + + runner.addCommand(command); + await runner.run(['dummy', '--key']); + + expect(command.boolArg('key'), true); + expect(() => command.boolArg('non-existent'), throwsArgumentError); + + expect(command.boolArg('key'), true); + expect(() => command.boolArg('non-existent'), throwsA(const TypeMatcher())); + + expect(command.boolArg('key-false'), false); + expect(command.boolArg('key-false'), false); + }); + + testUsingContext('String? safe argResults', () async { + final DummyFlutterCommand command = DummyFlutterCommand( + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + command.argParser.addOption('key'); + // argResults will be null at this point, if attempt to read them is made, + // exception `Null check operator used on a null value` would be thrown + expect(() => command.stringArg('key'), throwsA(const TypeMatcher())); + + runner.addCommand(command); + await runner.run(['dummy', '--key=value']); + + expect(command.stringArg('key'), 'value'); + expect(() => command.stringArg('non-existent'), throwsArgumentError); + + expect(command.stringArg('key'), 'value'); + expect(() => command.stringArg('non-existent'), throwsA(const TypeMatcher())); + }); + + testUsingContext('List safe argResults', () async { + final DummyFlutterCommand command = DummyFlutterCommand( + commandFunction: () async { + return const FlutterCommandResult(ExitStatus.success); + }, + ); + final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); + command.argParser.addMultiOption( + 'key', + allowed: ['a', 'b', 'c'], + ); + // argResults will be null at this point, if attempt to read them is made, + // exception `Null check operator used on a null value` would be thrown. + expect(() => command.stringsArg('key'), throwsA(const TypeMatcher())); + + runner.addCommand(command); + await runner.run(['dummy', '--key', 'a']); + + // throws error when trying to parse non-existent key. + expect(() => command.stringsArg('non-existent'), throwsA(const TypeMatcher())); + + expect(command.stringsArg('key'), ['a']); + + await runner.run(['dummy', '--key', 'a', '--key', 'b']); + expect(command.stringsArg('key'), ['a', 'b']); + + await runner.run(['dummy']); + expect(command.stringsArg('key'), []); + }); +} + +void verifyCommandRunner(CommandRunner runner) { + expect(runner.argParser, isNotNull, reason: '${runner.runtimeType} has no argParser'); + expect(runner.argParser.allowsAnything, isFalse, reason: '${runner.runtimeType} allows anything'); + expect(runner.argParser.allowTrailingOptions, isFalse, reason: '${runner.runtimeType} allows trailing options'); + verifyOptions(null, runner.argParser.options.values); + runner.commands.values.forEach(verifyCommand); +} + +void verifyCommand(Command runner) { + expect(runner.argParser, isNotNull, reason: 'command ${runner.name} has no argParser'); + verifyOptions(runner.name, runner.argParser.options.values); + + final String firstDescriptionLine = runner.description.split('\n').first; + expect(firstDescriptionLine, matches(_allowedTrailingPatterns), reason: "command ${runner.name}'s description does not end with the expected single period that a full sentence should end with"); + + if (!runner.hidden && runner.parent == null) { + expect( + runner.category, + anyOf( + FlutterCommandCategory.sdk, + FlutterCommandCategory.project, + FlutterCommandCategory.tools, + ), + reason: "top-level command ${runner.name} doesn't have a valid category", + ); + } + + runner.subcommands.values.forEach(verifyCommand); +} + +// Patterns for arguments names. +final RegExp _allowedArgumentNamePattern = RegExp(r'^([-a-z0-9]+)$'); +final RegExp _allowedArgumentNamePatternForPrecache = RegExp(r'^([-a-z0-9_]+)$'); +final RegExp _bannedArgumentNamePattern = RegExp(r'-uri$'); + +// Patterns for help messages. +final RegExp _bannedLeadingPatterns = RegExp(r'^[-a-z]', multiLine: true); +final RegExp _allowedTrailingPatterns = RegExp(r'([^ ]([^.^!^:][.!:])\)?|: https?://[^ ]+[^.]|^)$'); +final RegExp _bannedQuotePatterns = RegExp(r" '|' |'\.|\('|'\)|`"); +final RegExp _bannedArgumentReferencePatterns = RegExp(r'[^"=]--[^ ]'); +final RegExp _questionablePatterns = RegExp(r'[a-z]\.[A-Z]'); +final RegExp _bannedUri = RegExp(r'\b[Uu][Rr][Ii]\b'); +final RegExp _nonSecureFlutterDartUrl = RegExp(r'http://([a-z0-9-]+\.)*(flutter|dart)\.dev', caseSensitive: false); +const String _needHelp = "Every option must have help explaining what it does, even if it's " + 'for testing purposes, because this is the bare minimum of ' + 'documentation we can add just for ourselves. If it is not intended ' + 'for developers, then use "hide: !verboseHelp" to only show the ' + 'help when people run with "--help --verbose".'; + +const String _header = ' Comment: '; + +void verifyOptions(String? command, Iterable