Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/adb.dartAdded+18
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android.dartAdded+7
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_builder.dartAdded+53
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_console.dartAdded+84
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device.dartAdded+1365
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dartAdded+199
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_emulator.dartAdded+232
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_sdk.dartAdded+623
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio.dartAdded+579
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dartAdded+141
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_workflow.dartAdded+455
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/application_package.dartAdded+431
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/build_validation.dartAdded+49
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dartAdded+342
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dartAdded+294
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dartAdded+223
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle.dartAdded+1277
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_errors.dartAdded+750
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_utils.dartAdded+974
- novelforge-project/flutter/packages/flutter_tools/lib/src/android/java.dartAdded+247
- novelforge-project/flutter/packages/flutter_tools/lib/src/application_package.dartAdded+41
- novelforge-project/flutter/packages/flutter_tools/lib/src/artifacts.dartAdded+1468
- novelforge-project/flutter/packages/flutter_tools/lib/src/asset.dartAdded+1283
- novelforge-project/flutter/packages/flutter_tools/lib/src/build_info.dartAdded+1063
- novelforge-project/flutter/packages/flutter_tools/lib/src/bundle.dartAdded+64
- novelforge-project/flutter/packages/flutter_tools/lib/src/bundle_builder.dartAdded+217
- novelforge-project/flutter/packages/flutter_tools/lib/src/cache.dartAdded+1351
- novelforge-project/flutter/packages/flutter_tools/lib/src/cmake.dartAdded+125
- novelforge-project/flutter/packages/flutter_tools/lib/src/cmake_project.dartAdded+144
- novelforge-project/flutter/packages/flutter_tools/lib/src/compile.dartAdded+1082
- novelforge-project/flutter/packages/flutter_tools/lib/src/context_runner.dartAdded+400
- novelforge-project/flutter/packages/flutter_tools/lib/src/convert.dartAdded+81
- novelforge-project/flutter/packages/flutter_tools/lib/src/daemon.dartAdded+378
- novelforge-project/flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dartAdded+71
- novelforge-project/flutter/packages/flutter_tools/lib/src/desktop_device.dartAdded+353
- novelforge-project/flutter/packages/flutter_tools/lib/src/devfs.dartAdded+768
- novelforge-project/flutter/packages/flutter_tools/lib/src/device.dartAdded+1400
- novelforge-project/flutter/packages/flutter_tools/lib/src/device_port_forwarder.dartAdded+61
- novelforge-project/flutter/packages/flutter_tools/lib/src/device_vm_service_discovery_for_attach.dartAdded+110
- novelforge-project/flutter/packages/flutter_tools/lib/src/devtools_launcher.dartAdded+111
- novelforge-project/flutter/packages/flutter_tools/lib/src/doctor.dartAdded+806
- novelforge-project/flutter/packages/flutter_tools/lib/src/doctor_validator.dartAdded+314
- novelforge-project/flutter/packages/flutter_tools/lib/src/emulator.dartAdded+337
- novelforge-project/flutter/packages/flutter_tools/lib/src/features.dartAdded+316
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_application_package.dartAdded+111
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_cache.dartAdded+918
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_device_manager.dartAdded+148
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_features.dartAdded+85
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_manifest.dartAdded+796
- novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_plugins.dartAdded+1477
123456789101112131415161718// 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.
final RegExp _whitespace = RegExp(r'\s+');
/// Convert adb device names into more human readable descriptions.String cleanAdbDeviceName(String name) { // Some emulators use `___` in the name as separators. name = name.replaceAll('___', ', ');
// Convert `Nexus_7` / `Nexus_5X` style names to `Nexus 7` ones. name = name.replaceAll('_', ' ');
name = name.replaceAll(_whitespace, ' ').trim();
return name;}1234567// 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.
const int minApiLevel = 16;const String minVersionName = 'Jelly Bean';const String minVersionText = '4.1.x';1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253// 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 '../base/context.dart';import '../build_info.dart';import '../project.dart';
/// The builder in the current context.AndroidBuilder? get androidBuilder { return context.get<AndroidBuilder>();}
abstract class AndroidBuilder { const AndroidBuilder(); /// Builds an AAR artifact. Future<void> buildAar({ required FlutterProject project, required Set<AndroidBuildInfo> androidBuildInfo, required String target, String? outputDirectoryPath, required String buildNumber, });
/// Builds an APK artifact. Future<void> buildApk({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool configOnly = false, });
/// Builds an App Bundle artifact. Future<void> buildAab({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, bool configOnly = false, });
/// Returns a list of available build variant from the Android project. Future<List<String>> getBuildVariants({required FlutterProject project});
/// Outputs app link related project settings into a json file. /// /// The return future resolves to the path of the json file. Future<String> outputsAppLinkSettings( String buildVariant, { required FlutterProject project, });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// 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:async/async.dart';
import '../base/io.dart';import '../convert.dart';
/// Default factory that creates a real Android console connection.////// The default implementation will create real connections to a device./// Override this in tests with an implementation that returns mock responses.Future<Socket> kAndroidConsoleSocketFactory(String host, int port) => Socket.connect(host, port);
/// Currently active implementation of the AndroidConsoleFactory.////// The default implementation will create real connections to a device./// Override this in tests with an implementation that returns mock responses.typedef AndroidConsoleSocketFactory = Future<Socket> Function(String host, int port);
/// Creates a console connection to an Android emulator that can be used to run/// commands such as "avd name" which are not available to ADB.////// See documentation at/// https://developer.android.com/studio/run/emulator-consoleclass AndroidConsole { AndroidConsole(this._socket);
Socket? _socket; StreamQueue<String>? _queue;
Future<void> connect() async { assert(_socket != null); assert(_queue == null);
_queue = StreamQueue<String>(_socket!.asyncMap(ascii.decode));
// Discard any initial connection text. await _readResponse(); }
Future<String?> getAvdName() async { if (_queue == null) { return null; } _write('avd name\n'); return _readResponse(); }
void destroy() { _socket?.destroy(); _socket = null; _queue = null; }
Future<String?> _readResponse() async { if (_queue == null) { return null; } final StringBuffer output = StringBuffer(); while (true) { if (!await _queue!.hasNext) { destroy(); return null; } final String text = await _queue!.next; final String trimmedText = text.trim(); if (trimmedText == 'OK') { break; } if (trimmedText.endsWith('\nOK')) { output.write(trimmedText.substring(0, trimmedText.length - 3)); break; } output.write(text); } return output.toString().trim(); }
void _write(String text) { _socket?.add(ascii.encode(text)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365// 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:meta/meta.dart';import 'package:process/process.dart';
import '../application_package.dart';import '../base/common.dart' show throwToolExit;import '../base/file_system.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/platform.dart';import '../base/process.dart';import '../build_info.dart';import '../convert.dart';import '../device.dart';import '../device_port_forwarder.dart';import '../project.dart';import '../protocol_discovery.dart';import 'android.dart';import 'android_builder.dart';import 'android_console.dart';import 'android_sdk.dart';import 'application_package.dart';
/// Whether the [AndroidDevice] is believed to be a physical device or an emulator.enum HardwareType { emulator, physical }
/// Map to help our `isLocalEmulator` detection.////// See [AndroidDevice] for more explanation of why this is needed.const Map<String, HardwareType> kKnownHardware = <String, HardwareType>{ 'goldfish': HardwareType.emulator, 'qcom': HardwareType.physical, 'ranchu': HardwareType.emulator, 'samsungexynos7420': HardwareType.physical, 'samsungexynos7580': HardwareType.physical, 'samsungexynos7870': HardwareType.physical, 'samsungexynos7880': HardwareType.physical, 'samsungexynos8890': HardwareType.physical, 'samsungexynos8895': HardwareType.physical, 'samsungexynos9810': HardwareType.physical, 'samsungexynos7570': HardwareType.physical,};
/// A physical Android device or emulator.////// While [isEmulator] attempts to distinguish between the device categories,/// this is a best effort process and not a guarantee; certain physical devices/// identify as emulators. These device identifiers may be added to the [kKnownHardware]/// map to specify that they are actually physical devices.class AndroidDevice extends Device { AndroidDevice( super.id, { this.productID, required this.modelID, this.deviceCodeName, required Logger logger, required ProcessManager processManager, required Platform platform, required AndroidSdk androidSdk, required FileSystem fileSystem, AndroidConsoleSocketFactory androidConsoleSocketFactory = kAndroidConsoleSocketFactory, }) : _logger = logger, _processManager = processManager, _androidSdk = androidSdk, _platform = platform, _fileSystem = fileSystem, _androidConsoleSocketFactory = androidConsoleSocketFactory, _processUtils = ProcessUtils(logger: logger, processManager: processManager), super( category: Category.mobile, platformType: PlatformType.android, ephemeral: true, );
final Logger _logger; final ProcessManager _processManager; final AndroidSdk _androidSdk; final Platform _platform; final FileSystem _fileSystem; final ProcessUtils _processUtils; final AndroidConsoleSocketFactory _androidConsoleSocketFactory;
final String? productID; final String modelID; final String? deviceCodeName;
@override // Wirelessly paired Android devices should have `adb-tls-connect` in the id. // Source: https://android.googlesource.com/platform/packages/modules/adb/+/f4ba8d73079b99532069dbe888a58167b8723d6c/adb_mdns.h#30 DeviceConnectionInterface get connectionInterface => id.contains('adb-tls-connect') ? DeviceConnectionInterface.wireless : DeviceConnectionInterface.attached;
late final Future<Map<String, String>> _properties = () async { Map<String, String> properties = <String, String>{};
final List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']); _logger.printTrace(propCommand.join(' '));
try { // We pass an encoding of latin1 so that we don't try and interpret the // `adb shell getprop` result as UTF8. final ProcessResult result = await _processManager.run( propCommand, stdoutEncoding: latin1, stderrEncoding: latin1, ); if (result.exitCode == 0 || _allowHeapCorruptionOnWindows(result.exitCode, _platform)) { properties = parseAdbDeviceProperties(result.stdout as String); } else { _logger.printError('Error ${result.exitCode} retrieving device properties for $name:'); _logger.printError(result.stderr as String); } } on ProcessException catch (error) { _logger.printError('Error retrieving device properties for $name: $error'); } return properties; }();
Future<String?> _getProperty(String name) async { return (await _properties)[name]; }
@override late final Future<bool> isLocalEmulator = () async { final String? hardware = await _getProperty('ro.hardware'); _logger.printTrace('ro.hardware = $hardware'); if (kKnownHardware.containsKey(hardware)) { // Look for known hardware models. return kKnownHardware[hardware] == HardwareType.emulator; } // Fall back to a best-effort heuristic-based approach. final String? characteristics = await _getProperty('ro.build.characteristics'); _logger.printTrace('ro.build.characteristics = $characteristics'); return characteristics != null && characteristics.contains('emulator'); }();
/// The unique identifier for the emulator that corresponds to this device, or /// null if it is not an emulator. /// /// The ID returned matches that in the output of `flutter emulators`. Fetching /// this name may require connecting to the device and if an error occurs null /// will be returned. @override Future<String?> get emulatorId async { if (!(await isLocalEmulator)) { return null; }
// Emulators always have IDs in the format emulator-(port) where port is the // Android Console port number. final RegExp emulatorPortRegex = RegExp(r'emulator-(\d+)');
final Match? portMatch = emulatorPortRegex.firstMatch(id); if (portMatch == null || portMatch.groupCount < 1) { return null; }
const String host = 'localhost'; final int port = int.parse(portMatch.group(1)!); _logger.printTrace('Fetching avd name for $name via Android console on $host:$port');
try { final Socket socket = await _androidConsoleSocketFactory(host, port); final AndroidConsole console = AndroidConsole(socket);
try { await console .connect() .timeout(const Duration(seconds: 2), onTimeout: () => throw TimeoutException('Connection timed out'));
return await console .getAvdName() .timeout(const Duration(seconds: 2), onTimeout: () => throw TimeoutException('"avd name" timed out')); } finally { console.destroy(); } } on Exception catch (e) { _logger.printTrace('Failed to fetch avd name for emulator at $host:$port: $e'); // If we fail to connect to the device, we should not fail so just return // an empty name. This data is best-effort. return null; } }
@override late final Future<TargetPlatform> targetPlatform = () async { // http://developer.android.com/ndk/guides/abis.html (x86, armeabi-v7a, ...) switch (await _getProperty('ro.product.cpu.abi')) { case 'arm64-v8a': // Perform additional verification for 64 bit ABI. Some devices, // like the Kindle Fire 8, misreport the abilist. We might not // be able to retrieve this property, in which case we fall back // to assuming 64 bit. final String? abilist = await _getProperty('ro.product.cpu.abilist'); if (abilist == null || abilist.contains('arm64-v8a')) { return TargetPlatform.android_arm64; } else { return TargetPlatform.android_arm; } case 'x86_64': return TargetPlatform.android_x64; case 'x86': return TargetPlatform.android_x86; default: return TargetPlatform.android_arm; } }();
@override Future<bool> supportsRuntimeMode(BuildMode buildMode) async { switch (await targetPlatform) { case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: return buildMode != BuildMode.jitRelease; case TargetPlatform.android_x86: return buildMode == BuildMode.debug; case TargetPlatform.android: case TargetPlatform.darwin: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.ios: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: throw UnsupportedError('Invalid target platform for Android'); } }
@override Future<String> get sdkNameAndVersion async => 'Android ${await _sdkVersion} (API ${await apiVersion})';
Future<String?> get _sdkVersion => _getProperty('ro.build.version.release');
@visibleForTesting Future<String?> get apiVersion => _getProperty('ro.build.version.sdk');
AdbLogReader? _logReader; AdbLogReader? _pastLogReader;
List<String> adbCommandForDevice(List<String> args) { return <String>[_androidSdk.adbPath!, '-s', id, ...args]; }
Future<RunResult> runAdbCheckedAsync( List<String> params, { String? workingDirectory, bool allowReentrantFlutter = false, }) async { return _processUtils.run( adbCommandForDevice(params), throwOnError: true, workingDirectory: workingDirectory, allowReentrantFlutter: allowReentrantFlutter, allowedFailures: (int value) => _allowHeapCorruptionOnWindows(value, _platform), ); }
bool _isValidAdbVersion(String adbVersion) { // Sample output: 'Android Debug Bridge version 1.0.31' final Match? versionFields = RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion); if (versionFields != null) { final int majorVersion = int.parse(versionFields[1]!); final int minorVersion = int.parse(versionFields[2]!); final int patchVersion = int.parse(versionFields[3]!); if (majorVersion > 1) { return true; } if (majorVersion == 1 && minorVersion > 0) { return true; } if (majorVersion == 1 && minorVersion == 0 && patchVersion >= 39) { return true; } return false; } _logger.printError( 'Unrecognized adb version string $adbVersion. Skipping version check.'); return true; }
Future<bool> _checkForSupportedAdbVersion() async { final String? adbPath = _androidSdk.adbPath; if (adbPath == null) { return false; }
try { final RunResult adbVersion = await _processUtils.run( <String>[adbPath, 'version'], throwOnError: true, ); if (_isValidAdbVersion(adbVersion.stdout)) { return true; } _logger.printError('The ADB at "$adbPath" is too old; please install version 1.0.39 or later.'); } on Exception catch (error, trace) { _logger.printError('Error running ADB: $error', stackTrace: trace); }
return false; }
Future<bool> _checkForSupportedAndroidVersion() async { final String? adbPath = _androidSdk.adbPath; if (adbPath == null) { return false; } try { // If the server is automatically restarted, then we get irrelevant // output lines like this, which we want to ignore: // adb server is out of date. killing.. // * daemon started successfully * await _processUtils.run( <String>[adbPath, 'start-server'], throwOnError: true, );
// This has been reported to return null on some devices. In this case, // assume the lowest supported API to still allow Flutter to run. // Sample output: '22' final String sdkVersion = await _getProperty('ro.build.version.sdk') ?? minApiLevel.toString();
final int? sdkVersionParsed = int.tryParse(sdkVersion); if (sdkVersionParsed == null) { _logger.printError('Unexpected response from getprop: "$sdkVersion"'); return false; }
if (sdkVersionParsed < minApiLevel) { _logger.printError( 'The Android version ($sdkVersion) on the target device is too old. Please ' 'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.'); return false; }
return true; } on Exception catch (e, stacktrace) { _logger.printError('Unexpected failure from adb: $e'); _logger.printError('Stacktrace: $stacktrace'); return false; } }
String _getDeviceSha1Path(AndroidApk apk) { return '/data/local/tmp/sky.${apk.id}.sha1'; }
Future<String> _getDeviceApkSha1(AndroidApk apk) async { final RunResult result = await _processUtils.run( adbCommandForDevice(<String>['shell', 'cat', _getDeviceSha1Path(apk)])); return result.stdout; }
String _getSourceSha1(AndroidApk apk) { final File shaFile = _fileSystem.file('${apk.applicationPackage.path}.sha1'); return shaFile.existsSync() ? shaFile.readAsStringSync() : ''; }
@override String get name => modelID;
@override bool get supportsFlavors => true;
@override Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, }) async { // This call takes 400ms - 600ms. try { final RunResult listOut = await runAdbCheckedAsync(<String>[ 'shell', 'pm', 'list', 'packages', if (userIdentifier != null) ...<String>['--user', userIdentifier], app.id, ]); return LineSplitter.split(listOut.stdout).contains('package:${app.id}'); } on Exception catch (error) { _logger.printTrace('$error'); return false; } }
@override Future<bool> isLatestBuildInstalled(covariant AndroidApk app) async { final String installedSha1 = await _getDeviceApkSha1(app); return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app); }
@override Future<bool> installApp( covariant AndroidApk app, { String? userIdentifier, }) async { if (!await _adbIsValid) { return false; } final bool wasInstalled = await isAppInstalled(app, userIdentifier: userIdentifier); if (wasInstalled && await isLatestBuildInstalled(app)) { _logger.printTrace('Latest build already installed.'); return true; } _logger.printTrace('Installing APK.'); if (await _installApp(app, userIdentifier: userIdentifier)) { return true; } _logger.printTrace('Warning: Failed to install APK.'); if (!wasInstalled) { return false; } _logger.printStatus('Uninstalling old version...'); if (!await uninstallApp(app, userIdentifier: userIdentifier)) { _logger.printError('Error: Uninstalling old version failed.'); return false; } if (!await _installApp(app, userIdentifier: userIdentifier)) { _logger.printError('Error: Failed to install APK again.'); return false; } return true; }
Future<bool> _installApp( AndroidApk app, { String? userIdentifier, }) async { if (!app.applicationPackage.existsSync()) { _logger.printError('"${_fileSystem.path.relative(app.applicationPackage.path)}" does not exist.'); return false; }
final Status status = _logger.startProgress( 'Installing ${_fileSystem.path.relative(app.applicationPackage.path)}...', ); final RunResult installResult = await _processUtils.run( adbCommandForDevice(<String>[ 'install', '-t', '-r', if (userIdentifier != null) ...<String>['--user', userIdentifier], app.applicationPackage.path, ])); status.stop(); // Some versions of adb exit with exit code 0 even on failure :( // Parsing the output to check for failures. final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true); final String? failure = failureExp.stringMatch(installResult.stdout); if (failure != null) { _logger.printError('Package install error: $failure'); return false; } if (installResult.exitCode != 0) { if (installResult.stderr.contains('Bad user number')) { _logger.printError('Error: User "$userIdentifier" not found. Run "adb shell pm list users" to see list of available identifiers.'); } else { _logger.printError('Error: ADB exited with exit code ${installResult.exitCode}'); _logger.printError('$installResult'); } return false; } try { await runAdbCheckedAsync(<String>[ 'shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app), ]); } on ProcessException catch (error) { _logger.printError('adb shell failed to write the SHA hash: $error.'); return false; } return true; }
@override Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }) async { if (!await _adbIsValid) { return false; }
String uninstallOut; try { final RunResult uninstallResult = await _processUtils.run( adbCommandForDevice(<String>[ 'uninstall', if (userIdentifier != null) ...<String>['--user', userIdentifier], app.id, ]), throwOnError: true, ); uninstallOut = uninstallResult.stdout; } on Exception catch (error) { _logger.printError('adb uninstall failed: $error'); return false; } final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true); final String? failure = failureExp.stringMatch(uninstallOut); if (failure != null) { _logger.printError('Package uninstall error: $failure'); return false; } return true; }
// Whether the adb and Android versions are aligned. late final Future<bool> _adbIsValid = () async { return await _checkForSupportedAdbVersion() && await _checkForSupportedAndroidVersion(); }();
AndroidApk? _package;
@override Future<LaunchResult> startApp( AndroidApk? package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs = const <String, Object>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, }) async { if (!await _adbIsValid) { return LaunchResult.failed(); }
final TargetPlatform devicePlatform = await targetPlatform; if (devicePlatform == TargetPlatform.android_x86 && !debuggingOptions.buildInfo.isDebug) { _logger.printError('Profile and release builds are only supported on ARM/x64 targets.'); return LaunchResult.failed(); }
AndroidApk? builtPackage = package; AndroidArch androidArch; switch (devicePlatform) { case TargetPlatform.android_arm: androidArch = AndroidArch.armeabi_v7a; case TargetPlatform.android_arm64: androidArch = AndroidArch.arm64_v8a; case TargetPlatform.android_x64: androidArch = AndroidArch.x86_64; case TargetPlatform.android_x86: androidArch = AndroidArch.x86; case TargetPlatform.android: case TargetPlatform.darwin: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.ios: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: _logger.printError('Android platforms are only supported.'); return LaunchResult.failed(); }
if (!prebuiltApplication || _androidSdk.licensesAvailable && _androidSdk.latestVersion == null) { _logger.printTrace('Building APK'); final FlutterProject project = FlutterProject.current(); await androidBuilder!.buildApk( project: project, target: mainPath ?? 'lib/main.dart', androidBuildInfo: AndroidBuildInfo( debuggingOptions.buildInfo, targetArchs: <AndroidArch>[androidArch], fastStart: debuggingOptions.fastStart, multidexEnabled: (platformArgs['multidex'] as bool?) ?? false, ), ); // Package has been built, so we can get the updated application ID and // activity name from the .apk. builtPackage = await ApplicationPackageFactory.instance! .getPackageForPlatform(devicePlatform, buildInfo: debuggingOptions.buildInfo) as AndroidApk?; } // There was a failure parsing the android project information. if (builtPackage == null) { throwToolExit('Problem building Android application: see above error(s).'); }
_logger.printTrace("Stopping app '${builtPackage.name}' on $name."); await stopApp(builtPackage, userIdentifier: userIdentifier);
if (!await installApp(builtPackage, userIdentifier: userIdentifier)) { return LaunchResult.failed(); }
final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; ProtocolDiscovery? vmServiceDiscovery;
if (debuggingOptions.debuggingEnabled) { vmServiceDiscovery = ProtocolDiscovery.vmService( // Avoid using getLogReader, which returns a singleton instance, because the // VM Service discovery will dipose at the end. creating a new logger here allows // logs to be surfaced normally during `flutter drive`. await AdbLogReader.createLogReader( this, _processManager, ), portForwarder: portForwarder, hostPort: debuggingOptions.hostVmServicePort, devicePort: debuggingOptions.deviceVmServicePort, ipv6: ipv6, logger: _logger, ); }
final String dartVmFlags = computeDartVmFlags(debuggingOptions); final String? traceAllowlist = debuggingOptions.traceAllowlist; final String? traceSkiaAllowlist = debuggingOptions.traceSkiaAllowlist; final String? traceToFile = debuggingOptions.traceToFile; final List<String> cmd = <String>[ 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER', '-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP if (debuggingOptions.enableDartProfiling) ...<String>['--ez', 'enable-dart-profiling', 'true'], if (traceStartup) ...<String>['--ez', 'trace-startup', 'true'], if (route != null) ...<String>['--es', 'route', route], if (debuggingOptions.enableSoftwareRendering) ...<String>['--ez', 'enable-software-rendering', 'true'], if (debuggingOptions.skiaDeterministicRendering) ...<String>['--ez', 'skia-deterministic-rendering', 'true'], if (debuggingOptions.traceSkia) ...<String>['--ez', 'trace-skia', 'true'], if (traceAllowlist != null) ...<String>['--es', 'trace-allowlist', traceAllowlist], if (traceSkiaAllowlist != null) ...<String>['--es', 'trace-skia-allowlist', traceSkiaAllowlist], if (debuggingOptions.traceSystrace) ...<String>['--ez', 'trace-systrace', 'true'], if (traceToFile != null) ...<String>['--es', 'trace-to-file', traceToFile], if (debuggingOptions.endlessTraceBuffer) ...<String>['--ez', 'endless-trace-buffer', 'true'], if (debuggingOptions.dumpSkpOnShaderCompilation) ...<String>['--ez', 'dump-skp-on-shader-compilation', 'true'], if (debuggingOptions.cacheSkSL) ...<String>['--ez', 'cache-sksl', 'true'], if (debuggingOptions.purgePersistentCache) ...<String>['--ez', 'purge-persistent-cache', 'true'], if (debuggingOptions.enableImpeller == ImpellerStatus.enabled) ...<String>['--ez', 'enable-impeller', 'true'], if (debuggingOptions.enableImpeller == ImpellerStatus.disabled) ...<String>['--ez', 'enable-impeller', 'false'], if (debuggingOptions.enableVulkanValidation) ...<String>['--ez', 'enable-vulkan-validation', 'true'], if (debuggingOptions.debuggingEnabled) ...<String>[ if (debuggingOptions.buildInfo.isDebug) ...<String>[ ...<String>['--ez', 'enable-checked-mode', 'true'], ...<String>['--ez', 'verify-entry-points', 'true'], ], if (debuggingOptions.startPaused) ...<String>['--ez', 'start-paused', 'true'], if (debuggingOptions.disableServiceAuthCodes) ...<String>['--ez', 'disable-service-auth-codes', 'true'], if (dartVmFlags.isNotEmpty) ...<String>['--es', 'dart-flags', dartVmFlags], if (debuggingOptions.useTestFonts) ...<String>['--ez', 'use-test-fonts', 'true'], if (debuggingOptions.verboseSystemLogs) ...<String>['--ez', 'verbose-logging', 'true'], if (userIdentifier != null) ...<String>['--user', userIdentifier], ], builtPackage.launchActivity, ]; final String result = (await runAdbCheckedAsync(cmd)).stdout; // This invocation returns 0 even when it fails. if (result.contains('Error: ')) { _logger.printError(result.trim(), wrap: false); return LaunchResult.failed(); }
_package = builtPackage; if (!debuggingOptions.debuggingEnabled) { return LaunchResult.succeeded(); }
// Wait for the service protocol port here. This will complete once the // device has printed "VM Service is listening on...". _logger.printTrace('Waiting for VM Service port to be available...'); try { Uri? vmServiceUri; if (debuggingOptions.buildInfo.isDebug || debuggingOptions.buildInfo.isProfile) { vmServiceUri = await vmServiceDiscovery?.uri; if (vmServiceUri == null) { _logger.printError( 'Error waiting for a debug connection: ' 'The log reader stopped unexpectedly', ); return LaunchResult.failed(); } } return LaunchResult.succeeded(vmServiceUri: vmServiceUri); } on Exception catch (error) { _logger.printError('Error waiting for a debug connection: $error'); return LaunchResult.failed(); } finally { await vmServiceDiscovery?.cancel(); } }
@override bool get supportsHotReload => true;
@override bool get supportsHotRestart => true;
@override bool get supportsFastStart => true;
@override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { if (app == null) { return false; } final List<String> command = adbCommandForDevice(<String>[ 'shell', 'am', 'force-stop', if (userIdentifier != null) ...<String>['--user', userIdentifier], app.id, ]); return _processUtils.stream(command).then<bool>( (int exitCode) => exitCode == 0 || _allowHeapCorruptionOnWindows(exitCode, _platform)); }
@override Future<MemoryInfo> queryMemoryInfo() async { final AndroidApk? package = _package; if (package == null) { _logger.printError('Android package unknown, skipping dumpsys meminfo.'); return const MemoryInfo.empty(); } final RunResult runResult = await _processUtils.run(adbCommandForDevice(<String>[ 'shell', 'dumpsys', 'meminfo', package.id, '-d', ]));
if (runResult.exitCode != 0) { return const MemoryInfo.empty(); } return parseMeminfoDump(runResult.stdout); }
@override void clearLogs() { _processUtils.runSync(adbCommandForDevice(<String>['logcat', '-c'])); }
@override FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false, }) async { // The Android log reader isn't app-specific. The `app` parameter isn't used. if (includePastLogs) { return _pastLogReader ??= await AdbLogReader.createLogReader( this, _processManager, includePastLogs: true, ); } else { return _logReader ??= await AdbLogReader.createLogReader( this, _processManager, ); } }
@override late final DevicePortForwarder? portForwarder = () { final String? adbPath = _androidSdk.adbPath; if (adbPath == null) { return null; } return AndroidDevicePortForwarder( processManager: _processManager, logger: _logger, deviceId: id, adbPath: adbPath, ); }();
static final RegExp _timeRegExp = RegExp(r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}', multiLine: true);
/// Return the most recent timestamp in the Android log or [null] if there is /// no available timestamp. The format can be passed to logcat's -T option. @visibleForTesting Future<String?> lastLogcatTimestamp() async { RunResult output; try { output = await runAdbCheckedAsync(<String>[ 'shell', '-x', 'logcat', '-v', 'time', '-t', '1', ]); } on Exception catch (error) { _logger.printError('Failed to extract the most recent timestamp from the Android log: $error.'); return null; } final Match? timeMatch = _timeRegExp.firstMatch(output.stdout); return timeMatch?.group(0); }
@override bool isSupported() => true;
@override bool get supportsScreenshot => true;
@override Future<void> takeScreenshot(File outputFile) async { const String remotePath = '/data/local/tmp/flutter_screenshot.png'; await runAdbCheckedAsync(<String>['shell', 'screencap', '-p', remotePath]); await _processUtils.run( adbCommandForDevice(<String>['pull', remotePath, outputFile.path]), throwOnError: true, ); await runAdbCheckedAsync(<String>['shell', 'rm', remotePath]); }
@override bool isSupportedForProject(FlutterProject flutterProject) { return flutterProject.android.existsSync(); }
@override Future<void> dispose() async { _logReader?._stop(); _pastLogReader?._stop(); }}
Map<String, String> parseAdbDeviceProperties(String str) { final Map<String, String> properties = <String, String>{}; final RegExp propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]'); for (final Match match in propertyExp.allMatches(str)) { properties[match.group(1)!] = match.group(2)!; } return properties;}
/// Process the dumpsys info formatted in a table-like structure.////// Currently this only pulls information from the "App Summary" subsection.////// Example output:////// ```/// 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/// .../// ```////// For more information, see https://developer.android.com/studio/command-line/dumpsys.@visibleForTestingAndroidMemoryInfo parseMeminfoDump(String input) { final AndroidMemoryInfo androidMemoryInfo = AndroidMemoryInfo();
final List<String> lines = input.split('\n');
final String timelineData = lines.firstWhere((String line) => line.startsWith('${AndroidMemoryInfo._kUpTimeKey}: ')); final List<String> times = timelineData.trim().split('${AndroidMemoryInfo._kRealTimeKey}:'); androidMemoryInfo.realTime = int.tryParse(times.last.trim()) ?? 0;
lines .skipWhile((String line) => !line.contains('App Summary')) .takeWhile((String line) => !line.contains('TOTAL')) .where((String line) => line.contains(':')) .forEach((String line) { final List<String> sections = line.trim().split(':'); final String key = sections.first.trim(); final int value = int.tryParse(sections.last.trim()) ?? 0; switch (key) { case AndroidMemoryInfo._kJavaHeapKey: androidMemoryInfo.javaHeap = value; case AndroidMemoryInfo._kNativeHeapKey: androidMemoryInfo.nativeHeap = value; case AndroidMemoryInfo._kCodeKey: androidMemoryInfo.code = value; case AndroidMemoryInfo._kStackKey: androidMemoryInfo.stack = value; case AndroidMemoryInfo._kGraphicsKey: androidMemoryInfo.graphics = value; case AndroidMemoryInfo._kPrivateOtherKey: androidMemoryInfo.privateOther = value; case AndroidMemoryInfo._kSystemKey: androidMemoryInfo.system = value; } }); return androidMemoryInfo;}
/// Android specific implementation of memory info.class AndroidMemoryInfo extends MemoryInfo { static const String _kUpTimeKey = 'Uptime'; static const String _kRealTimeKey = 'Realtime'; static const String _kJavaHeapKey = 'Java Heap'; static const String _kNativeHeapKey = 'Native Heap'; static const String _kCodeKey = 'Code'; static const String _kStackKey = 'Stack'; static const String _kGraphicsKey = 'Graphics'; static const String _kPrivateOtherKey = 'Private Other'; static const String _kSystemKey = 'System'; static const String _kTotalKey = 'Total';
// Realtime is time since the system was booted includes deep sleep. Clock // is monotonic, and ticks even when the CPU is in power saving modes. int realTime = 0;
// Each measurement has KB as a unit. int javaHeap = 0; int nativeHeap = 0; int code = 0; int stack = 0; int graphics = 0; int privateOther = 0; int system = 0;
@override Map<String, Object> toJson() { return <String, Object>{ 'platform': 'Android', _kRealTimeKey: realTime, _kJavaHeapKey: javaHeap, _kNativeHeapKey: nativeHeap, _kCodeKey: code, _kStackKey: stack, _kGraphicsKey: graphics, _kPrivateOtherKey: privateOther, _kSystemKey: system, _kTotalKey: javaHeap + nativeHeap + code + stack + graphics + privateOther + system, }; }}
/// A log reader that logs from `adb logcat`.class AdbLogReader extends DeviceLogReader { AdbLogReader._(this._adbProcess, this.name);
@visibleForTesting factory AdbLogReader.test(Process adbProcess, String name) = AdbLogReader._;
/// Create a new [AdbLogReader] from an [AndroidDevice] instance. static Future<AdbLogReader> createLogReader( AndroidDevice device, ProcessManager processManager, { bool includePastLogs = false, }) async { // logcat -T is not supported on Android releases before Lollipop. const int kLollipopVersionCode = 21; final int? apiVersion = (String? v) { // If the API version string isn't found, conservatively assume that the // version is less recent than the one we're looking for. return v == null ? kLollipopVersionCode - 1 : int.tryParse(v); }(await device.apiVersion);
// Start the adb logcat process and filter the most recent logs since `lastTimestamp`. // Some devices (notably LG) will only output logcat via shell // https://github.com/flutter/flutter/issues/51853 final List<String> args = <String>[ 'shell', '-x', 'logcat', '-v', 'time', ];
// If past logs are included then filter for 'flutter' logs only. if (includePastLogs) { args.addAll(<String>['-s', 'flutter']); } else if (apiVersion != null && apiVersion >= kLollipopVersionCode) { // Otherwise, filter for logs appearing past the present. // '-T 0` means the timestamp of the logcat command invocation. final String? lastLogcatTimestamp = await device.lastLogcatTimestamp(); args.addAll(<String>[ '-T', if (lastLogcatTimestamp != null) "'$lastLogcatTimestamp'" else '0', ]); } final Process process = await processManager.start(device.adbCommandForDevice(args)); return AdbLogReader._(process, device.name); }
final Process _adbProcess;
@override final String name;
late final StreamController<String> _linesController = StreamController<String>.broadcast( onListen: _start, onCancel: _stop, );
@override Stream<String> get logLines => _linesController.stream;
void _start() { // We expect logcat streams to occasionally contain invalid utf-8, // see: https://github.com/flutter/flutter/pull/8864. const Utf8Decoder decoder = Utf8Decoder(reportErrors: false); _adbProcess.stdout.transform<String>(decoder) .transform<String>(const LineSplitter()) .listen(_onLine); _adbProcess.stderr.transform<String>(decoder) .transform<String>(const LineSplitter()) .listen(_onLine); unawaited(_adbProcess.exitCode.whenComplete(() { if (_linesController.hasListener) { _linesController.close(); } })); }
// 'W/ActivityManager(pid): ' static final RegExp _logFormat = RegExp(r'^[VDIWEF]\/.*?\(\s*(\d+)\):\s');
static final List<RegExp> _allowedTags = <RegExp>[ RegExp(r'^[VDIWEF]\/flutter[^:]*:\s+', caseSensitive: false), RegExp(r'^[IE]\/DartVM[^:]*:\s+'), RegExp(r'^[WEF]\/AndroidRuntime:\s+'), RegExp(r'^[WEF]\/AndroidRuntime\([0-9]+\):\s+'), RegExp(r'^[WEF]\/ActivityManager:\s+.*(\bflutter\b|\bdomokit\b|\bsky\b)'), RegExp(r'^[WEF]\/System\.err:\s+'), RegExp(r'^[F]\/[\S^:]+:\s+'), ];
// E/SurfaceSyncer(22636): Failed to find sync for id=9 // Some versions of Android spew this out. It is inactionable to the end user // and causes no problems for the application. static final RegExp _surfaceSyncerSpam = RegExp(r'^E/SurfaceSyncer\(\s*\d+\): Failed to find sync for id=\d+');
// 'F/libc(pid): Fatal signal 11' static final RegExp _fatalLog = RegExp(r'^F\/libc\s*\(\s*\d+\):\sFatal signal (\d+)');
// 'I/DEBUG(pid): ...' static final RegExp _tombstoneLine = RegExp(r'^[IF]\/DEBUG\s*\(\s*\d+\):\s(.+)$');
// 'I/DEBUG(pid): Tombstone written to: ' static final RegExp _tombstoneTerminator = RegExp(r'^Tombstone written to:\s');
// we default to true in case none of the log lines match bool _acceptedLastLine = true;
// Whether a fatal crash is happening or not. // During a fatal crash only lines from the crash are accepted, the rest are // dropped. bool _fatalCrash = false;
// The format of the line is controlled by the '-v' parameter passed to // adb logcat. We are currently passing 'time', which has the format: // mm-dd hh:mm:ss.milliseconds Priority/Tag( PID): .... void _onLine(String line) { // This line might be processed after the subscription is closed but before // adb stops streaming logs. if (_linesController.isClosed) { return; } final Match? timeMatch = AndroidDevice._timeRegExp.firstMatch(line); if (timeMatch == null || line.length == timeMatch.end) { _acceptedLastLine = false; return; } // Chop off the time. line = line.substring(timeMatch.end + 1); final Match? logMatch = _logFormat.firstMatch(line); if (logMatch != null) { bool acceptLine = false;
if (_fatalCrash) { // While a fatal crash is going on, only accept lines from the crash // Otherwise the crash log in the console may get interrupted
final Match? fatalMatch = _tombstoneLine.firstMatch(line);
if (fatalMatch != null) { acceptLine = true;
line = fatalMatch[1]!;
if (_tombstoneTerminator.hasMatch(line)) { // Hit crash terminator, stop logging the crash info _fatalCrash = false; } } } else if (appPid != null && int.parse(logMatch.group(1)!) == appPid) { acceptLine = !_surfaceSyncerSpam.hasMatch(line);
if (_fatalLog.hasMatch(line)) { // Hit fatal signal, app is now crashing _fatalCrash = true; } } else { // Filter on approved names and levels. acceptLine = _allowedTags.any((RegExp re) => re.hasMatch(line)); }
if (acceptLine) { _acceptedLastLine = true; _linesController.add(line); return; } _acceptedLastLine = false; } else if (line == '--------- beginning of system' || line == '--------- beginning of main') { // hide the ugly adb logcat log boundaries at the start _acceptedLastLine = false; } else { // If it doesn't match the log pattern at all, then pass it through if we // passed the last matching line through. It might be a multiline message. if (_acceptedLastLine) { _linesController.add(line); return; } } }
void _stop() { _linesController.close(); _adbProcess.kill(); }
@override void dispose() { _stop(); }}
/// A [DevicePortForwarder] implemented for Android devices that uses adb.class AndroidDevicePortForwarder extends DevicePortForwarder { AndroidDevicePortForwarder({ required ProcessManager processManager, required Logger logger, required String deviceId, required String adbPath, }) : _deviceId = deviceId, _adbPath = adbPath, _logger = logger, _processUtils = ProcessUtils(logger: logger, processManager: processManager);
final String _deviceId; final String _adbPath; final Logger _logger; final ProcessUtils _processUtils;
static int? _extractPort(String portString) { return int.tryParse(portString.trim()); }
@override List<ForwardedPort> get forwardedPorts { final List<ForwardedPort> ports = <ForwardedPort>[];
String stdout; try { stdout = _processUtils.runSync( <String>[ _adbPath, '-s', _deviceId, 'forward', '--list', ], throwOnError: true, ).stdout.trim(); } on ProcessException catch (error) { _logger.printError('Failed to list forwarded ports: $error.'); return ports; }
final List<String> lines = LineSplitter.split(stdout).toList(); for (final String line in lines) { if (!line.startsWith(_deviceId)) { continue; } final List<String> splitLine = line.split('tcp:');
// Sanity check splitLine. if (splitLine.length != 3) { continue; }
// Attempt to extract ports. final int? hostPort = _extractPort(splitLine[1]); final int? devicePort = _extractPort(splitLine[2]);
// Failed, skip. if (hostPort == null || devicePort == null) { continue; }
ports.add(ForwardedPort(hostPort, devicePort)); }
return ports; }
@override Future<int> forward(int devicePort, { int? hostPort }) async { hostPort ??= 0; final RunResult process = await _processUtils.run( <String>[ _adbPath, '-s', _deviceId, 'forward', 'tcp:$hostPort', 'tcp:$devicePort', ], throwOnError: true, );
if (process.stderr.isNotEmpty) { process.throwException('adb returned error:\n${process.stderr}'); }
if (process.exitCode != 0) { if (process.stdout.isNotEmpty) { process.throwException('adb returned error:\n${process.stdout}'); } process.throwException('adb failed without a message'); }
if (hostPort == 0) { if (process.stdout.isEmpty) { process.throwException('adb did not report forwarded port'); } hostPort = int.tryParse(process.stdout); if (hostPort == null) { process.throwException('adb returned invalid port number:\n${process.stdout}'); } } else { // stdout may be empty or the port we asked it to forward, though it's // not documented (or obvious) what triggers each case. // // Observations are: // - On MacOS it's always empty when Flutter spawns the process, but // - On MacOS it prints the port number when run from the terminal, unless // the port is already forwarded, when it also prints nothing. // - On ChromeOS, the port appears to be printed even when Flutter spawns // the process // // To cover all cases, we accept the output being either empty or exactly // the port number, but treat any other output as probably being an error // message. if (process.stdout.isNotEmpty && process.stdout.trim() != '$hostPort') { process.throwException('adb returned error:\n${process.stdout}'); } }
return hostPort!; }
@override Future<void> unforward(ForwardedPort forwardedPort) async { final String tcpLine = 'tcp:${forwardedPort.hostPort}'; final RunResult runResult = await _processUtils.run( <String>[ _adbPath, '-s', _deviceId, 'forward', '--remove', tcpLine, ], ); if (runResult.exitCode == 0) { return; } _logger.printError('Failed to unforward port: $runResult'); }
@override Future<void> dispose() async { for (final ForwardedPort port in forwardedPorts) { await unforward(port); } }}
// In platform tools 29.0.0 adb.exe seems to be ending with this heap// corruption error code on seemingly successful termination. Ignore// this error on windows.bool _allowHeapCorruptionOnWindows(int exitCode, Platform platform) { return exitCode == -1073740940 && platform.isWindows;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199// 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:process/process.dart';
import '../base/common.dart';import '../base/file_system.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/platform.dart';import '../base/process.dart';import '../base/user_messages.dart';import '../device.dart';import 'adb.dart';import 'android_device.dart';import 'android_sdk.dart';import 'android_workflow.dart';
/// Device discovery for Android physical devices and emulators.////// This class primarily delegates to the `adb` command line tool provided by/// the Android SDK to discover instances of connected android devices.////// See also:/// * [AndroidDevice], the type of discovered device.class AndroidDevices extends PollingDeviceDiscovery { AndroidDevices({ required AndroidWorkflow androidWorkflow, required ProcessManager processManager, required Logger logger, AndroidSdk? androidSdk, required FileSystem fileSystem, required Platform platform, required UserMessages userMessages, }) : _androidWorkflow = androidWorkflow, _androidSdk = androidSdk, _processUtils = ProcessUtils( logger: logger, processManager: processManager, ), _processManager = processManager, _logger = logger, _fileSystem = fileSystem, _platform = platform, _userMessages = userMessages, super('Android devices');
final AndroidWorkflow _androidWorkflow; final ProcessUtils _processUtils; final AndroidSdk? _androidSdk; final ProcessManager _processManager; final Logger _logger; final FileSystem _fileSystem; final Platform _platform; final UserMessages _userMessages;
@override bool get supportsPlatform => _androidWorkflow.appliesToHostPlatform;
@override bool get canListAnything => _androidWorkflow.canListDevices;
@override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async { if (_doesNotHaveAdb()) { return <AndroidDevice>[]; } String text; try { text = (await _processUtils.run(<String>[_androidSdk!.adbPath!, 'devices', '-l'], throwOnError: true, )).stdout.trim(); } on ProcessException catch (exception) { throwToolExit( 'Unable to run "adb", check your Android SDK installation and ' '$kAndroidHome environment variable: ${exception.executable}', ); } final List<AndroidDevice> devices = <AndroidDevice>[]; _parseADBDeviceOutput( text, devices: devices, ); return devices; }
@override Future<List<String>> getDiagnostics() async { if (_doesNotHaveAdb()) { return <String>[]; }
final RunResult result = await _processUtils.run(<String>[_androidSdk!.adbPath!, 'devices', '-l']); if (result.exitCode != 0) { return <String>[]; } final List<String> diagnostics = <String>[]; _parseADBDeviceOutput( result.stdout, diagnostics: diagnostics, ); return diagnostics; }
bool _doesNotHaveAdb() { return _androidSdk == null || _androidSdk.adbPath == null || !_processManager.canRun(_androidSdk.adbPath); }
// 015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper static final RegExp _kDeviceRegex = RegExp(r'^(\S+)\s+(\S+)(.*)');
/// Parse the given `adb devices` output in [text], and fill out the given list /// of devices and possible device issue diagnostics. Either argument can be null, /// in which case information for that parameter won't be populated. void _parseADBDeviceOutput( String text, { List<AndroidDevice>? devices, List<String>? diagnostics, }) { // Check for error messages from adb if (!text.contains('List of devices')) { diagnostics?.add(text); return; }
for (final String line in text.trim().split('\n')) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) { continue; }
// Skip lines about adb server and client version not matching if (line.startsWith(RegExp(r'adb server (version|is out of date)'))) { diagnostics?.add(line); continue; }
if (line.startsWith('List of devices')) { continue; }
if (_kDeviceRegex.hasMatch(line)) { final Match match = _kDeviceRegex.firstMatch(line)!;
final String deviceID = match[1]!; final String deviceState = match[2]!; String? rest = match[3];
final Map<String, String> info = <String, String>{}; if (rest != null && rest.isNotEmpty) { rest = rest.trim(); for (final String data in rest.split(' ')) { if (data.contains(':')) { final List<String> fields = data.split(':'); info[fields[0]] = fields[1]; } } }
final String? model = info['model']; if (model != null) { info['model'] = cleanAdbDeviceName(model); }
if (deviceState == 'unauthorized') { diagnostics?.add( 'Device $deviceID is not authorized.\n' 'You might need to check your device for an authorization dialog.' ); } else if (deviceState == 'offline') { diagnostics?.add('Device $deviceID is offline.'); } else { devices?.add(AndroidDevice( deviceID, productID: info['product'], modelID: info['model'] ?? deviceID, deviceCodeName: info['device'], androidSdk: _androidSdk!, fileSystem: _fileSystem, logger: _logger, platform: _platform, processManager: _processManager, )); } } else { diagnostics?.add( 'Unexpected failure parsing device information from adb output:\n' '$line\n' '${_userMessages.flutterToolBugInstructions}'); } } }
@override List<String> get wellKnownIds => const <String>[];}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232// 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:meta/meta.dart';import 'package:process/process.dart';
import '../base/file_system.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/process.dart';import '../convert.dart';import '../device.dart';import '../emulator.dart';import 'android_sdk.dart';import 'android_workflow.dart';
class AndroidEmulators extends EmulatorDiscovery { AndroidEmulators({ AndroidSdk? androidSdk, required AndroidWorkflow androidWorkflow, required FileSystem fileSystem, required Logger logger, required ProcessManager processManager, }) : _androidSdk = androidSdk, _androidWorkflow = androidWorkflow, _fileSystem = fileSystem, _logger = logger, _processManager = processManager, _processUtils = ProcessUtils(logger: logger, processManager: processManager);
final AndroidWorkflow _androidWorkflow; final AndroidSdk? _androidSdk; final FileSystem _fileSystem; final Logger _logger; final ProcessManager _processManager; final ProcessUtils _processUtils;
@override bool get supportsPlatform => true;
@override bool get canListAnything => _androidWorkflow.canListEmulators;
@override bool get canLaunchAnything => _androidWorkflow.canListEmulators && _androidSdk?.getAvdManagerPath() != null;
@override Future<List<Emulator>> get emulators => _getEmulatorAvds();
/// Return the list of available emulator AVDs. Future<List<AndroidEmulator>> _getEmulatorAvds() async { final String? emulatorPath = _androidSdk?.emulatorPath; if (emulatorPath == null) { return <AndroidEmulator>[]; }
final String listAvdsOutput = (await _processUtils.run( <String>[emulatorPath, '-list-avds'])).stdout.trim();
final List<AndroidEmulator> emulators = <AndroidEmulator>[]; _extractEmulatorAvdInfo(listAvdsOutput, emulators); return emulators; }
/// Parse the given `emulator -list-avds` output in [text], and fill out the given list /// of emulators by reading information from the relevant ini files. void _extractEmulatorAvdInfo(String text, List<AndroidEmulator> emulators) { for (final String id in text.trim().split('\n').where((String l) => l != '')) { emulators.add(_loadEmulatorInfo(id)); } }
AndroidEmulator _loadEmulatorInfo(String id) { id = id.trim(); final String? avdPath = _androidSdk?.getAvdPath(); final AndroidEmulator androidEmulatorWithoutProperties = AndroidEmulator( id, processManager: _processManager, logger: _logger, androidSdk: _androidSdk, ); if (avdPath == null) { return androidEmulatorWithoutProperties; } final File iniFile = _fileSystem.file(_fileSystem.path.join(avdPath, '$id.ini')); if (!iniFile.existsSync()) { return androidEmulatorWithoutProperties; } final Map<String, String> ini = parseIniLines(iniFile.readAsLinesSync()); final String? path = ini['path']; if (path == null) { return androidEmulatorWithoutProperties; } final File configFile = _fileSystem.file(_fileSystem.path.join(path, 'config.ini')); if (!configFile.existsSync()) { return androidEmulatorWithoutProperties; } final Map<String, String> properties = parseIniLines(configFile.readAsLinesSync()); return AndroidEmulator( id, properties: properties, processManager: _processManager, logger: _logger, androidSdk: _androidSdk, ); }}
class AndroidEmulator extends Emulator { AndroidEmulator(String id, { Map<String, String>? properties, required Logger logger, AndroidSdk? androidSdk, required ProcessManager processManager, }) : _properties = properties, _logger = logger, _androidSdk = androidSdk, _processUtils = ProcessUtils(logger: logger, processManager: processManager), super(id, properties != null && properties.isNotEmpty);
final Map<String, String>? _properties; final Logger _logger; final ProcessUtils _processUtils; final AndroidSdk? _androidSdk;
// Android Studio uses the ID with underscores replaced with spaces // for the name if displayname is not set so we do the same. @override String get name => _prop('avd.ini.displayname') ?? id.replaceAll('_', ' ').trim();
@override String? get manufacturer => _prop('hw.device.manufacturer');
@override Category get category => Category.mobile;
@override PlatformType get platformType => PlatformType.android;
String? _prop(String name) => _properties != null ? _properties[name] : null;
@override Future<void> launch({@visibleForTesting Duration? startupDuration, bool coldBoot = false}) async { final String? emulatorPath = _androidSdk?.emulatorPath; if (emulatorPath == null) { throw Exception('Emulator is missing from the Android SDK'); } final List<String> command = <String>[ emulatorPath, '-avd', id, if (coldBoot) '-no-snapshot-load', ]; final Process process = await _processUtils.start(command);
// Record output from the emulator process. final List<String> stdoutList = <String>[]; final List<String> stderrList = <String>[]; final StreamSubscription<String> stdoutSubscription = process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(stdoutList.add); final StreamSubscription<String> stderrSubscription = process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(stderrList.add); final Future<void> stdioFuture = Future.wait<void>(<Future<void>>[ stdoutSubscription.asFuture<void>(), stderrSubscription.asFuture<void>(), ]);
// The emulator continues running on success, so we don't wait for the // process to complete before continuing. However, if the process fails // after the startup phase (3 seconds), then we only echo its output if // its error code is non-zero and its stderr is non-empty. bool earlyFailure = true; unawaited(process.exitCode.then((int status) async { if (status == 0) { _logger.printTrace('The Android emulator exited successfully'); return; } // Make sure the process' stdout and stderr are drained. await stdioFuture; unawaited(stdoutSubscription.cancel()); unawaited(stderrSubscription.cancel()); if (stdoutList.isNotEmpty) { _logger.printTrace('Android emulator stdout:'); stdoutList.forEach(_logger.printTrace); } if (!earlyFailure && stderrList.isEmpty) { _logger.printStatus('The Android emulator exited with code $status'); return; } final String when = earlyFailure ? 'during startup' : 'after startup'; _logger.printError('The Android emulator exited with code $status $when'); _logger.printError('Android emulator stderr:'); stderrList.forEach(_logger.printError); _logger.printError('Address these issues and try again.'); }));
// Wait a few seconds for the emulator to start. await Future<void>.delayed(startupDuration ?? const Duration(seconds: 3)); earlyFailure = false; return; }}
@visibleForTestingMap<String, String> parseIniLines(List<String> contents) { final Map<String, String> results = <String, String>{};
final Iterable<List<String>> properties = contents .map<String>((String l) => l.trim()) // Strip blank lines/comments .where((String l) => l != '' && !l.startsWith('#')) // Discard anything that isn't simple name=value .where((String l) => l.contains('=')) // Split into name/value .map<List<String>>((String l) => l.split('='));
for (final List<String> property in properties) { results[property[0].trim()] = property[1].trim(); }
return results;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623// 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 '../base/common.dart';import '../base/config.dart';import '../base/file_system.dart';import '../base/platform.dart';import '../base/process.dart';import '../base/version.dart';import '../convert.dart';import '../globals.dart' as globals;import 'java.dart';
// ANDROID_SDK_ROOT is deprecated.// See https://developer.android.com/studio/command-line/variables.html#envarconst String kAndroidSdkRoot = 'ANDROID_SDK_ROOT';const String kAndroidHome = 'ANDROID_HOME';
// No official environment variable for the NDK root is documented:// https://developer.android.com/tools/variables#envar// The follow three seem to be most commonly used.const String kAndroidNdkHome = 'ANDROID_NDK_HOME';const String kAndroidNdkPath = 'ANDROID_NDK_PATH';const String kAndroidNdkRoot = 'ANDROID_NDK_ROOT';
final RegExp _numberedAndroidPlatformRe = RegExp(r'^android-([0-9]+)$');final RegExp _sdkVersionRe = RegExp(r'^ro.build.version.sdk=([0-9]+)$');
// Android SDK layout:
// $ANDROID_HOME/platform-tools/adb
// $ANDROID_HOME/build-tools/19.1.0/aapt, dx, zipalign// $ANDROID_HOME/build-tools/22.0.1/aapt// $ANDROID_HOME/build-tools/23.0.2/aapt// $ANDROID_HOME/build-tools/24.0.0-preview/aapt// $ANDROID_HOME/build-tools/25.0.2/apksigner
// $ANDROID_HOME/platforms/android-22/android.jar// $ANDROID_HOME/platforms/android-23/android.jar// $ANDROID_HOME/platforms/android-N/android.jarclass AndroidSdk { AndroidSdk(this.directory, { Java? java, FileSystem? fileSystem, }): _java = java { reinitialize(fileSystem: fileSystem); }
/// The Android SDK root directory. final Directory directory;
final Java? _java;
List<AndroidSdkVersion> _sdkVersions = <AndroidSdkVersion>[]; AndroidSdkVersion? _latestVersion;
/// Whether the `cmdline-tools` directory exists in the Android SDK. /// /// This is required to use the newest SDK manager which only works with /// the newer JDK. bool get cmdlineToolsAvailable => directory.childDirectory('cmdline-tools').existsSync();
/// Whether the `platform-tools` or `cmdline-tools` directory exists in the Android SDK. /// /// It is possible to have an Android SDK folder that is missing this with /// the expectation that it will be downloaded later, e.g. by gradle or the /// sdkmanager. The [licensesAvailable] property should be used to determine /// whether the licenses are at least possibly accepted. bool get platformToolsAvailable => cmdlineToolsAvailable || directory.childDirectory('platform-tools').existsSync();
/// Whether the `licenses` directory exists in the Android SDK. /// /// The existence of this folder normally indicates that the SDK licenses have /// been accepted, e.g. via the sdkmanager, Android Studio, or by copying them /// from another workstation such as in CI scenarios. If these files are valid /// gradle or the sdkmanager will be able to download and use other parts of /// the SDK on demand. bool get licensesAvailable => directory.childDirectory('licenses').existsSync();
static AndroidSdk? locateAndroidSdk() { String? findAndroidHomeDir() { String? androidHomeDir; if (globals.config.containsKey('android-sdk')) { androidHomeDir = globals.config.getValue('android-sdk') as String?; } else if (globals.platform.environment.containsKey(kAndroidHome)) { androidHomeDir = globals.platform.environment[kAndroidHome]; } else if (globals.platform.environment.containsKey(kAndroidSdkRoot)) { androidHomeDir = globals.platform.environment[kAndroidSdkRoot]; } else if (globals.platform.isLinux) { if (globals.fsUtils.homeDirPath != null) { androidHomeDir = globals.fs.path.join( globals.fsUtils.homeDirPath!, 'Android', 'Sdk', ); } } else if (globals.platform.isMacOS) { if (globals.fsUtils.homeDirPath != null) { androidHomeDir = globals.fs.path.join( globals.fsUtils.homeDirPath!, 'Library', 'Android', 'sdk', ); } } else if (globals.platform.isWindows) { if (globals.fsUtils.homeDirPath != null) { androidHomeDir = globals.fs.path.join( globals.fsUtils.homeDirPath!, 'AppData', 'Local', 'Android', 'sdk', ); } }
if (androidHomeDir != null) { if (validSdkDirectory(androidHomeDir)) { return androidHomeDir; } if (validSdkDirectory(globals.fs.path.join(androidHomeDir, 'sdk'))) { return globals.fs.path.join(androidHomeDir, 'sdk'); } }
// in build-tools/$version/aapt final List<File> aaptBins = globals.os.whichAll('aapt'); for (File aaptBin in aaptBins) { // Make sure we're using the aapt from the SDK. aaptBin = globals.fs.file(aaptBin.resolveSymbolicLinksSync()); final String dir = aaptBin.parent.parent.parent.path; if (validSdkDirectory(dir)) { return dir; } }
// in platform-tools/adb final List<File> adbBins = globals.os.whichAll('adb'); for (File adbBin in adbBins) { // Make sure we're using the adb from the SDK. adbBin = globals.fs.file(adbBin.resolveSymbolicLinksSync()); final String dir = adbBin.parent.parent.path; if (validSdkDirectory(dir)) { return dir; } }
return null; }
final String? androidHomeDir = findAndroidHomeDir(); if (androidHomeDir == null) { // No dice. globals.printTrace('Unable to locate an Android SDK.'); return null; }
return AndroidSdk(globals.fs.directory(androidHomeDir)); }
static bool validSdkDirectory(String dir) { return sdkDirectoryHasLicenses(dir) || sdkDirectoryHasPlatformTools(dir); }
static bool sdkDirectoryHasPlatformTools(String dir) { return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'platform-tools')); }
static bool sdkDirectoryHasLicenses(String dir) { return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'licenses')); }
List<AndroidSdkVersion> get sdkVersions => _sdkVersions;
AndroidSdkVersion? get latestVersion => _latestVersion;
late final String? adbPath = getPlatformToolsPath(globals.platform.isWindows ? 'adb.exe' : 'adb');
String? get emulatorPath => getEmulatorPath();
String? get avdManagerPath => getAvdManagerPath();
/// Locate the path for storing AVD emulator images. Returns null if none found. String? getAvdPath() { final String? avdHome = globals.platform.environment['ANDROID_AVD_HOME']; final String? home = globals.platform.environment['HOME']; final List<String> searchPaths = <String>[ if (avdHome != null) avdHome, if (home != null) globals.fs.path.join(home, '.android', 'avd'), ];
if (globals.platform.isWindows) { final String? homeDrive = globals.platform.environment['HOMEDRIVE']; final String? homePath = globals.platform.environment['HOMEPATH'];
if (homeDrive != null && homePath != null) { // Can't use path.join for HOMEDRIVE/HOMEPATH // https://github.com/dart-lang/path/issues/37 final String home = homeDrive + homePath; searchPaths.add(globals.fs.path.join(home, '.android', 'avd')); } }
for (final String searchPath in searchPaths) { if (globals.fs.directory(searchPath).existsSync()) { return searchPath; } } return null; }
Directory get _platformsDir => directory.childDirectory('platforms');
Iterable<Directory> get _platforms { Iterable<Directory> platforms = <Directory>[]; if (_platformsDir.existsSync()) { platforms = _platformsDir .listSync() .whereType<Directory>(); } return platforms; }
/// Validate the Android SDK. This returns an empty list if there are no /// issues; otherwise, it returns a list of issues found. List<String> validateSdkWellFormed() { if (adbPath == null || !globals.processManager.canRun(adbPath)) { return <String>['Android SDK file not found: ${adbPath ?? 'adb'}.']; }
if (sdkVersions.isEmpty || latestVersion == null) { final StringBuffer msg = StringBuffer('No valid Android SDK platforms found in ${_platformsDir.path}.'); if (_platforms.isEmpty) { msg.write(' Directory was empty.'); } else { msg.write(' Candidates were:\n'); msg.write(_platforms .map((Directory dir) => ' - ${dir.basename}') .join('\n')); } return <String>[msg.toString()]; }
return latestVersion!.validateSdkWellFormed(); }
String? getPlatformToolsPath(String binaryName) { final File cmdlineToolsBinary = directory.childDirectory('cmdline-tools').childFile(binaryName); if (cmdlineToolsBinary.existsSync()) { return cmdlineToolsBinary.path; } final File platformToolBinary = directory.childDirectory('platform-tools').childFile(binaryName); if (platformToolBinary.existsSync()) { return platformToolBinary.path; } return null; }
String? getEmulatorPath() { final String binaryName = globals.platform.isWindows ? 'emulator.exe' : 'emulator'; // Emulator now lives inside "emulator" but used to live inside "tools" so // try both. final List<String> searchFolders = <String>['emulator', 'tools']; for (final String folder in searchFolders) { final File file = directory.childDirectory(folder).childFile(binaryName); if (file.existsSync()) { return file.path; } } return null; }
String? getCmdlineToolsPath(String binaryName, {bool skipOldTools = false}) { // First look for the latest version of the command-line tools final File cmdlineToolsLatestBinary = directory .childDirectory('cmdline-tools') .childDirectory('latest') .childDirectory('bin') .childFile(binaryName); if (cmdlineToolsLatestBinary.existsSync()) { return cmdlineToolsLatestBinary.path; }
// Next look for the highest version of the command-line tools final Directory cmdlineToolsDir = directory.childDirectory('cmdline-tools'); if (cmdlineToolsDir.existsSync()) { final List<Version> cmdlineTools = cmdlineToolsDir .listSync() .whereType<Directory>() .map((Directory subDirectory) { try { return Version.parse(subDirectory.basename); } on Exception { return null; } }) .whereType<Version>() .toList(); cmdlineTools.sort();
for (final Version cmdlineToolsVersion in cmdlineTools.reversed) { final File cmdlineToolsBinary = directory .childDirectory('cmdline-tools') .childDirectory(cmdlineToolsVersion.toString()) .childDirectory('bin') .childFile(binaryName); if (cmdlineToolsBinary.existsSync()) { return cmdlineToolsBinary.path; } } } if (skipOldTools) { return null; }
// Finally fallback to the old SDK tools final File toolsBinary = directory.childDirectory('tools').childDirectory('bin').childFile(binaryName); if (toolsBinary.existsSync()) { return toolsBinary.path; }
return null; }
String? getAvdManagerPath() => getCmdlineToolsPath(globals.platform.isWindows ? 'avdmanager.bat' : 'avdmanager');
/// From https://developer.android.com/ndk/guides/other_build_systems. static const Map<String, String> _llvmHostDirectoryName = <String, String>{ 'macos': 'darwin-x86_64', 'linux': 'linux-x86_64', 'windows': 'windows-x86_64', };
/// Locates the binary path for an NDK binary. /// /// The order of resolution is as follows: /// /// 1. If [globals.config] defines an `'android-ndk'` use that. /// 2. If the environment variable `ANDROID_NDK_HOME` is defined, use that. /// 3. If the environment variable `ANDROID_NDK_PATH` is defined, use that. /// 4. If the environment variable `ANDROID_NDK_ROOT` is defined, use that. /// 5. Look for the default install location inside the Android SDK: /// [directory]/ndk/\<version\>/. If multiple versions exist, use the /// newest. String? getNdkBinaryPath( String binaryName, { Platform? platform, Config? config, }) { platform ??= globals.platform; config ??= globals.config; Directory? findAndroidNdkHomeDir() { String? androidNdkHomeDir; if (config!.containsKey('android-ndk')) { androidNdkHomeDir = config.getValue('android-ndk') as String?; } else if (platform!.environment.containsKey(kAndroidNdkHome)) { androidNdkHomeDir = platform.environment[kAndroidNdkHome]; } else if (platform.environment.containsKey(kAndroidNdkPath)) { androidNdkHomeDir = platform.environment[kAndroidNdkPath]; } else if (platform.environment.containsKey(kAndroidNdkRoot)) { androidNdkHomeDir = platform.environment[kAndroidNdkRoot]; } if (androidNdkHomeDir != null) { return directory.fileSystem.directory(androidNdkHomeDir); }
// Look for the default install location of the NDK inside the Android // SDK when installed through `sdkmanager` or Android studio. final Directory ndk = directory.childDirectory('ndk'); if (!ndk.existsSync()) { return null; } final List<Version> ndkVersions = ndk .listSync() .map((FileSystemEntity entity) { try { return Version.parse(entity.basename); } on Exception { return null; } }) .whereType<Version>() .toList() // Use latest NDK first. ..sort((Version a, Version b) => -a.compareTo(b)); if (ndkVersions.isEmpty) { return null; } return ndk.childDirectory(ndkVersions.first.toString()); }
final Directory? androidNdkHomeDir = findAndroidNdkHomeDir(); if (androidNdkHomeDir == null) { return null; } final File executable = androidNdkHomeDir .childDirectory('toolchains') .childDirectory('llvm') .childDirectory('prebuilt') .childDirectory(_llvmHostDirectoryName[platform.operatingSystem]!) .childDirectory('bin') .childFile(binaryName); if (executable.existsSync()) { // LLVM missing in this NDK version. return executable.path; } return null; }
String? getNdkClangPath({Platform? platform, Config? config}) { platform ??= globals.platform; return getNdkBinaryPath( platform.isWindows ? 'clang.exe' : 'clang', platform: platform, config: config, ); }
String? getNdkArPath({Platform? platform, Config? config}) { platform ??= globals.platform; return getNdkBinaryPath( platform.isWindows ? 'llvm-ar.exe' : 'llvm-ar', platform: platform, config: config, ); }
String? getNdkLdPath({Platform? platform, Config? config}) { platform ??= globals.platform; return getNdkBinaryPath( platform.isWindows ? 'ld.lld.exe' : 'ld.lld', platform: platform, config: config, ); }
/// Sets up various paths used internally. /// /// This method should be called in a case where the tooling may have updated /// SDK artifacts, such as after running a gradle build. void reinitialize({FileSystem? fileSystem}) { List<Version> buildTools = <Version>[]; // 19.1.0, 22.0.1, ...
final Directory buildToolsDir = directory.childDirectory('build-tools'); if (buildToolsDir.existsSync()) { buildTools = buildToolsDir .listSync() .map((FileSystemEntity entity) { try { return Version.parse(entity.basename); } on Exception { return null; } }) .whereType<Version>() .toList(); }
// Match up platforms with the best corresponding build-tools. _sdkVersions = _platforms.map<AndroidSdkVersion?>((Directory platformDir) { final String platformName = platformDir.basename; int platformVersion;
try { final Match? numberedVersion = _numberedAndroidPlatformRe.firstMatch(platformName); if (numberedVersion != null) { platformVersion = int.parse(numberedVersion.group(1)!); } else { final String buildProps = platformDir.childFile('build.prop').readAsStringSync(); final Iterable<Match> versionMatches = const LineSplitter() .convert(buildProps) .map<RegExpMatch?>(_sdkVersionRe.firstMatch) .whereType<Match>();
if (versionMatches.isEmpty) { return null; }
final String? versionString = versionMatches.first.group(1); if (versionString == null) { return null; } platformVersion = int.parse(versionString); } } on Exception { return null; }
Version? buildToolsVersion = Version.primary(buildTools.where((Version version) { return version.major == platformVersion; }).toList());
buildToolsVersion ??= Version.primary(buildTools);
if (buildToolsVersion == null) { return null; }
return AndroidSdkVersion._( this, sdkLevel: platformVersion, platformName: platformName, buildToolsVersion: buildToolsVersion, fileSystem: fileSystem ?? globals.fs, ); }).whereType<AndroidSdkVersion>().toList();
_sdkVersions.sort();
_latestVersion = _sdkVersions.isEmpty ? null : _sdkVersions.last; }
/// Returns the filesystem path of the Android SDK manager tool. String? get sdkManagerPath { final String executable = globals.platform.isWindows ? 'sdkmanager.bat' : 'sdkmanager'; final String? path = getCmdlineToolsPath(executable, skipOldTools: true); if (path != null) { return path; } return null; }
/// Returns the version of the Android SDK manager tool or null if not found. String? get sdkManagerVersion { if (sdkManagerPath == null || !globals.processManager.canRun(sdkManagerPath)) { throwToolExit( 'Android sdkmanager not found. Update to the latest Android SDK and ensure that ' 'the cmdline-tools are installed to resolve this.' ); } final RunResult result = globals.processUtils.runSync( <String>[sdkManagerPath!, '--version'], environment: _java?.environment, ); if (result.exitCode != 0) { globals.printTrace('sdkmanager --version failed: exitCode: ${result.exitCode} stdout: ${result.stdout} stderr: ${result.stderr}'); return null; } return result.stdout.trim(); }
@override String toString() => 'AndroidSdk: $directory';}
class AndroidSdkVersion implements Comparable<AndroidSdkVersion> { AndroidSdkVersion._( this.sdk, { required this.sdkLevel, required this.platformName, required this.buildToolsVersion, required FileSystem fileSystem, }) : _fileSystem = fileSystem;
final AndroidSdk sdk; final int sdkLevel; final String platformName; final Version buildToolsVersion;
final FileSystem _fileSystem;
String get buildToolsVersionName => buildToolsVersion.toString();
String get androidJarPath => getPlatformsPath('android.jar');
/// Return the path to the android application package tool. /// /// This is used to dump the xml in order to launch built android applications. /// /// See also: /// * [AndroidApk.fromApk], which depends on this to determine application identifiers. String get aaptPath => getBuildToolsPath('aapt');
List<String> validateSdkWellFormed() { final String? existsAndroidJarPath = _exists(androidJarPath); if (existsAndroidJarPath != null) { return <String>[existsAndroidJarPath]; }
final String? canRunAaptPath = _canRun(aaptPath); if (canRunAaptPath != null) { return <String>[canRunAaptPath]; }
return <String>[]; }
String getPlatformsPath(String itemName) { return sdk.directory.childDirectory('platforms').childDirectory(platformName).childFile(itemName).path; }
String getBuildToolsPath(String binaryName) { return sdk.directory.childDirectory('build-tools').childDirectory(buildToolsVersionName).childFile(binaryName).path; }
@override int compareTo(AndroidSdkVersion other) => sdkLevel - other.sdkLevel;
@override String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]';
String? _exists(String path) { if (!_fileSystem.isFileSync(path)) { return 'Android SDK file not found: $path.'; } return null; }
String? _canRun(String path) { if (!globals.processManager.canRun(path)) { return 'Android SDK file not found: $path.'; } return null; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579// 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 '../base/common.dart';import '../base/file_system.dart';import '../base/io.dart';import '../base/process.dart';import '../base/utils.dart';import '../base/version.dart';import '../convert.dart';import '../globals.dart' as globals;import '../ios/plist_parser.dart';import 'android_studio_validator.dart';
// Android Studio layout:
// Linux/Windows:// $HOME/.AndroidStudioX.Y/system/.home// $HOME/.cache/Google/AndroidStudioX.Y/.home
// macOS:// /Applications/Android Studio.app/Contents/// $HOME/Applications/Android Studio.app/Contents/
// Match Android Studio >= 4.1 base folder (AndroidStudio*.*)// and < 4.1 (.AndroidStudio*.*)final RegExp _dotHomeStudioVersionMatcher = RegExp(r'^\.?(AndroidStudio[^\d]*)([\d.]+)');
class AndroidStudio { /// A [version] value of null represents an unknown version. AndroidStudio( this.directory, { this.version, this.configuredPath, this.studioAppName = 'AndroidStudio', this.presetPluginsPath, }) { _initAndValidate(); }
static AndroidStudio? fromMacOSBundle( String bundlePath, { String? configuredPath, }) { final String studioPath = globals.fs.path.join(bundlePath, 'Contents'); final String plistFile = globals.fs.path.join(studioPath, 'Info.plist'); final Map<String, dynamic> plistValues = globals.plistParser.parseFile(plistFile); // If we've found a JetBrainsToolbox wrapper, ignore it. if (plistValues.containsKey('JetBrainsToolboxApp')) { return null; }
final String? versionString = plistValues[PlistParser.kCFBundleShortVersionStringKey] as String?;
Version? version; if (versionString != null) { version = Version.parse(versionString); }
String? pathsSelectorValue; final Map<String, dynamic>? jvmOptions = castStringKeyedMap(plistValues['JVMOptions']); if (jvmOptions != null) { final Map<String, dynamic>? jvmProperties = castStringKeyedMap(jvmOptions['Properties']); if (jvmProperties != null) { pathsSelectorValue = jvmProperties['idea.paths.selector'] as String; } }
final int? major = version?.major; final int? minor = version?.minor; String? presetPluginsPath; final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath != null && pathsSelectorValue != null) { if (major != null && major >= 4 && minor != null && minor >= 1) { presetPluginsPath = globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'Google', pathsSelectorValue, ); } else { presetPluginsPath = globals.fs.path.join( homeDirPath, 'Library', 'Application Support', pathsSelectorValue, ); } } return AndroidStudio( studioPath, version: version, presetPluginsPath: presetPluginsPath, configuredPath: configuredPath, ); }
static AndroidStudio? fromHomeDot(Directory homeDotDir) { final Match? versionMatch = _dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename); if (versionMatch?.groupCount != 2) { return null; } final Version? version = Version.parse(versionMatch![2]); final String? studioAppName = versionMatch[1]; if (studioAppName == null || version == null) { return null; }
final int major = version.major; final int minor = version.minor;
// The install path is written in a .home text file, // it location is in <base dir>/.home for Android Studio >= 4.1 // and <base dir>/system/.home for Android Studio < 4.1 String dotHomeFilePath;
if (major >= 4 && minor >= 1) { dotHomeFilePath = globals.fs.path.join(homeDotDir.path, '.home'); } else { dotHomeFilePath = globals.fs.path.join(homeDotDir.path, 'system', '.home'); }
String? installPath;
try { installPath = globals.fs.file(dotHomeFilePath).readAsStringSync(); } on Exception { // ignored, installPath will be null, which is handled below }
if (installPath != null && globals.fs.isDirectorySync(installPath)) { return AndroidStudio( installPath, version: version, studioAppName: studioAppName, ); } return null; }
final String directory; final String studioAppName;
/// The version of Android Studio. /// /// A null value represents an unknown version. final Version? version;
final String? configuredPath; final String? presetPluginsPath;
String? _javaPath; bool _isValid = false; final List<String> _validationMessages = <String>[];
/// The path of the JDK bundled with Android Studio. /// /// This will be null if the bundled JDK could not be found or run. /// /// If you looking to invoke the java binary or add it to the system /// environment variables, consider using the [Java] class instead. String? get javaPath => _javaPath;
bool get isValid => _isValid;
String? get pluginsPath { if (presetPluginsPath != null) { return presetPluginsPath!; }
// TODO(andrewkolos): This is a bug. We shouldn't treat an unknown // version as equivalent to 0.0. // See https://github.com/flutter/flutter/issues/121468. final int major = version?.major ?? 0; final int minor = version?.minor ?? 0; final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath == null) { return null; } if (globals.platform.isMacOS) { /// plugin path of Android Studio has been changed after version 4.1. if (major >= 4 && minor >= 1) { return globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'Google', 'AndroidStudio$major.$minor', ); } else { return globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'AndroidStudio$major.$minor', ); } } else { // JetBrains Toolbox write plugins here final String toolboxPluginsPath = '$directory.plugins';
if (globals.fs.directory(toolboxPluginsPath).existsSync()) { return toolboxPluginsPath; }
if (major >= 4 && minor >= 1 && globals.platform.isLinux) { return globals.fs.path.join( homeDirPath, '.local', 'share', 'Google', '$studioAppName$major.$minor', ); }
return globals.fs.path.join( homeDirPath, '.$studioAppName$major.$minor', 'config', 'plugins', ); } }
List<String> get validationMessages => _validationMessages;
/// Locates the newest, valid version of Android Studio. /// /// In the case that `--android-studio-dir` is configured, the version of /// Android Studio found at that location is always returned, even if it is /// invalid. static AndroidStudio? latestValid() { final Directory? configuredStudioDir = _configuredDir();
// Find all available Studio installations. final List<AndroidStudio> studios = allInstalled(); if (studios.isEmpty) { return null; }
final AndroidStudio? manuallyConfigured = studios .where((AndroidStudio studio) => studio.configuredPath != null && configuredStudioDir != null && _pathsAreEqual(studio.configuredPath!, configuredStudioDir.path)) .firstOrNull;
if (manuallyConfigured != null) { return manuallyConfigured; }
AndroidStudio? newest; for (final AndroidStudio studio in studios.where((AndroidStudio s) => s.isValid)) { if (newest == null) { newest = studio; continue; }
// We prefer installs with known versions. if (studio.version != null && newest.version == null) { newest = studio; } else if (studio.version != null && newest.version != null && studio.version! > newest.version!) { newest = studio; } else if (studio.version == null && newest.version == null && studio.directory.compareTo(newest.directory) > 0) { newest = studio; } }
return newest; }
static List<AndroidStudio> allInstalled() => globals.platform.isMacOS ? _allMacOS() : _allLinuxOrWindows();
static List<AndroidStudio> _allMacOS() { final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
void checkForStudio(String path) { if (!globals.fs.isDirectorySync(path)) { return; } try { final Iterable<Directory> directories = globals.fs .directory(path) .listSync(followLinks: false) .whereType<Directory>(); for (final Directory directory in directories) { final String name = directory.basename; // An exact match, or something like 'Android Studio 3.0 Preview.app'. if (name.startsWith('Android Studio') && name.endsWith('.app')) { candidatePaths.add(directory); } else if (!directory.path.endsWith('.app')) { checkForStudio(directory.path); } } } on Exception catch (e) { globals.printTrace('Exception while looking for Android Studio: $e'); } }
checkForStudio('/Applications'); final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath != null) { checkForStudio(globals.fs.path.join( homeDirPath, 'Applications', )); }
Directory? configuredStudioDir = _configuredDir(); if (configuredStudioDir != null) { if (configuredStudioDir.basename == 'Contents') { configuredStudioDir = configuredStudioDir.parent; } if (!candidatePaths .any((FileSystemEntity e) => _pathsAreEqual(e.path, configuredStudioDir!.path))) { candidatePaths.add(configuredStudioDir); } }
// Query Spotlight for unexpected installation locations. String spotlightQueryResult = ''; try { final ProcessResult spotlightResult = globals.processManager.runSync(<String>[ 'mdfind', // com.google.android.studio, com.google.android.studio-EAP 'kMDItemCFBundleIdentifier="com.google.android.studio*"', ]); spotlightQueryResult = spotlightResult.stdout as String; } on ProcessException { // The Spotlight query is a nice-to-have, continue checking known installation locations. } for (final String studioPath in LineSplitter.split(spotlightQueryResult)) { final Directory appBundle = globals.fs.directory(studioPath); if (!candidatePaths.any((FileSystemEntity e) => e.path == studioPath)) { candidatePaths.add(appBundle); } }
return candidatePaths .map<AndroidStudio?>((FileSystemEntity e) { if (configuredStudioDir == null) { return AndroidStudio.fromMacOSBundle(e.path); }
return AndroidStudio.fromMacOSBundle( e.path, configuredPath: _pathsAreEqual(configuredStudioDir.path, e.path) ? configuredStudioDir.path : null, ); }) .whereType<AndroidStudio>() .toList(); }
static List<AndroidStudio> _allLinuxOrWindows() { final List<AndroidStudio> studios = <AndroidStudio>[];
bool alreadyFoundStudioAt(String path, { Version? newerThan }) { return studios.any((AndroidStudio studio) { if (studio.directory != path) { return false; } if (newerThan != null) { if (studio.version == null) { return false; } return studio.version!.compareTo(newerThan) >= 0; } return true; }); }
// Read all $HOME/.AndroidStudio*/system/.home // or $HOME/.cache/Google/AndroidStudio*/.home files. // There may be several pointing to the same installation, // so we grab only the latest one. final String? homeDirPath = globals.fsUtils.homeDirPath;
if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) { final Directory homeDir = globals.fs.directory(homeDirPath);
final List<Directory> directoriesToSearch = <Directory>[homeDir];
// >=4.1 has new install location at $HOME/.cache/Google final String cacheDirPath = globals.fs.path.join(homeDirPath, '.cache', 'Google');
if (globals.fs.isDirectorySync(cacheDirPath)) { directoriesToSearch.add(globals.fs.directory(cacheDirPath)); }
final List<Directory> entities = <Directory>[];
for (final Directory baseDir in directoriesToSearch) { final Iterable<Directory> directories = baseDir.listSync(followLinks: false).whereType<Directory>(); entities.addAll(directories.where((Directory directory) => _dotHomeStudioVersionMatcher.hasMatch(directory.basename))); }
for (final Directory entity in entities) { final AndroidStudio? studio = AndroidStudio.fromHomeDot(entity); if (studio != null && !alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { studios.removeWhere((AndroidStudio other) => other.directory == studio.directory); studios.add(studio); } } }
// Discover Android Studio > 4.1 if (globals.platform.isWindows && globals.platform.environment.containsKey('LOCALAPPDATA')) { final Directory cacheDir = globals.fs.directory(globals.fs.path.join(globals.platform.environment['LOCALAPPDATA']!, 'Google')); if (!cacheDir.existsSync()) { return studios; } for (final Directory dir in cacheDir.listSync().whereType<Directory>()) { final String name = globals.fs.path.basename(dir.path); AndroidStudioValidator.idToTitle.forEach((String id, String title) { if (name.startsWith(id)) { final String version = name.substring(id.length); String? installPath;
try { installPath = globals.fs.file(globals.fs.path.join(dir.path, '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && globals.fs.isDirectorySync(installPath)) { final AndroidStudio studio = AndroidStudio( installPath, version: Version.parse(version), studioAppName: title, ); if (!alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { studios.removeWhere((AndroidStudio other) => _pathsAreEqual(other.directory, studio.directory)); studios.add(studio); } } } }); } }
final String? configuredStudioDir = globals.config.getValue('android-studio-dir') as String?; if (configuredStudioDir != null) { final AndroidStudio? matchingAlreadyFoundInstall = studios .where((AndroidStudio other) => _pathsAreEqual(configuredStudioDir, other.directory)) .firstOrNull; if (matchingAlreadyFoundInstall != null) { studios.remove(matchingAlreadyFoundInstall); studios.add( AndroidStudio( configuredStudioDir, configuredPath: configuredStudioDir, version: matchingAlreadyFoundInstall.version, ), ); } else { studios.add(AndroidStudio(configuredStudioDir, configuredPath: configuredStudioDir)); } }
if (globals.platform.isLinux) { void checkWellKnownPath(String path) { if (globals.fs.isDirectorySync(path) && !alreadyFoundStudioAt(path)) { studios.add(AndroidStudio(path)); } }
// Add /opt/android-studio and $HOME/android-studio, if they exist. checkWellKnownPath('/opt/android-studio'); checkWellKnownPath('${globals.fsUtils.homeDirPath}/android-studio'); } return studios; }
/// Gets the Android Studio install directory set by the user, if it is configured. /// /// The returned [Directory], if not null, is guaranteed to have existed during /// this function's execution. static Directory? _configuredDir() { final String? configuredPath = globals.config.getValue('android-studio-dir') as String?; if (configuredPath == null) { return null; } final Directory result = globals.fs.directory(configuredPath);
bool? configuredStudioPathExists; String? exceptionMessage; try { configuredStudioPathExists = result.existsSync(); } on FileSystemException catch (e) { exceptionMessage = e.toString(); }
if (configuredStudioPathExists == false || exceptionMessage != null) { throwToolExit('''Could not find the Android Studio installation at the manually configured path "$configuredPath".${exceptionMessage == null ? '' : 'Encountered exception: $exceptionMessage\n\n'}Please verify that the path is correct and update it by running this command: flutter config --android-studio-dir '<path>'To have flutter search for Android Studio installations automatically, removethe configured path by running this command: flutter config --android-studio-dir'''); }
return result; }
static String? extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) { return keyMatcher.stringMatch(plistValue)?.split('=').last.trim().replaceAll('"', ''); }
void _initAndValidate() { _isValid = false; _validationMessages.clear();
if (configuredPath != null) { _validationMessages.add('android-studio-dir = $configuredPath'); }
if (!globals.fs.isDirectorySync(directory)) { _validationMessages.add('Android Studio not found at $directory'); return; }
final String javaPath; if (globals.platform.isMacOS) { if (version != null && version!.major < 2020) { javaPath = globals.fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home'); } else if (version != null && version!.major < 2022) { javaPath = globals.fs.path.join(directory, 'jre', 'Contents', 'Home'); // See https://github.com/flutter/flutter/issues/125246 for more context. } else { javaPath = globals.fs.path.join(directory, 'jbr', 'Contents', 'Home'); } } else { if (version != null && version!.major < 2022) { javaPath = globals.fs.path.join(directory, 'jre'); } else { javaPath = globals.fs.path.join(directory, 'jbr'); } } final String javaExecutable = globals.fs.path.join(javaPath, 'bin', 'java'); if (!globals.processManager.canRun(javaExecutable)) { _validationMessages.add('Unable to find bundled Java version.'); } else { RunResult? result; try { result = globals.processUtils.runSync(<String>[javaExecutable, '-version']); } on ProcessException catch (e) { _validationMessages.add('Failed to run Java: $e'); } if (result != null && result.exitCode == 0) { final List<String> versionLines = result.stderr.split('\n'); final String javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; _validationMessages.add('Java version $javaVersion'); _javaPath = javaPath; _isValid = true; } else { _validationMessages.add('Unable to determine bundled Java version.'); } } }
@override String toString() => 'Android Studio ($version)';}
bool _pathsAreEqual(String path, String other) { return globals.fs.path.canonicalize(path) == globals.fs.path.canonicalize(other);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141// 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 '../base/config.dart';import '../base/file_system.dart';import '../base/platform.dart';import '../base/user_messages.dart';import '../doctor_validator.dart';import '../intellij/intellij.dart';import 'android_studio.dart';
const String _androidStudioTitle = 'Android Studio';const String _androidStudioId = 'AndroidStudio';const String _androidStudioPreviewTitle = 'Android Studio Preview';const String _androidStudioPreviewId = 'AndroidStudioPreview';
class AndroidStudioValidator extends DoctorValidator { AndroidStudioValidator(this._studio, { required FileSystem fileSystem, required UserMessages userMessages, }) : _userMessages = userMessages, _fileSystem = fileSystem, super('Android Studio');
final AndroidStudio _studio; final FileSystem _fileSystem; final UserMessages _userMessages;
static const Map<String, String> idToTitle = <String, String>{ _androidStudioId: _androidStudioTitle, _androidStudioPreviewId: _androidStudioPreviewTitle, };
static List<DoctorValidator> allValidators(Config config, Platform platform, FileSystem fileSystem, UserMessages userMessages) { final List<AndroidStudio> studios = AndroidStudio.allInstalled(); return <DoctorValidator>[ if (studios.isEmpty) NoAndroidStudioValidator(config: config, platform: platform, userMessages: userMessages) else ...studios.map<DoctorValidator>( (AndroidStudio studio) => AndroidStudioValidator(studio, fileSystem: fileSystem, userMessages: userMessages) ), ]; }
@override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; ValidationType type = ValidationType.missing;
final String studioVersionText = _studio.version == null ? _userMessages.androidStudioVersion('unknown') : _userMessages.androidStudioVersion(_studio.version.toString()); messages.add(ValidationMessage( _userMessages.androidStudioLocation(_studio.directory), ));
if (_studio.pluginsPath != null) { final IntelliJPlugins plugins = IntelliJPlugins(_studio.pluginsPath!, fileSystem: _fileSystem); plugins.validatePackage( messages, <String>['flutter-intellij', 'flutter-intellij.jar'], 'Flutter', IntelliJPlugins.kIntellijFlutterPluginUrl, minVersion: IntelliJPlugins.kMinFlutterPluginVersion, ); plugins.validatePackage( messages, <String>['Dart'], 'Dart', IntelliJPlugins.kIntellijDartPluginUrl, ); }
if (_studio.version == null) { messages.add(const ValidationMessage.error('Unable to determine Android Studio version.')); }
if (_studio.isValid) { type = _hasIssues(messages) ? ValidationType.partial : ValidationType.success; messages.addAll(_studio.validationMessages.map<ValidationMessage>( (String m) => ValidationMessage(m), )); } else { type = ValidationType.partial; messages.addAll(_studio.validationMessages.map<ValidationMessage>( (String m) => ValidationMessage.error(m), )); messages.add(ValidationMessage(_userMessages.androidStudioNeedsUpdate)); if (_studio.configuredPath != null) { messages.add(ValidationMessage(_userMessages.androidStudioResetDir)); } }
return ValidationResult(type, messages, statusInfo: studioVersionText); }
bool _hasIssues(List<ValidationMessage> messages) { return messages.any((ValidationMessage message) => message.isError); }}
class NoAndroidStudioValidator extends DoctorValidator { NoAndroidStudioValidator({ required Config config, required Platform platform, required UserMessages userMessages, }) : _config = config, _platform = platform, _userMessages = userMessages, super('Android Studio');
final Config _config; final Platform _platform; final UserMessages _userMessages;
@override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[];
final String? cfgAndroidStudio = _config.getValue( 'android-studio-dir', ) as String?; if (cfgAndroidStudio != null) { messages.add(ValidationMessage.error( _userMessages.androidStudioMissing(cfgAndroidStudio), )); } messages.add(ValidationMessage(_userMessages.androidStudioInstallation(_platform)));
return ValidationResult( ValidationType.notAvailable, messages, statusInfo: 'not installed', ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455// Copyright 2014 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
import 'dart:async';
import 'package:process/process.dart';
import '../base/common.dart';import '../base/context.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/platform.dart';import '../base/user_messages.dart' hide userMessages;import '../base/version.dart';import '../convert.dart';import '../doctor_validator.dart';import '../features.dart';import 'android_sdk.dart';import 'java.dart';
const int kAndroidSdkMinVersion = 29;final Version kAndroidJavaMinVersion = Version(1, 8, 0);final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3);
AndroidWorkflow? get androidWorkflow => context.get<AndroidWorkflow>();AndroidValidator? get androidValidator => context.get<AndroidValidator>();AndroidLicenseValidator? get androidLicenseValidator => context.get<AndroidLicenseValidator>();
enum LicensesAccepted { none, some, all, unknown,}
final RegExp licenseCounts = RegExp(r'(\d+) of (\d+) SDK package licenses? not accepted.');final RegExp licenseNotAccepted = RegExp(r'licenses? not accepted', caseSensitive: false);final RegExp licenseAccepted = RegExp(r'All SDK package licenses accepted.');
class AndroidWorkflow implements Workflow { AndroidWorkflow({ required AndroidSdk? androidSdk, required FeatureFlags featureFlags, }) : _androidSdk = androidSdk, _featureFlags = featureFlags;
final AndroidSdk? _androidSdk; final FeatureFlags _featureFlags;
@override bool get appliesToHostPlatform => _featureFlags.isAndroidEnabled;
@override bool get canListDevices => appliesToHostPlatform && _androidSdk != null && _androidSdk.adbPath != null;
@override bool get canLaunchDevices => appliesToHostPlatform && _androidSdk != null && _androidSdk.adbPath != null && _androidSdk.validateSdkWellFormed().isEmpty;
@override bool get canListEmulators => canListDevices && _androidSdk?.emulatorPath != null;}
/// A validator that checks if the Android SDK and Java SDK are available and/// installed correctly.////// Android development requires the Android SDK, and at least one Java SDK. While/// newer Java compilers can be used to compile the Java application code, the SDK/// tools themselves required JDK 1.8. This older JDK is normally bundled with/// Android Studio.class AndroidValidator extends DoctorValidator { AndroidValidator({ required Java? java, required AndroidSdk? androidSdk, required Logger logger, required Platform platform, required UserMessages userMessages, }) : _java = java, _androidSdk = androidSdk, _logger = logger, _platform = platform, _userMessages = userMessages, super('Android toolchain - develop for Android devices');
final Java? _java; final AndroidSdk? _androidSdk; final Logger _logger; final Platform _platform; final UserMessages _userMessages;
@override String get slowWarning => '${_task ?? 'This'} is taking a long time...'; String? _task;
/// Returns false if we cannot determine the Java version or if the version /// is older that the minimum allowed version of 1.8. Future<bool> _checkJavaVersion(List<ValidationMessage> messages) async { _task = 'Checking Java status'; try { if (_java?.binaryPath == null) { messages.add(ValidationMessage.error(_userMessages.androidMissingJdk)); return false; } messages.add(ValidationMessage(_userMessages.androidJdkLocation(_java!.binaryPath))); if (!_java.canRun()) { messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(_java.binaryPath))); return false; } Version? javaVersion; try { javaVersion = _java.version; } on Exception catch (error) { _logger.printTrace(error.toString()); } if (javaVersion == null) { // Could not determine the java version. messages.add(ValidationMessage.error(_userMessages.androidUnknownJavaVersion)); return false; } if (javaVersion < kAndroidJavaMinVersion) { messages.add(ValidationMessage.error(_userMessages.androidJavaMinimumVersion(javaVersion.toString()))); return false; } messages.add(ValidationMessage(_userMessages.androidJavaVersion(javaVersion.toString()))); return true; } finally { _task = null; } }
@override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; final AndroidSdk? androidSdk = _androidSdk; if (androidSdk == null) { // No Android SDK found. if (_platform.environment.containsKey(kAndroidHome)) { final String androidHomeDir = _platform.environment[kAndroidHome]!; messages.add(ValidationMessage.error(_userMessages.androidBadSdkDir(kAndroidHome, androidHomeDir))); } else { // Instruct user to set [kAndroidSdkRoot] and not deprecated [kAndroidHome] // See https://github.com/flutter/flutter/issues/39301 messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform))); } return ValidationResult(ValidationType.missing, messages); }
messages.add(ValidationMessage(_userMessages.androidSdkLocation(androidSdk.directory.path)));
_task = 'Validating Android SDK command line tools are available'; if (!androidSdk.cmdlineToolsAvailable) { messages.add(ValidationMessage.error(_userMessages.androidMissingCmdTools)); return ValidationResult(ValidationType.missing, messages); }
_task = 'Validating Android SDK licenses'; if (androidSdk.licensesAvailable && !androidSdk.platformToolsAvailable) { messages.add(ValidationMessage.hint(_userMessages.androidSdkLicenseOnly(kAndroidHome))); return ValidationResult(ValidationType.partial, messages); }
String? sdkVersionText; final AndroidSdkVersion? androidSdkLatestVersion = androidSdk.latestVersion; if (androidSdkLatestVersion != null) { if (androidSdkLatestVersion.sdkLevel < kAndroidSdkMinVersion || androidSdkLatestVersion.buildToolsVersion < kAndroidSdkBuildToolsMinVersion) { messages.add(ValidationMessage.error( _userMessages.androidSdkBuildToolsOutdated( kAndroidSdkMinVersion, kAndroidSdkBuildToolsMinVersion.toString(), _platform, )), ); return ValidationResult(ValidationType.missing, messages); } sdkVersionText = _userMessages.androidStatusInfo(androidSdkLatestVersion.buildToolsVersionName);
messages.add(ValidationMessage(_userMessages.androidSdkPlatformToolsVersion( androidSdkLatestVersion.platformName, androidSdkLatestVersion.buildToolsVersionName))); } else { messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform))); }
if (_platform.environment.containsKey(kAndroidHome)) { final String androidHomeDir = _platform.environment[kAndroidHome]!; messages.add(ValidationMessage('$kAndroidHome = $androidHomeDir')); } if (_platform.environment.containsKey(kAndroidSdkRoot)) { final String androidSdkRoot = _platform.environment[kAndroidSdkRoot]!; messages.add(ValidationMessage('$kAndroidSdkRoot = $androidSdkRoot')); }
_task = 'Validating Android SDK'; final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isNotEmpty) { // Android SDK is not functional. messages.addAll(validationResult.map<ValidationMessage>((String message) { return ValidationMessage.error(message); })); messages.add(ValidationMessage(_userMessages.androidSdkInstallHelp(_platform))); return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); }
_task = 'Finding Java binary';
// Check JDK version. if (!await _checkJavaVersion(messages)) { return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); }
// Success. return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText); }}
/// A subvalidator that checks if the licenses within the detected Android/// SDK have been accepted.class AndroidLicenseValidator extends DoctorValidator { AndroidLicenseValidator({ required Java? java, required AndroidSdk? androidSdk, required Platform platform, required ProcessManager processManager, required Logger logger, required Stdio stdio, required UserMessages userMessages, }) : _java = java, _androidSdk = androidSdk, _platform = platform, _processManager = processManager, _logger = logger, _stdio = stdio, _userMessages = userMessages, super('Android license subvalidator');
final Java? _java; final AndroidSdk? _androidSdk; final Stdio _stdio; final Platform _platform; final ProcessManager _processManager; final Logger _logger; final UserMessages _userMessages;
@override String get slowWarning => 'Checking Android licenses is taking an unexpectedly long time...';
@override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[];
// Match pre-existing early termination behavior if (_androidSdk == null || _androidSdk.latestVersion == null || _androidSdk.validateSdkWellFormed().isNotEmpty || ! await _checkJavaVersionNoOutput()) { return ValidationResult(ValidationType.missing, messages); }
final String sdkVersionText = _userMessages.androidStatusInfo(_androidSdk.latestVersion!.buildToolsVersionName);
// Check for licenses. switch (await licensesAccepted) { case LicensesAccepted.all: messages.add(ValidationMessage(_userMessages.androidLicensesAll)); case LicensesAccepted.some: messages.add(ValidationMessage.hint(_userMessages.androidLicensesSome)); return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); case LicensesAccepted.none: messages.add(ValidationMessage.error(_userMessages.androidLicensesNone)); return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); case LicensesAccepted.unknown: messages.add(ValidationMessage.error(_userMessages.androidLicensesUnknown(_platform))); return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText); } return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText); }
Future<bool> _checkJavaVersionNoOutput() async { final String? javaBinary = _java?.binaryPath;
if (javaBinary == null) { return false; } if (!_processManager.canRun(javaBinary)) { return false; } String? javaVersion; try { final ProcessResult result = await _processManager.run(<String>[javaBinary, '-version']); if (result.exitCode == 0) { final List<String> versionLines = (result.stderr as String).split('\n'); javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; } } on Exception catch (error) { _logger.printTrace(error.toString()); } if (javaVersion == null) { // Could not determine the java version. return false; } return true; }
Future<LicensesAccepted> get licensesAccepted async { LicensesAccepted? status;
void handleLine(String line) { if (licenseCounts.hasMatch(line)) { final Match? match = licenseCounts.firstMatch(line); if (match?.group(1) != match?.group(2)) { status = LicensesAccepted.some; } else { status = LicensesAccepted.none; } } else if (licenseNotAccepted.hasMatch(line)) { // The licenseNotAccepted pattern is trying to match the same line as // licenseCounts, but is more general. In case the format changes, a // more general match may keep doctor mostly working. status = LicensesAccepted.none; } else if (licenseAccepted.hasMatch(line)) { status ??= LicensesAccepted.all; } }
if (!_canRunSdkManager()) { return LicensesAccepted.unknown; }
try { final Process process = await _processManager.start( <String>[_androidSdk!.sdkManagerPath!, '--licenses'], environment: _java?.environment, ); process.stdin.write('n\n'); // We expect logcat streams to occasionally contain invalid utf-8, // see: https://github.com/flutter/flutter/pull/8864. final Future<void> output = process.stdout .transform<String>(const Utf8Decoder(reportErrors: false)) .transform<String>(const LineSplitter()) .listen(handleLine) .asFuture<void>(); final Future<void> errors = process.stderr .transform<String>(const Utf8Decoder(reportErrors: false)) .transform<String>(const LineSplitter()) .listen(handleLine) .asFuture<void>(); await Future.wait<void>(<Future<void>>[output, errors]); return status ?? LicensesAccepted.unknown; } on ProcessException catch (e) { _logger.printTrace('Failed to run Android sdk manager: $e'); return LicensesAccepted.unknown; } }
/// Run the Android SDK manager tool in order to accept SDK licenses. Future<bool> runLicenseManager() async { if (_androidSdk == null) { _logger.printStatus(_userMessages.androidSdkShort); return false; }
if (!_canRunSdkManager()) { throwToolExit( 'Android sdkmanager not found. Update to the latest Android SDK and ensure that ' 'the cmdline-tools are installed to resolve this.' ); }
try { final Process process = await _processManager.start( <String>[_androidSdk.sdkManagerPath!, '--licenses'], environment: _java?.environment, );
// The real stdin will never finish streaming. Pipe until the child process // finishes. unawaited(process.stdin.addStream(_stdio.stdin) // If the process exits unexpectedly with an error, that will be // handled by the caller. .then( (Object? socket) => socket, onError: (dynamic err, StackTrace stack) { _logger.printTrace('Echoing stdin to the licenses subprocess failed:'); _logger.printTrace('$err\n$stack'); }, ), );
final List<String> stderrLines = <String>[]; // Wait for stdout and stderr to be fully processed, because process.exitCode // may complete first. try { await Future.wait<void>(<Future<void>>[ _stdio.addStdoutStream(process.stdout), process.stderr.forEach((List<int> event) { _stdio.stderr.add(event); stderrLines.add(utf8.decode(event)); }), ]); } on Exception catch (err, stack) { _logger.printTrace('Echoing stdout or stderr from the license subprocess failed:'); _logger.printTrace('$err\n$stack'); }
final int exitCode = await process.exitCode; if (exitCode != 0) { throwToolExit(_messageForSdkManagerError(stderrLines, exitCode)); } return true; } on ProcessException catch (e) { throwToolExit(_userMessages.androidCannotRunSdkManager( _androidSdk.sdkManagerPath ?? '', e.toString(), _platform, )); } }
bool _canRunSdkManager() { final String? sdkManagerPath = _androidSdk?.sdkManagerPath; if (sdkManagerPath == null) { return false; } return _processManager.canRun(sdkManagerPath); }
String _messageForSdkManagerError( List<String> androidSdkStderr, int exitCode, ) { final String sdkManagerPath = _androidSdk!.sdkManagerPath!;
final bool failedDueToJdkIncompatibility = androidSdkStderr.join().contains( RegExp(r'java\.lang\.UnsupportedClassVersionError.*SdkManagerCli ' r'has been compiled by a more recent version of the Java Runtime'));
if (failedDueToJdkIncompatibility) { return 'Android sdkmanager tool was found, but failed to run ($sdkManagerPath): "exited code $exitCode".\n' 'It appears the version of the Java binary used (${_java!.binaryPath}) is ' 'too out-of-date and is incompatible with the Android sdkmanager tool.\n' 'If the Java binary came bundled with Android Studio, consider updating ' 'your installation of Android studio. Alternatively, you can uninstall ' 'the Android SDK command-line tools and install an earlier version. '; }
return _userMessages.androidCannotRunSdkManager( sdkManagerPath, 'exited code $exitCode', _platform, ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431// 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:collection';
import 'package:meta/meta.dart';import 'package:process/process.dart';import 'package:xml/xml.dart';
import '../application_package.dart';import '../base/common.dart';import '../base/file_system.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/process.dart';import '../base/user_messages.dart';import '../build_info.dart';import '../project.dart';import 'android_sdk.dart';import 'gradle.dart';
/// An application package created from an already built Android APK.class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackage { AndroidApk({ required super.id, required this.applicationPackage, required this.versionCode, required this.launchActivity, });
/// Creates a new AndroidApk from an existing APK. /// /// Returns `null` if the APK was invalid or any required tooling was missing. static AndroidApk? fromApk( File apk, { required AndroidSdk androidSdk, required ProcessManager processManager, required UserMessages userMessages, required Logger logger, required ProcessUtils processUtils, }) { final String? aaptPath = androidSdk.latestVersion?.aaptPath; if (aaptPath == null || !processManager.canRun(aaptPath)) { logger.printError(userMessages.aaptNotFound); return null; }
String apptStdout; try { apptStdout = processUtils.runSync( <String>[ aaptPath, 'dump', 'xmltree', apk.path, 'AndroidManifest.xml', ], throwOnError: true, ).stdout.trim(); } on ProcessException catch (error) { logger.printError('Failed to extract manifest from APK: $error.'); return null; }
final ApkManifestData? data = ApkManifestData.parseFromXmlDump(apptStdout, logger);
if (data == null) { logger.printError('Unable to read manifest info from ${apk.path}.'); return null; }
final String? packageName = data.packageName; if (packageName == null || data.launchableActivityName == null) { logger.printError('Unable to read manifest info from ${apk.path}.'); return null; }
return AndroidApk( id: packageName, applicationPackage: apk, versionCode: data.versionCode == null ? null : int.tryParse(data.versionCode!), launchActivity: '${data.packageName}/${data.launchableActivityName}', ); }
@override final FileSystemEntity applicationPackage;
/// The path to the activity that should be launched. final String launchActivity;
/// The version code of the APK. final int? versionCode;
/// Creates a new AndroidApk based on the information in the Android manifest. static Future<AndroidApk?> fromAndroidProject( AndroidProject androidProject, { required AndroidSdk? androidSdk, required ProcessManager processManager, required UserMessages userMessages, required ProcessUtils processUtils, required Logger logger, required FileSystem fileSystem, BuildInfo? buildInfo, }) async { final File apkFile; final String filename; if (buildInfo == null) { filename = 'app.apk'; } else if (buildInfo.flavor == null) { filename = 'app-${buildInfo.mode.cliName}.apk'; } else { filename = 'app-${buildInfo.lowerCasedFlavor}-${buildInfo.mode.cliName}.apk'; }
if (androidProject.isUsingGradle && androidProject.isSupportedVersion) { Directory apkDirectory = getApkDirectory(androidProject.parent); if (androidProject.parent.isModule) { // Module builds output the apk in a subdirectory that corresponds // to the buildmode of the apk. apkDirectory = apkDirectory.childDirectory(buildInfo!.mode.cliName); } apkFile = apkDirectory.childFile(filename); if (apkFile.existsSync()) { // Grab information from the .apk. The gradle build script might alter // the application Id, so we need to look at what was actually built. return AndroidApk.fromApk( apkFile, androidSdk: androidSdk!, processManager: processManager, logger: logger, userMessages: userMessages, processUtils: processUtils, ); } // The .apk hasn't been built yet, so we work with what we have. The run // command will grab a new AndroidApk after building, to get the updated // IDs. } else { apkFile = fileSystem.file(fileSystem.path.join(getAndroidBuildDirectory(), filename)); }
final File manifest = androidProject.appManifestFile;
if (!manifest.existsSync()) { logger.printError('AndroidManifest.xml could not be found.'); logger.printError('Please check ${manifest.path} for errors.'); return null; }
final String manifestString = manifest.readAsStringSync(); XmlDocument document; try { document = XmlDocument.parse(manifestString); } on XmlException catch (exception) { String manifestLocation; if (androidProject.isUsingGradle) { manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml'); } else { manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml'); } logger.printError('AndroidManifest.xml is not a valid XML document.'); logger.printError('Please check $manifestLocation for errors.'); throwToolExit('XML Parser error message: $exception'); }
final Iterable<XmlElement> manifests = document.findElements('manifest'); if (manifests.isEmpty) { logger.printError('AndroidManifest.xml has no manifest element.'); logger.printError('Please check ${manifest.path} for errors.'); return null; }
// Starting from AGP version 7.3, the `package` attribute in Manifest.xml // can be replaced with the `namespace` attribute under the `android` section in `android/app/build.gradle`. final String? packageId = manifests.first.getAttribute('package') ?? androidProject.namespace;
String? launchActivity; for (final XmlElement activity in document.findAllElements('activity')) { final String? enabled = activity.getAttribute('android:enabled'); if (enabled != null && enabled == 'false') { continue; }
for (final XmlElement element in activity.findElements('intent-filter')) { String? actionName = ''; String? categoryName = ''; for (final XmlNode node in element.children) { if (node is! XmlElement) { continue; } final String? name = node.getAttribute('android:name'); if (name == 'android.intent.action.MAIN') { actionName = name; } else if (name == 'android.intent.category.LAUNCHER') { categoryName = name; } } if (actionName != null && categoryName != null && actionName.isNotEmpty && categoryName.isNotEmpty) { final String? activityName = activity.getAttribute('android:name'); launchActivity = '$packageId/$activityName'; break; } } }
if (packageId == null || launchActivity == null) { logger.printError('package identifier or launch activity not found.'); logger.printError('Please check ${manifest.path} for errors.'); return null; }
return AndroidApk( id: packageId, applicationPackage: apkFile, versionCode: null, launchActivity: launchActivity, ); }
@override String get name => applicationPackage.basename;}
abstract class _Entry { const _Entry(this.parent, this.level);
final _Element? parent; final int level;}
class _Element extends _Entry { _Element._(this.name, _Element? parent, int level) : super(parent, level);
factory _Element.fromLine(String line, _Element? parent) { // E: application (line=29) final List<String> parts = line.trimLeft().split(' '); return _Element._(parts[1], parent, line.length - line.trimLeft().length); }
final List<_Entry> children = <_Entry>[]; final String? name;
void addChild(_Entry child) { children.add(child); }
_Attribute? firstAttribute(String name) { for (final _Attribute child in children.whereType<_Attribute>()) { if (child.key?.startsWith(name) ?? false) { return child; } } return null; }
_Element? firstElement(String name) { for (final _Element child in children.whereType<_Element>()) { if (child.name?.startsWith(name) ?? false) { return child; } } return null; }
Iterable<_Element> allElements(String name) { return children.whereType<_Element>().where((_Element e) => e.name?.startsWith(name) ?? false); }}
class _Attribute extends _Entry { const _Attribute._(this.key, this.value, _Element? parent, int level) : super(parent, level);
factory _Attribute.fromLine(String line, _Element parent) { // A: android:label(0x01010001)="hello_world" (Raw: "hello_world") const String attributePrefix = 'A: '; final List<String> keyVal = line.substring(line.indexOf(attributePrefix) + attributePrefix.length).split('='); return _Attribute._(keyVal[0], keyVal[1], parent, line.length - line.trimLeft().length); }
final String? key; final String? value;}
class ApkManifestData { ApkManifestData._(this._data);
static bool _isAttributeWithValuePresent( _Element baseElement, String childElement, String attributeName, String attributeValue) { final Iterable<_Element> allElements = baseElement.allElements(childElement); for (final _Element oneElement in allElements) { final String? elementAttributeValue = oneElement .firstAttribute(attributeName) ?.value; if (elementAttributeValue != null && elementAttributeValue.startsWith(attributeValue)) { return true; } } return false; }
static ApkManifestData? parseFromXmlDump(String data, Logger logger) { if (data.trim().isEmpty) { return null; }
final List<String> lines = data.split('\n'); assert(lines.length > 3);
final int manifestLine = lines.indexWhere((String line) => line.contains('E: manifest')); final _Element manifest = _Element.fromLine(lines[manifestLine], null); _Element currentElement = manifest;
for (final String line in lines.skip(manifestLine)) { final String trimLine = line.trimLeft(); final int level = line.length - trimLine.length;
// Handle level out while (currentElement.parent != null && level <= currentElement.level) { currentElement = currentElement.parent!; }
if (level > currentElement.level) { switch (trimLine[0]) { case 'A': currentElement .addChild(_Attribute.fromLine(line, currentElement)); case 'E': final _Element element = _Element.fromLine(line, currentElement); currentElement.addChild(element); currentElement = element; } } }
final _Element? application = manifest.firstElement('application'); if (application == null) { return null; }
final Iterable<_Element> activities = application.allElements('activity');
_Element? launchActivity; for (final _Element activity in activities) { final _Attribute? enabled = activity.firstAttribute('android:enabled'); final Iterable<_Element> intentFilters = activity.allElements('intent-filter'); final bool isEnabledByDefault = enabled == null; final bool isExplicitlyEnabled = enabled != null && (enabled.value?.contains('0xffffffff') ?? false); if (!(isEnabledByDefault || isExplicitlyEnabled)) { continue; }
for (final _Element element in intentFilters) { final bool isMainAction = _isAttributeWithValuePresent( element, 'action', 'android:name', '"android.intent.action.MAIN"'); if (!isMainAction) { continue; } final bool isLauncherCategory = _isAttributeWithValuePresent( element, 'category', 'android:name', '"android.intent.category.LAUNCHER"'); if (!isLauncherCategory) { continue; } launchActivity = activity; break; } if (launchActivity != null) { break; } }
final _Attribute? package = manifest.firstAttribute('package'); // "io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") final String? packageName = package?.value?.substring(1, package.value?.indexOf('" '));
if (launchActivity == null) { logger.printError('Error running $packageName. Default activity not found'); return null; }
final _Attribute? nameAttribute = launchActivity.firstAttribute('android:name'); // "io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") final String? activityName = nameAttribute?.value?.substring(1, nameAttribute.value?.indexOf('" '));
// Example format: (type 0x10)0x1 final _Attribute? versionCodeAttr = manifest.firstAttribute('android:versionCode'); if (versionCodeAttr == null) { logger.printError('Error running $packageName. Manifest versionCode not found'); return null; } if (versionCodeAttr.value?.startsWith('(type 0x10)') != true) { logger.printError('Error running $packageName. Manifest versionCode invalid'); return null; } final int? versionCode = versionCodeAttr.value == null ? null : int.tryParse(versionCodeAttr.value!.substring(11)); if (versionCode == null) { logger.printError('Error running $packageName. Manifest versionCode invalid'); return null; }
final Map<String, Map<String, String>> map = <String, Map<String, String>>{ if (packageName != null) 'package': <String, String>{'name': packageName}, 'version-code': <String, String>{'name': versionCode.toString()}, if (activityName != null) 'launchable-activity': <String, String>{'name': activityName}, };
return ApkManifestData._(map); }
final Map<String, Map<String, String>> _data;
@visibleForTesting Map<String, Map<String, String>> get data => UnmodifiableMapView<String, Map<String, String>>(_data);
String? get packageName => _data['package'] == null ? null : _data['package']?['name'];
String? get versionCode => _data['version-code'] == null ? null : _data['version-code']?['name'];
String? get launchableActivityName { return _data['launchable-activity'] == null ? null : _data['launchable-activity']?['name']; }
@override String toString() => _data.toString();}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// 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 '../base/common.dart';import '../build_info.dart';
const String kGooglePlayVersioning = 'https://developer.android.com/studio/publish/versioning.html';const String kSupportedAbis = 'https://flutter.dev/docs/deployment/android#what-are-the-supported-target-architectures';
/// Validates that the build mode and build number are valid for a given build.void validateBuild(AndroidBuildInfo androidBuildInfo) { final BuildInfo buildInfo = androidBuildInfo.buildInfo; if (buildInfo.codeSizeDirectory != null && androidBuildInfo.targetArchs.length > 1) { throwToolExit( 'Cannot perform code size analysis when building for multiple ABIs. ' 'Specify one of android-arm, android-arm64, or android-x64 in the ' '--target-platform flag.' ); } if (buildInfo.mode.isPrecompiled && androidBuildInfo.targetArchs.contains(AndroidArch.x86)) { throwToolExit( 'Cannot build ${androidBuildInfo.buildInfo.mode.cliName} mode for x86 ABI.\n' 'For more information see $kSupportedAbis .' ); } if (buildInfo.buildNumber != null) { final int? result = int.tryParse(buildInfo.buildNumber!); if (result == null) { throwToolExit( 'buildNumber: ${buildInfo.buildNumber} was not a valid integer value.\n' 'For more information see $kGooglePlayVersioning .' ); } if (result < 0) { throwToolExit( 'buildNumber: ${buildInfo.buildNumber} must be a positive integer value.\n' 'For more information see $kGooglePlayVersioning .' ); } if (result > 2100000000) { throwToolExit( 'buildNumber: ${buildInfo.buildNumber} is greater than the maximum ' 'allowed value of 2100000000.\n' 'For more information see $kGooglePlayVersioning .' ); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342// 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:xml/xml.dart';import 'package:yaml/yaml.dart';
import '../base/deferred_component.dart';import '../base/error_handling_io.dart';import '../base/file_system.dart';import '../build_system/build_system.dart';import 'deferred_components_validator.dart';
/// A class to configure and run deferred component setup verification checks/// and tasks.////// Once constructed, checks and tasks can be executed by calling the respective/// methods. The results of the checks are stored internally and can be/// displayed to the user by calling [displayResults].class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator { /// Constructs a validator instance. /// /// The [env] property is used to locate the project files that are checked. /// /// The [templatesDir] parameter is optional. If null, the tool's default /// templates directory will be used. /// /// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit] /// methods will exit the tool when this validator detects a recommended /// change. This defaults to true. DeferredComponentsGenSnapshotValidator(this.env, { bool exitOnFail = true, String? title, }) : super(env.projectDir, env.logger, env.platform, exitOnFail: exitOnFail, title: title);
/// The build environment that should be used to find the input files to run /// checks against. /// /// The checks in this class are meant to be used as part of a build process, /// so an environment should be available. final Environment env;
// The key used to identify the metadata element as the loading unit id to // deferred component mapping. static const String _mappingKey = 'io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping';
/// Checks if the base module `app`'s `AndroidManifest.xml` contains the /// required meta-data that maps loading units to deferred components. /// /// Returns true if the check passed with no recommended changes, and false /// otherwise. /// /// Flutter engine uses a manifest meta-data mapping to determine which /// deferred component includes a particular loading unit id. This method /// checks if `app`'s `AndroidManifest.xml` contains this metadata. If not, it /// will generate a modified AndroidManifest.xml with the correct metadata /// entry. /// /// An example mapping: /// /// 2:componentA,3:componentB,4:componentC /// /// Where loading unit 2 is included in componentA, loading unit 3 is included /// in componentB, and loading unit 4 is included in componentC. bool checkAppAndroidManifestComponentLoadingUnitMapping(List<DeferredComponent> components, List<LoadingUnit> generatedLoadingUnits) { final Directory androidDir = projectDir.childDirectory('android'); inputs.add(projectDir.childFile('pubspec.yaml'));
// We do not use the Xml package to handle the writing, as we do not want to // erase any user applied formatting and comments. The changes can be // applied with dart io and custom parsing. final File appManifestFile = androidDir .childDirectory('app') .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml'); inputs.add(appManifestFile); if (!appManifestFile.existsSync()) { invalidFiles[appManifestFile.path] = 'Error: $appManifestFile does not ' 'exist or could not be found. Please ensure an AndroidManifest.xml ' "exists for the app's base module."; return false; } XmlDocument document; try { document = XmlDocument.parse(appManifestFile.readAsStringSync()); } on XmlException { invalidFiles[appManifestFile.path] = 'Error parsing $appManifestFile ' 'Please ensure that the android manifest is a valid XML document and ' 'try again.'; return false; } on FileSystemException { invalidFiles[appManifestFile.path] = 'Error reading $appManifestFile ' 'even though it exists. Please ensure that you have read permission for ' 'this file and try again.'; return false; } // Create loading unit mapping. final Map<int, String> mapping = <int, String>{}; for (final DeferredComponent component in components) { component.assignLoadingUnits(generatedLoadingUnits); final Set<LoadingUnit>? loadingUnits = component.loadingUnits; if (loadingUnits == null) { continue; } for (final LoadingUnit unit in loadingUnits) { if (!mapping.containsKey(unit.id)) { mapping[unit.id] = component.name; } } } for (final LoadingUnit unit in generatedLoadingUnits) { if (!mapping.containsKey(unit.id)) { // Store an empty string for unassigned loading units, // indicating that it is in the base component. mapping[unit.id] = ''; } } // Encode the mapping as a string. final StringBuffer mappingBuffer = StringBuffer(); for (final int key in mapping.keys) { mappingBuffer.write('$key:${mapping[key]},'); } String encodedMapping = mappingBuffer.toString(); // remove trailing comma if any if (encodedMapping.endsWith(',')) { encodedMapping = encodedMapping.substring(0, encodedMapping.length - 1); } // Check for existing metadata entry and see if needs changes. bool exists = false; bool modified = false; for (final XmlElement application in document.findAllElements('application')) { for (final XmlElement metaData in application.findElements('meta-data')) { final String? name = metaData.getAttribute('android:name'); if (name == _mappingKey) { exists = true; final String? storedMappingString = metaData.getAttribute('android:value'); if (storedMappingString != encodedMapping) { metaData.setAttribute('android:value', encodedMapping); modified = true; } } } } if (!exists) { // Create an meta-data XmlElement that contains the mapping. final XmlElement mappingMetadataElement = XmlElement(XmlName.fromString('meta-data'), <XmlAttribute>[ XmlAttribute(XmlName.fromString('android:name'), _mappingKey), XmlAttribute(XmlName.fromString('android:value'), encodedMapping), ], ); for (final XmlElement application in document.findAllElements('application')) { application.children.add(mappingMetadataElement); break; } } if (!exists || modified) { final File manifestOutput = outputDir .childDirectory('app') .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml'); ErrorHandlingFileSystem.deleteIfExists(manifestOutput); manifestOutput.createSync(recursive: true); manifestOutput.writeAsStringSync(document.toXmlString(pretty: true), flush: true); modifiedFiles.add(manifestOutput.path); return false; } return true; }
/// Compares the provided loading units against the contents of the /// `deferred_components_loading_units.yaml` file. /// /// Returns true if a loading unit cache file exists and all loading units /// match, and false otherwise. /// /// This method will parse the cached loading units file if it exists and /// compare it to the provided generatedLoadingUnits. It will distinguish /// between newly added loading units and no longer existing loading units. If /// the cache file does not exist, then all generatedLoadingUnits will be /// considered new. bool checkAgainstLoadingUnitsCache( List<LoadingUnit> generatedLoadingUnits) { final List<LoadingUnit> cachedLoadingUnits = _parseLoadingUnitsCache(projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName)); loadingUnitComparisonResults = <String, Object>{}; final Set<LoadingUnit> unmatchedLoadingUnits = <LoadingUnit>{}; final List<LoadingUnit> newLoadingUnits = <LoadingUnit>[]; unmatchedLoadingUnits.addAll(cachedLoadingUnits); final Set<int> addedNewIds = <int>{}; for (final LoadingUnit genUnit in generatedLoadingUnits) { bool matched = false; for (final LoadingUnit cacheUnit in cachedLoadingUnits) { if (genUnit.equalsIgnoringPath(cacheUnit)) { matched = true; unmatchedLoadingUnits.remove(cacheUnit); break; } } if (!matched && !addedNewIds.contains(genUnit.id)) { newLoadingUnits.add(genUnit); addedNewIds.add(genUnit.id); } } loadingUnitComparisonResults!['new'] = newLoadingUnits; loadingUnitComparisonResults!['missing'] = unmatchedLoadingUnits; loadingUnitComparisonResults!['match'] = newLoadingUnits.isEmpty && unmatchedLoadingUnits.isEmpty; return loadingUnitComparisonResults!['match']! as bool; }
List<LoadingUnit> _parseLoadingUnitsCache(File cacheFile) { final List<LoadingUnit> loadingUnits = <LoadingUnit>[]; inputs.add(cacheFile); if (!cacheFile.existsSync()) { return loadingUnits; } final YamlMap data = loadYaml(cacheFile.readAsStringSync()) as YamlMap; // validate yaml format. if (!data.containsKey('loading-units')) { invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " 'entry did not exist.'; return loadingUnits; } else { if (data['loading-units'] is! YamlList && data['loading-units'] != null) { invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " 'is not a list.'; return loadingUnits; } if (data['loading-units'] != null) { for (final Object? loadingUnitData in data['loading-units'] as List<Object?>) { if (loadingUnitData is! YamlMap) { invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'loading-units' " 'is not a list of maps.'; return loadingUnits; } final YamlMap loadingUnitDataMap = loadingUnitData; if (loadingUnitDataMap['id'] == null) { invalidFiles[cacheFile.path] = 'Invalid loading units yaml file, all ' "loading units must have an 'id'"; return loadingUnits; } if (loadingUnitDataMap['libraries'] != null) { if (loadingUnitDataMap['libraries'] is! YamlList) { invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'libraries' " 'is not a list.'; return loadingUnits; } for (final Object? node in loadingUnitDataMap['libraries'] as YamlList) { if (node is! String) { invalidFiles[cacheFile.path] = "Invalid loading units yaml file, 'libraries' " 'is not a list of strings.'; return loadingUnits; } } } } } }
// Parse out validated yaml. if (data.containsKey('loading-units')) { if (data['loading-units'] != null) { for (final Object? loadingUnitData in data['loading-units'] as List<Object?>) { final YamlMap? loadingUnitDataMap = loadingUnitData as YamlMap?; final List<String> libraries = <String>[]; final YamlList? nodes = loadingUnitDataMap?['libraries'] as YamlList?; if (nodes != null) { for (final Object node in nodes.whereType<Object>()) { libraries.add(node as String); } } loadingUnits.add( LoadingUnit( id: loadingUnitDataMap!['id'] as int, libraries: libraries, )); } } } return loadingUnits; }
/// Writes the provided generatedLoadingUnits as `deferred_components_loading_units.yaml` /// /// This cache file is used to detect any changes in the loading units /// produced by gen_snapshot. Running [checkAgainstLoadingUnitCache] with a /// mismatching or missing cache will result in a failed validation. This /// prevents unexpected changes in loading units causing misconfigured /// deferred components. void writeLoadingUnitsCache(List<LoadingUnit>? generatedLoadingUnits) { generatedLoadingUnits ??= <LoadingUnit>[]; final File cacheFile = projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName); outputs.add(cacheFile); ErrorHandlingFileSystem.deleteIfExists(cacheFile); cacheFile.createSync(recursive: true);
final StringBuffer buffer = StringBuffer(); buffer.write('''# ==============================================================================# The contents of this file are automatically generated and it is not# recommended to modify this file manually.# ==============================================================================## In order to prevent unexpected splitting of deferred apps, this file records# the last generated set of loading units. It only possible to obtain the final# configuration of loading units after compilation is complete. This means# improperly setup deferred imports can only be detected after compilation.## This file allows the build tool to detect any changes in the generated# loading units. During the next build attempt, loading units in this file are# compared against the newly generated loading units to check for any new or# removed loading units. In the case where loading units do not match, the build# will fail and ask the developer to verify that the `deferred-components`# configuration in `pubspec.yaml` is correct. Developers should make any# necessary changes to integrate new and changed loading units or remove no# longer existing loading units from the configuration. The build command should# then be re-run to continue the build process.## Sometimes, changes to the generated loading units may be unintentional. If# the list of loading units in this file is not what is expected, the app's# deferred imports should be reviewed. Third party plugins and packages may# also introduce deferred imports that result in unexpected loading units.loading-units:'''); final Set<int> usedIds = <int>{}; for (final LoadingUnit unit in generatedLoadingUnits) { if (usedIds.contains(unit.id)) { continue; } buffer.write(' - id: ${unit.id}\n'); if (unit.libraries.isNotEmpty) { buffer.write(' libraries:\n'); for (final String lib in unit.libraries) { buffer.write(' - $lib\n'); } } usedIds.add(unit.id); } cacheFile.writeAsStringSync(buffer.toString(), flush: true); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294// 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:xml/xml.dart';
import '../base/deferred_component.dart';import '../base/error_handling_io.dart';import '../base/file_system.dart';import '../base/logger.dart';import '../globals.dart' as globals;import '../project.dart';import '../template.dart';import 'deferred_components_validator.dart';
/// A class to configure and run deferred component setup verification checks/// and tasks.////// Once constructed, checks and tasks can be executed by calling the respective/// methods. The results of the checks are stored internally and can be/// displayed to the user by calling [displayResults].class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator { /// Constructs a validator instance. /// /// The [templatesDir] parameter is optional. If null, the tool's default /// templates directory will be used. /// /// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit] /// methods will exit the tool when this validator detects a recommended /// change. This defaults to true. DeferredComponentsPrebuildValidator(super.projectDir, super.logger, super.platform, { super.exitOnFail, super.title, Directory? templatesDir, }) : _templatesDir = templatesDir;
final Directory? _templatesDir;
/// Checks if an android dynamic feature module exists for each deferred /// component. /// /// Returns true if the check passed with no recommended changes, and false /// otherwise. /// /// This method looks for the existence of `android/<componentname>/build.gradle` /// and `android/<componentname>/src/main/AndroidManifest.xml`. If either of /// these files does not exist, it will generate it in the validator output /// directory based off of a template. /// /// This method does not check if the contents of either of the files are /// valid, as there are many ways that they can be validly configured. Future<bool> checkAndroidDynamicFeature(List<DeferredComponent> components) async { inputs.add(projectDir.childFile('pubspec.yaml')); if (components.isEmpty) { return false; } bool changesMade = false; for (final DeferredComponent component in components) { final _DeferredComponentAndroidFiles androidFiles = _DeferredComponentAndroidFiles( name: component.name, projectDir: projectDir, logger: logger, templatesDir: _templatesDir ); if (!androidFiles.verifyFilesExist()) { // generate into temp directory final Map<String, List<File>> results = await androidFiles.generateFiles( alternateAndroidDir: outputDir, clearAlternateOutputDir: true, ); if (results.containsKey('outputs')) { for (final File file in results['outputs']!) { generatedFiles.add(file.path); changesMade = true; } outputs.addAll(results['outputs']!); } if (results.containsKey('inputs')) { inputs.addAll(results['inputs']!); } } } return !changesMade; }
/// Checks if the base module `app`'s `strings.xml` contain string /// resources for each component's name. /// /// Returns true if the check passed with no recommended changes, and false /// otherwise. /// /// In each dynamic feature module's AndroidManifest.xml, the /// name of the module is a string resource. This checks if /// the needed string resources are in the base module `strings.xml`. /// If not, this method will generate a modified `strings.xml` (or a /// completely new one if the original file did not exist) in the /// validator's output directory. /// /// For example, if there is a deferred component named `component1`, /// there should be the following string resource: /// /// <string name="component1Name">component1</string> /// /// The string element's name attribute should be the component name with /// `Name` as a suffix, and the text contents should be the component name. bool checkAndroidResourcesStrings(List<DeferredComponent> components) { final Directory androidDir = projectDir.childDirectory('android'); inputs.add(projectDir.childFile('pubspec.yaml'));
// Add component name mapping to strings.xml final File stringRes = androidDir .childDirectory('app') .childDirectory('src') .childDirectory('main') .childDirectory('res') .childDirectory('values') .childFile('strings.xml'); inputs.add(stringRes); final File stringResOutput = outputDir .childDirectory('app') .childDirectory('src') .childDirectory('main') .childDirectory('res') .childDirectory('values') .childFile('strings.xml'); ErrorHandlingFileSystem.deleteIfExists(stringResOutput); if (components.isEmpty) { return true; } final Map<String, String> requiredEntriesMap = <String, String>{}; for (final DeferredComponent component in components) { requiredEntriesMap['${component.name}Name'] = component.name; } if (stringRes.existsSync()) { bool modified = false; XmlDocument document; try { document = XmlDocument.parse(stringRes.readAsStringSync()); } on XmlException { invalidFiles[stringRes.path] = 'Error parsing $stringRes ' 'Please ensure that the strings.xml is a valid XML document and ' 'try again.'; return false; } // Check if all required lines are present, and fix if name exists, but // wrong string stored. for (final XmlElement resources in document.findAllElements('resources')) { for (final XmlElement element in resources.findElements('string')) { final String? name = element.getAttribute('name'); if (requiredEntriesMap.containsKey(name)) { if (element.innerText != requiredEntriesMap[name]) { element.innerText = requiredEntriesMap[name]!; modified = true; } requiredEntriesMap.remove(name); } } requiredEntriesMap.forEach((String key, String value) { modified = true; final XmlElement newStringElement = XmlElement( XmlName.fromString('string'), <XmlAttribute>[ XmlAttribute(XmlName.fromString('name'), key), ], <XmlNode>[ XmlText(value), ], ); resources.children.add(newStringElement); }); break; } if (modified) { stringResOutput.createSync(recursive: true); stringResOutput.writeAsStringSync(document.toXmlString(pretty: true)); modifiedFiles.add(stringResOutput.path); return false; } return true; } // strings.xml does not exist, generate completely new file. stringResOutput.createSync(recursive: true); final StringBuffer buffer = StringBuffer(); buffer.writeln('''<?xml version="1.0" encoding="utf-8"?><resources>'''); for (final String key in requiredEntriesMap.keys) { buffer.write(' <string name="$key">${requiredEntriesMap[key]}</string>\n'); } buffer.write('''</resources>
'''); stringResOutput.writeAsStringSync(buffer.toString(), flush: true, mode: FileMode.append); generatedFiles.add(stringResOutput.path); return false; }
/// Deletes all files inside of the validator's output directory. void clearOutputDir() { final Directory dir = projectDir.childDirectory('build').childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory); ErrorHandlingFileSystem.deleteIfExists(dir, recursive: true); }}
// Handles a single deferred component's android dynamic feature module// directory.class _DeferredComponentAndroidFiles { _DeferredComponentAndroidFiles({ required this.name, required this.projectDir, required this.logger, Directory? templatesDir, }) : _templatesDir = templatesDir;
// The name of the deferred component. final String name; final Directory projectDir; final Logger logger; final Directory? _templatesDir;
Directory get androidDir => projectDir.childDirectory('android'); Directory get componentDir => androidDir.childDirectory(name);
File get androidManifestFile => componentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); File get buildGradleFile => componentDir.childFile('build.gradle');
// True when AndroidManifest.xml and build.gradle exist for the android dynamic feature. bool verifyFilesExist() { return androidManifestFile.existsSync() && buildGradleFile.existsSync(); }
// Generates any missing basic files for the dynamic feature into a temporary directory. Future<Map<String, List<File>>> generateFiles({Directory? alternateAndroidDir, bool clearAlternateOutputDir = false}) async { final Directory outputDir = alternateAndroidDir?.childDirectory(name) ?? componentDir; if (clearAlternateOutputDir && alternateAndroidDir != null) { ErrorHandlingFileSystem.deleteIfExists(outputDir); } final List<File> inputs = <File>[]; inputs.add(androidManifestFile); inputs.add(buildGradleFile); final Map<String, List<File>> results = <String, List<File>>{'inputs': inputs}; results['outputs'] = await _setupComponentFiles(outputDir); return results; }
// generates default build.gradle and AndroidManifest.xml for the deferred component. Future<List<File>> _setupComponentFiles(Directory outputDir) async { Template template; final Directory? templatesDir = _templatesDir; if (templatesDir != null) { final Directory templateComponentDir = templatesDir.childDirectory('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component'); template = Template(templateComponentDir, templateComponentDir, fileSystem: globals.fs, logger: logger, templateRenderer: globals.templateRenderer, ); } else { template = await Template.fromName('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component', fileSystem: globals.fs, templateManifest: null, logger: logger, templateRenderer: globals.templateRenderer, ); } final Map<String, Object> context = <String, Object>{ 'androidIdentifier': FlutterProject.current().manifest.androidPackage ?? 'com.example.${FlutterProject.current().manifest.appName}', 'componentName': name, };
template.render(outputDir, context);
final List<File> generatedFiles = <File>[];
final File tempBuildGradle = outputDir.childFile('build.gradle'); if (!buildGradleFile.existsSync()) { generatedFiles.add(tempBuildGradle); } else { ErrorHandlingFileSystem.deleteIfExists(tempBuildGradle); } final File tempAndroidManifest = outputDir .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml'); if (!androidManifestFile.existsSync()) { generatedFiles.add(tempAndroidManifest); } else { ErrorHandlingFileSystem.deleteIfExists(tempAndroidManifest); } return generatedFiles; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223// 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 '../base/common.dart';import '../base/deferred_component.dart';import '../base/file_system.dart';import '../base/logger.dart';import '../base/platform.dart';import '../base/terminal.dart';
/// A class to configure and run deferred component setup verification checks/// and tasks.////// Once constructed, checks and tasks can be executed by calling the respective/// methods. The results of the checks are stored internally and can be/// displayed to the user by calling [displayResults].////// The results of each check are handled internally as they are not meant to/// be run isolated.abstract class DeferredComponentsValidator { DeferredComponentsValidator(this.projectDir, this.logger, this.platform, { this.exitOnFail = true, String? title, }) : outputDir = projectDir .childDirectory('build') .childDirectory(kDeferredComponentsTempDirectory), inputs = <File>[], outputs = <File>[], title = title ?? 'Deferred components setup verification', generatedFiles = <String>[], modifiedFiles = <String>[], invalidFiles = <String, String>{}, diffLines = <String>[];
/// Logger to use for [displayResults] output. final Logger logger;
final Platform platform;
/// When true, failed checks and tasks will result in [attemptToolExit] /// triggering [throwToolExit]. final bool exitOnFail;
/// The name of the golden file that tracks the latest loading units /// generated. static const String kLoadingUnitsCacheFileName = 'deferred_components_loading_units.yaml'; /// The directory in the build folder to generate missing/modified files into. static const String kDeferredComponentsTempDirectory = 'android_deferred_components_setup_files';
/// The title printed at the top of the results of [displayResults] final String title;
/// The root directory of the flutter project. final Directory projectDir;
/// The temporary directory that the validator writes recommended files into. final Directory outputDir;
/// Files that were newly generated by this validator. final List<String> generatedFiles;
/// Existing files that were modified by this validator. final List<String> modifiedFiles;
/// Files that were invalid and unable to be checked. These files are input /// files that the validator tries to read rather than output files the /// validator generates. The key is the file name and the value is the message /// or reason it was invalid. final Map<String, String> invalidFiles;
// TODO(garyq): implement the diff task. /// Output of the diff task. final List<String> diffLines;
/// Tracks the new and missing loading units. Map<String, dynamic>? loadingUnitComparisonResults;
/// All files read by the validator. final List<File> inputs; /// All files output by the validator. final List<File> outputs;
/// Returns true if there were any recommended changes that should /// be applied. /// /// Returns false if no problems or recommendations were detected. /// /// If no checks are run, then this will default to false and will remain so /// until a failing check finishes running. bool get changesNeeded => generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty || invalidFiles.isNotEmpty || (loadingUnitComparisonResults != null && !(loadingUnitComparisonResults!['match'] as bool));
/// Handles the results of all executed checks by calling [displayResults] and /// [attemptToolExit]. /// /// This should be called after all desired checks and tasks are executed. void handleResults() { displayResults(); attemptToolExit(); }
static const String _thickDivider = '================================================================================='; static const String _thinDivider = '---------------------------------------------------------------------------------';
/// Displays the results of this validator's executed checks and tasks in a /// human readable format. /// /// All checks that are desired should be run before calling this method. void displayResults() { if (changesNeeded) { logger.printStatus(_thickDivider); logger.printStatus(title, indent: (_thickDivider.length - title.length) ~/ 2, emphasis: true); logger.printStatus(_thickDivider); // Log any file reading/existence errors. if (invalidFiles.isNotEmpty) { logger.printStatus('Errors checking the following files:\n', emphasis: true); for (final String key in invalidFiles.keys) { logger.printStatus(' - $key: ${invalidFiles[key]}\n'); } } // Log diff file contents, with color highlighting if (diffLines.isNotEmpty) { logger.printStatus('Diff between `android` and expected files:', emphasis: true); logger.printStatus(''); for (final String line in diffLines) { // We only care about diffs in files that have // counterparts. if (line.startsWith('Only in android')) { continue; } TerminalColor color = TerminalColor.grey; if (line.startsWith('+')) { color = TerminalColor.green; } else if (line.startsWith('-')) { color = TerminalColor.red; } logger.printStatus(line, color: color); } logger.printStatus(''); } // Log any newly generated and modified files. if (generatedFiles.isNotEmpty) { logger.printStatus('Newly generated android files:', emphasis: true); for (final String filePath in generatedFiles) { final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); } logger.printStatus(''); } if (modifiedFiles.isNotEmpty) { logger.printStatus('Modified android files:', emphasis: true); for (final String filePath in modifiedFiles) { final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); } logger.printStatus(''); } if (generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty) { logger.printStatus('''The above files have been placed into `build/$kDeferredComponentsTempDirectory`,a temporary directory. The files should be reviewed and moved into the project's`android` directory.'''); if (diffLines.isNotEmpty && !platform.isWindows) { logger.printStatus(r'''
The recommended changes can be quickly applied by running:
$ patch -p0 < build/setup_deferred_components.diff'''); } logger.printStatus('$_thinDivider\n'); } // Log loading unit golden changes, if any. if (loadingUnitComparisonResults != null) { if ((loadingUnitComparisonResults!['new'] as List<LoadingUnit>).isNotEmpty) { logger.printStatus('New loading units were found:', emphasis: true); for (final LoadingUnit unit in loadingUnitComparisonResults!['new'] as List<LoadingUnit>) { logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); } logger.printStatus(''); } if ((loadingUnitComparisonResults!['missing'] as Set<LoadingUnit>).isNotEmpty) { logger.printStatus('Previously existing loading units no longer exist:', emphasis: true); for (final LoadingUnit unit in loadingUnitComparisonResults!['missing'] as Set<LoadingUnit>) { logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); } logger.printStatus(''); } if (loadingUnitComparisonResults!['match'] as bool) { logger.printStatus('No change in generated loading units.\n'); } else { logger.printStatus('''It is recommended to verify that the changed loading units are expectedand to update the `deferred-components` section in `pubspec.yaml` toincorporate any changes. The full list of generated loading units can bereferenced in the $kLoadingUnitsCacheFileName file located alongsidepubspec.yaml.
This loading unit check will not fail again on the next build attemptif no additional changes to the loading units are detected.$_thinDivider\n'''); } } // TODO(garyq): Add link to web tutorial/guide once it is written. logger.printStatus('''Setup verification can be skipped by passing the `--no-validate-deferred-components`flag, however, doing so may put your app at risk of not functioning even if thebuild is successful.$_thickDivider'''); return; } logger.printStatus('$title passed.'); }
void attemptToolExit() { if (exitOnFail && changesNeeded) { throwToolExit('Setup for deferred components incomplete. See recommended actions.', exitCode: 1); } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277// 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:math';
import 'package:crypto/crypto.dart';import 'package:meta/meta.dart';import 'package:process/process.dart';import 'package:unified_analytics/unified_analytics.dart';import 'package:xml/xml.dart';
import '../artifacts.dart';import '../base/analyze_size.dart';import '../base/common.dart';import '../base/deferred_component.dart';import '../base/file_system.dart';import '../base/io.dart';import '../base/logger.dart';import '../base/net.dart';import '../base/platform.dart';import '../base/process.dart';import '../base/project_migrator.dart';import '../base/terminal.dart';import '../base/utils.dart';import '../build_info.dart';import '../cache.dart';import '../convert.dart';import '../flutter_manifest.dart';import '../globals.dart' as globals;import '../project.dart';import '../reporting/reporting.dart';import 'android_builder.dart';import 'android_studio.dart';import 'gradle_errors.dart';import 'gradle_utils.dart';import 'java.dart';import 'migrations/android_studio_java_gradle_conflict_migration.dart';import 'migrations/min_sdk_version_migration.dart';import 'migrations/top_level_gradle_build_file_migration.dart';import 'multidex.dart';
/// The regex to grab variant names from printBuildVariants gradle task////// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy////// The expected output from the task should be similar to:////// BuildVariant: debug/// BuildVariant: release/// BuildVariant: profilefinal RegExp _kBuildVariantRegex = RegExp('^BuildVariant: (?<$_kBuildVariantRegexGroupName>.*)\$');const String _kBuildVariantRegexGroupName = 'variant';const String _kBuildVariantTaskName = 'printBuildVariants';
String _getOutputAppLinkSettingsTaskFor(String buildVariant) { return _taskForBuildVariant('output', buildVariant, 'AppLinkSettings');}
/// The directory where the APK artifact is generated.Directory getApkDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('apk') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk');}
/// The directory where the app bundle artifact is generated.@visibleForTestingDirectory getBundleDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('bundle') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('bundle');}
/// The directory where the repo is generated./// Only applicable to AARs.Directory getRepoDirectory(Directory buildDirectory) { return buildDirectory .childDirectory('outputs') .childDirectory('repo');}
/// Returns the name of Gradle task that starts with [prefix].String _taskFor(String prefix, BuildInfo buildInfo) { final String buildType = camelCase(buildInfo.modeName); final String productFlavor = buildInfo.flavor ?? ''; return _taskForBuildVariant(prefix, '$productFlavor${sentenceCase(buildType)}');}
String _taskForBuildVariant(String prefix, String buildVariant, [String suffix = '']) { return '$prefix${sentenceCase(buildVariant)}$suffix';}
/// Returns the task to build an APK.@visibleForTestingString getAssembleTaskFor(BuildInfo buildInfo) { return _taskFor('assemble', buildInfo);}
/// Returns the task to build an AAB.@visibleForTestingString getBundleTaskFor(BuildInfo buildInfo) { return _taskFor('bundle', buildInfo);}
/// Returns the task to build an AAR.@visibleForTestingString getAarTaskFor(BuildInfo buildInfo) { return _taskFor('assembleAar', buildInfo);}
/// Returns the output APK file names for a given [AndroidBuildInfo].////// For example, when [splitPerAbi] is true, multiple APKs are created.Iterable<String> _apkFilesFor(AndroidBuildInfo androidBuildInfo) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? ''; final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor'; if (androidBuildInfo.splitPerAbi) { return androidBuildInfo.targetArchs.map<String>((AndroidArch arch) { final String abi = arch.archName; return 'app$flavorString-$abi-$buildType.apk'; }); } return <String>['app$flavorString-$buildType.apk'];}
// The maximum time to wait before the tool retries a Gradle build.const Duration kMaxRetryTime = Duration(seconds: 10);
/// An implementation of the [AndroidBuilder] that delegates to gradle.class AndroidGradleBuilder implements AndroidBuilder { AndroidGradleBuilder({ required Java? java, required Logger logger, required ProcessManager processManager, required FileSystem fileSystem, required Artifacts artifacts, required Usage usage, required Analytics analytics, required GradleUtils gradleUtils, required Platform platform, required AndroidStudio? androidStudio, }) : _java = java, _logger = logger, _fileSystem = fileSystem, _artifacts = artifacts, _usage = usage, _analytics = analytics, _gradleUtils = gradleUtils, _androidStudio = androidStudio, _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), _processUtils = ProcessUtils(logger: logger, processManager: processManager);
final Java? _java; final Logger _logger; final ProcessUtils _processUtils; final FileSystem _fileSystem; final Artifacts _artifacts; final Usage _usage; final Analytics _analytics; final GradleUtils _gradleUtils; final FileSystemUtils _fileSystemUtils; final AndroidStudio? _androidStudio;
/// Builds the AAR and POM files for the current Flutter module or plugin. @override Future<void> buildAar({ required FlutterProject project, required Set<AndroidBuildInfo> androidBuildInfo, required String target, String? outputDirectoryPath, required String buildNumber, }) async { Directory outputDirectory = _fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory); if (project.isModule) { // Module projects artifacts are located in `build/host`. outputDirectory = outputDirectory.childDirectory('host'); } for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { await buildGradleAar( project: project, androidBuildInfo: androidBuildInfo, target: target, outputDirectory: outputDirectory, buildNumber: buildNumber, ); } printHowToConsumeAar( buildModes: androidBuildInfo .map<String>((AndroidBuildInfo androidBuildInfo) { return androidBuildInfo.buildInfo.modeName; }).toSet(), androidPackage: project.manifest.androidPackage, repoDirectory: getRepoDirectory(outputDirectory), buildNumber: buildNumber, logger: _logger, fileSystem: _fileSystem, ); }
/// Builds the APK. @override Future<void> buildApk({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: false, localGradleErrors: gradleErrors, configOnly: configOnly, maxRetries: 1, ); }
/// Builds the App Bundle. @override Future<void> buildAab({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: true, localGradleErrors: gradleErrors, validateDeferredComponents: validateDeferredComponents, deferredComponentsEnabled: deferredComponentsEnabled, configOnly: configOnly, maxRetries: 1, ); }
Future<RunResult> _runGradleTask( String taskName, { List<String> options = const <String>[], required FlutterProject project }) async { final Status status = _logger.startProgress( "Running Gradle task '$taskName'...", ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), ...options, // suppresses gradle output. taskName, ];
RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } return result; }
/// Builds an app. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [target] is the target dart entry point. Typically, `lib/main.dart`. /// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`, /// otherwise the output artifact is an `*.apk`. /// * [maxRetries] If not `null`, this is the max number of build retries in case a retry is triggered. Future<void> buildGradleApp({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required bool isBuildingBundle, required List<GradleHandledError> localGradleErrors, required bool configOnly, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, int retry = 0, @visibleForTesting int? maxRetries, }) async { if (!project.android.isSupportedVersion) { _exitWithUnsupportedProjectMessage(_usage, _logger.terminal, analytics: _analytics); }
final List<ProjectMigrator> migrators = <ProjectMigrator>[ TopLevelGradleBuildFileMigration(project.android, _logger), AndroidStudioJavaGradleConflictMigration(_logger, project: project.android, androidStudio: _androidStudio, java: globals.java), MinSdkVersionMigration(project.android, _logger), ];
final ProjectMigration migration = ProjectMigration(migrators); migration.run();
final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot); if (usesAndroidX) { BuildEvent('app-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-using-android-x', buildType: 'gradle')); } else if (!usesAndroidX) { BuildEvent('app-not-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle'));
_logger.printStatus("${_logger.terminal.warningMark} Your app isn't using AndroidX.", emphasis: true); _logger.printStatus( 'To avoid potential build failures, you can quickly migrate your app ' 'by following the steps on https://goo.gl/CP92wY .', indent: 4, ); } // The default Gradle script reads the version name and number // from the local.properties file. updateLocalProperties( project: project, buildInfo: androidBuildInfo.buildInfo);
final List<String> command = <String>[ // This does more than get gradlewrapper. It creates the file, ensures it // exists and verifies the file is executable. _gradleUtils.getExecutable(project), ];
// All automatically created files should exist. if (configOnly) { _logger.printStatus('Config complete.'); return; }
// Assembly work starts here. final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String assembleTask = isBuildingBundle ? getBundleTaskFor(buildInfo) : getAssembleTaskFor(buildInfo);
final Status status = _logger.startProgress( "Running Gradle task '$assembleTask'...", );
if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); } final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo .targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); } command.add('-Ptarget=$target'); // Only attempt adding multidex support if all the flutter generated files exist. // If the files do not exist and it was unintentional, the app will fail to build // and prompt the developer if they wish Flutter to add the files again via gradle_error.dart. if (androidBuildInfo.multidexEnabled && multiDexApplicationExists(project.directory) && androidManifestHasNameVariable(project.directory)) { command.add('-Pmultidex-enabled=true'); ensureMultiDexApplicationExists(project.directory); _logger.printStatus('Building with Flutter multidex support enabled.'); } // If using v1 embedding, we want to use FlutterApplication as the base app. final String baseApplicationName = project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ? 'android.app.Application' : 'io.flutter.app.FlutterApplication'; command.add('-Pbase-application-name=$baseApplicationName'); final List<DeferredComponent>? deferredComponents = project.manifest.deferredComponents; if (deferredComponents != null) { if (deferredComponentsEnabled) { command.add('-Pdeferred-components=true'); androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents'); } // Pass in deferred components regardless of building split aot to satisfy // android dynamic features registry in build.gradle. final List<String> componentNames = <String>[]; for (final DeferredComponent component in deferredComponents) { componentNames.add(component.name); } if (componentNames.isNotEmpty) { command.add('-Pdeferred-component-names=${componentNames.join(',')}'); // Multi-apk applications cannot use shrinking. This is only relevant when using // android dynamic feature modules. _logger.printStatus( 'Shrinking has been disabled for this build due to deferred components. Shrinking is ' 'not available for multi-apk applications. This limitation is expected to be removed ' 'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow); command.add('-Pshrink=false'); } } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.fileSystemRoots.isNotEmpty) { command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); } if (buildInfo.fileSystemScheme != null) { command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); } if (androidBuildInfo.splitPerAbi) { command.add('-Psplit-per-abi=true'); } if (androidBuildInfo.fastStart) { command.add('-Pfast-start=true'); } command.add(assembleTask);
GradleHandledError? detectedGradleError; String? detectedGradleErrorLine; String? consumeLog(String line) { if (detectedGradleError != null) { // Pipe stdout/stderr from Gradle. return line; } for (final GradleHandledError gradleError in localGradleErrors) { if (gradleError.test(line)) { detectedGradleErrorLine = line; detectedGradleError = gradleError; // The first error match wins. break; } } // Pipe stdout/stderr from Gradle. return line; }
final Stopwatch sw = Stopwatch() ..start(); int exitCode = 1; try { exitCode = await _processUtils.stream( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, mapFunction: consumeLog, ); } on ProcessException catch (exception) { consumeLog(exception.toString()); // Rethrow the exception if the error isn't handled by any of the // `localGradleErrors`. if (detectedGradleError == null) { rethrow; } } finally { status.stop(); }
final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle', elapsedMilliseconds: elapsedDuration.inMilliseconds, ));
if (exitCode != 0) { if (detectedGradleError == null) { BuildEvent('gradle-unknown-failure', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'gradle-unknown-failure', buildType: 'gradle'));
throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); } final GradleBuildStatus status = await detectedGradleError!.handler( line: detectedGradleErrorLine!, project: project, usesAndroidX: usesAndroidX, multidexEnabled: androidBuildInfo.multidexEnabled, );
if (maxRetries == null || retry < maxRetries) { switch (status) { case GradleBuildStatus.retry: // Use binary exponential backoff before retriggering the build. // The expected wait times are: 100ms, 200ms, 400ms, and so on... final int waitTime = min(pow(2, retry).toInt() * 100, kMaxRetryTime.inMicroseconds); retry += 1; _logger.printStatus('Retrying Gradle Build: #$retry, wait time: ${waitTime}ms'); await Future<void>.delayed(Duration(milliseconds: waitTime)); await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: isBuildingBundle, localGradleErrors: localGradleErrors, retry: retry, maxRetries: maxRetries, configOnly: configOnly, ); final String successEventLabel = 'gradle-${detectedGradleError!.eventLabel}-success';
BuildEvent(successEventLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: successEventLabel, buildType: 'gradle'));
return; case GradleBuildStatus.exit: // Continue and throw tool exit. } } final String usageLabel = 'gradle-${detectedGradleError?.eventLabel}-failure'; BuildEvent(usageLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: usageLabel, buildType: 'gradle'));
throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); }
if (isBuildingBundle) { final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage, _analytics); final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsMB(bundleFile.lengthSync())})';
if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo); }
_logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(bundleFile.path)}$appSize.', color: TerminalColor.green, ); return; } // Gradle produced APKs. final Iterable<String> apkFilesPaths = project.isModule ? findApkFilesModule(project, androidBuildInfo, _logger, _usage, _analytics) : listApkPaths(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project);
// Generate sha1 for every generated APKs. for (final File apkFile in apkFilesPaths.map(apkDirectory.childFile)) { if (!apkFile.existsSync()) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: _logger, usage: _usage, analytics: _analytics, ); }
final String filename = apkFile.basename; _logger.printTrace('Calculate SHA1: $apkDirectory/$filename'); final File apkShaFile = apkDirectory.childFile('$filename.sha1'); apkShaFile.writeAsStringSync(_calculateSha(apkFile));
final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsMB(apkFile.lengthSync())})'; _logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(apkFile.path)}$appSize.', color: TerminalColor.green, );
if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo); } } }
Future<void> _performCodeSizeAnalysis(String kind, File zipFile, AndroidBuildInfo androidBuildInfo,) async { final SizeAnalyzer sizeAnalyzer = SizeAnalyzer( fileSystem: _fileSystem, logger: _logger, flutterUsage: _usage, analytics: _analytics, ); final String archName = androidBuildInfo.targetArchs.single.archName; final BuildInfo buildInfo = androidBuildInfo.buildInfo; final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('snapshot.$archName.json'); final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('trace.$archName.json'); final Map<String, Object?> output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot( zipFile: zipFile, aotSnapshot: aotSnapshot, precompilerTrace: precompilerTrace, kind: kind, ); final File outputFile = _fileSystemUtils.getUniqueFile( _fileSystem .directory(_fileSystemUtils.homeDirPath) .childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json', ) ..writeAsStringSync(jsonEncode(output)); // This message is used as a sentinel in analyze_apk_size_test.dart _logger.printStatus( 'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}', );
// DevTools expects a file path relative to the .flutter-devtools/ dir. final String relativeAppSizePath = outputFile.path .split('.flutter-devtools/') .last .trim(); _logger.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' 'dart devtools --appSizeBase=$relativeAppSizePath' ); }
/// Builds AAR and POM files. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [outputDir] is the destination of the artifacts, /// * [buildNumber] is the build number of the output aar, Future<void> buildGradleAar({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required Directory outputDirectory, required String buildNumber, }) async { final FlutterManifest manifest = project.manifest; if (!manifest.isModule) { throwToolExit('AARs can only be built for module projects.'); }
final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String aarTask = getAarTaskFor(buildInfo); final Status status = _logger.startProgress( "Running Gradle task '$aarTask'...", );
final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot!); final String initScript = _fileSystem.path.join( flutterRoot, 'packages', 'flutter_tools', 'gradle', 'aar_init_script.gradle', ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), '-I=$initScript', '-Pflutter-root=$flutterRoot', '-Poutput-dir=${outputDirectory.path}', '-Pis-plugin=${manifest.isPlugin}', '-PbuildNumber=$buildNumber', ]; if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); }
if (target.isNotEmpty) { command.add('-Ptarget=$target'); } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) { _logger.printStatus( 'Dart obfuscation is not supported in ${sentenceCase(buildInfo.friendlyModeName)}' ' mode, building as un-obfuscated.', ); }
final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}');
// Copy the local engine repo in the output directory. try { copyDirectory( localEngineRepo, getRepoDirectory(outputDirectory), ); } on FileSystemException catch (error, st) { throwToolExit( 'Failed to copy the local engine ${localEngineRepo.path} repo ' 'in ${outputDirectory.path}: $error, $st' ); } command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo.targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); }
command.add(aarTask);
final Stopwatch sw = Stopwatch() ..start(); RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle-aar', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle-aar', elapsedMilliseconds: elapsedDuration.inMilliseconds, ));
if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed with exit code ${result.exitCode}.', exitCode: result.exitCode, ); } final Directory repoDirectory = getRepoDirectory(outputDirectory); if (!repoDirectory.existsSync()) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed to produce $repoDirectory.', exitCode: exitCode, ); } _logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(repoDirectory.path)}.', color: TerminalColor.green, ); }
@override Future<List<String>> getBuildVariants({required FlutterProject project}) async { final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( _kBuildVariantTaskName, options: const <String>['-q'], project: project, );
final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('print', 'android build variants', elapsedDuration); _analytics.send(Event.timing( workflow: 'print', variableName: 'android build variants', elapsedMilliseconds: elapsedDuration.inMilliseconds, ));
if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); return const <String>[]; } final List<String> options = <String>[]; for (final String line in LineSplitter.split(result.stdout)) { final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line); if (match != null) { options.add(match.namedGroup(_kBuildVariantRegexGroupName)!); } } return options; }
@override Future<String> outputsAppLinkSettings( String buildVariant, { required FlutterProject project, }) async { final String taskName = _getOutputAppLinkSettingsTaskFor(buildVariant); final Directory directory = await project.buildDirectory .childDirectory('deeplink_data').create(recursive: true); final String outputPath = globals.fs.path.join( directory.absolute.path, 'app-link-settings-$buildVariant.json', ); final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( taskName, options: <String>['-q', '-PoutputPath=$outputPath'], project: project, ); final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('outputs', 'app link settings', elapsedDuration); _analytics.send(Event.timing( workflow: 'outputs', variableName: 'app link settings', elapsedMilliseconds: elapsedDuration.inMilliseconds, ));
if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit(result.stderr); } return outputPath; }}
/// Prints how to consume the AAR from a host app.void printHowToConsumeAar({ required Set<String> buildModes, String? androidPackage = 'unknown', required Directory repoDirectory, required Logger logger, required FileSystem fileSystem, String? buildNumber,}) { assert(buildModes.isNotEmpty); buildNumber ??= '1.0';
logger.printStatus('\nConsuming the Module', emphasis: true); logger.printStatus(''' 1. Open ${fileSystem.path.join('<host>', 'app', 'build.gradle')} 2. Ensure you have the repositories configured, otherwise add them:
String storageUrl = System.env.$kFlutterStorageBaseUrl ?: "https://storage.googleapis.com" repositories { maven { url '${repoDirectory.path}' } maven { url "\$storageUrl/download.flutter.io" } }
3. Make the host app depend on the Flutter module:
dependencies {''');
for (final String buildMode in buildModes) { logger.printStatus(""" ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'"""); }
logger.printStatus(''' }''');
if (buildModes.contains('profile')) { logger.printStatus('''
4. Add the `profile` build type:
android { buildTypes { profile { initWith debug } } }'''); }
logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar');}
String _hex(List<int> bytes) { final StringBuffer result = StringBuffer(); for (final int part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); } return result.toString();}
String _calculateSha(File file) { final List<int> bytes = file.readAsBytesSync(); return _hex(sha1.convert(bytes).bytes);}
void _exitWithUnsupportedProjectMessage(Usage usage, Terminal terminal, {required Analytics analytics}) { BuildEvent('unsupported-project', type: 'gradle', eventError: 'gradle-plugin', flutterUsage: usage).send(); analytics.send(Event.flutterBuildInfo( label: 'unsupported-project', buildType: 'gradle', error: 'gradle-plugin', ));
throwToolExit( '${terminal.warningMark} Your app is using an unsupported Gradle project. ' 'To fix this problem, create a new project by running `flutter create -t app <app-directory>` ' 'and then move the dart code, assets and pubspec.yaml to the new project.', );}
/// Returns [true] if the current app uses AndroidX.// TODO(egarciad): https://github.com/flutter/flutter/issues/40800// Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`.bool isAppUsingAndroidX(Directory androidDirectory) { final File properties = androidDirectory.childFile('gradle.properties'); if (!properties.existsSync()) { return false; } return properties.readAsStringSync().contains('android.useAndroidX=true');}
/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].@visibleForTestingIterable<String> findApkFilesModule( FlutterProject project, AndroidBuildInfo androidBuildInfo, Logger logger, Usage usage, Analytics analytics,) { final Iterable<String> apkFileNames = _apkFilesFor(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project); final Iterable<File> apks = apkFileNames.expand<File>((String apkFileName) { File apkFile = apkDirectory.childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String modeName = camelCase(buildInfo.modeName); apkFile = apkDirectory .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final String? flavor = buildInfo.flavor; if (flavor != null) { // Android Studio Gradle plugin v3 adds flavor to path. apkFile = apkDirectory .childDirectory(flavor) .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } } return const <File>[]; }); if (apks.isEmpty) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: logger, usage: usage, analytics: analytics, ); } return apks.map((File file) => file.path);}
/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].////// The flutter.gradle plugin will copy APK outputs into:/// `$buildDir/app/outputs/flutter-apk/app-<abi>-<flavor-flag>-<build-mode-flag>.apk`@visibleForTestingIterable<String> listApkPaths( AndroidBuildInfo androidBuildInfo,) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final List<String> apkPartialName = <String>[ if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false) androidBuildInfo.buildInfo.lowerCasedFlavor!, '$buildType.apk', ]; if (androidBuildInfo.splitPerAbi) { return <String>[ for (final AndroidArch androidArch in androidBuildInfo.targetArchs) <String>[ 'app', androidArch.archName, ...apkPartialName, ].join('-'), ]; } return <String>[ <String>[ 'app', ...apkPartialName, ].join('-'), ];}
@visibleForTestingFile findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage, Analytics analytics) { final List<File> fileCandidates = <File>[ getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app.aab'), getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app-${buildInfo.modeName}.aab'), ]; if (buildInfo.flavor != null) { // The Android Gradle plugin 3.0.0 adds the flavor name to the path. // For example: In release mode, if the flavor name is `foo_bar`, then // the directory name is `foo_barRelease`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app.aab'));
// The Android Gradle plugin 3.5.0 adds the flavor name to file name. // For example: In release mode, if the flavor name is `foo_bar`, then // the file name is `app-foo_bar-release.aab`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab'));
// The Android Gradle plugin 4.1.0 does only lowercase the first character of flavor name. fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.uncapitalizedFlavor}-${buildInfo.modeName}.aab'));
// The Android Gradle plugin uses kebab-case and lowercases the first character of the flavor name // when multiple flavor dimensions are used: // e.g. // flavorDimensions "dimension1","dimension2" // productFlavors { // foo { // dimension "dimension1" // } // bar { // dimension "dimension2" // } // } fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${kebabCase(buildInfo.uncapitalizedFlavor!)}-${buildInfo.modeName}.aab')); } for (final File bundleFile in fileCandidates) { if (bundleFile.existsSync()) { return bundleFile; } } _exitWithExpectedFileNotFound( project: project, fileExtension: '.aab', logger: logger, usage: usage, analytics: analytics, );}
/// Throws a [ToolExit] exception and logs the event.Never _exitWithExpectedFileNotFound({ required FlutterProject project, required String fileExtension, required Logger logger, required Usage usage, required Analytics analytics,}) {
final String androidGradlePluginVersion = getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger); final String gradleBuildSettings = 'androidGradlePluginVersion: $androidGradlePluginVersion, ' 'fileExtension: $fileExtension';
BuildEvent('gradle-expected-file-not-found', type: 'gradle', settings: gradleBuildSettings, flutterUsage: usage, ).send(); analytics.send(Event.flutterBuildInfo( label: 'gradle-expected-file-not-found', buildType: 'gradle', settings: gradleBuildSettings, ));
throwToolExit( 'Gradle build failed to produce an $fileExtension file. ' "It's likely that this file was generated under ${project.android.buildDirectory.path}, " "but the tool couldn't find it." );}
void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) { final File targetFile = fileSystem.file(targetPath); if (!targetFile.existsSync()) { throwToolExit("The file $targetPath wasn't found in the local engine out directory."); } final File linkFile = fileSystem.file(linkPath); final Link symlink = linkFile.parent.childLink(linkFile.basename); try { symlink.createSync(targetPath, recursive: true); } on FileSystemException catch (exception) { throwToolExit( 'Failed to create the symlink $linkPath->$targetPath: $exception' ); }}
String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) { final File pomFile = fileSystem.file(pomPath); if (!pomFile.existsSync()) { throwToolExit("The file $pomPath wasn't found in the local engine out directory."); } XmlDocument document; try { document = XmlDocument.parse(pomFile.readAsStringSync()); } on XmlException { throwToolExit( 'Error parsing $pomPath. Please ensure that this is a valid XML document.' ); } on FileSystemException { throwToolExit( 'Error reading $pomPath. Please ensure that you have read permission to this ' 'file and try again.'); } final Iterable<XmlElement> project = document.findElements('project'); assert(project.isNotEmpty); for (final XmlElement versionElement in document.findAllElements('version')) { if (versionElement.parent == project.first) { return versionElement.innerText; } } throwToolExit('Error while parsing the <version> element from $pomPath');}
/// Returns the local Maven repository for a local engine build./// For example, if the engine is built locally at <home>/engine/src/out/android_release_unopt/// This method generates symlinks in the temp directory to the engine artifacts/// following the convention specified on https://maven.apache.org/pom.html#RepositoriesDirectory _getLocalEngineRepo({ required String engineOutPath, required AndroidBuildInfo androidBuildInfo, required FileSystem fileSystem,}) {
final String abi = _getAbiByLocalEnginePath(engineOutPath); final Directory localEngineRepo = fileSystem.systemTempDirectory .createTempSync('flutter_tool_local_engine_repo.'); final String buildMode = androidBuildInfo.buildInfo.modeName; final String artifactVersion = _getLocalArtifactVersion( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.pom', ), fileSystem, ); for (final String artifact in const <String>['pom', 'jar']) { // The Android embedding artifacts. _createSymlink( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', 'flutter_embedding_$buildMode', artifactVersion, 'flutter_embedding_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); // The engine artifacts (libflutter.so). _createSymlink( fileSystem.path.join( engineOutPath, '${abi}_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', '${abi}_$buildMode', artifactVersion, '${abi}_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); } for (final String artifact in <String>['flutter_embedding_$buildMode', '${abi}_$buildMode']) { _createSymlink( fileSystem.path.join( engineOutPath, '$artifact.maven-metadata.xml', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', artifact, 'maven-metadata.xml', ), fileSystem, ); } return localEngineRepo;}
String _getAbiByLocalEnginePath(String engineOutPath) { String result = 'armeabi_v7a'; if (engineOutPath.contains('x86')) { result = 'x86'; } else if (engineOutPath.contains('x64')) { result = 'x86_64'; } else if (engineOutPath.contains('arm64')) { result = 'arm64_v8a'; } return result;}
String _getTargetPlatformByLocalEnginePath(String engineOutPath) { String result = 'android-arm'; if (engineOutPath.contains('x86')) { result = 'android-x86'; } else if (engineOutPath.contains('x64')) { result = 'android-x64'; } else if (engineOutPath.contains('arm64')) { result = 'android-arm64'; } return result;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750// 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:meta/meta.dart';
import '../base/error_handling_io.dart';import '../base/file_system.dart';import '../base/process.dart';import '../base/terminal.dart';import '../globals.dart' as globals;import '../project.dart';import '../reporting/reporting.dart';import 'gradle_utils.dart';import 'multidex.dart';
typedef GradleErrorTest = bool Function(String);
/// A Gradle error handled by the tool.class GradleHandledError { const GradleHandledError({ required this.test, required this.handler, this.eventLabel, });
/// The test function. /// Returns [true] if the current error message should be handled. final GradleErrorTest test;
/// The handler function. final Future<GradleBuildStatus> Function({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) handler;
/// The [BuildEvent] label is named gradle-[eventLabel]. /// If not empty, the build event is logged along with /// additional metadata such as the attempt number. final String? eventLabel;}
/// The status of the Gradle build.enum GradleBuildStatus { /// The tool cannot recover from the failure and should exit. exit, /// The tool can retry the exact same build. retry,}
/// Returns a simple test function that evaluates to `true` if at least one of/// `errorMessages` is contained in the error message.GradleErrorTest _lineMatcher(List<String> errorMessages) { return (String line) { return errorMessages.any((String errorMessage) => line.contains(errorMessage)); };}
/// The list of Gradle errors that the tool can handle.////// The handlers are executed in the order in which they appear in the list.////// Only the first error handler for which the [test] function returns [true]/// is handled. As a result, sort error handlers based on how strict the [test]/// function is to eliminate false positives.final List<GradleHandledError> gradleErrors = <GradleHandledError>[ licenseNotAcceptedHandler, networkErrorHandler, permissionDeniedErrorHandler, flavorUndefinedHandler, r8FailureHandler, minSdkVersionHandler, transformInputIssueHandler, lockFileDepMissingHandler, multidexErrorHandler, incompatibleKotlinVersionHandler, minCompileSdkVersionHandler, jvm11RequiredHandler, outdatedGradleHandler, sslExceptionHandler, zipExceptionHandler, incompatibleJavaAndGradleVersionsHandler, remoteTerminatedHandshakeHandler, couldNotOpenCacheDirectoryHandler,];
const String _boxTitle = 'Flutter Fix';
// Multidex error message.@visibleForTestingfinal GradleHandledError multidexErrorHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:', 'The number of method references in a .dex file cannot exceed 64K.', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printStatus('${globals.logger.terminal.warningMark} App requires Multidex support', emphasis: true); if (multidexEnabled) { globals.printStatus( 'Multidex support is required for your android app to build since the number of methods has exceeded 64k. ' 'See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information. ' "You may pass the --no-multidex flag to skip Flutter's multidex support to use a manual solution.\n", indent: 4, ); if (!androidManifestHasNameVariable(project.directory)) { globals.printStatus( r'Your `android/app/src/main/AndroidManifest.xml` does not contain `android:name="${applicationName}"` ' 'under the `application` element. This may be due to creating your project with an old version of Flutter. ' 'Add the `android:name="\${applicationName}"` attribute to your AndroidManifest.xml to enable Flutter\'s multidex support:\n', indent: 4, ); globals.printStatus(r'''<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... <application ... android:name=''', indent: 8, newline: false, color: TerminalColor.grey, ); globals.printStatus(r'"${applicationName}"', color: TerminalColor.green, newline: true); globals.printStatus(r''' ...>''', indent: 8, color: TerminalColor.grey, );
globals.printStatus( 'You may also roll your own multidex support by following the guide at: https://developer.android.com/studio/build/multidex\n', indent: 4, ); return GradleBuildStatus.exit; } if (!multiDexApplicationExists(project.directory)) { globals.printStatus( 'Flutter tool can add multidex support. The following file will be added by flutter:\n', indent: 4, ); globals.printStatus( 'android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java\n', indent: 8, ); String selection = 'n'; // Default to 'no' if no interactive terminal. try { selection = await globals.terminal.promptForCharInput( <String>['y', 'n'], logger: globals.logger, prompt: 'Do you want to continue with adding multidex support for Android?', defaultChoiceIndex: 0, ); } on StateError catch (e) { globals.printError( e.message, indent: 0, ); } if (selection == 'y') { ensureMultiDexApplicationExists(project.directory); globals.printStatus( 'Multidex enabled. Retrying build.\n', indent: 0, ); return GradleBuildStatus.retry; } } } else { globals.printBox( 'Flutter multidex handling is disabled. If you wish to let the tool configure multidex, use the --multidex flag.', title: _boxTitle, ); } return GradleBuildStatus.exit; }, eventLabel: 'multidex-error',);
// Permission defined error message.@visibleForTestingfinal GradleHandledError permissionDeniedErrorHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'Permission denied', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printBox( '${globals.logger.terminal.warningMark} 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 directory with execute permissions.', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'permission-denied',);
/// Gradle crashes for several known reasons when downloading that are not/// actionable by Flutter.@visibleForTestingfinal GradleHandledError networkErrorHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'java.io.FileNotFoundException: https://downloads.gradle.org', 'java.io.IOException: Unable to tunnel through proxy', 'java.io.IOException: Server returned HTTP response code: 502', 'java.lang.RuntimeException: Timeout of', 'java.util.zip.ZipException: error in opening zip file', 'javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake', 'java.net.SocketException: Connection reset', 'java.io.FileNotFoundException', "> Could not get resource 'http", ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printError( '${globals.logger.terminal.warningMark} ' 'Gradle threw an error while downloading artifacts from the network.' ); return GradleBuildStatus.retry; }, eventLabel: 'network',);
/// Handles corrupted jar or other types of zip files.////// If a terminal is attached, this handler prompts the user if they would like to/// delete the $HOME/.gradle directory prior to retrying the build.////// If this handler runs on a bot (e.g. a CI bot), the $HOME/.gradle is automatically deleted.////// See also:/// * https://github.com/flutter/flutter/issues/51195/// * https://github.com/flutter/flutter/issues/89959/// * https://docs.gradle.org/current/userguide/directory_layout.html#dir:gradle_user_home@visibleForTestingfinal GradleHandledError zipExceptionHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'java.util.zip.ZipException: error in opening zip file', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printError( '${globals.logger.terminal.warningMark} ' 'Your .gradle directory under the home directory might be corrupted.' ); bool shouldDeleteUserGradle = await globals.botDetector.isRunningOnBot; if (!shouldDeleteUserGradle && globals.terminal.stdinHasTerminal) { try { final String selection = await globals.terminal.promptForCharInput( <String>['y', 'n'], logger: globals.logger, prompt: 'Do you want to delete the .gradle directory under the home directory?', defaultChoiceIndex: 0, ); shouldDeleteUserGradle = selection == 'y'; } on StateError catch (e) { globals.printError( e.message, indent: 0, ); } } if (shouldDeleteUserGradle) { final String? homeDir = globals.platform.environment['HOME']; if (homeDir == null) { globals.logger.printStatus("Could not delete .gradle directory because there isn't a HOME env variable"); return GradleBuildStatus.retry; } final Directory userGradle = globals.fs.directory(globals.fs.path.join(homeDir, '.gradle')); globals.logger.printStatus('Deleting ${userGradle.path}'); try { ErrorHandlingFileSystem.deleteIfExists(userGradle, recursive: true); } on FileSystemException catch (err) { globals.printTrace('Failed to delete Gradle cache: $err'); } } return GradleBuildStatus.retry; }, eventLabel: 'zip-exception',);
// R8 failure.@visibleForTestingfinal GradleHandledError r8FailureHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'com.android.tools.r8', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printBox( '${globals.logger.terminal.warningMark} The shrinker may have failed to optimize the Java bytecode.\n' 'To disable the shrinker, pass the `--no-shrink` flag to this command.\n' 'To learn more, see: https://developer.android.com/studio/build/shrink-code', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'r8',);
/// Handle Gradle error thrown when Gradle needs to download additional/// Android SDK components (e.g. Platform Tools), and the license/// for that component has not been accepted.@visibleForTestingfinal GradleHandledError licenseNotAcceptedHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'You have not accepted the license agreements of the following SDK components', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { const String licenseNotAcceptedMatcher = r'You have not accepted the license agreements of the following SDK components:\s*\[(.+)\]';
final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true); final Match? licenseMatch = licenseFailure.firstMatch(line); globals.printBox( '${globals.logger.terminal.warningMark} Unable to download needed Android SDK components, as the ' 'following licenses have not been accepted: ' '${licenseMatch?.group(1)}\n\n' 'To resolve this, please run the following command in a Terminal:\n' 'flutter doctor --android-licenses', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'license-not-accepted',);
final RegExp _undefinedTaskPattern = RegExp(r'Task .+ not found in root project.');
final RegExp _assembleTaskPattern = RegExp(r'assemble(\S+)');
/// Handler when a flavor is undefined.@visibleForTestingfinal GradleHandledError flavorUndefinedHandler = GradleHandledError( test: (String line) { return _undefinedTaskPattern.hasMatch(line); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final RunResult tasksRunResult = await globals.processUtils.run( <String>[ globals.gradleUtils!.getExecutable(project), 'app:tasks' , '--all', '--console=auto', ], throwOnError: true, workingDirectory: project.android.hostAppGradleRoot.path, environment: globals.java?.environment, ); // Extract build types and product flavors. final Set<String> variants = <String>{}; for (final String task in tasksRunResult.stdout.split('\n')) { final Match? match = _assembleTaskPattern.matchAsPrefix(task); if (match != null) { final String variant = match.group(1)!.toLowerCase(); if (!variant.endsWith('test')) { variants.add(variant); } } } final Set<String> productFlavors = <String>{}; for (final String variant1 in variants) { for (final String variant2 in variants) { if (variant2.startsWith(variant1) && variant2 != variant1) { final String buildType = variant2.substring(variant1.length); if (variants.contains(buildType)) { productFlavors.add(variant1); } } } } final String errorMessage = '${globals.logger.terminal.warningMark} Gradle project does not define a task suitable for the requested build.'; final File buildGradle = project.directory.childDirectory('android').childDirectory('app').childFile('build.gradle'); if (productFlavors.isEmpty) { globals.printBox( '$errorMessage\n\n' 'The ${buildGradle.absolute.path} file does not define ' 'any custom product flavors. ' 'You cannot use the --flavor option.', title: _boxTitle, ); } else { globals.printBox( '$errorMessage\n\n' 'The ${buildGradle.absolute.path} file defines product ' 'flavors: ${productFlavors.join(', ')}. ' 'You must specify a --flavor option to select one of them.', title: _boxTitle, ); } return GradleBuildStatus.exit; }, eventLabel: 'flavor-undefined',);
final RegExp _minSdkVersionPattern = RegExp(r'uses-sdk:minSdkVersion ([0-9]+) cannot be smaller than version ([0-9]+) declared in library \[\:(.+)\]');
/// Handler when a plugin requires a higher Android API level.@visibleForTestingfinal GradleHandledError minSdkVersionHandler = GradleHandledError( test: (String line) { return _minSdkVersionPattern.hasMatch(line); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradleFile = project.directory .childDirectory('android') .childDirectory('app') .childFile('build.gradle');
final Match? minSdkVersionMatch = _minSdkVersionPattern.firstMatch(line); assert(minSdkVersionMatch?.groupCount == 3);
final String textInBold = globals.logger.terminal.bolden( 'Fix this issue by adding the following to the file ${gradleFile.path}:\n' 'android {\n' ' defaultConfig {\n' ' minSdkVersion ${minSdkVersionMatch?.group(2)}\n' ' }\n' '}\n' ); globals.printBox( 'The plugin ${minSdkVersionMatch?.group(3)} requires a higher Android SDK version.\n' '$textInBold\n' 'Following this change, your app will not be available to users running Android SDKs below ${minSdkVersionMatch?.group(2)}.\n' 'Consider searching for a version of this plugin that supports these lower versions of the Android SDK instead.\n' 'For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'plugin-min-sdk',);
/// Handler when https://issuetracker.google.com/issues/141126614 or/// https://github.com/flutter/flutter/issues/58247 is triggered.@visibleForTestingfinal GradleHandledError transformInputIssueHandler = GradleHandledError( test: (String line) { return line.contains('https://issuetracker.google.com/issues/158753935'); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradleFile = project.directory .childDirectory('android') .childDirectory('app') .childFile('build.gradle'); final String textInBold = globals.logger.terminal.bolden( 'Fix this issue by adding the following to the file ${gradleFile.path}:\n' 'android {\n' ' lintOptions {\n' ' checkReleaseBuilds false\n' ' }\n' '}' ); globals.printBox( 'This issue appears to be https://github.com/flutter/flutter/issues/58247.\n' '$textInBold', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'transform-input-issue',);
/// Handler when a dependency is missing in the lockfile.@visibleForTestingfinal GradleHandledError lockFileDepMissingHandler = GradleHandledError( test: (String line) { return line.contains('which is not part of the dependency lock state'); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradleFile = project.directory .childDirectory('android') .childFile('build.gradle'); final String textInBold = globals.logger.terminal.bolden( 'To regenerate the lockfiles run: `./gradlew :generateLockfiles` in ${gradleFile.path}\n' 'To remove dependency locking, remove the `dependencyLocking` from ${gradleFile.path}' ); globals.printBox( 'You need to update the lockfile, or disable Gradle dependency locking.\n' '$textInBold', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'lock-dep-issue',);
@visibleForTestingfinal GradleHandledError incompatibleKotlinVersionHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'was compiled with an incompatible version of Kotlin', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradleFile = project.directory .childDirectory('android') .childFile('build.gradle'); globals.printBox( '${globals.logger.terminal.warningMark} 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 update ${gradleFile.path}:\n' "ext.kotlin_version = '<latest-version>'", title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'incompatible-kotlin-version',);
final RegExp _outdatedGradlePattern = RegExp(r'The current Gradle version (.+) is not compatible with the Kotlin Gradle plugin');
@visibleForTestingfinal GradleHandledError outdatedGradleHandler = GradleHandledError( test: _outdatedGradlePattern.hasMatch, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradleFile = project.directory .childDirectory('android') .childFile('build.gradle'); final File gradlePropertiesFile = project.directory .childDirectory('android') .childDirectory('gradle') .childDirectory('wrapper') .childFile('gradle-wrapper.properties'); globals.printBox( '${globals.logger.terminal.warningMark} Your project needs to upgrade Gradle and the Android Gradle plugin.\n\n' 'To fix this issue, replace the following content:\n' '${gradleFile.path}:\n' ' ${globals.terminal.color("- classpath 'com.android.tools.build:gradle:<current-version>'", TerminalColor.red)}\n' ' ${globals.terminal.color("+ classpath 'com.android.tools.build:gradle:$templateAndroidGradlePluginVersion'", TerminalColor.green)}\n' '${gradlePropertiesFile.path}:\n' ' ${globals.terminal.color('- https://services.gradle.org/distributions/gradle-<current-version>-all.zip', TerminalColor.red)}\n' ' ${globals.terminal.color('+ https://services.gradle.org/distributions/gradle-$templateDefaultGradleVersion-all.zip', TerminalColor.green)}', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'outdated-gradle-version',);
final RegExp _minCompileSdkVersionPattern = RegExp(r'The minCompileSdk \(([0-9]+)\) specified in a');
@visibleForTestingfinal GradleHandledError minCompileSdkVersionHandler = GradleHandledError( test: _minCompileSdkVersionPattern.hasMatch, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final Match? minCompileSdkVersionMatch = _minCompileSdkVersionPattern.firstMatch(line); assert(minCompileSdkVersionMatch?.groupCount == 1);
final File gradleFile = project.directory .childDirectory('android') .childDirectory('app') .childFile('build.gradle'); globals.printBox( '${globals.logger.terminal.warningMark} Your project requires a higher compileSdk version.\n' 'Fix this issue by bumping the compileSdk version in ${gradleFile.path}:\n' 'android {\n' ' compileSdk ${minCompileSdkVersionMatch?.group(1)}\n' '}', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'min-compile-sdk-version',);
@visibleForTestingfinal GradleHandledError jvm11RequiredHandler = GradleHandledError( test: (String line) { return line.contains('Android Gradle plugin requires Java 11 to run'); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printBox( '${globals.logger.terminal.warningMark} 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 https://developer.android.com/studio/install.\n\n' 'To check the Java version used by Flutter, run `flutter doctor -v`.', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'java11-required',);
/// Handles SSL exceptions: https://github.com/flutter/flutter/issues/104628@visibleForTestingfinal GradleHandledError sslExceptionHandler = GradleHandledError( test: _lineMatcher(const <String>[ 'javax.net.ssl.SSLException: Tag mismatch!', 'javax.crypto.AEADBadTagException: Tag mismatch!', ]), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printError( '${globals.logger.terminal.warningMark} ' 'Gradle threw an error while downloading artifacts from the network.' ); return GradleBuildStatus.retry; }, eventLabel: 'ssl-exception-tag-mismatch',);
/// If an incompatible Java and Gradle versions error is caught, we expect an/// error specifying that the Java major class file version, one of/// https://javaalmanac.io/bytecode/versions/, is unsupported by Gradle.final RegExp _unsupportedClassFileMajorVersionPattern = RegExp(r'Unsupported class file major version\s+\d+');
@visibleForTestingfinal GradleHandledError incompatibleJavaAndGradleVersionsHandler = GradleHandledError( test: (String line) { return _unsupportedClassFileMajorVersionPattern.hasMatch(line); }, handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { final File gradlePropertiesFile = project.directory .childDirectory('android') .childDirectory('gradle') .childDirectory('wrapper') .childFile('gradle-wrapper.properties'); // TODO(reidbaker): Replace URL with constant defined in // https://github.com/flutter/flutter/pull/123916. globals.printBox( "${globals.logger.terminal.warningMark} Your project's Gradle version " 'is incompatible with the Java version that Flutter is using for Gradle.\n\n' 'If you recently upgraded Android Studio, consult the migration guide ' 'at docs.flutter.dev/go/android-java-gradle-error.\n\n' 'Otherwise, to fix this issue, first, check the Java version used by Flutter by ' 'running `flutter doctor --verbose`.\n\n' 'Then, update the Gradle version specified in ${gradlePropertiesFile.path} ' 'to be compatible with that Java version. ' 'See the link below for more information on compatible Java/Gradle versions:\n' 'https://docs.gradle.org/current/userguide/compatibility.html#java\n\n', title: _boxTitle, ); return GradleBuildStatus.exit; }, eventLabel: 'incompatible-java-gradle-version',);
@visibleForTestingfinal GradleHandledError remoteTerminatedHandshakeHandler = GradleHandledError( test: (String line) => line.contains('Remote host terminated the handshake'), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printError( '${globals.logger.terminal.warningMark} ' 'Gradle threw an error while downloading artifacts from the network.' );
return GradleBuildStatus.retry; }, eventLabel: 'remote-terminated-handshake',);
@visibleForTestingfinal GradleHandledError couldNotOpenCacheDirectoryHandler = GradleHandledError( test: (String line) => line.contains('> Could not open cache directory '), handler: ({ required String line, required FlutterProject project, required bool usesAndroidX, required bool multidexEnabled, }) async { globals.printError( '${globals.logger.terminal.warningMark} ' 'Gradle threw an error while resolving dependencies.' );
return GradleBuildStatus.retry; }, eventLabel: 'could-not-open-cache-directory',);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974// 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:meta/meta.dart';import 'package:process/process.dart';import 'package:unified_analytics/unified_analytics.dart';
import '../base/common.dart';import '../base/file_system.dart';import '../base/logger.dart';import '../base/os.dart';import '../base/platform.dart';import '../base/utils.dart';import '../base/version.dart';import '../base/version_range.dart';import '../build_info.dart';import '../cache.dart';import '../globals.dart' as globals;import '../project.dart';import '../reporting/reporting.dart';import 'android_sdk.dart';
// These are the versions used in the project templates.//// In general, Flutter aims to default to the latest version.// However, this currently requires to migrate existing integration tests to the latest supported values.//// Please see the README before changing any of these values.const String templateDefaultGradleVersion = '7.6.3';const String templateAndroidGradlePluginVersion = '7.3.0';const String templateAndroidGradlePluginVersionForModule = '7.3.0';const String templateKotlinGradlePluginVersion = '1.7.10';
// The Flutter Gradle Plugin is only applied to app projects, and modules that// are built from source using (`include_flutter.groovy`). The remaining// projects are: plugins, and modules compiled as AARs. In modules, the// ephemeral directory `.android` is always regenerated after `flutter pub get`,// so new versions are picked up after a Flutter upgrade.//// Please see the README before changing any of these values.const String compileSdkVersion = '34';const String minSdkVersion = '19';const String targetSdkVersion = '33';const String ndkVersion = '23.1.7779620';
// Update these when new major versions of Java are supported by new Gradle// versions that we support.// Source of truth: https://docs.gradle.org/current/userguide/compatibility.htmlconst String oneMajorVersionHigherJavaVersion = '20';
// Update this when new versions of Gradle come out including minor versions// and should correspond to the maximum Gradle version we test in CI.//// Supported here means supported by the tooling for// flutter analyze --suggestions and does not imply broader flutter support.const String maxKnownAndSupportedGradleVersion = '8.0.2';
// Update this when new versions of AGP come out.//// Supported here means tooling is aware of this version's Java <-> AGP// compatibility.@visibleForTestingconst String maxKnownAndSupportedAgpVersion = '8.1';
// Update this when new versions of AGP come out.const String maxKnownAgpVersion = '8.3';
// Oldest documented version of AGP that has a listed minimum// compatible Java version.const String oldestDocumentedJavaAgpCompatibilityVersion = '4.2';
// Constant used in [_buildAndroidGradlePluginRegExp] and// [_settingsAndroidGradlePluginRegExp] to identify the version section.const String _versionGroupName = 'version';
// AGP can be defined in build.gradle// Expected content:// "classpath 'com.android.tools.build:gradle:7.3.0'"// ?<version> is used to name the version group which helps with extraction.final RegExp _buildAndroidGradlePluginRegExp = RegExp(r'com\.android\.tools\.build:gradle:(?<version>\d+\.\d+\.\d+)');
// AGP can be defined in settings.gradle.// Expected content:// "id "com.android.application" version "{{agpVersion}}""// ?<version> is used to name the version group which helps with extraction.final RegExp _settingsAndroidGradlePluginRegExp = RegExp( r'^\s+id\s+"com.android.application"\s+version\s+"(?<version>\d+\.\d+\.\d+)"', multiLine: true);
// Expected content format (with lines above and below).// Version can have 2 or 3 numbers.// 'distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip'// '^\s*' protects against commented out lines.final RegExp distributionUrlRegex = RegExp(r'^\s*distributionUrl\s*=\s*.*\.zip', multiLine: true);
// Modified version of the gradle distribution url match designed to only match// gradle.org urls so that we can guarantee any modifications to the url// still points to a hosted zip.final RegExp gradleOrgVersionMatch = RegExp( r'^\s*distributionUrl\s*=\s*https\\://services\.gradle\.org/distributions/gradle-((?:\d|\.)+)-(.*)\.zip', multiLine: true );
// This matches uncommented minSdkVersion lines in the module-level build.gradle// file which have minSdkVersion 16,17, or 18 (the Jelly Bean api levels).final RegExp jellyBeanMinSdkVersionMatch = RegExp(r'(?<=^\s*)minSdkVersion 1[678](?=\s*(?://|$))', multiLine: true);
// From https://docs.gradle.org/current/userguide/command_line_interface.html#command_line_interfaceconst String gradleVersionFlag = r'--version';
// Directory under android/ that gradle uses to store gradle information.// Regularly used with [gradleWrapperDirectory] and// [gradleWrapperPropertiesFilename].// Different from the directory of gradle files stored in// `_cache.getArtifactDirectory('gradle_wrapper')`const String gradleDirectoryName = 'gradle';const String gradleWrapperDirectoryName = 'wrapper';const String gradleWrapperPropertiesFilename = 'gradle-wrapper.properties';
/// Provides utilities to run a Gradle task, such as finding the Gradle executable/// or constructing a Gradle project.class GradleUtils { GradleUtils({ required Platform platform, required Logger logger, required Cache cache, required OperatingSystemUtils operatingSystemUtils, }) : _platform = platform, _logger = logger, _cache = cache, _operatingSystemUtils = operatingSystemUtils;
final Cache _cache; final Platform _platform; final Logger _logger; final OperatingSystemUtils _operatingSystemUtils;
/// Gets the Gradle executable path and prepares the Gradle project. /// This is the `gradlew` or `gradlew.bat` script in the `android/` directory. String getExecutable(FlutterProject project) { final Directory androidDir = project.android.hostAppGradleRoot; injectGradleWrapperIfNeeded(androidDir);
final File gradle = androidDir.childFile(getGradlewFileName(_platform));
if (gradle.existsSync()) { _logger.printTrace('Using gradle from ${gradle.absolute.path}.'); // If the Gradle executable doesn't have execute permission, // then attempt to set it. _operatingSystemUtils.makeExecutable(gradle); return gradle.absolute.path; } throwToolExit( 'Unable to locate gradlew script. Please check that ${gradle.path} ' 'exists or that ${gradle.dirname} can be read.'); }
/// Injects the Gradle wrapper files if any of these files don't exist in [directory]. void injectGradleWrapperIfNeeded(Directory directory) { copyDirectory( _cache.getArtifactDirectory('gradle_wrapper'), directory, shouldCopyFile: (File sourceFile, File destinationFile) { // Don't override the existing files in the project. return !destinationFile.existsSync(); }, onFileCopied: (File source, File dest) { _operatingSystemUtils.makeExecutable(dest); } ); // Add the `gradle-wrapper.properties` file if it doesn't exist. final Directory propertiesDirectory = directory .childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName); final File propertiesFile = propertiesDirectory.childFile(gradleWrapperPropertiesFilename);
if (propertiesFile.existsSync()) { return; } propertiesDirectory.createSync(recursive: true); final String gradleVersion = getGradleVersionForAndroidPlugin(directory, _logger); final String propertyContents = '''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distszipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdistributionUrl=https\\://services.gradle.org/distributions/gradle-$gradleVersion-all.zip'''; propertiesFile.writeAsStringSync(propertyContents); }}
/// Returns the Gradle version that the current Android plugin depends on when found,/// otherwise it returns a default version.////// The Android plugin version is specified in the [build.gradle] file within/// the project's Android directory.String getGradleVersionForAndroidPlugin(Directory directory, Logger logger) { final File buildFile = directory.childFile('build.gradle'); if (!buildFile.existsSync()) { logger.printTrace( "$buildFile doesn't exist, assuming Gradle version: $templateDefaultGradleVersion"); return templateDefaultGradleVersion; } final String buildFileContent = buildFile.readAsStringSync(); final Iterable<Match> pluginMatches = _buildAndroidGradlePluginRegExp.allMatches(buildFileContent); if (pluginMatches.isEmpty) { logger.printTrace("$buildFile doesn't provide an AGP version, assuming Gradle version: $templateDefaultGradleVersion"); return templateDefaultGradleVersion; } final String? androidPluginVersion = pluginMatches.first.group(1); logger.printTrace('$buildFile provides AGP version: $androidPluginVersion'); return getGradleVersionFor(androidPluginVersion ?? 'unknown');}
/// Returns the gradle file from the top level directory./// The returned file is not guaranteed to be present.File getGradleWrapperFile(Directory directory) { return directory.childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .childFile(gradleWrapperPropertiesFilename);}
/// Parses the gradle wrapper distribution url to return a string containing/// the version number.////// Expected input is of the form '...gradle-7.4.2-all.zip', and the output/// would be of the form '7.4.2'.String? parseGradleVersionFromDistributionUrl(String? distributionUrl) { if (distributionUrl == null) { return null; } final List<String> zipParts = distributionUrl.split('-'); if (zipParts.length < 2) { return null; } return zipParts[1];}
/// Returns either the gradle-wrapper.properties value from the passed in/// [directory] or if not present the version available in local path.////// If gradle version is not found null is returned./// [directory] should be an android directory with a build.gradle file.Future<String?> getGradleVersion( Directory directory, Logger logger, ProcessManager processManager) async { final File propertiesFile = getGradleWrapperFile(directory);
if (propertiesFile.existsSync()) { final String wrapperFileContent = propertiesFile.readAsStringSync();
final RegExpMatch? distributionUrl = distributionUrlRegex.firstMatch(wrapperFileContent); if (distributionUrl != null) { final String? gradleVersion = parseGradleVersionFromDistributionUrl(distributionUrl.group(0)); if (gradleVersion != null) { return gradleVersion; } else { // Did not find gradle zip url. Likely this is a bug in our parsing. logger.printWarning(_formatParseWarning(wrapperFileContent)); } } else { // If no distributionUrl log then treat as if there was no propertiesFile. logger.printTrace( '$propertiesFile does not provide a Gradle version falling back to system gradle.'); } } else { // Could not find properties file. logger.printTrace( '$propertiesFile does not exist falling back to system gradle'); } // System installed Gradle version. if (processManager.canRun('gradle')) { final String gradleVersionVerbose = (await processManager.run(<String>['gradle', gradleVersionFlag])).stdout as String; // Expected format:/*
------------------------------------------------------------Gradle 7.6------------------------------------------------------------
Build time: 2022-11-25 13:35:10 UTCRevision: daece9dbc5b79370cc8e4fd6fe4b2cd400e150a8
Kotlin: 1.7.10Groovy: 3.0.13Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021JVM: 17.0.6 (Homebrew 17.0.6+0)OS: Mac OS X 13.2.1 aarch64 */ // Observation shows that the version can have 2 or 3 numbers. // Inner parentheticals `(\.\d+)?` denote the optional third value. // Outer parentheticals `Gradle (...)` denote a grouping used to extract // the version number. final RegExp gradleVersionRegex = RegExp(r'Gradle\s+(\d+\.\d+(?:\.\d+)?)'); final RegExpMatch? version = gradleVersionRegex.firstMatch(gradleVersionVerbose); if (version == null) { // Most likely a bug in our parse implementation/regex. logger.printWarning(_formatParseWarning(gradleVersionVerbose)); return null; } return version.group(1); } else { logger.printTrace('Could not run system gradle'); return null; }}
/// Returns the Android Gradle Plugin (AGP) version that the current project/// depends on when found, null otherwise.////// The Android plugin version is specified in the [build.gradle] or/// [settings.gradle] file within the project's/// Android directory ([androidDirectory]).String? getAgpVersion(Directory androidDirectory, Logger logger) { final File buildFile = androidDirectory.childFile('build.gradle'); if (!buildFile.existsSync()) { logger.printTrace('Can not find build.gradle in $androidDirectory'); return null; } final String buildFileContent = buildFile.readAsStringSync(); final RegExpMatch? buildMatch = _buildAndroidGradlePluginRegExp.firstMatch(buildFileContent); if (buildMatch != null) { final String? androidPluginVersion = buildMatch.namedGroup(_versionGroupName); logger.printTrace('$buildFile provides AGP version: $androidPluginVersion'); return androidPluginVersion; } logger.printTrace( "$buildFile doesn't provide an AGP version. Checking settings."); final File settingsFile = androidDirectory.childFile('settings.gradle'); if (!settingsFile.existsSync()) { logger.printTrace('$settingsFile does not exist.'); return null; } final String settingsFileContent = settingsFile.readAsStringSync(); final RegExpMatch? settingsMatch = _settingsAndroidGradlePluginRegExp.firstMatch(settingsFileContent);
if (settingsMatch != null) { final String? androidPluginVersion = settingsMatch.namedGroup(_versionGroupName); logger.printTrace( '$settingsFile provides AGP version: $androidPluginVersion'); return androidPluginVersion; } logger.printTrace("$settingsFile doesn't provide an AGP version."); return null;}
String _formatParseWarning(String content) { return 'Could not parse gradle version from: \n' '$content \n' 'If there is a version please look for an existing bug ' 'https://github.com/flutter/flutter/issues/' ' and if one does not exist file a new issue.';}
// Validate that Gradle version and AGP are compatible with each other.//// Returns true if versions are compatible.// Null Gradle version or AGP version returns false.// If compatibility can not be evaluated returns false.// If versions are newer than the max known version a warning is logged and true// returned.//// Source of truth found here:// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle// AGP has a minimum version of gradle required but no max starting at// AGP version 2.3.0+.bool validateGradleAndAgp(Logger logger, {required String? gradleV, required String? agpV}) {
const String oldestSupportedAgpVersion = '3.3.0'; const String oldestSupportedGradleVersion = '4.10.1';
if (gradleV == null || agpV == null) { logger .printTrace('Gradle version or AGP version unknown ($gradleV, $agpV).'); return false; }
// First check if versions are too old. if (isWithinVersionRange(agpV, min: '0.0', max: oldestSupportedAgpVersion, inclusiveMax: false)) { logger.printTrace('AGP Version: $agpV is too old.'); return false; } if (isWithinVersionRange(gradleV, min: '0.0', max: oldestSupportedGradleVersion, inclusiveMax: false)) { logger.printTrace('Gradle Version: $gradleV is too old.'); return false; }
// Check highest supported version before checking unknown versions. if (isWithinVersionRange(agpV, min: '8.0', max: maxKnownAndSupportedAgpVersion)) { return isWithinVersionRange(gradleV, min: '8.0', max: maxKnownAndSupportedGradleVersion); } // Check if versions are newer than the max known versions. if (isWithinVersionRange(agpV, min: maxKnownAndSupportedAgpVersion, max: '100.100')) { // Assume versions we do not know about are valid but log. final bool validGradle = isWithinVersionRange(gradleV, min: '8.0', max: '100.00'); logger.printTrace('Newer than known AGP version ($agpV), gradle ($gradleV).' '\n Treating as valid configuration.'); return validGradle; }
// Begin Known Gradle <-> AGP validation. // Max agp here is a made up version to contain all 7.4 changes. if (isWithinVersionRange(agpV, min: '7.4', max: '7.5')) { return isWithinVersionRange(gradleV, min: '7.5', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '7.3', max: '7.4', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '7.4', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '7.2', max: '7.3', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '7.3.3', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '7.1', max: '7.2', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '7.2', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '7.0', max: '7.1', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '7.0', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '4.2.0', max: '7.0', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '6.7.1', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '4.1.0', max: '4.2.0', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '6.5', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange(agpV, min: '4.0.0', max: '4.1.0', inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: '6.1.1', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange( agpV, min: '3.6.0', max: '3.6.4', )) { return isWithinVersionRange(gradleV, min: '5.6.4', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange( agpV, min: '3.5.0', max: '3.5.4', )) { return isWithinVersionRange(gradleV, min: '5.4.1', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange( agpV, min: '3.4.0', max: '3.4.3', )) { return isWithinVersionRange(gradleV, min: '5.1.1', max: maxKnownAndSupportedGradleVersion); } if (isWithinVersionRange( agpV, min: '3.3.0', max: '3.3.3', )) { return isWithinVersionRange(gradleV, min: '4.10.1', max: maxKnownAndSupportedGradleVersion); }
logger.printTrace('Unknown Gradle-Agp compatibility, $gradleV, $agpV'); return false;}
/// Validate that the [javaVersion] and Gradle version are compatible with/// each other.////// Source of truth:/// https://docs.gradle.org/current/userguide/compatibility.html#javabool validateJavaAndGradle(Logger logger, {required String? javaV, required String? gradleV}) { // https://docs.gradle.org/current/userguide/compatibility.html#java const String oldestSupportedJavaVersion = '1.8'; const String oldestDocumentedJavaGradleCompatibility = '2.0';
// Begin Java <-> Gradle validation.
if (javaV == null || gradleV == null) { logger.printTrace( 'Java version or Gradle version unknown ($javaV, $gradleV).'); return false; }
// First check if versions are too old. if (isWithinVersionRange(javaV, min: '1.1', max: oldestSupportedJavaVersion, inclusiveMax: false)) { logger.printTrace('Java Version: $javaV is too old.'); return false; } if (isWithinVersionRange(gradleV, min: '0.0', max: oldestDocumentedJavaGradleCompatibility, inclusiveMax: false)) { logger.printTrace('Gradle Version: $gradleV is too old.'); return false; }
// Check if versions are newer than the max supported versions. if (isWithinVersionRange( javaV, min: oneMajorVersionHigherJavaVersion, max: '100.100', )) { // Assume versions Java versions newer than [maxSupportedJavaVersion] // required a higher gradle version. final bool validGradle = isWithinVersionRange(gradleV, min: maxKnownAndSupportedGradleVersion, max: '100.00'); logger.printWarning( 'Newer than known valid Java version ($javaV), gradle ($gradleV).' '\n Treating as valid configuration.'); return validGradle; }
// Begin known Java <-> Gradle evaluation. for (final JavaGradleCompat data in _javaGradleCompatList) { if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) { return isWithinVersionRange(gradleV, min: data.gradleMin, max: data.gradleMax); } }
logger.printTrace('Unknown Java-Gradle compatibility $javaV, $gradleV'); return false;}
/// Returns compatibility information for the valid range of Gradle versions for/// the specified Java version.////// Returns null when the tooling has not documented the compatibile Gradle/// versions for the Java version (either the version is too old or too new). If/// this seems like a mistake, the caller may need to update the/// [_javaGradleCompatList] detailing Java/Gradle compatibility.JavaGradleCompat? getValidGradleVersionRangeForJavaVersion( Logger logger, { required String javaV,}) { for (final JavaGradleCompat data in _javaGradleCompatList) { if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) { return data; } }
logger.printTrace('Unable to determine valid Gradle version range for Java version $javaV.'); return null;}
/// Validate that the specified Java and Android Gradle Plugin (AGP) versions are/// compatible with each other.////// Returns true when the specified Java and AGP versions are/// definitely compatible; otherwise, false is assumed by default. In addition,/// this will return false when either a null Java or AGP version is provided.////// Source of truth are the AGP release notes:/// https://developer.android.com/build/releases/gradle-pluginbool validateJavaAndAgp(Logger logger, {required String? javaV, required String? agpV}) { if (javaV == null || agpV == null) { logger.printTrace( 'Java version or AGP version unknown ($javaV, $agpV).'); return false; }
// Check if AGP version is too old to perform validation. if (isWithinVersionRange(agpV, min: '1.0', max: oldestDocumentedJavaAgpCompatibilityVersion, inclusiveMax: false)) { logger.printTrace('AGP Version: $agpV is too old to determine Java compatibility.'); return false; }
if (isWithinVersionRange(agpV, min: maxKnownAndSupportedAgpVersion, max: '100.100', inclusiveMin: false)) { logger.printTrace('AGP Version: $agpV is too new to determine Java compatibility.'); return false; }
// Begin known Java <-> AGP evaluation. for (final JavaAgpCompat data in _javaAgpCompatList) { if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) { return isWithinVersionRange(javaV, min: data.javaMin, max: '100.100'); } }
logger.printTrace('Unknown Java-AGP compatibility $javaV, $agpV'); return false; }
/// Returns compatibility information concerning the minimum AGP /// version for the specified Java version. JavaAgpCompat? getMinimumAgpVersionForJavaVersion(Logger logger, {required String javaV}) { for (final JavaAgpCompat data in _javaAgpCompatList) { if (isWithinVersionRange(javaV, min: data.javaMin, max: '100.100')) { return data; } }
logger.printTrace('Unable to determine minimum AGP version for specified Java version.'); return null;}
/// Returns valid Java range for specified Gradle and AGP verisons.////// Assumes that gradleV and agpV are compatible versions.VersionRange getJavaVersionFor({required String gradleV, required String agpV}) { // Find minimum Java version based on AGP compatibility. String? minJavaVersion; for (final JavaAgpCompat data in _javaAgpCompatList) { if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) { minJavaVersion = data.javaMin; } }
// Find maximum Java version based on Gradle compatibility. String? maxJavaVersion; for (final JavaGradleCompat data in _javaGradleCompatList.reversed) { if (isWithinVersionRange(gradleV, min: data.gradleMin, max: maxKnownAndSupportedGradleVersion)) { maxJavaVersion = data.javaMax; } }
return VersionRange(minJavaVersion, maxJavaVersion);}
/// Returns the Gradle version that is required by the given Android Gradle plugin version/// by picking the largest compatible version from/// https://developer.android.com/studio/releases/gradle-plugin#updating-gradleString getGradleVersionFor(String androidPluginVersion) { final List<GradleForAgp> compatList = <GradleForAgp> [ GradleForAgp(agpMin: '1.0.0', agpMax: '1.1.3', minRequiredGradle: '2.3'), GradleForAgp(agpMin: '1.2.0', agpMax: '1.3.1', minRequiredGradle: '2.9'), GradleForAgp(agpMin: '1.5.0', agpMax: '1.5.0', minRequiredGradle: '2.2.1'), GradleForAgp(agpMin: '2.0.0', agpMax: '2.1.2', minRequiredGradle: '2.13'), GradleForAgp(agpMin: '2.1.3', agpMax: '2.2.3', minRequiredGradle: '2.14.1'), GradleForAgp(agpMin: '2.3.0', agpMax: '2.9.9', minRequiredGradle: '3.3'), GradleForAgp(agpMin: '3.0.0', agpMax: '3.0.9', minRequiredGradle: '4.1'), GradleForAgp(agpMin: '3.1.0', agpMax: '3.1.9', minRequiredGradle: '4.4'), GradleForAgp(agpMin: '3.2.0', agpMax: '3.2.1', minRequiredGradle: '4.6'), GradleForAgp(agpMin: '3.3.0', agpMax: '3.3.2', minRequiredGradle: '4.10.2'), GradleForAgp(agpMin: '3.4.0', agpMax: '3.5.0', minRequiredGradle: '5.6.2'), GradleForAgp(agpMin: '4.0.0', agpMax: '4.1.0', minRequiredGradle: '6.7'), // 7.5 is a made up value to include everything through 7.4.* GradleForAgp(agpMin: '7.0.0', agpMax: '7.5', minRequiredGradle: '7.5'), GradleForAgp(agpMin: '7.5.0', agpMax: '100.100', minRequiredGradle: '8.0'), // Assume if AGP is newer than this code know about return the highest gradle // version we know about. GradleForAgp(agpMin: maxKnownAgpVersion, agpMax: maxKnownAgpVersion, minRequiredGradle: maxKnownAndSupportedGradleVersion),
]; for (final GradleForAgp data in compatList) { if (isWithinVersionRange(androidPluginVersion, min: data.agpMin, max: data.agpMax)) { return data.minRequiredGradle; } } if (isWithinVersionRange(androidPluginVersion, min: maxKnownAgpVersion, max: '100.100')) { return maxKnownAndSupportedGradleVersion; } throwToolExit('Unsupported Android Plugin version: $androidPluginVersion.');}
/// Overwrite local.properties in the specified Flutter project's Android/// sub-project, if needed.////// If [requireAndroidSdk] is true (the default) and no Android SDK is found,/// this will fail with a [ToolExit].void updateLocalProperties({ required FlutterProject project, BuildInfo? buildInfo, bool requireAndroidSdk = true,}) { if (requireAndroidSdk && globals.androidSdk == null) { exitWithNoSdkMessage(); } final File localProperties = project.android.localPropertiesFile; bool changed = false;
SettingsFile settings; if (localProperties.existsSync()) { settings = SettingsFile.parseFromFile(localProperties); } else { settings = SettingsFile(); changed = true; }
void changeIfNecessary(String key, String? value) { if (settings.values[key] == value) { return; } if (value == null) { settings.values.remove(key); } else { settings.values[key] = value; } changed = true; }
final AndroidSdk? androidSdk = globals.androidSdk; if (androidSdk != null) { changeIfNecessary('sdk.dir', globals.fsUtils.escapePath(androidSdk.directory.path)); }
changeIfNecessary('flutter.sdk', globals.fsUtils.escapePath(Cache.flutterRoot!)); if (buildInfo != null) { changeIfNecessary('flutter.buildMode', buildInfo.modeName); final String? buildName = validatedBuildNameForPlatform( TargetPlatform.android_arm, buildInfo.buildName ?? project.manifest.buildName, globals.logger, ); changeIfNecessary('flutter.versionName', buildName); final String? buildNumber = validatedBuildNumberForPlatform( TargetPlatform.android_arm, buildInfo.buildNumber ?? project.manifest.buildNumber, globals.logger, ); changeIfNecessary('flutter.versionCode', buildNumber); }
if (changed) { settings.writeContents(localProperties); }}
/// Writes standard Android local properties to the specified [properties] file.////// Writes the path to the Android SDK, if known.void writeLocalProperties(File properties) { final SettingsFile settings = SettingsFile(); final AndroidSdk? androidSdk = globals.androidSdk; if (androidSdk != null) { settings.values['sdk.dir'] = globals.fsUtils.escapePath(androidSdk.directory.path); } settings.writeContents(properties);}
void exitWithNoSdkMessage() { BuildEvent('unsupported-project', type: 'gradle', eventError: 'android-sdk-not-found', flutterUsage: globals.flutterUsage) .send(); globals.analytics.send(Event.flutterBuildInfo( label: 'unsupported-project', buildType: 'gradle', error: 'android-sdk-not-found', )); throwToolExit('${globals.logger.terminal.warningMark} No Android SDK found. ' 'Try setting the ANDROID_HOME environment variable.');}
// Data class to hold normal/defined Java <-> Gradle compatability criteria.//// The [javaMax] is exclusive in terms of supporting the noted [gradleMin],// whereas [javaMin] is inclusive.@immutableclass JavaGradleCompat { const JavaGradleCompat({ required this.javaMin, required this.javaMax, required this.gradleMin, required this.gradleMax, });
final String javaMin; final String javaMax; final String gradleMin; final String gradleMax;
@override bool operator ==(Object other) => other is JavaGradleCompat && other.javaMin == javaMin && other.javaMax == javaMax && other.gradleMin == gradleMin && other.gradleMax == gradleMax;
@override int get hashCode => Object.hash(javaMin, javaMax, gradleMin, gradleMax);}
// Data class to hold defined Java <-> AGP compatibility criteria.//// The [agpMin] and [agpMax] are inclusive in terms of having the// noted [javaMin] and [javaDefault] versions.@immutableclass JavaAgpCompat { const JavaAgpCompat({ required this.javaMin, required this.javaDefault, required this.agpMin, required this.agpMax, });
final String javaMin; final String javaDefault; final String agpMin; final String agpMax;
@override bool operator ==(Object other) => other is JavaAgpCompat && other.javaMin == javaMin && other.javaDefault == javaDefault && other.agpMin == agpMin && other.agpMax == agpMax;
@override int get hashCode => Object.hash(javaMin, javaDefault, agpMin, agpMax);}
class GradleForAgp { GradleForAgp({ required this.agpMin, required this.agpMax, required this.minRequiredGradle, });
final String agpMin; final String agpMax; final String minRequiredGradle;}
// Returns gradlew file name based on the platform.String getGradlewFileName(Platform platform) { if (platform.isWindows) { return 'gradlew.bat'; } else { return 'gradlew'; }}
/// List of compatible Java/Gradle versions.////// Should be updated when a new version of Java is supported by a new version/// of Gradle, as https://docs.gradle.org/current/userguide/compatibility.html/// details.List<JavaGradleCompat> _javaGradleCompatList = const <JavaGradleCompat>[ JavaGradleCompat( javaMin: '19', javaMax: '20', gradleMin: '7.6', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '18', javaMax: '19', gradleMin: '7.5', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '17', javaMax: '18', gradleMin: '7.3', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '16', javaMax: '17', gradleMin: '7.0', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '15', javaMax: '16', gradleMin: '6.7', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '14', javaMax: '15', gradleMin: '6.3', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '13', javaMax: '14', gradleMin: '6.0', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '12', javaMax: '13', gradleMin: '5.4', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '11', javaMax: '12', gradleMin: '5.0', gradleMax: maxKnownAndSupportedGradleVersion, ), // 1.11 is a made up java version to cover everything in 1.10.* JavaGradleCompat( javaMin: '1.10', javaMax: '1.11', gradleMin: '4.7', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '1.9', javaMax: '1.10', gradleMin: '4.3', gradleMax: maxKnownAndSupportedGradleVersion, ), JavaGradleCompat( javaMin: '1.8', javaMax: '1.9', gradleMin: '2.0', gradleMax: maxKnownAndSupportedGradleVersion, ), ];
// List of compatible Java/AGP versions, where agpMax versions are inclusive. // // Should be updated whenever a new version of AGP is released as // https://developer.android.com/build/releases/gradle-plugin details. List<JavaAgpCompat> _javaAgpCompatList = const <JavaAgpCompat>[ JavaAgpCompat( javaMin: '17', javaDefault: '17', agpMin: '8.0', agpMax: maxKnownAndSupportedAgpVersion, ), JavaAgpCompat( javaMin: '11', javaDefault: '11', agpMin: '7.0', agpMax: '7.4', ), JavaAgpCompat( // You may use JDK 1.7 with AGP 4.2, but we treat 1.8 as the default since // it is used by default for this AGP version and lower versions of Java // are deprecated for executing Gradle. javaMin: '1.8', javaDefault: '1.8', agpMin: '4.2', agpMax: '4.2', ), ];123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247// 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:process/process.dart';
import '../base/config.dart';import '../base/file_system.dart';import '../base/logger.dart';import '../base/os.dart';import '../base/platform.dart';import '../base/process.dart';import '../base/version.dart';import 'android_studio.dart';
const String _javaExecutable = 'java';
/// Represents an installation of Java.class Java { Java({ required this.javaHome, required this.binaryPath, required Logger logger, required FileSystem fileSystem, required OperatingSystemUtils os, required Platform platform, required ProcessManager processManager, }): _logger = logger, _fileSystem = fileSystem, _os = os, _platform = platform, _processManager = processManager, _processUtils = ProcessUtils(processManager: processManager, logger: logger);
/// Within the Java ecosystem, this environment variable is typically set /// the install location of a Java Runtime Environment (JRE) or Java /// Development Kit (JDK). /// /// Tools that depend on Java and need to find it will often check this /// variable. If you are looking to set `JAVA_HOME` when stating a process, /// consider using the [environment] instance property instead. static String javaHomeEnvironmentVariable = 'JAVA_HOME';
/// Finds the Java runtime environment that should be used for all java-dependent /// operations across the tool. /// /// This searches for Java in the following places, in order: /// /// 1. the runtime environment bundled with Android Studio; /// 2. the runtime environment found in the JAVA_HOME env variable, if set; or /// 3. the java binary found on PATH. /// /// Returns null if no java binary could be found. static Java? find({ required Config config, required AndroidStudio? androidStudio, required Logger logger, required FileSystem fileSystem, required Platform platform, required ProcessManager processManager, }) { final OperatingSystemUtils os = OperatingSystemUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager ); final String? home = _findJavaHome( config: config, logger: logger, androidStudio: androidStudio, platform: platform ); final String? binary = _findJavaBinary( logger: logger, javaHome: home, fileSystem: fileSystem, operatingSystemUtils: os, platform: platform );
if (binary == null) { return null; }
return Java( javaHome: home, binaryPath: binary, logger: logger, fileSystem: fileSystem, os: os, platform: platform, processManager: processManager, ); }
/// The path of the runtime environments' home directory. /// /// This should only be used for logging and validation purposes. /// If you need to set JAVA_HOME when starting a process, consider /// using [environment] instead. /// If you need to inspect the files of the runtime, considering adding /// a new method to this class instead. final String? javaHome;
/// The path of the runtime environments' java binary. /// /// This should be only used for logging and validation purposes. /// If you need to invoke the binary directly, consider adding a new method /// to this class instead. final String binaryPath;
final Logger _logger; final FileSystem _fileSystem; final OperatingSystemUtils _os; final Platform _platform; final ProcessManager _processManager; final ProcessUtils _processUtils;
/// Returns an environment variable map with /// 1. JAVA_HOME set if this object has a known home directory, and /// 2. The java binary folder appended onto PATH, if the binary location is known. /// /// This map should be used as the environment when invoking any Java-dependent /// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.) Map<String, String> get environment { return <String, String>{ if (javaHome != null) javaHomeEnvironmentVariable: javaHome!, 'PATH': _fileSystem.path.dirname(binaryPath) + _os.pathVarSeparator + _platform.environment['PATH']!, }; }
/// Returns the version of java in the format \d(.\d)+(.\d)+ /// Returns null if version could not be determined. late final Version? version = (() { if (!canRun()) { return null; }
final RunResult result = _processUtils.runSync( <String>[binaryPath, '--version'], environment: environment, ); if (result.exitCode != 0) { _logger.printTrace('java --version failed: exitCode: ${result.exitCode}' ' stdout: ${result.stdout} stderr: ${result.stderr}'); return null; } final String rawVersionOutput = result.stdout; final List<String> versionLines = rawVersionOutput.split('\n'); // Should look something like 'openjdk 19.0.2 2023-01-17'. final String longVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
// The contents that matter come in the format '11.0.18', '1.8.0_202 or 21'. final RegExp jdkVersionRegex = RegExp(r'(?<version>\d+(\.\d+(\.\d+(?:_\d+)?)?)?)'); final Iterable<RegExpMatch> matches = jdkVersionRegex.allMatches(rawVersionOutput); if (matches.isEmpty) { // Fallback to second string format like "java 21.0.1 2023-09-19 LTS" final RegExp secondJdkVersionRegex = RegExp(r'java\s+(?<version>\d+(\.\d+)?(\.\d+)?)\s+\d\d\d\d-\d\d-\d\d'); final RegExpMatch? match = secondJdkVersionRegex.firstMatch(versionLines[0]); if (match != null) { final Version? parsedVersion = Version.parse(match.namedGroup('version')); if (parsedVersion == null) { return null; } return parsedVersion; } _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput)); return null; } final String? version = matches.first.namedGroup('version'); if (version == null || version.split('_').isEmpty) { _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput)); return null; }
// Trim away _d+ from versions 1.8 and below. final String versionWithoutBuildInfo = version.split('_').first;
final Version? parsedVersion = Version.parse(versionWithoutBuildInfo); if (parsedVersion == null) { return null; } return Version.withText( parsedVersion.major, parsedVersion.minor, parsedVersion.patch, longVersionText, ); })();
bool canRun() { return _processManager.canRun(binaryPath); }}
String? _findJavaHome({ required Config config, required Logger logger, required AndroidStudio? androidStudio, required Platform platform,}) { final Object? configured = config.getValue('jdk-dir'); if (configured != null) { return configured as String; }
final String? androidStudioJavaPath = androidStudio?.javaPath; if (androidStudioJavaPath != null) { return androidStudioJavaPath; }
final String? javaHomeEnv = platform.environment[Java.javaHomeEnvironmentVariable]; if (javaHomeEnv != null) { return javaHomeEnv; } return null;}
String? _findJavaBinary({ required Logger logger, required String? javaHome, required FileSystem fileSystem, required OperatingSystemUtils operatingSystemUtils, required Platform platform,}) { if (javaHome != null) { return fileSystem.path.join(javaHome, 'bin', 'java'); }
// Fallback to PATH based lookup. return operatingSystemUtils.which(_javaExecutable)?.path;}
// Returns a user visible String that says the tool failed to parse// the version of java along with the output.String _formatJavaVersionWarning(String javaVersionRaw) { return 'Could not parse java version from: \n' '$javaVersionRaw \n' 'If there is a version please look for an existing bug ' 'https://github.com/flutter/flutter/issues/ ' 'and if one does not exist file a new issue.';}1234567891011121314151617181920212223242526272829303132333435363738394041// 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 'base/context.dart';import 'base/file_system.dart';import 'build_info.dart';
abstract class ApplicationPackageFactory { static ApplicationPackageFactory? get instance => context.get<ApplicationPackageFactory>();
/// Create an [ApplicationPackage] for the given platform. Future<ApplicationPackage?> getPackageForPlatform( TargetPlatform platform, { BuildInfo? buildInfo, File? applicationBinary, });}
abstract class ApplicationPackage { ApplicationPackage({ required this.id });
/// Package ID from the Android Manifest or equivalent. final String id;
String? get name;
String? get displayName => name;
@override String toString() => displayName ?? id;}
/// An interface for application package that is created from prebuilt binary.abstract class PrebuiltApplicationPackage implements ApplicationPackage { /// The application bundle of the prebuilt application. /// /// The same ApplicationPackage should be able to be recreated by passing /// the file to [FlutterApplicationPackageFactory.getPackageForPlatform]. FileSystemEntity get applicationPackage;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468// 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:meta/meta.dart';import 'package:process/process.dart';
import 'base/common.dart';import 'base/file_system.dart';import 'base/os.dart';import 'base/platform.dart';import 'base/user_messages.dart';import 'base/utils.dart';import 'build_info.dart';import 'cache.dart';import 'globals.dart' as globals;
enum Artifact { /// The tool which compiles a dart kernel file into native code. genSnapshot, /// The flutter tester binary. flutterTester, flutterFramework, flutterXcframework, /// The framework directory of the macOS desktop. flutterMacOSFramework, vmSnapshotData, isolateSnapshotData, icuData, platformKernelDill, platformLibrariesJson, flutterPatchedSdkPath,
/// The root directory of the dart SDK. engineDartSdkPath, /// The dart binary used to execute any of the required snapshots. engineDartBinary, /// The dart binary for running aot snapshots engineDartAotRuntime, /// The snapshot of frontend_server compiler. frontendServerSnapshotForEngineDartSdk, /// The dart snapshot of the dart2js compiler. dart2jsSnapshot, /// The dart snapshot of the dart2wasm compiler. dart2wasmSnapshot, /// The wasm-opt binary that ships with the dart-sdk wasmOptBinary,
/// The root of the Linux desktop sources. linuxDesktopPath, // The root of the cpp headers for Linux desktop. linuxHeaders, /// The root of the Windows desktop sources. windowsDesktopPath, /// The root of the cpp client code for Windows desktop. windowsCppClientWrapper,
/// The root of the sky_engine package. skyEnginePath,
// Fuchsia artifacts from the engine prebuilts. fuchsiaKernelCompiler, fuchsiaFlutterRunner,
/// Tools related to subsetting or icon font files. fontSubset, constFinder,
/// The location of file generators. flutterToolsFileGenerators,
/// Pre-built desktop debug app. flutterPreviewDevice,}
/// A subset of [Artifact]s that are platform and build mode independentenum HostArtifact { /// The root of the web implementation of the dart SDK. flutterWebSdk, /// The libraries JSON file for web release builds. flutterWebLibrariesJson,
// The flutter.js bootstrapping file provided by the engine. flutterJsDirectory,
/// Folder that contains platform dill files for the web sdk. webPlatformKernelFolder,
/// The summary dill for the dartdevc target. webPlatformDDCKernelDill, /// The summary dill with null safety enabled for the dartdevc target.g webPlatformDDCSoundKernelDill, /// The summary dill for the dartdevc target. webPlatformDart2JSKernelDill, /// The summary dill with null safety enabled for the dartdevc target. webPlatformDart2JSSoundKernelDill,
/// The precompiled SDKs and sourcemaps for web debug builds. webPrecompiledSdk, webPrecompiledSdkSourcemaps, webPrecompiledCanvaskitSdk, webPrecompiledCanvaskitSdkSourcemaps, webPrecompiledCanvaskitAndHtmlSdk, webPrecompiledCanvaskitAndHtmlSdkSourcemaps, webPrecompiledSoundSdk, webPrecompiledSoundSdkSourcemaps, webPrecompiledCanvaskitSoundSdk, webPrecompiledCanvaskitSoundSdkSourcemaps, webPrecompiledCanvaskitAndHtmlSoundSdk, webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps,
iosDeploy, idevicesyslog, idevicescreenshot, iproxy,
/// The root of the sky_engine package. skyEnginePath,
// The Impeller shader compiler. impellerc, // The Impeller Scene 3D model importer. scenec, // Impeller's tessellation library. libtessellator,}
// TODO(knopp): Remove once darwin artifacts are universal and moved out of darwin-x64String _enginePlatformDirectoryName(TargetPlatform platform) { if (platform == TargetPlatform.darwin) { return 'darwin-x64'; } return getNameForTargetPlatform(platform);}
// Remove android target platform type.TargetPlatform? _mapTargetPlatform(TargetPlatform? targetPlatform) { switch (targetPlatform) { case TargetPlatform.android: return TargetPlatform.android_arm64; case TargetPlatform.ios: case TargetPlatform.darwin: case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case null: return targetPlatform; }}
String? _artifactToFileName(Artifact artifact, Platform hostPlatform, [ BuildMode? mode ]) { final String exe = hostPlatform.isWindows ? '.exe' : ''; switch (artifact) { case Artifact.genSnapshot: return 'gen_snapshot'; case Artifact.flutterTester: return 'flutter_tester$exe'; case Artifact.flutterFramework: return 'Flutter.framework'; case Artifact.flutterXcframework: return 'Flutter.xcframework'; case Artifact.flutterMacOSFramework: return 'FlutterMacOS.framework'; case Artifact.vmSnapshotData: return 'vm_isolate_snapshot.bin'; case Artifact.isolateSnapshotData: return 'isolate_snapshot.bin'; case Artifact.icuData: return 'icudtl.dat'; case Artifact.platformKernelDill: return 'platform_strong.dill'; case Artifact.platformLibrariesJson: return 'libraries.json'; case Artifact.flutterPatchedSdkPath: assert(false, 'No filename for sdk path, should not be invoked'); return null; case Artifact.engineDartSdkPath: return 'dart-sdk'; case Artifact.engineDartBinary: return 'dart$exe'; case Artifact.engineDartAotRuntime: return 'dartaotruntime$exe'; case Artifact.dart2jsSnapshot: return 'dart2js.dart.snapshot'; case Artifact.dart2wasmSnapshot: return 'dart2wasm_product.snapshot'; case Artifact.wasmOptBinary: return 'wasm-opt$exe'; case Artifact.frontendServerSnapshotForEngineDartSdk: return 'frontend_server_aot.dart.snapshot'; case Artifact.linuxDesktopPath: return ''; case Artifact.linuxHeaders: return 'flutter_linux'; case Artifact.windowsCppClientWrapper: return 'cpp_client_wrapper'; case Artifact.windowsDesktopPath: return ''; case Artifact.skyEnginePath: return 'sky_engine'; case Artifact.fuchsiaKernelCompiler: return 'kernel_compiler.snapshot'; case Artifact.fuchsiaFlutterRunner: final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; final String productOrNo = mode.isRelease ? '_product' : ''; return 'flutter$jitOrAot${productOrNo}_runner-0.far'; case Artifact.fontSubset: return 'font-subset$exe'; case Artifact.constFinder: return 'const_finder.dart.snapshot'; case Artifact.flutterToolsFileGenerators: return ''; case Artifact.flutterPreviewDevice: return 'flutter_preview$exe'; }}
String _hostArtifactToFileName(HostArtifact artifact, Platform platform) { final String exe = platform.isWindows ? '.exe' : ''; String dll = '.so'; if (platform.isWindows) { dll = '.dll'; } else if (platform.isMacOS) { dll = '.dylib'; } switch (artifact) { case HostArtifact.flutterWebSdk: return ''; case HostArtifact.flutterJsDirectory: return 'flutter_js'; case HostArtifact.iosDeploy: return 'ios-deploy'; case HostArtifact.idevicesyslog: return 'idevicesyslog'; case HostArtifact.idevicescreenshot: return 'idevicescreenshot'; case HostArtifact.iproxy: return 'iproxy'; case HostArtifact.skyEnginePath: return 'sky_engine'; case HostArtifact.webPlatformKernelFolder: return 'kernel'; case HostArtifact.webPlatformDDCKernelDill: return 'ddc_outline.dill'; case HostArtifact.webPlatformDDCSoundKernelDill: return 'ddc_outline_sound.dill'; case HostArtifact.webPlatformDart2JSKernelDill: return 'dart2js_platform_unsound.dill'; case HostArtifact.webPlatformDart2JSSoundKernelDill: return 'dart2js_platform.dill'; case HostArtifact.flutterWebLibrariesJson: return 'libraries.json'; case HostArtifact.webPrecompiledSdk: case HostArtifact.webPrecompiledCanvaskitSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledSoundSdk: case HostArtifact.webPrecompiledCanvaskitSoundSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: return 'dart_sdk.js'; case HostArtifact.webPrecompiledSdkSourcemaps: case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: case HostArtifact.webPrecompiledSoundSdkSourcemaps: case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: return 'dart_sdk.js.map'; case HostArtifact.impellerc: return 'impellerc$exe'; case HostArtifact.scenec: return 'scenec$exe'; case HostArtifact.libtessellator: return 'libtessellator$dll'; }}
class EngineBuildPaths { const EngineBuildPaths({ required this.targetEngine, required this.hostEngine, required this.webSdk, });
final String? targetEngine; final String? hostEngine; final String? webSdk;}
/// Information about a local engine build (i.e. `--local-engine[-host]=...`).////// See https://github.com/flutter/flutter/wiki/The-flutter-tool#using-a-locally-built-engine-with-the-flutter-tool/// for more information about local engine builds.class LocalEngineInfo { /// Creates a reference to a local engine build. /// /// The [targetOutPath] and [hostOutPath] are assumed to be resolvable /// paths to the built engine artifacts for the target (device) and host /// (build) platforms, respectively. const LocalEngineInfo({ required this.targetOutPath, required this.hostOutPath, });
/// The path to the engine artifacts for the target (device) platform. /// /// For example, if the target platform is Android debug, this would be a path /// like `/path/to/engine/src/out/android_debug_unopt`. To retrieve just the /// name (platform), see [localTargetName]. final String targetOutPath;
/// The path to the engine artifacts for the host (build) platform. /// /// For example, if the host platform is debug, this would be a path like /// `/path/to/engine/src/out/host_debug_unopt`. To retrieve just the name /// (platform), see [localHostName]. final String hostOutPath;
/// The name of the target (device) platform, i.e. `android_debug_unopt`. String get localTargetName => globals.fs.path.basename(targetOutPath);
/// The name of the host (build) platform, e.g. `host_debug_unopt`. String get localHostName => globals.fs.path.basename(hostOutPath);}
// Manages the engine artifacts of Flutter.abstract class Artifacts { /// A test-specific implementation of artifacts that returns stable paths for /// all artifacts. /// /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. /// /// Creates a [LocalEngineArtifacts] if `localEngine` is non-null @visibleForTesting factory Artifacts.test({FileSystem? fileSystem}) { return _TestArtifacts(fileSystem ?? MemoryFileSystem.test()); }
/// A test-specific implementation of artifacts that returns stable paths for /// all artifacts, and uses a local engine. /// /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. @visibleForTesting factory Artifacts.testLocalEngine({ required String localEngine, required String localEngineHost, FileSystem? fileSystem, }) { return _TestLocalEngine( localEngine, localEngineHost, fileSystem ?? MemoryFileSystem.test()); }
static Artifacts getLocalEngine(EngineBuildPaths engineBuildPaths) { Artifacts artifacts = CachedArtifacts( fileSystem: globals.fs, platform: globals.platform, cache: globals.cache, operatingSystemUtils: globals.os ); if (engineBuildPaths.hostEngine != null && engineBuildPaths.targetEngine != null) { artifacts = CachedLocalEngineArtifacts( engineBuildPaths.hostEngine!, engineOutPath: engineBuildPaths.targetEngine!, cache: globals.cache, fileSystem: globals.fs, processManager: globals.processManager, platform: globals.platform, operatingSystemUtils: globals.os, parent: artifacts, ); } if (engineBuildPaths.webSdk != null) { artifacts = CachedLocalWebSdkArtifacts( parent: artifacts, webSdkPath: engineBuildPaths.webSdk!, fileSystem: globals.fs, platform: globals.platform, operatingSystemUtils: globals.os ); } return artifacts; }
/// Returns the requested [artifact] for the [platform], [mode], and [environmentType] combination. String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, });
/// Retrieve a host specific artifact that does not depend on the /// current build mode or environment. FileSystemEntity getHostArtifact( HostArtifact artifact, );
// Returns which set of engine artifacts is currently used for the [platform] // and [mode] combination. String getEngineType(TargetPlatform platform, [ BuildMode? mode ]);
/// Whether these artifacts correspond to a non-versioned local engine. bool get isLocalEngine;
/// If these artifacts are bound to a local engine build, returns info about /// the location and name of the local engine, otherwise returns null. LocalEngineInfo? get localEngineInfo;}
/// Manages the engine artifacts downloaded to the local cache.class CachedArtifacts implements Artifacts { CachedArtifacts({ required FileSystem fileSystem, required Platform platform, required Cache cache, required OperatingSystemUtils operatingSystemUtils, }) : _fileSystem = fileSystem, _platform = platform, _cache = cache, _operatingSystemUtils = operatingSystemUtils;
final FileSystem _fileSystem; final Platform _platform; final Cache _cache; final OperatingSystemUtils _operatingSystemUtils;
@override LocalEngineInfo? get localEngineInfo => null;
@override FileSystemEntity getHostArtifact( HostArtifact artifact, ) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSdk: case HostArtifact.webPrecompiledSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSdk: case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSoundSdk: case HostArtifact.webPrecompiledSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSoundSdk: case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); case HostArtifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); return _fileSystem.directory(path); case HostArtifact.iosDeploy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); case HostArtifact.iproxy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); final String engineDir = _getEngineArtifactsPath(_currentHostPlatform(_platform, _operatingSystemUtils))!; return _fileSystem.file(_fileSystem.path.join(engineDir, artifactFileName)); } }
@override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { platform = _mapTargetPlatform(platform); switch (platform) { case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: assert(platform != TargetPlatform.android); return _getAndroidArtifactPath(artifact, platform!, mode!); case TargetPlatform.ios: return _getIosArtifactPath(artifact, platform!, mode, environmentType); case TargetPlatform.darwin: case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: return _getDesktopArtifactPath(artifact, platform, mode); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: return _getFuchsiaArtifactPath(artifact, platform!, mode!); case TargetPlatform.tester: case TargetPlatform.web_javascript: case null: return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); } }
@override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return _fileSystem.path.basename(_getEngineArtifactsPath(platform, mode)!); }
String _getDesktopArtifactPath(Artifact artifact, TargetPlatform? platform, BuildMode? mode) { // When platform is null, a generic host platform artifact is being requested // and not the gen_snapshot for darwin as a target platform. if (platform != null && artifact == Artifact.genSnapshot) { final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _fileSystem.path.join(engineDir, _artifactToFileName(artifact, _platform)); } return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); }
String _getAndroidArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { final String engineDir = _getEngineArtifactsPath(platform, mode)!; switch (artifact) { case Artifact.genSnapshot: assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.'); final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); return _fileSystem.path.join(engineDir, hostPlatform, _artifactToFileName(artifact, _platform)); case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.wasmOptBinary: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.constFinder: case Artifact.flutterFramework: case Artifact.flutterMacOSFramework: case Artifact.flutterPatchedSdkPath: case Artifact.flutterTester: case Artifact.flutterXcframework: case Artifact.fontSubset: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } }
String _getIosArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode, EnvironmentType? environmentType) { switch (artifact) { case Artifact.genSnapshot: case Artifact.flutterXcframework: final String artifactFileName = _artifactToFileName(artifact, _platform)!; final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _fileSystem.path.join(engineDir, artifactFileName); case Artifact.flutterFramework: final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _getIosEngineArtifactPath(engineDir, environmentType, _fileSystem, _platform); case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.wasmOptBinary: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.constFinder: case Artifact.flutterMacOSFramework: case Artifact.flutterPatchedSdkPath: case Artifact.flutterTester: case Artifact.fontSubset: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } }
String _getFuchsiaArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { final String root = _fileSystem.path.join( _cache.getArtifactDirectory('flutter_runner').path, 'flutter', platform.fuchsiaArchForTargetPlatform, mode.isRelease ? 'release' : mode.toString(), ); final String runtime = mode.isJit ? 'jit' : 'aot'; switch (artifact) { case Artifact.genSnapshot: final String genSnapshot = mode.isRelease ? 'gen_snapshot_product' : 'gen_snapshot'; return _fileSystem.path.join(root, runtime, 'dart_binaries', genSnapshot); case Artifact.flutterPatchedSdkPath: const String artifactFileName = 'flutter_runner_patched_sdk'; return _fileSystem.path.join(root, runtime, artifactFileName); case Artifact.platformKernelDill: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, 'flutter_runner_patched_sdk', artifactFileName); case Artifact.fuchsiaKernelCompiler: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, 'dart_binaries', artifactFileName); case Artifact.fuchsiaFlutterRunner: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, artifactFileName); case Artifact.constFinder: case Artifact.flutterFramework: case Artifact.flutterMacOSFramework: case Artifact.flutterTester: case Artifact.flutterXcframework: case Artifact.fontSubset: case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.wasmOptBinary: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } }
String _getFlutterPatchedSdkPath(BuildMode? mode) { final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, 'common', mode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); }
String _getFlutterWebSdkPath() { return _cache.getWebSdkDirectory().path; }
String _getHostArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode) { switch (artifact) { case Artifact.genSnapshot: // For script snapshots any gen_snapshot binary will do. Returning gen_snapshot for // android_arm in profile mode because it is available on all supported host platforms. return _getAndroidArtifactPath(artifact, TargetPlatform.android_arm, BuildMode.profile); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join( _dartSdkPath(_cache), 'bin', 'snapshots', _artifactToFileName(artifact, _platform), ); case Artifact.wasmOptBinary: return _fileSystem.path.join( _dartSdkPath(_cache), 'bin', 'utils', _artifactToFileName(artifact, _platform), ); case Artifact.flutterTester: case Artifact.vmSnapshotData: case Artifact.isolateSnapshotData: case Artifact.icuData: final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; final String platformDirName = _enginePlatformDirectoryName(platform); return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); case Artifact.platformKernelDill: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), _artifactToFileName(artifact, _platform)); case Artifact.platformLibrariesJson: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', _artifactToFileName(artifact, _platform)); case Artifact.flutterPatchedSdkPath: return _getFlutterPatchedSdkPath(mode); case Artifact.engineDartSdkPath: return _dartSdkPath(_cache); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join(_dartSdkPath(_cache), 'bin', _artifactToFileName(artifact, _platform)); case Artifact.flutterMacOSFramework: case Artifact.linuxDesktopPath: case Artifact.windowsDesktopPath: case Artifact.linuxHeaders: // TODO(zanderso): remove once debug desktop artifacts are uploaded // under a separate directory from the host artifacts. // https://github.com/flutter/flutter/issues/38935 String platformDirName = _enginePlatformDirectoryName(platform); if (mode == BuildMode.profile || mode == BuildMode.release) { platformDirName = '$platformDirName-${mode!.cliName}'; } final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); case Artifact.windowsCppClientWrapper: final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, 'windows-x64', _artifactToFileName(artifact, _platform, mode)); case Artifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); return _fileSystem.path.join(dartPackageDirectory.path, _artifactToFileName(artifact, _platform)); case Artifact.fontSubset: case Artifact.constFinder: return _cache.getArtifactDirectory('engine') .childDirectory(_enginePlatformDirectoryName(platform)) .childFile(_artifactToFileName(artifact, _platform, mode)!) .path; case Artifact.flutterFramework: case Artifact.flutterXcframework: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: throw StateError('Artifact $artifact not available for platform $platform.'); case Artifact.flutterToolsFileGenerators: return _getFileGeneratorsPath(); case Artifact.flutterPreviewDevice: assert(platform == TargetPlatform.windows_x64); return _cache.getArtifactDirectory('flutter_preview').childFile('flutter_preview.exe').path; } }
String? _getEngineArtifactsPath(TargetPlatform platform, [ BuildMode? mode ]) { final String engineDir = _cache.getArtifactDirectory('engine').path; final String platformName = _enginePlatformDirectoryName(platform); switch (platform) { case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.darwin: case TargetPlatform.windows_x64: // TODO(zanderso): remove once debug desktop artifacts are uploaded // under a separate directory from the host artifacts. // https://github.com/flutter/flutter/issues/38935 if (mode == BuildMode.debug || mode == null) { return _fileSystem.path.join(engineDir, platformName); } final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode.cliName, '-')}' : ''; return _fileSystem.path.join(engineDir, platformName + suffix); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: assert(mode == null, 'Platform $platform does not support different build modes.'); return _fileSystem.path.join(engineDir, platformName); case TargetPlatform.ios: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: assert(mode != null, 'Need to specify a build mode for platform $platform.'); final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode!.cliName, '-')}' : ''; return _fileSystem.path.join(engineDir, platformName + suffix); case TargetPlatform.android: assert(false, 'cannot use TargetPlatform.android to look up artifacts'); return null; } }
@override bool get isLocalEngine => false;}
TargetPlatform _currentHostPlatform(Platform platform, OperatingSystemUtils operatingSystemUtils) { if (platform.isMacOS) { return TargetPlatform.darwin; } if (platform.isLinux) { return operatingSystemUtils.hostPlatform == HostPlatform.linux_x64 ? TargetPlatform.linux_x64 : TargetPlatform.linux_arm64; } if (platform.isWindows) { return TargetPlatform.windows_x64; } throw UnimplementedError('Host OS not supported.');}
String _getIosEngineArtifactPath(String engineDirectory, EnvironmentType? environmentType, FileSystem fileSystem, Platform hostPlatform) { final Directory xcframeworkDirectory = fileSystem .directory(engineDirectory) .childDirectory(_artifactToFileName(Artifact.flutterXcframework, hostPlatform)!);
if (!xcframeworkDirectory.existsSync()) { throwToolExit('No xcframework found at ${xcframeworkDirectory.path}. Try running "flutter precache --ios".'); } Directory? flutterFrameworkSource; for (final Directory platformDirectory in xcframeworkDirectory.listSync().whereType<Directory>()) { if (!platformDirectory.basename.startsWith('ios-')) { continue; } // ios-x86_64-simulator, ios-arm64_x86_64-simulator, or ios-arm64. final bool simulatorDirectory = platformDirectory.basename.endsWith('-simulator'); if ((environmentType == EnvironmentType.simulator && simulatorDirectory) || (environmentType == EnvironmentType.physical && !simulatorDirectory)) { flutterFrameworkSource = platformDirectory; } } if (flutterFrameworkSource == null) { throwToolExit('No iOS frameworks found in ${xcframeworkDirectory.path}'); }
return flutterFrameworkSource .childDirectory(_artifactToFileName(Artifact.flutterFramework, hostPlatform)!) .path;}
/// Manages the artifacts of a locally built engine.class CachedLocalEngineArtifacts implements Artifacts { CachedLocalEngineArtifacts( this._hostEngineOutPath, { required String engineOutPath, required FileSystem fileSystem, required Cache cache, required ProcessManager processManager, required Platform platform, required OperatingSystemUtils operatingSystemUtils, Artifacts? parent, }) : _fileSystem = fileSystem, localEngineInfo = LocalEngineInfo( targetOutPath: engineOutPath, hostOutPath: _hostEngineOutPath, ), _cache = cache, _processManager = processManager, _platform = platform, _operatingSystemUtils = operatingSystemUtils, _backupCache = parent ?? CachedArtifacts( fileSystem: fileSystem, platform: platform, cache: cache, operatingSystemUtils: operatingSystemUtils );
@override final LocalEngineInfo localEngineInfo;
final String _hostEngineOutPath; final FileSystem _fileSystem; final Cache _cache; final ProcessManager _processManager; final Platform _platform; final OperatingSystemUtils _operatingSystemUtils; final Artifacts _backupCache;
@override FileSystemEntity getHostArtifact(HostArtifact artifact) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSdk: case HostArtifact.webPrecompiledSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSdk: case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSoundSdk: case HostArtifact.webPrecompiledSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSoundSdk: case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); case HostArtifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); return _fileSystem.directory(path); case HostArtifact.iosDeploy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); case HostArtifact.iproxy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); final File file = _fileSystem.file(_fileSystem.path.join(_hostEngineOutPath, artifactFileName)); if (!file.existsSync()) { return _backupCache.getHostArtifact(artifact); } return file; } }
@override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { platform ??= _currentHostPlatform(_platform, _operatingSystemUtils); platform = _mapTargetPlatform(platform); final bool isDirectoryArtifact = artifact == Artifact.flutterPatchedSdkPath; final String? artifactFileName = isDirectoryArtifact ? null : _artifactToFileName(artifact, _platform, mode); switch (artifact) { case Artifact.genSnapshot: return _genSnapshotPath(); case Artifact.flutterTester: return _flutterTesterPath(platform!); case Artifact.isolateSnapshotData: case Artifact.vmSnapshotData: return _fileSystem.path.join(localEngineInfo.targetOutPath, 'gen', 'flutter', 'lib', 'snapshot', artifactFileName); case Artifact.icuData: case Artifact.flutterXcframework: case Artifact.flutterMacOSFramework: return _fileSystem.path.join(localEngineInfo.targetOutPath, artifactFileName); case Artifact.platformKernelDill: if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk', artifactFileName); } return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), artifactFileName); case Artifact.platformLibrariesJson: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', artifactFileName); case Artifact.flutterFramework: return _getIosEngineArtifactPath( localEngineInfo.targetOutPath, environmentType, _fileSystem, _platform); case Artifact.flutterPatchedSdkPath: // When using local engine always use [BuildMode.debug] regardless of // what was specified in [mode] argument because local engine will // have only one flutter_patched_sdk in standard location, that // is happen to be what debug(non-release) mode is using. if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk'); } return _getFlutterPatchedSdkPath(BuildMode.debug); case Artifact.skyEnginePath: return _fileSystem.path.join(_hostEngineOutPath, 'gen', 'dart-pkg', artifactFileName); case Artifact.fuchsiaKernelCompiler: final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); final String modeName = mode!.isRelease ? 'release' : mode.toString(); final String dartBinaries = 'dart_binaries-$modeName-$hostPlatform'; return _fileSystem.path.join(localEngineInfo.targetOutPath, 'host_bundle', dartBinaries, 'kernel_compiler.dart.snapshot'); case Artifact.fuchsiaFlutterRunner: final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; final String productOrNo = mode.isRelease ? '_product' : ''; return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter$jitOrAot${productOrNo}_runner-0.far'); case Artifact.fontSubset: return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); case Artifact.constFinder: return _fileSystem.path.join(_hostEngineOutPath, 'gen', artifactFileName); case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.windowsDesktopPath: case Artifact.windowsCppClientWrapper: return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); case Artifact.engineDartSdkPath: return _getDartSdkPath(); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join(_getDartSdkPath(), 'bin', artifactFileName); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join(_getDartSdkPath(), 'bin', 'snapshots', artifactFileName); case Artifact.wasmOptBinary: return _fileSystem.path.join(_getDartSdkPath(), 'bin', 'utils', artifactFileName); case Artifact.flutterToolsFileGenerators: return _getFileGeneratorsPath(); case Artifact.flutterPreviewDevice: return _backupCache.getArtifactPath( artifact, platform: platform, mode: mode, environmentType: environmentType, ); } }
@override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return _fileSystem.path.basename(localEngineInfo.targetOutPath); }
String _getFlutterPatchedSdkPath(BuildMode? buildMode) { return _fileSystem.path.join(localEngineInfo.targetOutPath, buildMode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); }
String _getDartSdkPath() { final String builtPath = _fileSystem.path.join(_hostEngineOutPath, 'dart-sdk'); if (_fileSystem.isDirectorySync(_fileSystem.path.join(builtPath, 'bin'))) { return builtPath; }
// If we couldn't find a built dart sdk, let's look for a prebuilt one. final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); if (_fileSystem.isDirectorySync(prebuiltPath)) { return prebuiltPath; }
throw ToolExit('Unable to find a built dart sdk at: "$builtPath" or a prebuilt dart sdk at: "$prebuiltPath"'); }
String _getFlutterPrebuiltsPath() { final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_hostEngineOutPath)); return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); }
String _getPrebuiltTarget() { final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); switch (hostPlatform) { case TargetPlatform.darwin: return 'macos-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.ios: case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.web_javascript: case TargetPlatform.tester: throwToolExit('Unsupported host platform: $hostPlatform'); } }
String _getFlutterWebSdkPath() { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_web_sdk'); }
String _genSnapshotPath() { const List<String> clangDirs = <String>['.', 'clang_x64', 'clang_x86', 'clang_i386', 'clang_arm64']; final String genSnapshotName = _artifactToFileName(Artifact.genSnapshot, _platform)!; for (final String clangDir in clangDirs) { final String genSnapshotPath = _fileSystem.path.join(localEngineInfo.targetOutPath, clangDir, genSnapshotName); if (_processManager.canRun(genSnapshotPath)) { return genSnapshotPath; } } throw Exception('Unable to find $genSnapshotName'); }
String _flutterTesterPath(TargetPlatform platform) { if (_platform.isLinux) { return _fileSystem.path.join(localEngineInfo.targetOutPath, _artifactToFileName(Artifact.flutterTester, _platform)); } else if (_platform.isMacOS) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester'); } else if (_platform.isWindows) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester.exe'); } throw Exception('Unsupported platform $platform.'); }
@override bool get isLocalEngine => true;}
class CachedLocalWebSdkArtifacts implements Artifacts { CachedLocalWebSdkArtifacts({ required Artifacts parent, required String webSdkPath, required FileSystem fileSystem, required Platform platform, required OperatingSystemUtils operatingSystemUtils }) : _parent = parent, _webSdkPath = webSdkPath, _fileSystem = fileSystem, _platform = platform, _operatingSystemUtils = operatingSystemUtils;
final Artifacts _parent; final String _webSdkPath; final FileSystem _fileSystem; final Platform _platform; final OperatingSystemUtils _operatingSystemUtils;
@override String getArtifactPath(Artifact artifact, {TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType}) { if (platform == TargetPlatform.web_javascript) { switch (artifact) { case Artifact.engineDartSdkPath: return _getDartSdkPath(); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join( _getDartSdkPath(), 'bin', _artifactToFileName(artifact, _platform, mode)); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join( _getDartSdkPath(), 'bin', 'snapshots', _artifactToFileName(artifact, _platform, mode), ); case Artifact.wasmOptBinary: return _fileSystem.path.join( _getDartSdkPath(), 'bin', 'utils', _artifactToFileName(artifact, _platform, mode), ); case Artifact.genSnapshot: case Artifact.flutterTester: case Artifact.flutterFramework: case Artifact.flutterXcframework: case Artifact.flutterMacOSFramework: case Artifact.vmSnapshotData: case Artifact.isolateSnapshotData: case Artifact.icuData: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.flutterPatchedSdkPath: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.windowsDesktopPath: case Artifact.windowsCppClientWrapper: case Artifact.skyEnginePath: case Artifact.fuchsiaKernelCompiler: case Artifact.fuchsiaFlutterRunner: case Artifact.fontSubset: case Artifact.constFinder: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: break; } } return _parent.getArtifactPath(artifact, platform: platform, mode: mode, environmentType: environmentType); }
@override String getEngineType(TargetPlatform platform, [BuildMode? mode]) => _parent.getEngineType(platform, mode);
@override FileSystemEntity getHostArtifact(HostArtifact artifact) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSdk: case HostArtifact.webPrecompiledSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSdk: case HostArtifact.webPrecompiledCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledSoundSdk: case HostArtifact.webPrecompiledSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitSoundSdk: case HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.iosDeploy: case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: case HostArtifact.iproxy: case HostArtifact.skyEnginePath: case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: return _parent.getHostArtifact(artifact); } }
String _getDartSdkPath() { // If we couldn't find a built dart sdk, let's look for a prebuilt one. final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); if (_fileSystem.isDirectorySync(prebuiltPath)) { return prebuiltPath; }
throw ToolExit('Unable to find a prebuilt dart sdk at: "$prebuiltPath"'); }
String _getFlutterPrebuiltsPath() { final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_webSdkPath)); return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); }
String _getPrebuiltTarget() { final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); switch (hostPlatform) { case TargetPlatform.darwin: return 'macos-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.ios: case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.web_javascript: case TargetPlatform.tester: throwToolExit('Unsupported host platform: $hostPlatform'); } }
String _getFlutterWebSdkPath() { return _fileSystem.path.join(_webSdkPath, 'flutter_web_sdk'); }
@override bool get isLocalEngine => _parent.isLocalEngine;
@override LocalEngineInfo? get localEngineInfo => _parent.localEngineInfo;}
/// An implementation of [Artifacts] that provides individual overrides.////// If an artifact is not provided, the lookup delegates to the parent.class OverrideArtifacts implements Artifacts { /// Creates a new [OverrideArtifacts]. /// /// [parent] must be provided. OverrideArtifacts({ required this.parent, this.frontendServer, this.engineDartBinary, this.platformKernelDill, this.flutterPatchedSdk, });
final Artifacts parent; final File? frontendServer; final File? engineDartBinary; final File? platformKernelDill; final File? flutterPatchedSdk;
@override LocalEngineInfo? get localEngineInfo => parent.localEngineInfo;
@override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { if (artifact == Artifact.engineDartBinary && engineDartBinary != null) { return engineDartBinary!.path; } if (artifact == Artifact.frontendServerSnapshotForEngineDartSdk && frontendServer != null) { return frontendServer!.path; } if (artifact == Artifact.platformKernelDill && platformKernelDill != null) { return platformKernelDill!.path; } if (artifact == Artifact.flutterPatchedSdkPath && flutterPatchedSdk != null) { return flutterPatchedSdk!.path; } return parent.getArtifactPath( artifact, platform: platform, mode: mode, environmentType: environmentType, ); }
@override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) => parent.getEngineType(platform, mode);
@override bool get isLocalEngine => parent.isLocalEngine;
@override FileSystemEntity getHostArtifact(HostArtifact artifact) { return parent.getHostArtifact( artifact, ); }}
/// Locate the Dart SDK.String _dartSdkPath(Cache cache) { return cache.getRoot().childDirectory('dart-sdk').path;}
class _TestArtifacts implements Artifacts { _TestArtifacts(this.fileSystem);
final FileSystem fileSystem;
@override LocalEngineInfo? get localEngineInfo => null;
@override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { // The path to file generators is the same even in the test environment. if (artifact == Artifact.flutterToolsFileGenerators) { return _getFileGeneratorsPath(); }
final StringBuffer buffer = StringBuffer(); buffer.write(artifact); if (platform != null) { buffer.write('.$platform'); } if (mode != null) { buffer.write('.$mode'); } if (environmentType != null) { buffer.write('.$environmentType'); } return buffer.toString(); }
@override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return 'test-engine'; }
@override bool get isLocalEngine => false;
@override FileSystemEntity getHostArtifact(HostArtifact artifact) { return fileSystem.file(artifact.toString()); }}
class _TestLocalEngine extends _TestArtifacts { _TestLocalEngine( String engineOutPath, String engineHostOutPath, super.fileSystem, ) : localEngineInfo = LocalEngineInfo( targetOutPath: engineOutPath, hostOutPath: engineHostOutPath, );
@override bool get isLocalEngine => true;
@override final LocalEngineInfo localEngineInfo;}
String _getFileGeneratorsPath() { final String flutterRoot = Cache.defaultFlutterRoot( fileSystem: globals.localFileSystem, platform: const LocalPlatform(), userMessages: UserMessages(), ); return globals.localFileSystem.path.join( flutterRoot, 'packages', 'flutter_tools', 'lib', 'src', 'web', 'file_generators', );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283// 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:typed_data';
import 'package:meta/meta.dart';import 'package:package_config/package_config.dart';import 'package:standard_message_codec/standard_message_codec.dart';
import 'base/common.dart';import 'base/context.dart';import 'base/deferred_component.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/platform.dart';import 'build_info.dart';import 'cache.dart';import 'convert.dart';import 'dart/package_map.dart';import 'devfs.dart';import 'flutter_manifest.dart';import 'license_collector.dart';import 'project.dart';
const String defaultManifestPath = 'pubspec.yaml';
const String kFontManifestJson = 'FontManifest.json';
// Should match '2x', '/1x', '1.5x', etc.final RegExp _assetVariantDirectoryRegExp = RegExp(r'/?(\d+(\.\d*)?)x$');
/// The effect of adding `uses-material-design: true` to the pubspec is to insert/// the following snippet into the asset manifest:////// ```yaml/// material:/// - family: MaterialIcons/// fonts:/// - asset: fonts/MaterialIcons-Regular.otf/// ```const List<Map<String, Object>> kMaterialFonts = <Map<String, Object>>[ <String, Object>{ 'family': 'MaterialIcons', 'fonts': <Map<String, String>>[ <String, String>{ 'asset': 'fonts/MaterialIcons-Regular.otf', }, ], },];
const List<String> kMaterialShaders = <String>[ 'shaders/ink_sparkle.frag',];
/// Injected factory class for spawning [AssetBundle] instances.abstract class AssetBundleFactory { /// The singleton instance, pulled from the [AppContext]. static AssetBundleFactory get instance => context.get<AssetBundleFactory>()!;
static AssetBundleFactory defaultInstance({ required Logger logger, required FileSystem fileSystem, required Platform platform, bool splitDeferredAssets = false, }) => _ManifestAssetBundleFactory(logger: logger, fileSystem: fileSystem, platform: platform, splitDeferredAssets: splitDeferredAssets);
/// Creates a new [AssetBundle]. AssetBundle createBundle();}
enum AssetKind { regular, font, shader, model,}
abstract class AssetBundle { Map<String, DevFSContent> get entries;
Map<String, AssetKind> get entryKinds;
/// The files that were specified under the deferred components assets sections /// in pubspec. Map<String, Map<String, DevFSContent>> get deferredComponentsEntries;
/// Additional files that this bundle depends on that are not included in the /// output result. List<File> get additionalDependencies;
/// Input files used to build this asset bundle. List<File> get inputFiles;
bool wasBuiltOnce();
bool needsBuild({ String manifestPath = defaultManifestPath });
/// Returns 0 for success; non-zero for failure. Future<int> build({ String manifestPath = defaultManifestPath, required String packagesPath, bool deferredComponentsEnabled = false, TargetPlatform? targetPlatform, String? flavor, });}
class _ManifestAssetBundleFactory implements AssetBundleFactory { _ManifestAssetBundleFactory({ required Logger logger, required FileSystem fileSystem, required Platform platform, bool splitDeferredAssets = false, }) : _logger = logger, _fileSystem = fileSystem, _platform = platform, _splitDeferredAssets = splitDeferredAssets;
final Logger _logger; final FileSystem _fileSystem; final Platform _platform; final bool _splitDeferredAssets;
@override AssetBundle createBundle() => ManifestAssetBundle(logger: _logger, fileSystem: _fileSystem, platform: _platform, splitDeferredAssets: _splitDeferredAssets);}
/// An asset bundle based on a pubspec.yaml file.class ManifestAssetBundle implements AssetBundle { /// Constructs an [ManifestAssetBundle] that gathers the set of assets from the /// pubspec.yaml manifest. ManifestAssetBundle({ required Logger logger, required FileSystem fileSystem, required Platform platform, bool splitDeferredAssets = false, }) : _logger = logger, _fileSystem = fileSystem, _platform = platform, _splitDeferredAssets = splitDeferredAssets, _licenseCollector = LicenseCollector(fileSystem: fileSystem);
final Logger _logger; final FileSystem _fileSystem; final LicenseCollector _licenseCollector; final Platform _platform; final bool _splitDeferredAssets;
@override final Map<String, DevFSContent> entries = <String, DevFSContent>{};
@override final Map<String, AssetKind> entryKinds = <String, AssetKind>{};
@override final Map<String, Map<String, DevFSContent>> deferredComponentsEntries = <String, Map<String, DevFSContent>>{};
@override final List<File> inputFiles = <File>[];
// If an asset corresponds to a wildcard directory, then it may have been // updated without changes to the manifest. These are only tracked for // the current project. final Map<Uri, Directory> _wildcardDirectories = <Uri, Directory>{};
DateTime? _lastBuildTimestamp;
// We assume the main asset is designed for a device pixel ratio of 1.0. static const String _kAssetManifestJsonFilename = 'AssetManifest.json'; static const String _kAssetManifestBinFilename = 'AssetManifest.bin'; static const String _kAssetManifestBinJsonFilename = 'AssetManifest.bin.json';
static const String _kNoticeFile = 'NOTICES'; // Comically, this can't be name with the more common .gz file extension // because when it's part of an AAR and brought into another APK via gradle, // gradle individually traverses all the files of the AAR and unzips .gz // files (b/37117906). A less common .Z extension still describes how the // file is formatted if users want to manually inspect the application // bundle and is recognized by default file handlers on OS such as macOS.˚ static const String _kNoticeZippedFile = 'NOTICES.Z';
@override bool wasBuiltOnce() => _lastBuildTimestamp != null;
@override bool needsBuild({ String manifestPath = defaultManifestPath }) { final DateTime? lastBuildTimestamp = _lastBuildTimestamp; if (lastBuildTimestamp == null) { return true; }
final FileStat stat = _fileSystem.file(manifestPath).statSync(); if (stat.type == FileSystemEntityType.notFound) { return true; }
for (final Directory directory in _wildcardDirectories.values) { if (!directory.existsSync()) { return true; // directory was deleted. } for (final File file in directory.listSync().whereType<File>()) { final DateTime dateTime = file.statSync().modified; if (dateTime.isAfter(lastBuildTimestamp)) { return true; } } }
return stat.modified.isAfter(lastBuildTimestamp); }
@override Future<int> build({ String manifestPath = defaultManifestPath, FlutterProject? flutterProject, required String packagesPath, bool deferredComponentsEnabled = false, TargetPlatform? targetPlatform, String? flavor, }) async { if (flutterProject == null) { try { flutterProject = FlutterProject.fromDirectory(_fileSystem.file(manifestPath).parent); } on Exception catch (e) { _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); _logger.printError('$e'); return 1; } }
final FlutterManifest flutterManifest = flutterProject.manifest; // If the last build time isn't set before this early return, empty pubspecs will // hang on hot reload, as the incremental dill files will never be copied to the // device. _lastBuildTimestamp = DateTime.now(); if (flutterManifest.isEmpty) { entries[_kAssetManifestJsonFilename] = DevFSStringContent('{}'); entryKinds[_kAssetManifestJsonFilename] = AssetKind.regular; final ByteData emptyAssetManifest = const StandardMessageCodec().encodeMessage(<dynamic, dynamic>{})!; entries[_kAssetManifestBinFilename] = DevFSByteContent(emptyAssetManifest.buffer.asUint8List(0, emptyAssetManifest.lengthInBytes)); entryKinds[_kAssetManifestBinFilename] = AssetKind.regular; // Create .bin.json on web builds. if (targetPlatform == TargetPlatform.web_javascript) { entries[_kAssetManifestBinJsonFilename] = DevFSStringContent('""'); entryKinds[_kAssetManifestBinJsonFilename] = AssetKind.regular; } return 0; }
final String assetBasePath = _fileSystem.path.dirname(_fileSystem.path.absolute(manifestPath)); final File packageConfigFile = _fileSystem.file(packagesPath); inputFiles.add(packageConfigFile); final PackageConfig packageConfig = await loadPackageConfigWithLogging( packageConfigFile, logger: _logger, ); final List<Uri> wildcardDirectories = <Uri>[];
// The _assetVariants map contains an entry for each asset listed // in the pubspec.yaml file's assets and font sections. The // value of each image asset is a list of resolution-specific "variants", // see _AssetDirectoryCache. final Map<_Asset, List<_Asset>>? assetVariants = _parseAssets( packageConfig, flutterManifest, wildcardDirectories, assetBasePath, targetPlatform, flavor: flavor, );
if (assetVariants == null) { return 1; }
// Parse assets for deferred components. final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = _parseDeferredComponentsAssets( flutterManifest, packageConfig, assetBasePath, wildcardDirectories, flutterProject.directory, flavor: flavor, ); if (!_splitDeferredAssets || !deferredComponentsEnabled) { // Include the assets in the regular set of assets if not using deferred // components. deferredComponentsAssetVariants.values.forEach(assetVariants.addAll); deferredComponentsAssetVariants.clear(); deferredComponentsEntries.clear(); }
final bool includesMaterialFonts = flutterManifest.usesMaterialDesign; final List<Map<String, Object?>> fonts = _parseFonts( flutterManifest, packageConfig, primary: true, );
// Add fonts, assets, and licenses from packages. final Map<String, List<File>> additionalLicenseFiles = <String, List<File>>{}; for (final Package package in packageConfig.packages) { final Uri packageUri = package.packageUriRoot; if (packageUri.scheme == 'file') { final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml')); inputFiles.add(_fileSystem.file(packageManifestPath)); final FlutterManifest? packageFlutterManifest = FlutterManifest.createFromPath( packageManifestPath, logger: _logger, fileSystem: _fileSystem, ); if (packageFlutterManifest == null) { continue; } // Collect any additional licenses from each package. final List<File> licenseFiles = <File>[]; for (final String relativeLicensePath in packageFlutterManifest.additionalLicenses) { final String absoluteLicensePath = _fileSystem.path.fromUri(package.root.resolve(relativeLicensePath)); licenseFiles.add(_fileSystem.file(absoluteLicensePath).absolute); } additionalLicenseFiles[packageFlutterManifest.appName] = licenseFiles;
// Skip the app itself if (packageFlutterManifest.appName == flutterManifest.appName) { continue; } final String packageBasePath = _fileSystem.path.dirname(packageManifestPath);
final Map<_Asset, List<_Asset>>? packageAssets = _parseAssets( packageConfig, packageFlutterManifest, // Do not track wildcard directories for dependencies. <Uri>[], packageBasePath, targetPlatform, packageName: package.name, attributedPackage: package, );
if (packageAssets == null) { return 1; } assetVariants.addAll(packageAssets); if (!includesMaterialFonts && packageFlutterManifest.usesMaterialDesign) { _logger.printError( 'package:${package.name} has `uses-material-design: true` set but ' 'the primary pubspec contains `uses-material-design: false`. ' 'If the application needs material icons, then `uses-material-design` ' ' must be set to true.' ); } fonts.addAll(_parseFonts( packageFlutterManifest, packageConfig, packageName: package.name, primary: false, )); } }
// Save the contents of each image, image variant, and font // asset in entries. for (final _Asset asset in assetVariants.keys) { final File assetFile = asset.lookupAssetFile(_fileSystem); final List<_Asset> variants = assetVariants[asset]!; if (!assetFile.existsSync() && variants.isEmpty) { _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); _logger.printError('No file or variants found for $asset.\n'); if (asset.package != null) { _logger.printError('This asset was included from package ${asset.package?.name}.'); } return 1; } // The file name for an asset's "main" entry is whatever appears in // the pubspec.yaml file. The main entry's file must always exist for // font assets. It need not exist for an image if resolution-specific // variant files exist. An image's main entry is treated the same as a // "1x" resolution variant and if both exist then the explicit 1x // variant is preferred. if (assetFile.existsSync() && !variants.contains(asset)) { variants.insert(0, asset); } for (final _Asset variant in variants) { final File variantFile = variant.lookupAssetFile(_fileSystem); inputFiles.add(variantFile); assert(variantFile.existsSync()); entries[variant.entryUri.path] ??= DevFSFileContent(variantFile); entryKinds[variant.entryUri.path] ??= variant.assetKind; } } // Save the contents of each deferred component image, image variant, and font // asset in deferredComponentsEntries. for (final String componentName in deferredComponentsAssetVariants.keys) { deferredComponentsEntries[componentName] = <String, DevFSContent>{}; final Map<_Asset, List<_Asset>> assetsMap = deferredComponentsAssetVariants[componentName]!; for (final _Asset asset in assetsMap.keys) { final File assetFile = asset.lookupAssetFile(_fileSystem); if (!assetFile.existsSync() && assetsMap[asset]!.isEmpty) { _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); _logger.printError('No file or variants found for $asset.\n'); if (asset.package != null) { _logger.printError('This asset was included from package ${asset.package?.name}.'); } return 1; } // The file name for an asset's "main" entry is whatever appears in // the pubspec.yaml file. The main entry's file must always exist for // font assets. It need not exist for an image if resolution-specific // variant files exist. An image's main entry is treated the same as a // "1x" resolution variant and if both exist then the explicit 1x // variant is preferred. if (assetFile.existsSync() && !assetsMap[asset]!.contains(asset)) { assetsMap[asset]!.insert(0, asset); } for (final _Asset variant in assetsMap[asset]!) { final File variantFile = variant.lookupAssetFile(_fileSystem); assert(variantFile.existsSync()); deferredComponentsEntries[componentName]![variant.entryUri.path] ??= DevFSFileContent(variantFile); } } } final List<_Asset> materialAssets = <_Asset>[ if (flutterManifest.usesMaterialDesign) ..._getMaterialFonts(), // For all platforms, include the shaders unconditionally. They are // small, and whether they're used is determined only by the app source // code and not by the Flutter manifest. ..._getMaterialShaders(), ]; for (final _Asset asset in materialAssets) { final File assetFile = asset.lookupAssetFile(_fileSystem); assert(assetFile.existsSync(), 'Missing ${assetFile.path}'); entries[asset.entryUri.path] ??= DevFSFileContent(assetFile); entryKinds[asset.entryUri.path] ??= asset.assetKind; }
// Update wildcard directories we can detect changes in them. for (final Uri uri in wildcardDirectories) { _wildcardDirectories[uri] ??= _fileSystem.directory(uri); }
final Map<String, List<String>> assetManifest = _createAssetManifest(assetVariants, deferredComponentsAssetVariants); final DevFSByteContent assetManifestBinary = _createAssetManifestBinary(assetManifest); final DevFSStringContent assetManifestJson = DevFSStringContent(json.encode(assetManifest)); final DevFSStringContent fontManifest = DevFSStringContent(json.encode(fonts)); final LicenseResult licenseResult = _licenseCollector.obtainLicenses(packageConfig, additionalLicenseFiles); if (licenseResult.errorMessages.isNotEmpty) { licenseResult.errorMessages.forEach(_logger.printError); return 1; }
additionalDependencies = licenseResult.dependencies; inputFiles.addAll(additionalDependencies);
if (wildcardDirectories.isNotEmpty) { // Force the depfile to contain missing files so that Gradle does not skip // the task. Wildcard directories are not compatible with full incremental // builds. For more context see https://github.com/flutter/flutter/issues/56466 . _logger.printTrace( 'Manifest contained wildcard assets. Inserting missing file into ' 'build graph to force rerun. for more information see #56466.' ); final int suffix = Object().hashCode; additionalDependencies.add( _fileSystem.file('DOES_NOT_EXIST_RERUN_FOR_WILDCARD$suffix').absolute); }
_setIfChanged(_kAssetManifestJsonFilename, assetManifestJson, AssetKind.regular); _setIfChanged(_kAssetManifestBinFilename, assetManifestBinary, AssetKind.regular); // Create .bin.json on web builds. if (targetPlatform == TargetPlatform.web_javascript) { final DevFSStringContent assetManifestBinaryJson = DevFSStringContent(json.encode( base64.encode(assetManifestBinary.bytes) )); _setIfChanged(_kAssetManifestBinJsonFilename, assetManifestBinaryJson, AssetKind.regular); } _setIfChanged(kFontManifestJson, fontManifest, AssetKind.regular); _setLicenseIfChanged(licenseResult.combinedLicenses, targetPlatform); return 0; }
@override List<File> additionalDependencies = <File>[]; void _setIfChanged(String key, DevFSContent content, AssetKind assetKind) { final DevFSContent? oldContent = entries[key]; // In the case that the content is unchanged, we want to avoid an overwrite // as the isModified property may be reset to true, if (oldContent is DevFSByteContent && content is DevFSByteContent && _compareIntLists(oldContent.bytes, content.bytes)) { return; }
entries[key] = content; entryKinds[key] = assetKind; }
static bool _compareIntLists(List<int> o1, List<int> o2) { if (o1.length != o2.length) { return false; }
for (int index = 0; index < o1.length; index++) { if (o1[index] != o2[index]) { return false; } }
return true; }
void _setLicenseIfChanged( String combinedLicenses, TargetPlatform? targetPlatform, ) { // On the web, don't compress the NOTICES file since the client doesn't have // dart:io to decompress it. So use the standard _setIfChanged to check if // the strings still match. if (targetPlatform == TargetPlatform.web_javascript) { _setIfChanged(_kNoticeFile, DevFSStringContent(combinedLicenses), AssetKind.regular); return; }
// On other platforms, let the NOTICES file be compressed. But use a // specialized DevFSStringCompressingBytesContent class to compare // the uncompressed strings to not incur decompression/decoding while making // the comparison. if (!entries.containsKey(_kNoticeZippedFile) || (entries[_kNoticeZippedFile] as DevFSStringCompressingBytesContent?) ?.equals(combinedLicenses) != true) { entries[_kNoticeZippedFile] = DevFSStringCompressingBytesContent( combinedLicenses, // A zlib dictionary is a hinting string sequence with the most // likely string occurrences at the end. This ends up just being // common English words with domain specific words like copyright. hintString: 'copyrightsoftwaretothisinandorofthe', ); entryKinds[_kNoticeZippedFile] = AssetKind.regular; } }
List<_Asset> _getMaterialFonts() { final List<_Asset> result = <_Asset>[]; for (final Map<String, Object> family in kMaterialFonts) { final Object? fonts = family['fonts']; if (fonts == null) { continue; } for (final Map<String, Object> font in fonts as List<Map<String, String>>) { final String? asset = font['asset'] as String?; if (asset == null) { continue; } final Uri entryUri = _fileSystem.path.toUri(asset); result.add(_Asset( baseDir: _fileSystem.path.join( Cache.flutterRoot!, 'bin', 'cache', 'artifacts', 'material_fonts', ), relativeUri: Uri(path: entryUri.pathSegments.last), entryUri: entryUri, package: null, assetKind: AssetKind.font, )); } }
return result; }
List<_Asset> _getMaterialShaders() { final String shaderPath = _fileSystem.path.join( Cache.flutterRoot!, 'packages', 'flutter', 'lib', 'src', 'material', 'shaders', ); // This file will exist in a real invocation unless the git checkout is // corrupted somehow, but unit tests generally don't create this file // in their mock file systems. Leaving it out in those cases is harmless. if (!_fileSystem.directory(shaderPath).existsSync()) { return <_Asset>[]; }
final List<_Asset> result = <_Asset>[]; for (final String shader in kMaterialShaders) { final Uri entryUri = _fileSystem.path.toUri(shader); result.add(_Asset( baseDir: shaderPath, relativeUri: Uri(path: entryUri.pathSegments.last), entryUri: entryUri, package: null, assetKind: AssetKind.shader, )); }
return result; }
List<Map<String, Object?>> _parseFonts( FlutterManifest manifest, PackageConfig packageConfig, { String? packageName, required bool primary, }) { return <Map<String, Object?>>[ if (primary && manifest.usesMaterialDesign) ...kMaterialFonts, if (packageName == null) ...manifest.fontsDescriptor else for (final Font font in _parsePackageFonts( manifest, packageName, packageConfig, )) font.descriptor, ]; }
Map<String, Map<_Asset, List<_Asset>>> _parseDeferredComponentsAssets( FlutterManifest flutterManifest, PackageConfig packageConfig, String assetBasePath, List<Uri> wildcardDirectories, Directory projectDirectory, { String? flavor, }) { final List<DeferredComponent>? components = flutterManifest.deferredComponents; final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = <String, Map<_Asset, List<_Asset>>>{}; if (components == null) { return deferredComponentsAssetVariants; } for (final DeferredComponent component in components) { final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem); final Map<_Asset, List<_Asset>> componentAssets = <_Asset, List<_Asset>>{}; for (final AssetsEntry assetsEntry in component.assets) { if (assetsEntry.uri.path.endsWith('/')) { wildcardDirectories.add(assetsEntry.uri); _parseAssetsFromFolder( packageConfig, flutterManifest, assetBasePath, cache, componentAssets, assetsEntry.uri, ); } else { _parseAssetFromFile( packageConfig, flutterManifest, assetBasePath, cache, componentAssets, assetsEntry.uri, ); } }
componentAssets.removeWhere((_Asset asset, List<_Asset> variants) => !asset.matchesFlavor(flavor)); deferredComponentsAssetVariants[component.name] = componentAssets; } return deferredComponentsAssetVariants; }
Map<String, List<String>> _createAssetManifest( Map<_Asset, List<_Asset>> assetVariants, Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants ) { final Map<String, List<String>> manifest = <String, List<String>>{}; final Map<_Asset, List<String>> entries = <_Asset, List<String>>{}; assetVariants.forEach((_Asset main, List<_Asset> variants) { entries[main] = <String>[ for (final _Asset variant in variants) variant.entryUri.path, ]; }); for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) { componentAssets.forEach((_Asset main, List<_Asset> variants) { entries[main] = <String>[ for (final _Asset variant in variants) variant.entryUri.path, ]; }); } final List<_Asset> sortedKeys = entries.keys.toList() ..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path)); for (final _Asset main in sortedKeys) { final String decodedEntryPath = Uri.decodeFull(main.entryUri.path); final List<String> rawEntryVariantsPaths = entries[main]!; final List<String> decodedEntryVariantPaths = rawEntryVariantsPaths .map((String value) => Uri.decodeFull(value)) .toList(); manifest[decodedEntryPath] = decodedEntryVariantPaths; } return manifest; }
// Matches path-like strings ending in a number followed by an 'x'. // Example matches include "assets/animals/2.0x", "plants/3x", and "2.7x". static final RegExp _extractPixelRatioFromKeyRegExp = RegExp(r'/?(\d+(\.\d*)?)x$');
DevFSByteContent _createAssetManifestBinary( Map<String, List<String>> assetManifest ) { double? parseScale(String key) { final Uri assetUri = Uri.parse(key); String directoryPath = ''; if (assetUri.pathSegments.length > 1) { directoryPath = assetUri.pathSegments[assetUri.pathSegments.length - 2]; }
final Match? match = _extractPixelRatioFromKeyRegExp.firstMatch(directoryPath); if (match != null && match.groupCount > 0) { return double.parse(match.group(1)!); }
return null; }
final Map<String, dynamic> result = <String, dynamic>{};
for (final MapEntry<String, dynamic> manifestEntry in assetManifest.entries) { final List<dynamic> resultVariants = <dynamic>[]; final List<String> entries = (manifestEntry.value as List<dynamic>).cast<String>(); for (final String variant in entries) { final Map<String, dynamic> resultVariant = <String, dynamic>{}; final double? variantDevicePixelRatio = parseScale(variant); resultVariant['asset'] = variant; if (variantDevicePixelRatio != null) { resultVariant['dpr'] = variantDevicePixelRatio; } resultVariants.add(resultVariant); } result[manifestEntry.key] = resultVariants; }
final ByteData message = const StandardMessageCodec().encodeMessage(result)!; return DevFSByteContent(message.buffer.asUint8List(0, message.lengthInBytes)); }
/// Prefixes family names and asset paths of fonts included from packages with /// 'packages/<package_name>' List<Font> _parsePackageFonts( FlutterManifest manifest, String packageName, PackageConfig packageConfig, ) { final List<Font> packageFonts = <Font>[]; for (final Font font in manifest.fonts) { final List<FontAsset> packageFontAssets = <FontAsset>[]; for (final FontAsset fontAsset in font.fontAssets) { final Uri assetUri = fontAsset.assetUri; if (assetUri.pathSegments.first == 'packages' && !_fileSystem.isFileSync(_fileSystem.path.fromUri( packageConfig[packageName]?.packageUriRoot.resolve('../${assetUri.path}')))) { packageFontAssets.add(FontAsset( fontAsset.assetUri, weight: fontAsset.weight, style: fontAsset.style, )); } else { packageFontAssets.add(FontAsset( Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), weight: fontAsset.weight, style: fontAsset.style, )); } } packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets)); } return packageFonts; }
/// Given an assetBase location and a pubspec.yaml Flutter manifest, return a /// map of assets to asset variants. /// /// Returns null on missing assets. /// /// Given package: 'test_package' and an assets directory like this: /// /// - assets/foo /// - assets/var1/foo /// - assets/var2/foo /// - assets/bar /// /// This will return: /// ``` /// { /// asset: packages/test_package/assets/foo: [ /// asset: packages/test_package/assets/foo, /// asset: packages/test_package/assets/var1/foo, /// asset: packages/test_package/assets/var2/foo, /// ], /// asset: packages/test_package/assets/bar: [ /// asset: packages/test_package/assets/bar, /// ], /// } /// ``` Map<_Asset, List<_Asset>>? _parseAssets( PackageConfig packageConfig, FlutterManifest flutterManifest, List<Uri> wildcardDirectories, String assetBase, TargetPlatform? targetPlatform, { String? packageName, Package? attributedPackage, String? flavor, }) { final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
final _AssetDirectoryCache cache = _AssetDirectoryCache(_fileSystem); for (final AssetsEntry assetsEntry in flutterManifest.assets) { if (assetsEntry.uri.path.endsWith('/')) { wildcardDirectories.add(assetsEntry.uri); _parseAssetsFromFolder( packageConfig, flutterManifest, assetBase, cache, result, assetsEntry.uri, packageName: packageName, attributedPackage: attributedPackage, flavors: assetsEntry.flavors, ); } else { _parseAssetFromFile( packageConfig, flutterManifest, assetBase, cache, result, assetsEntry.uri, packageName: packageName, attributedPackage: attributedPackage, flavors: assetsEntry.flavors, ); } }
result.removeWhere((_Asset asset, List<_Asset> variants) { if (!asset.matchesFlavor(flavor)) { _logger.printTrace('Skipping assets entry "${asset.entryUri.path}" since ' 'its configured flavor(s) did not match the provided flavor (if any).\n' 'Configured flavors: ${asset.flavors.join(', ')}\n'); return true; } return false; });
for (final Uri shaderUri in flutterManifest.shaders) { _parseAssetFromFile( packageConfig, flutterManifest, assetBase, cache, result, shaderUri, packageName: packageName, attributedPackage: attributedPackage, assetKind: AssetKind.shader, ); }
for (final Uri modelUri in flutterManifest.models) { _parseAssetFromFile( packageConfig, flutterManifest, assetBase, cache, result, modelUri, packageName: packageName, attributedPackage: attributedPackage, assetKind: AssetKind.model, ); }
// Add assets referenced in the fonts section of the manifest. for (final Font font in flutterManifest.fonts) { for (final FontAsset fontAsset in font.fontAssets) { final _Asset baseAsset = _resolveAsset( packageConfig, assetBase, fontAsset.assetUri, packageName, attributedPackage, assetKind: AssetKind.font, ); final File baseAssetFile = baseAsset.lookupAssetFile(_fileSystem); if (!baseAssetFile.existsSync()) { _logger.printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".'); return null; } result[baseAsset] = <_Asset>[]; } }
return result; }
void _parseAssetsFromFolder( PackageConfig packageConfig, FlutterManifest flutterManifest, String assetBase, _AssetDirectoryCache cache, Map<_Asset, List<_Asset>> result, Uri assetUri, { String? packageName, Package? attributedPackage, List<String>? flavors, }) { final String directoryPath = _fileSystem.path.join( assetBase, assetUri.toFilePath(windows: _platform.isWindows));
if (!_fileSystem.directory(directoryPath).existsSync()) { _logger.printError('Error: unable to find directory entry in pubspec.yaml: $directoryPath'); return; }
final Iterable<FileSystemEntity> entities = _fileSystem.directory(directoryPath).listSync();
final Iterable<File> files = entities.whereType<File>(); for (final File file in files) { final String relativePath = _fileSystem.path.relative(file.path, from: assetBase); final Uri uri = Uri.file(relativePath, windows: _platform.isWindows);
_parseAssetFromFile( packageConfig, flutterManifest, assetBase, cache, result, uri, packageName: packageName, attributedPackage: attributedPackage, originUri: assetUri, flavors: flavors, ); } }
void _parseAssetFromFile( PackageConfig packageConfig, FlutterManifest flutterManifest, String assetBase, _AssetDirectoryCache cache, Map<_Asset, List<_Asset>> result, Uri assetUri, { Uri? originUri, String? packageName, Package? attributedPackage, AssetKind assetKind = AssetKind.regular, List<String>? flavors, }) { final _Asset asset = _resolveAsset( packageConfig, assetBase, assetUri, packageName, attributedPackage, assetKind: assetKind, originUri: originUri, flavors: flavors, );
_checkForFlavorConflicts(asset, result.keys.toList());
final List<_Asset> variants = <_Asset>[]; final File assetFile = asset.lookupAssetFile(_fileSystem);
for (final String path in cache.variantsFor(assetFile.path)) { final String relativePath = _fileSystem.path.relative(path, from: asset.baseDir); final Uri relativeUri = _fileSystem.path.toUri(relativePath); final Uri? entryUri = asset.symbolicPrefixUri == null ? relativeUri : asset.symbolicPrefixUri?.resolveUri(relativeUri); if (entryUri != null) { variants.add( _Asset( baseDir: asset.baseDir, entryUri: entryUri, relativeUri: relativeUri, package: attributedPackage, assetKind: assetKind, ), ); } }
result[asset] = variants; }
// Since it is not clear how overlapping asset declarations should work in the // presence of conditions such as `flavor`, we throw an Error. // // To be more specific, it is not clear if conditions should be combined with // or-logic or and-logic, or if it should depend on the specificity of the // declarations (file versus directory). If you would like examples, consider these: // // ```yaml // # Should assets/free.mp3 always be included since "assets/" has no flavor? // assets: // - assets/ // - path: assets/free.mp3 // flavor: free // // # Should "assets/paid/pip.mp3" be included for both the "paid" and "free" flavors? // # Or, since "assets/paid/pip.mp3" is more specific than "assets/paid/"", should // # it take precedence over the latter (included only in "free" flavor)? // assets: // - path: assets/paid/ // flavor: paid // - path: assets/paid/pip.mp3 // flavor: free // - asset // ``` // // Since it is not obvious what logic (if any) would be intuitive and preferable // to the vast majority of users (if any), we play it safe by throwing a `ToolExit` // in any of these situations. We can always loosen up this restriction later // without breaking anyone. void _checkForFlavorConflicts(_Asset newAsset, List<_Asset> previouslyParsedAssets) { bool cameFromDirectoryEntry(_Asset asset) { return asset.originUri.path.endsWith('/'); }
String flavorErrorInfo(_Asset asset) { if (asset.flavors.isEmpty) { return 'An entry with the path "${asset.originUri}" does not specify any flavors.'; }
final Iterable<String> flavorsWrappedWithQuotes = asset.flavors.map((String e) => '"$e"'); return 'An entry with the path "${asset.originUri}" specifies the flavor(s): ' '${flavorsWrappedWithQuotes.join(', ')}.'; }
final _Asset? preExistingAsset = previouslyParsedAssets .where((_Asset other) => other.entryUri == newAsset.entryUri) .firstOrNull;
if (preExistingAsset == null || preExistingAsset.hasEquivalentFlavorsWith(newAsset)) { return; }
final StringBuffer errorMessage = StringBuffer( 'Multiple assets entries include the file ' '"${newAsset.entryUri.path}", but they specify different lists of flavors.\n');
errorMessage.writeln(flavorErrorInfo(preExistingAsset)); errorMessage.writeln(flavorErrorInfo(newAsset));
if (cameFromDirectoryEntry(newAsset)|| cameFromDirectoryEntry(preExistingAsset)) { errorMessage.writeln(); errorMessage.write('Consider organizing assets with different flavors ' 'into different directories.'); }
throwToolExit(errorMessage.toString()); }
_Asset _resolveAsset( PackageConfig packageConfig, String assetsBaseDir, Uri assetUri, String? packageName, Package? attributedPackage, { Uri? originUri, AssetKind assetKind = AssetKind.regular, List<String>? flavors, }) { final String assetPath = _fileSystem.path.fromUri(assetUri); if (assetUri.pathSegments.first == 'packages' && !_fileSystem.isFileSync(_fileSystem.path.join(assetsBaseDir, assetPath))) { // The asset is referenced in the pubspec.yaml as // 'packages/PACKAGE_NAME/PATH/TO/ASSET . final _Asset? packageAsset = _resolvePackageAsset( assetUri, packageConfig, attributedPackage, assetKind: assetKind, originUri: originUri, flavors: flavors, ); if (packageAsset != null) { return packageAsset; } }
return _Asset( baseDir: assetsBaseDir, entryUri: packageName == null ? assetUri // Asset from the current application. : Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName. relativeUri: assetUri, package: attributedPackage, originUri: originUri, assetKind: assetKind, flavors: flavors, ); }
_Asset? _resolvePackageAsset( Uri assetUri, PackageConfig packageConfig, Package? attributedPackage, { AssetKind assetKind = AssetKind.regular, Uri? originUri, List<String>? flavors, }) { assert(assetUri.pathSegments.first == 'packages'); if (assetUri.pathSegments.length > 1) { final String packageName = assetUri.pathSegments[1]; final Package? package = packageConfig[packageName]; final Uri? packageUri = package?.packageUriRoot; if (packageUri != null && packageUri.scheme == 'file') { return _Asset( baseDir: _fileSystem.path.fromUri(packageUri), entryUri: assetUri, relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)), package: attributedPackage, assetKind: assetKind, originUri: originUri, flavors: flavors, ); } } _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); _logger.printError('Could not resolve package for asset $assetUri.\n'); if (attributedPackage != null) { _logger.printError('This asset was included from package ${attributedPackage.name}'); } return null; }}
@immutableclass _Asset { const _Asset({ required this.baseDir, Uri? originUri, required this.relativeUri, required this.entryUri, required this.package, this.assetKind = AssetKind.regular, List<String>? flavors, }): originUri = originUri ?? entryUri, flavors = flavors ?? const <String>[];
final String baseDir;
final Package? package;
/// The platform-independent URL provided by the user in the pubspec that this /// asset was found from. final Uri originUri;
/// A platform-independent URL where this asset can be found on disk on the /// host system relative to [baseDir]. final Uri relativeUri;
/// A platform-independent URL representing the entry for the asset manifest. final Uri entryUri;
final AssetKind assetKind;
final List<String> flavors;
File lookupAssetFile(FileSystem fileSystem) { return fileSystem.file(fileSystem.path.join(baseDir, fileSystem.path.fromUri(relativeUri))); }
/// The delta between what the entryUri is and the relativeUri (e.g., /// packages/flutter_gallery). Uri? get symbolicPrefixUri { if (entryUri == relativeUri) { return null; } final int index = entryUri.path.indexOf(relativeUri.path); return index == -1 ? null : Uri(path: entryUri.path.substring(0, index)); }
bool matchesFlavor(String? flavor) { if (flavors.isEmpty) { return true; }
if (flavor == null) { return false; }
return flavors.contains(flavor); }
bool hasEquivalentFlavorsWith(_Asset other) { final Set<String> assetFlavors = flavors.toSet(); final Set<String> otherFlavors = other.flavors.toSet(); return assetFlavors.length == otherFlavors.length && assetFlavors.every( (String e) => otherFlavors.contains(e), ); }
@override String toString() => 'asset: $entryUri';
@override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is _Asset && other.baseDir == baseDir && other.relativeUri == relativeUri && other.entryUri == entryUri && other.assetKind == assetKind && hasEquivalentFlavorsWith(other); }
@override int get hashCode => Object.hashAll(<Object>[ baseDir, relativeUri, entryUri, assetKind, ...flavors, ]);}
// Given an assets directory like this://// assets/foo.png// assets/2x/foo.png// assets/3.0x/foo.png// assets/bar/foo.png// assets/bar.png//// variantsFor('assets/foo.png') => ['/assets/foo.png', '/assets/2x/foo.png', 'assets/3.0x/foo.png']// variantsFor('assets/bar.png') => ['/assets/bar.png']// variantsFor('assets/bar/foo.png') => ['/assets/bar/foo.png']class _AssetDirectoryCache { _AssetDirectoryCache(this._fileSystem);
final FileSystem _fileSystem; final Map<String, List<String>> _cache = <String, List<String>>{}; final Map<String, List<File>> _variantsPerFolder = <String, List<File>>{};
List<String> variantsFor(String assetPath) { final String directory = _fileSystem.path.dirname(assetPath);
if (!_fileSystem.directory(directory).existsSync()) { return const <String>[]; }
if (_cache.containsKey(assetPath)) { return _cache[assetPath]!; } if (!_variantsPerFolder.containsKey(directory)) { _variantsPerFolder[directory] = _fileSystem.directory(directory) .listSync() .whereType<Directory>() .where((Directory dir) => _assetVariantDirectoryRegExp.hasMatch(dir.basename)) .expand((Directory dir) => dir.listSync()) .whereType<File>() .toList(); } final File assetFile = _fileSystem.file(assetPath); final List<File> potentialVariants = _variantsPerFolder[directory]!; final String basename = assetFile.basename; return _cache[assetPath] = <String>[ // It's possible that the user specifies only explicit variants (e.g. .../1x/asset.png), // so there does not necessarily need to be a file at the given path. if (assetFile.existsSync()) assetPath, ...potentialVariants .where((File file) => file.basename == basename) .map((File file) => file.path), ]; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063// 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:package_config/package_config_types.dart';
import 'artifacts.dart';import 'base/config.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/os.dart';import 'base/utils.dart';import 'convert.dart';import 'globals.dart' as globals;import 'web/compile.dart';
/// Whether icon font subsetting is enabled by default.const bool kIconTreeShakerEnabledDefault = true;
/// Information about a build to be performed or used.class BuildInfo { const BuildInfo( this.mode, this.flavor, { this.trackWidgetCreation = false, this.frontendServerStarterPath, List<String>? extraFrontEndOptions, List<String>? extraGenSnapshotOptions, List<String>? fileSystemRoots, this.androidProjectArgs = const <String>[], this.fileSystemScheme, this.buildNumber, this.buildName, this.splitDebugInfoPath, this.dartObfuscation = false, List<String>? dartDefines, this.bundleSkSLPath, List<String>? dartExperiments, this.webRenderer = WebRendererMode.auto, required this.treeShakeIcons, this.performanceMeasurementFile, this.packagesPath = '.dart_tool/package_config.json', // TODO(zanderso): make this required and remove the default. this.nullSafetyMode = NullSafetyMode.sound, this.codeSizeDirectory, this.androidGradleDaemon = true, this.packageConfig = PackageConfig.empty, this.initializeFromDill, this.assumeInitializeFromDillUpToDate = false, this.buildNativeAssets = true, }) : extraFrontEndOptions = extraFrontEndOptions ?? const <String>[], extraGenSnapshotOptions = extraGenSnapshotOptions ?? const <String>[], fileSystemRoots = fileSystemRoots ?? const <String>[], dartDefines = dartDefines ?? const <String>[], dartExperiments = dartExperiments ?? const <String>[];
final BuildMode mode;
/// The null safety mode the application should be run in. /// /// If not provided, defaults to [NullSafetyMode.autodetect]. final NullSafetyMode nullSafetyMode;
/// Whether the build should subset icon fonts. final bool treeShakeIcons;
/// Represents a custom Android product flavor or an Xcode scheme, null for /// using the default. /// /// If not null, the Gradle build task will be `assembleFlavorMode` (e.g. /// `assemblePaidRelease`), and the Xcode build configuration will be /// Mode-Flavor (e.g. Release-Paid). final String? flavor;
/// The path to the package configuration file to use for compilation. /// /// This is used by package:package_config to locate the actual package_config.json /// file. If not provided, defaults to `.dart_tool/package_config.json`. final String packagesPath;
final List<String> fileSystemRoots; final String? fileSystemScheme;
/// Whether the build should track widget creation locations. final bool trackWidgetCreation;
/// If provided, the frontend server will be started in JIT mode from this /// file. final String? frontendServerStarterPath;
/// Extra command-line options for front-end. final List<String> extraFrontEndOptions;
/// Extra command-line options for gen_snapshot. final List<String> extraGenSnapshotOptions;
/// Internal version number (not displayed to users). /// Each build must have a unique number to differentiate it from previous builds. /// It is used to determine whether one build is more recent than another, with higher numbers indicating more recent build. /// On Android it is used as versionCode. /// On Xcode builds it is used as CFBundleVersion. /// On Windows it is used as the build suffix for the product and file versions. final String? buildNumber;
/// A "x.y.z" string used as the version number shown to users. /// For each new version of your app, you will provide a version number to differentiate it from previous versions. /// On Android it is used as versionName. /// On Xcode builds it is used as CFBundleShortVersionString. /// On Windows it is used as the major, minor, and patch parts of the product and file versions. final String? buildName;
/// An optional directory path to save debugging information from dwarf stack /// traces. If null, stack trace information is not stripped from the /// executable. final String? splitDebugInfoPath;
/// Whether to apply dart source code obfuscation. final bool dartObfuscation;
/// An optional path to a JSON containing object SkSL shaders. /// /// Currently this is only supported for Android builds. final String? bundleSkSLPath;
/// Additional constant values to be made available in the Dart program. /// /// These values can be used with the const `fromEnvironment` constructors of /// [bool], [String], [int], and [double]. final List<String> dartDefines;
/// A list of Dart experiments. final List<String> dartExperiments;
/// When compiling to web, which web renderer mode we are using (html, canvaskit, auto) final WebRendererMode webRenderer;
/// The name of a file where flutter assemble will output performance /// information in a JSON format. /// /// This is not considered a build input and will not force assemble to /// rerun tasks. final String? performanceMeasurementFile;
/// If provided, an output directory where one or more v8-style heap snapshots /// will be written for code size profiling. final String? codeSizeDirectory;
/// Whether to enable the Gradle daemon when performing an Android build. /// /// Starting the daemon is the default behavior of the gradle wrapper script created /// in a Flutter project. Setting this value to false will cause the tool to pass /// `--no-daemon` to the gradle wrapper script, preventing it from spawning a daemon /// process. /// /// For one-off builds or CI systems, preventing the daemon from spawning will /// reduce system resource usage, at the cost of any subsequent builds starting /// up slightly slower. /// /// The Gradle daemon may also be disabled in the Android application's properties file. final bool androidGradleDaemon;
/// Additional key value pairs that are passed directly to the gradle project via the `-P` /// flag. final List<String> androidProjectArgs;
/// The package configuration for the loaded application. /// /// This is captured once during startup, but the actual package configuration /// may change during a 'flutter run` workflow. final PackageConfig packageConfig;
/// The kernel file that the resident compiler will be initialized with. /// /// If this is null, it will be initialized from the default cached location. final String? initializeFromDill;
/// If set, assumes that the file passed in [initializeFromDill] is up to date /// and skips the check and potential invalidation of files. final bool assumeInitializeFromDillUpToDate;
/// If set, builds native assets with `build.dart` from all packages. final bool buildNativeAssets;
static const BuildInfo debug = BuildInfo(BuildMode.debug, null, trackWidgetCreation: true, treeShakeIcons: false); static const BuildInfo profile = BuildInfo(BuildMode.profile, null, treeShakeIcons: kIconTreeShakerEnabledDefault); static const BuildInfo jitRelease = BuildInfo(BuildMode.jitRelease, null, treeShakeIcons: kIconTreeShakerEnabledDefault); static const BuildInfo release = BuildInfo(BuildMode.release, null, treeShakeIcons: kIconTreeShakerEnabledDefault);
/// Returns whether a debug build is requested. /// /// Exactly one of [isDebug], [isProfile], or [isRelease] is true. bool get isDebug => mode == BuildMode.debug;
/// Returns whether a profile build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isProfile => mode == BuildMode.profile;
/// Returns whether a release build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isRelease => mode == BuildMode.release;
/// Returns whether a JIT release build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isJitRelease => mode == BuildMode.jitRelease;
bool get usesAot => isAotBuildMode(mode); bool get supportsEmulator => isEmulatorBuildMode(mode); bool get supportsSimulator => isEmulatorBuildMode(mode); String get modeName => mode.cliName; String get friendlyModeName => getFriendlyModeName(mode);
/// the flavor name in the output apk files is lower-cased (see Flutter Gradle Plugin), /// so the lower cased flavor name is used to compute the output file name String? get lowerCasedFlavor => flavor?.toLowerCase();
/// the flavor name in the output bundle files has the first character lower-cased, /// so the uncapitalized flavor name is used to compute the output file name String? get uncapitalizedFlavor => _uncapitalize(flavor);
/// Convert to a structured string encoded structure appropriate for usage /// in build system [Environment.defines]. /// /// Fields that are `null` are excluded from this configuration. Map<String, String> toBuildSystemEnvironment() { // packagesPath and performanceMeasurementFile are not passed into // the Environment map. return <String, String>{ kBuildMode: mode.cliName, if (dartDefines.isNotEmpty) kDartDefines: encodeDartDefines(dartDefines), kDartObfuscation: dartObfuscation.toString(), if (frontendServerStarterPath != null) kFrontendServerStarterPath: frontendServerStarterPath!, if (extraFrontEndOptions.isNotEmpty) kExtraFrontEndOptions: extraFrontEndOptions.join(','), if (extraGenSnapshotOptions.isNotEmpty) kExtraGenSnapshotOptions: extraGenSnapshotOptions.join(','), if (splitDebugInfoPath != null) kSplitDebugInfo: splitDebugInfoPath!, kTrackWidgetCreation: trackWidgetCreation.toString(), kIconTreeShakerFlag: treeShakeIcons.toString(), if (bundleSkSLPath != null) kBundleSkSLPath: bundleSkSLPath!, if (codeSizeDirectory != null) kCodeSizeDirectory: codeSizeDirectory!, if (fileSystemRoots.isNotEmpty) kFileSystemRoots: fileSystemRoots.join(','), if (fileSystemScheme != null) kFileSystemScheme: fileSystemScheme!, if (buildName != null) kBuildName: buildName!, if (buildNumber != null) kBuildNumber: buildNumber!, }; }
/// Convert to a structured string encoded structure appropriate for usage as /// environment variables or to embed in other scripts. /// /// Fields that are `null` are excluded from this configuration. Map<String, String> toEnvironmentConfig() { return <String, String>{ if (dartDefines.isNotEmpty) 'DART_DEFINES': encodeDartDefines(dartDefines), 'DART_OBFUSCATION': dartObfuscation.toString(), if (frontendServerStarterPath != null) 'FRONTEND_SERVER_STARTER_PATH': frontendServerStarterPath!, if (extraFrontEndOptions.isNotEmpty) 'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions.join(','), if (extraGenSnapshotOptions.isNotEmpty) 'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions.join(','), if (splitDebugInfoPath != null) 'SPLIT_DEBUG_INFO': splitDebugInfoPath!, 'TRACK_WIDGET_CREATION': trackWidgetCreation.toString(), 'TREE_SHAKE_ICONS': treeShakeIcons.toString(), if (performanceMeasurementFile != null) 'PERFORMANCE_MEASUREMENT_FILE': performanceMeasurementFile!, if (bundleSkSLPath != null) 'BUNDLE_SKSL_PATH': bundleSkSLPath!, 'PACKAGE_CONFIG': packagesPath, if (codeSizeDirectory != null) 'CODE_SIZE_DIRECTORY': codeSizeDirectory!, if (flavor != null) 'FLAVOR': flavor!, }; }
/// Convert this config to a series of project level arguments to be passed /// on the command line to gradle. List<String> toGradleConfig() { // PACKAGE_CONFIG not currently supported. return <String>[ if (dartDefines.isNotEmpty) '-Pdart-defines=${encodeDartDefines(dartDefines)}', '-Pdart-obfuscation=$dartObfuscation', if (frontendServerStarterPath != null) '-Pfrontend-server-starter-path=$frontendServerStarterPath', if (extraFrontEndOptions.isNotEmpty) '-Pextra-front-end-options=${extraFrontEndOptions.join(',')}', if (extraGenSnapshotOptions.isNotEmpty) '-Pextra-gen-snapshot-options=${extraGenSnapshotOptions.join(',')}', if (splitDebugInfoPath != null) '-Psplit-debug-info=$splitDebugInfoPath', '-Ptrack-widget-creation=$trackWidgetCreation', '-Ptree-shake-icons=$treeShakeIcons', if (performanceMeasurementFile != null) '-Pperformance-measurement-file=$performanceMeasurementFile', if (bundleSkSLPath != null) '-Pbundle-sksl-path=$bundleSkSLPath', if (codeSizeDirectory != null) '-Pcode-size-directory=$codeSizeDirectory', for (final String projectArg in androidProjectArgs) '-P$projectArg', ]; }}
/// Information about an Android build to be performed or used.class AndroidBuildInfo { const AndroidBuildInfo( this.buildInfo, { this.targetArchs = const <AndroidArch>[ AndroidArch.armeabi_v7a, AndroidArch.arm64_v8a, AndroidArch.x86_64, ], this.splitPerAbi = false, this.fastStart = false, this.multidexEnabled = false, });
// The build info containing the mode and flavor. final BuildInfo buildInfo;
/// Whether to split the shared library per ABI. /// /// When this is false, multiple ABIs will be contained within one primary /// build artifact. When this is true, multiple build artifacts (one per ABI) /// will be produced. final bool splitPerAbi;
/// The target platforms for the build. final Iterable<AndroidArch> targetArchs;
/// Whether to bootstrap an empty application. final bool fastStart;
/// Whether to enable multidex support for apps with more than 64k methods. final bool multidexEnabled;}
/// A summary of the compilation strategy used for Dart.enum BuildMode { /// Built in JIT mode with no optimizations, enabled asserts, and a VM service. debug,
/// Built in AOT mode with some optimizations and a VM service. profile,
/// Built in AOT mode with all optimizations and no VM service. release,
/// Built in JIT mode with all optimizations and no VM service. jitRelease;
factory BuildMode.fromCliName(String value) => values.singleWhere( (BuildMode element) => element.cliName == value, orElse: () => throw ArgumentError('$value is not a supported build mode'), );
static const Set<BuildMode> releaseModes = <BuildMode>{ release, jitRelease, }; static const Set<BuildMode> jitModes = <BuildMode>{ debug, jitRelease, };
/// Whether this mode is considered release. /// /// Useful for determining whether we should enable/disable asserts or /// other development features. bool get isRelease => releaseModes.contains(this);
/// Whether this mode is using the JIT runtime. bool get isJit => jitModes.contains(this);
/// Whether this mode is using the precompiled runtime. bool get isPrecompiled => !isJit;
String get cliName => snakeCase(name);
@override String toString() => cliName;}
/// Environment type of the target device.enum EnvironmentType { physical, simulator,}
String? validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String? buildNumber, Logger logger) { if (buildNumber == null) { return null; } if (targetPlatform == TargetPlatform.ios || targetPlatform == TargetPlatform.darwin) { // See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html final RegExp disallowed = RegExp(r'[^\d\.]'); String tmpBuildNumber = buildNumber.replaceAll(disallowed, ''); if (tmpBuildNumber.isEmpty) { return null; } final List<String> segments = tmpBuildNumber .split('.') .where((String segment) => segment.isNotEmpty) .toList(); if (segments.isEmpty) { segments.add('0'); } tmpBuildNumber = segments.join('.'); if (tmpBuildNumber != buildNumber) { logger.printTrace('Invalid build-number: $buildNumber for iOS/macOS, overridden by $tmpBuildNumber.\n' 'See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); } return tmpBuildNumber; } if (targetPlatform == TargetPlatform.android_arm || targetPlatform == TargetPlatform.android_arm64 || targetPlatform == TargetPlatform.android_x64 || targetPlatform == TargetPlatform.android_x86) { // See versionCode at https://developer.android.com/studio/publish/versioning final RegExp disallowed = RegExp(r'[^\d]'); String tmpBuildNumberStr = buildNumber.replaceAll(disallowed, ''); int tmpBuildNumberInt = int.tryParse(tmpBuildNumberStr) ?? 0; if (tmpBuildNumberInt < 1) { tmpBuildNumberInt = 1; } tmpBuildNumberStr = tmpBuildNumberInt.toString(); if (tmpBuildNumberStr != buildNumber) { logger.printTrace('Invalid build-number: $buildNumber for Android, overridden by $tmpBuildNumberStr.\n' 'See versionCode at https://developer.android.com/studio/publish/versioning'); } return tmpBuildNumberStr; } return buildNumber;}
String? validatedBuildNameForPlatform(TargetPlatform targetPlatform, String? buildName, Logger logger) { if (buildName == null) { return null; } if (targetPlatform == TargetPlatform.ios || targetPlatform == TargetPlatform.darwin) { // See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html final RegExp disallowed = RegExp(r'[^\d\.]'); String tmpBuildName = buildName.replaceAll(disallowed, ''); if (tmpBuildName.isEmpty) { return null; } final List<String> segments = tmpBuildName .split('.') .where((String segment) => segment.isNotEmpty) .toList(); while (segments.length < 3) { segments.add('0'); } tmpBuildName = segments.join('.'); if (tmpBuildName != buildName) { logger.printTrace('Invalid build-name: $buildName for iOS/macOS, overridden by $tmpBuildName.\n' 'See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); } return tmpBuildName; } if (targetPlatform == TargetPlatform.android || targetPlatform == TargetPlatform.android_arm || targetPlatform == TargetPlatform.android_arm64 || targetPlatform == TargetPlatform.android_x64 || targetPlatform == TargetPlatform.android_x86) { // See versionName at https://developer.android.com/studio/publish/versioning return buildName; } return buildName;}
String getFriendlyModeName(BuildMode mode) { return snakeCase(mode.cliName).replaceAll('_', ' ');}
// Returns true if the selected build mode uses ahead-of-time compilation.bool isAotBuildMode(BuildMode mode) { return mode == BuildMode.profile || mode == BuildMode.release;}
// Returns true if the given build mode can be used on emulators / simulators.bool isEmulatorBuildMode(BuildMode mode) { return mode == BuildMode.debug;}
enum TargetPlatform { android, ios, darwin, linux_x64, linux_arm64, windows_x64, fuchsia_arm64, fuchsia_x64, tester, web_javascript, // The arch specific android target platforms are soft-deprecated. // Instead of using TargetPlatform as a combination arch + platform // the code will be updated to carry arch information in [DarwinArch] // and [AndroidArch]. android_arm, android_arm64, android_x64, android_x86;
String get fuchsiaArchForTargetPlatform { switch (this) { case TargetPlatform.fuchsia_arm64: return 'arm64'; case TargetPlatform.fuchsia_x64: return 'x64'; case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.darwin: case TargetPlatform.ios: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: throw UnsupportedError('Unexpected Fuchsia platform $this'); } }
String get simpleName { switch (this) { case TargetPlatform.linux_x64: case TargetPlatform.darwin: case TargetPlatform.windows_x64: return 'x64'; case TargetPlatform.linux_arm64: return 'arm64'; case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.ios: case TargetPlatform.tester: case TargetPlatform.web_javascript: throw UnsupportedError('Unexpected target platform $this'); } }}
/// iOS and macOS target device architecture.//// TODO(cbracken): split TargetPlatform.ios into ios_armv7, ios_arm64.enum DarwinArch { armv7, // Deprecated. Used to display 32-bit unsupported devices. arm64, x86_64;
/// Returns the Dart SDK's name for the specified target architecture. /// /// When building for Darwin platforms, the tool invokes architecture-specific /// variants of `gen_snapshot`, one for each target architecture. The output /// instructions are then built into architecture-specific binaries, which are /// merged into a universal binary using the `lipo` tool. String get dartName { return switch (this) { DarwinArch.armv7 => 'armv7', DarwinArch.arm64 => 'arm64', DarwinArch.x86_64 => 'x64' }; }}
// TODO(zanderso): replace all android TargetPlatform usage with AndroidArch.enum AndroidArch { armeabi_v7a, arm64_v8a, x86, x86_64;
String get archName { return switch (this) { AndroidArch.armeabi_v7a => 'armeabi-v7a', AndroidArch.arm64_v8a => 'arm64-v8a', AndroidArch.x86_64 => 'x86_64', AndroidArch.x86 => 'x86' }; }
String get platformName { return switch (this) { AndroidArch.armeabi_v7a => 'android-arm', AndroidArch.arm64_v8a => 'android-arm64', AndroidArch.x86_64 => 'android-x64', AndroidArch.x86 => 'android-x86' }; }}
/// The default set of iOS device architectures to build for.List<DarwinArch> defaultIOSArchsForEnvironment( EnvironmentType environmentType, Artifacts artifacts,) { // Handle single-arch local engines. final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; if (localEngineInfo != null) { final String localEngineName = localEngineInfo.localTargetName; if (localEngineName.contains('_arm64')) { return <DarwinArch>[ DarwinArch.arm64 ]; } if (localEngineName.contains('_sim')) { return <DarwinArch>[ DarwinArch.x86_64 ]; } } else if (environmentType == EnvironmentType.simulator) { return <DarwinArch>[ DarwinArch.x86_64, DarwinArch.arm64, ]; } return <DarwinArch>[ DarwinArch.arm64, ];}
/// The default set of macOS device architectures to build for.List<DarwinArch> defaultMacOSArchsForEnvironment(Artifacts artifacts) { // Handle single-arch local engines. final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; if (localEngineInfo != null) { if (localEngineInfo.localTargetName.contains('_arm64')) { return <DarwinArch>[ DarwinArch.arm64 ]; } return <DarwinArch>[ DarwinArch.x86_64 ]; } return <DarwinArch>[ DarwinArch.x86_64, DarwinArch.arm64, ];}
DarwinArch getIOSArchForName(String arch) { switch (arch) { case 'armv7': case 'armv7f': // iPhone 4S. case 'armv7s': // iPad 4. return DarwinArch.armv7; case 'arm64': case 'arm64e': // iPhone XS/XS Max/XR and higher. arm64 runs on arm64e devices. return DarwinArch.arm64; case 'x86_64': return DarwinArch.x86_64; } throw Exception('Unsupported iOS arch name "$arch"');}
DarwinArch getDarwinArchForName(String arch) { switch (arch) { case 'arm64': return DarwinArch.arm64; case 'x86_64': return DarwinArch.x86_64; } throw Exception('Unsupported MacOS arch name "$arch"');}
String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch? darwinArch}) { switch (platform) { case TargetPlatform.android_arm: return 'android-arm'; case TargetPlatform.android_arm64: return 'android-arm64'; case TargetPlatform.android_x64: return 'android-x64'; case TargetPlatform.android_x86: return 'android-x86'; case TargetPlatform.ios: if (darwinArch != null) { return 'ios-${darwinArch.name}'; } return 'ios'; case TargetPlatform.darwin: if (darwinArch != null) { return 'darwin-${darwinArch.name}'; } return 'darwin'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.fuchsia_arm64: return 'fuchsia-arm64'; case TargetPlatform.fuchsia_x64: return 'fuchsia-x64'; case TargetPlatform.tester: return 'flutter-tester'; case TargetPlatform.web_javascript: return 'web-javascript'; case TargetPlatform.android: return 'android'; }}
TargetPlatform getTargetPlatformForName(String platform) { switch (platform) { case 'android': return TargetPlatform.android; case 'android-arm': return TargetPlatform.android_arm; case 'android-arm64': return TargetPlatform.android_arm64; case 'android-x64': return TargetPlatform.android_x64; case 'android-x86': return TargetPlatform.android_x86; case 'fuchsia-arm64': return TargetPlatform.fuchsia_arm64; case 'fuchsia-x64': return TargetPlatform.fuchsia_x64; case 'ios': return TargetPlatform.ios; case 'darwin': // For backward-compatibility and also for Tester, where it must match // host platform name (HostPlatform.darwin_x64) case 'darwin-x64': case 'darwin-arm64': return TargetPlatform.darwin; case 'linux-x64': return TargetPlatform.linux_x64; case 'linux-arm64': return TargetPlatform.linux_arm64; case 'windows-x64': return TargetPlatform.windows_x64; case 'web-javascript': return TargetPlatform.web_javascript; case 'flutter-tester': return TargetPlatform.tester; } throw Exception('Unsupported platform name "$platform"');}
AndroidArch getAndroidArchForName(String platform) { switch (platform) { case 'android-arm': return AndroidArch.armeabi_v7a; case 'android-arm64': return AndroidArch.arm64_v8a; case 'android-x64': return AndroidArch.x86_64; case 'android-x86': return AndroidArch.x86; } throw Exception('Unsupported Android arch name "$platform"');}
HostPlatform getCurrentHostPlatform() { if (globals.platform.isMacOS) { return HostPlatform.darwin_x64; } if (globals.platform.isLinux) { // support x64 and arm64 architecture. return globals.os.hostPlatform; } if (globals.platform.isWindows) { return HostPlatform.windows_x64; }
globals.printWarning('Unsupported host platform, defaulting to Linux');
return HostPlatform.linux_x64;}
FileSystemEntity getWebPlatformBinariesDirectory(Artifacts artifacts, WebRendererMode webRenderer) { return artifacts.getHostArtifact(HostArtifact.webPlatformKernelFolder);}
/// Returns the top-level build output directory.String getBuildDirectory([Config? config, FileSystem? fileSystem]) { // TODO(johnmccutchan): Stop calling this function as part of setting // up command line argument processing. final Config localConfig = config ?? globals.config; final FileSystem localFilesystem = fileSystem ?? globals.fs;
final String buildDir = localConfig.getValue('build-dir') as String? ?? 'build'; if (localFilesystem.path.isAbsolute(buildDir)) { throw Exception( 'build-dir config setting in ${globals.config.configPath} must be relative'); } return buildDir;}
/// Returns the Android build output directory.String getAndroidBuildDirectory() { // TODO(cbracken): move to android subdir. return getBuildDirectory();}
/// Returns the AOT build output directory.String getAotBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'aot');}
/// Returns the asset build output directory.String getAssetBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'flutter_assets');}
/// Returns the iOS build output directory.String getIosBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'ios');}
/// Returns the macOS build output directory.String getMacOSBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'macos');}
/// Returns the web build output directory.String getWebBuildDirectory([bool isWasm = false]) { return globals.fs.path.join(getBuildDirectory(), isWasm ? 'web_wasm' : 'web');}
/// Returns the Linux build output directory.String getLinuxBuildDirectory([TargetPlatform? targetPlatform]) { final String arch = (targetPlatform == null) ? _getCurrentHostPlatformArchName() : targetPlatform.simpleName; final String subDirs = 'linux/$arch'; return globals.fs.path.join(getBuildDirectory(), subDirs);}
/// Returns the Windows build output directory.String getWindowsBuildDirectory(TargetPlatform targetPlatform) { final String arch = targetPlatform.simpleName; return globals.fs.path.join(getBuildDirectory(), 'windows', arch);}
/// Returns the Fuchsia build output directory.String getFuchsiaBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'fuchsia');}
/// Defines specified via the `--dart-define` command-line option.////// These values are URI-encoded and then combined into a comma-separated string.const String kDartDefines = 'DartDefines';
/// The define to pass a [BuildMode].const String kBuildMode = 'BuildMode';
/// The define to pass whether we compile 64-bit android-arm code.const String kTargetPlatform = 'TargetPlatform';
/// The define to control what target file is used.const String kTargetFile = 'TargetFile';
/// Whether to enable or disable track widget creation.const String kTrackWidgetCreation = 'TrackWidgetCreation';
/// If provided, the frontend server will be started in JIT mode from this file.const String kFrontendServerStarterPath = 'FrontendServerStarterPath';
/// Additional configuration passed to the dart front end.////// This is expected to be a comma separated list of strings.const String kExtraFrontEndOptions = 'ExtraFrontEndOptions';
/// Additional configuration passed to gen_snapshot.////// This is expected to be a comma separated list of strings.const String kExtraGenSnapshotOptions = 'ExtraGenSnapshotOptions';
/// Whether the build should run gen_snapshot as a split aot build for deferred/// components.const String kDeferredComponents = 'DeferredComponents';
/// Whether to strip source code information out of release builds and where to save it.const String kSplitDebugInfo = 'SplitDebugInfo';
/// Alternative scheme for file URIs.////// May be used along with [kFileSystemRoots] to support a multi-root/// filesystem.const String kFileSystemScheme = 'FileSystemScheme';
/// Additional filesystem roots.////// If provided, must be used along with [kFileSystemScheme].const String kFileSystemRoots = 'FileSystemRoots';
/// The define to control what iOS architectures are built for.////// This is expected to be a space-delimited list of architectures. If not/// provided, defaults to arm64.const String kIosArchs = 'IosArchs';
/// The define to control what macOS architectures are built for.////// This is expected to be a space-delimited list of architectures. If not/// provided, defaults to x86_64 and arm64.////// Supported values are x86_64 and arm64.const String kDarwinArchs = 'DarwinArchs';
/// The define to control what Android architectures are built for.////// This is expected to be a space-delimited list of architectures.const String kAndroidArchs = 'AndroidArchs';
/// If the current build is `flutter build aar`.////// This is expected to be a boolean.////// If not provided, defaults to false.const String kIsAndroidLibrary = 'IsAndroidLibrary';
/// The define to control what min Android SDK version is built for.////// This is expected to be int.////// If not provided, defaults to `minSdkVersion` from gradle_utils.dart.////// This is passed in by flutter.groovy's invocation of `flutter assemble`.////// For more info, see:/// https://developer.android.com/ndk/guides/sdk-versions#minsdkversion/// https://developer.android.com/ndk/guides/other_build_systems#overviewconst String kMinSdkVersion = 'MinSdkVersion';
/// Path to the SDK root to be used as the isysroot.const String kSdkRoot = 'SdkRoot';
/// Whether to enable Dart obfuscation and where to save the symbol map.const String kDartObfuscation = 'DartObfuscation';
/// Whether to enable Native Assets.////// If true, native assets are built and the mapping for native assets lookup/// at runtime is embedded in the kernel file.////// If false, native assets are not built, and an empty mapping is embedded in/// the kernel file. Used for targets that trigger kernel builds but/// are not OS/architecture specific.////// Supported values are 'true' and 'false'.////// Defaults to 'true'.const String kNativeAssets = 'NativeAssets';
/// An output directory where one or more code-size measurements may be written.const String kCodeSizeDirectory = 'CodeSizeDirectory';
/// SHA identifier of the Apple developer code signing identity.////// Same as EXPANDED_CODE_SIGN_IDENTITY Xcode build setting./// Also discoverable via `security find-identity -p codesigning`.const String kCodesignIdentity = 'CodesignIdentity';
/// The build define controlling whether icon fonts should be stripped down to/// only the glyphs used by the application.const String kIconTreeShakerFlag = 'TreeShakeIcons';
/// The input key for an SkSL bundle path.const String kBundleSkSLPath = 'BundleSkSLPath';
/// The define to pass build nameconst String kBuildName = 'BuildName';
/// The app flavor to build.const String kFlavor = 'Flavor';
/// The define to pass build numberconst String kBuildNumber = 'BuildNumber';
/// The action Xcode is taking.////// Will be "build" when building and "install" when archiving.const String kXcodeAction = 'Action';
final Converter<String, String> _defineEncoder = utf8.encoder.fuse(base64.encoder);final Converter<String, String> _defineDecoder = base64.decoder.fuse(utf8.decoder);
/// Encode a List of dart defines in a base64 string.////// This encoding does not include `,`, which is used to distinguish/// the individual entries, nor does it include `%` which is often a/// control character on windows command lines.////// When decoding this string, it can be safely split on commas, since any/// user provided commands will still be encoded.////// If the presence of the `/` character ends up being an issue, this can/// be changed to use base32 instead.String encodeDartDefines(List<String> defines) { return defines.map(_defineEncoder.convert).join(',');}
List<String> decodeCommaSeparated(Map<String, String> environmentDefines, String key) { if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { return <String>[]; } return environmentDefines[key]! .split(',') .cast<String>() .toList();}
/// Dart defines are encoded inside [environmentDefines] as a comma-separated list.List<String> decodeDartDefines(Map<String, String> environmentDefines, String key) { if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { return <String>[]; } return environmentDefines[key]! .split(',') .map<Object>(_defineDecoder.convert) .cast<String>() .toList();}
/// The null safety runtime mode the app should be built in.enum NullSafetyMode { sound, unsound, /// The null safety mode was not detected. Only supported for 'flutter test'. autodetect,}
String _getCurrentHostPlatformArchName() { final HostPlatform hostPlatform = getCurrentHostPlatform(); return hostPlatform.platformName;}
String? _uncapitalize(String? s) { if (s == null || s.isEmpty) { return s; } return s.substring(0, 1).toLowerCase() + s.substring(1);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364// 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:convert/convert.dart';import 'package:crypto/crypto.dart';
import 'base/config.dart';import 'base/file_system.dart';import 'build_info.dart';import 'convert.dart';import 'globals.dart' as globals;
String get defaultMainPath => globals.fs.path.join('lib', 'main.dart');const String defaultManifestPath = 'pubspec.yaml';String get defaultDepfilePath => globals.fs.path.join(getBuildDirectory(), 'snapshot_blob.bin.d');
String getDefaultApplicationKernelPath({ required bool trackWidgetCreation,}) { return getKernelPathForTransformerOptions( globals.fs.path.join(getBuildDirectory(), 'app.dill'), trackWidgetCreation: trackWidgetCreation, );}
String getDefaultCachedKernelPath({ required bool trackWidgetCreation, required List<String> dartDefines, List<String> extraFrontEndOptions = const <String>[], FileSystem? fileSystem, Config? config,}) { final StringBuffer buffer = StringBuffer(); final List<String> cacheFrontEndOptions = extraFrontEndOptions.toList() ..removeWhere((String arg) => arg.startsWith('--enable-experiment=')); buffer.writeAll(dartDefines); buffer.writeAll(cacheFrontEndOptions); String buildPrefix = ''; if (buffer.isNotEmpty) { final String output = buffer.toString(); final Digest digest = md5.convert(utf8.encode(output)); buildPrefix = '${hex.encode(digest.bytes)}.'; } return getKernelPathForTransformerOptions( (fileSystem ?? globals.fs).path.join(getBuildDirectory( config ?? globals.config, fileSystem ?? globals.fs ), '${buildPrefix}cache.dill'), trackWidgetCreation: trackWidgetCreation, );}
String getKernelPathForTransformerOptions( String path, { required bool trackWidgetCreation,}) { if (trackWidgetCreation) { path += '.track.dill'; } return path;}
const String defaultPrivateKeyPath = 'privatekey.der';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217// 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:meta/meta.dart';import 'package:pool/pool.dart';
import 'asset.dart' hide defaultManifestPath;import 'base/common.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'build_info.dart';import 'build_system/build_system.dart';import 'build_system/depfile.dart';import 'build_system/targets/common.dart';import 'build_system/targets/scene_importer.dart';import 'build_system/targets/shader_compiler.dart';import 'bundle.dart';import 'cache.dart';import 'devfs.dart';import 'globals.dart' as globals;import 'project.dart';
/// Provides a `build` method that builds the bundle.class BundleBuilder { /// Builds the bundle for the given target platform. /// /// The default `mainPath` is `lib/main.dart`. /// The default `manifestPath` is `pubspec.yaml`. /// /// If [buildNativeAssets], native assets are built and the mapping for native /// assets lookup at runtime is embedded in the kernel file, otherwise an /// empty native assets mapping is embedded in the kernel file. Future<void> build({ required TargetPlatform platform, required BuildInfo buildInfo, FlutterProject? project, String? mainPath, String manifestPath = defaultManifestPath, String? applicationKernelFilePath, String? depfilePath, String? assetDirPath, bool buildNativeAssets = true, @visibleForTesting BuildSystem? buildSystem, }) async { project ??= FlutterProject.current(); mainPath ??= defaultMainPath; depfilePath ??= defaultDepfilePath; assetDirPath ??= getAssetBuildDirectory(); buildSystem ??= globals.buildSystem;
// If the precompiled flag was not passed, force us into debug mode. final Environment environment = Environment( projectDir: project.directory, outputDir: globals.fs.directory(assetDirPath), buildDir: project.dartTool.childDirectory('flutter_build'), cacheDir: globals.cache.getRoot(), flutterRootDir: globals.fs.directory(Cache.flutterRoot), engineVersion: globals.artifacts!.isLocalEngine ? null : globals.flutterVersion.engineRevision, defines: <String, String>{ // used by the KernelSnapshot target kTargetPlatform: getNameForTargetPlatform(platform), kTargetFile: mainPath, kDeferredComponents: 'false', ...buildInfo.toBuildSystemEnvironment(), if (!buildNativeAssets) kNativeAssets: 'false' }, artifacts: globals.artifacts!, fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, analytics: globals.analytics, platform: globals.platform, generateDartPluginRegistry: true, ); final Target target = buildInfo.mode == BuildMode.debug ? const CopyFlutterBundle() : const ReleaseCopyFlutterBundle(); final BuildResult result = await buildSystem.build(target, environment);
if (!result.success) { for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace : null, ); } throwToolExit('Failed to build bundle.'); } final Depfile depfile = Depfile(result.inputFiles, result.outputFiles); final File outputDepfile = globals.fs.file(depfilePath); if (!outputDepfile.parent.existsSync()) { outputDepfile.parent.createSync(recursive: true); } environment.depFileService.writeToFile(depfile, outputDepfile);
// Work around for flutter_tester placing kernel artifacts in odd places. if (applicationKernelFilePath != null) { final File outputDill = globals.fs.directory(assetDirPath).childFile('kernel_blob.bin'); if (outputDill.existsSync()) { outputDill.copySync(applicationKernelFilePath); } } return; }}
Future<AssetBundle?> buildAssets({ required String manifestPath, String? assetDirPath, String? packagesPath, TargetPlatform? targetPlatform, String? flavor,}) async { assetDirPath ??= getAssetBuildDirectory(); packagesPath ??= globals.fs.path.absolute('.packages');
// Build the asset bundle. final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle(); final int result = await assetBundle.build( manifestPath: manifestPath, packagesPath: packagesPath, targetPlatform: targetPlatform, flavor: flavor, ); if (result != 0) { return null; }
return assetBundle;}
Future<void> writeBundle( Directory bundleDir, Map<String, DevFSContent> assetEntries, Map<String, AssetKind> entryKinds, { Logger? loggerOverride, required TargetPlatform targetPlatform,}) async { loggerOverride ??= globals.logger; if (bundleDir.existsSync()) { try { bundleDir.deleteSync(recursive: true); } on FileSystemException catch (err) { loggerOverride.printWarning( 'Failed to clean up asset directory ${bundleDir.path}: $err\n' 'To clean build artifacts, use the command "flutter clean".' ); } } bundleDir.createSync(recursive: true);
final ShaderCompiler shaderCompiler = ShaderCompiler( processManager: globals.processManager, logger: globals.logger, fileSystem: globals.fs, artifacts: globals.artifacts!, );
final SceneImporter sceneImporter = SceneImporter( processManager: globals.processManager, logger: globals.logger, fileSystem: globals.fs, artifacts: globals.artifacts!, );
// Limit number of open files to avoid running out of file descriptors. final Pool pool = Pool(64); await Future.wait<void>( assetEntries.entries.map<Future<void>>((MapEntry<String, DevFSContent> entry) async { final PoolResource resource = await pool.request(); try { // This will result in strange looking files, for example files with `/` // on Windows or files that end up getting URI encoded such as `#.ext` // to `%23.ext`. However, we have to keep it this way since the // platform channels in the framework will URI encode these values, // and the native APIs will look for files this way. final File file = globals.fs.file(globals.fs.path.join(bundleDir.path, entry.key)); final AssetKind assetKind = entryKinds[entry.key] ?? AssetKind.regular; file.parent.createSync(recursive: true); final DevFSContent devFSContent = entry.value; if (devFSContent is DevFSFileContent) { final File input = devFSContent.file as File; bool doCopy = true; switch (assetKind) { case AssetKind.regular: break; case AssetKind.font: break; case AssetKind.shader: doCopy = !await shaderCompiler.compileShader( input: input, outputPath: file.path, target: ShaderTarget.sksl, // TODO(zanderso): configure impeller target when enabled. json: targetPlatform == TargetPlatform.web_javascript, ); case AssetKind.model: doCopy = !await sceneImporter.importScene( input: input, outputPath: file.path, ); } if (doCopy) { input.copySync(file.path); } } else { await file.writeAsBytes(await entry.value.contentsAsBytes()); } } finally { resource.release(); } }));}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351// 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:crypto/crypto.dart';import 'package:file/memory.dart';import 'package:meta/meta.dart';import 'package:process/process.dart';
import 'base/common.dart';import 'base/error_handling_io.dart';import 'base/file_system.dart';import 'base/io.dart' show HttpClient, HttpClientRequest, HttpClientResponse, HttpHeaders, HttpStatus, SocketException;import 'base/logger.dart';import 'base/net.dart';import 'base/os.dart' show OperatingSystemUtils;import 'base/platform.dart';import 'base/terminal.dart';import 'base/user_messages.dart';import 'convert.dart';import 'features.dart';
const String kFlutterRootEnvironmentVariableName = 'FLUTTER_ROOT'; // should point to //flutter/ (root of flutter/flutter repo)const String kFlutterEngineEnvironmentVariableName = 'FLUTTER_ENGINE'; // should point to //engine/src/ (root of flutter/engine repo)const String kSnapshotFileName = 'flutter_tools.snapshot'; // in //flutter/bin/cache/const String kFlutterToolsScriptFileName = 'flutter_tools.dart'; // in //flutter/packages/flutter_tools/bin/const String kFlutterEnginePackageName = 'sky_engine';
/// A tag for a set of development artifacts that need to be cached.class DevelopmentArtifact {
const DevelopmentArtifact._(this.name, {this.feature});
/// The name of the artifact. /// /// This should match the flag name in precache.dart. final String name;
/// A feature to control the visibility of this artifact. final Feature? feature;
/// Artifacts required for Android development. static const DevelopmentArtifact androidGenSnapshot = DevelopmentArtifact._('android_gen_snapshot', feature: flutterAndroidFeature); static const DevelopmentArtifact androidMaven = DevelopmentArtifact._('android_maven', feature: flutterAndroidFeature);
// Artifacts used for internal builds. static const DevelopmentArtifact androidInternalBuild = DevelopmentArtifact._('android_internal_build', feature: flutterAndroidFeature);
/// Artifacts required for iOS development. static const DevelopmentArtifact iOS = DevelopmentArtifact._('ios', feature: flutterIOSFeature);
/// Artifacts required for web development. static const DevelopmentArtifact web = DevelopmentArtifact._('web', feature: flutterWebFeature);
/// Artifacts required for desktop macOS. static const DevelopmentArtifact macOS = DevelopmentArtifact._('macos', feature: flutterMacOSDesktopFeature);
/// Artifacts required for desktop Windows. static const DevelopmentArtifact windows = DevelopmentArtifact._('windows', feature: flutterWindowsDesktopFeature);
/// Artifacts required for desktop Linux. static const DevelopmentArtifact linux = DevelopmentArtifact._('linux', feature: flutterLinuxDesktopFeature);
/// Artifacts required for Fuchsia. static const DevelopmentArtifact fuchsia = DevelopmentArtifact._('fuchsia', feature: flutterFuchsiaFeature);
/// Artifacts required for the Flutter Runner. static const DevelopmentArtifact flutterRunner = DevelopmentArtifact._('flutter_runner', feature: flutterFuchsiaFeature);
/// Artifacts required for any development platform. /// /// This does not need to be explicitly returned from requiredArtifacts as /// it will always be downloaded. static const DevelopmentArtifact universal = DevelopmentArtifact._('universal');
/// The values of DevelopmentArtifacts. static final List<DevelopmentArtifact> values = <DevelopmentArtifact>[ androidGenSnapshot, androidMaven, androidInternalBuild, iOS, web, macOS, windows, linux, fuchsia, universal, flutterRunner, ];
@override String toString() => 'Artifact($name)';}
/// A wrapper around the `bin/cache/` directory.////// This does not provide any artifacts by default. See [FlutterCache] for the default/// artifact set.////// ## Artifact mirrors////// Some environments cannot reach the Google Cloud Storage buckets and CIPD due/// to regional or corporate policies.////// To enable Flutter users in these environments, the Flutter tool supports/// custom artifact mirrors that the administrators of such environments may/// provide. To use an artifact mirror, the user defines the [kFlutterStorageBaseUrl]/// (`FLUTTER_STORAGE_BASE_URL`) environment variable that points to the mirror./// Flutter tool reads this variable and uses it instead of the default URLs.////// For more details on specific URLs used to download artifacts, see/// [storageBaseUrl] and [cipdBaseUrl].class Cache { /// [rootOverride] is configurable for testing. /// [artifacts] is configurable for testing. Cache({ @protected Directory? rootOverride, @protected List<ArtifactSet>? artifacts, required Logger logger, required FileSystem fileSystem, required Platform platform, required OperatingSystemUtils osUtils, }) : _rootOverride = rootOverride, _logger = logger, _fileSystem = fileSystem, _platform = platform, _osUtils = osUtils, _net = Net(logger: logger, platform: platform), _fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), _artifacts = artifacts ?? <ArtifactSet>[];
/// Create a [Cache] for testing. /// /// Defaults to a memory file system, fake platform, /// buffer logger, and no accessible artifacts. /// By default, the root cache directory path is "cache". factory Cache.test({ Directory? rootOverride, List<ArtifactSet>? artifacts, Logger? logger, FileSystem? fileSystem, Platform? platform, required ProcessManager processManager, }) { fileSystem ??= rootOverride?.fileSystem ?? MemoryFileSystem.test(); platform ??= FakePlatform(environment: <String, String>{}); logger ??= BufferLogger.test(); return Cache( rootOverride: rootOverride ?? fileSystem.directory('cache'), artifacts: artifacts ?? <ArtifactSet>[], logger: logger, fileSystem: fileSystem, platform: platform, osUtils: OperatingSystemUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, ), ); }
final Logger _logger; final Platform _platform; final FileSystem _fileSystem; final OperatingSystemUtils _osUtils; final Directory? _rootOverride; final List<ArtifactSet> _artifacts; final Net _net; final FileSystemUtils _fsUtils;
late final ArtifactUpdater _artifactUpdater = _createUpdater();
@visibleForTesting @protected void registerArtifact(ArtifactSet artifactSet) { _artifacts.add(artifactSet); }
/// This has to be lazy because it requires FLUTTER_ROOT to be initialized. ArtifactUpdater _createUpdater() { return ArtifactUpdater( operatingSystemUtils: _osUtils, logger: _logger, fileSystem: _fileSystem, tempStorage: getDownloadDir(), platform: _platform, httpClient: HttpClient(), allowedBaseUrls: <String>[ storageBaseUrl, realmlessStorageBaseUrl, cipdBaseUrl, ], ); }
static const List<String> _hostsBlockedInChina = <String> [ 'storage.googleapis.com', 'chrome-infra-packages.appspot.com', ];
// Initialized by FlutterCommandRunner on startup. // Explore making this field lazy to catch non-initialized access. static String? flutterRoot;
/// Determine the absolute and normalized path for the root of the current /// Flutter checkout. /// /// This method has a series of fallbacks for determining the repo location. The /// first success will immediately return the root without further checks. /// /// The order of these tests is: /// 1. FLUTTER_ROOT environment variable contains the path. /// 2. Platform script is a data URI scheme, returning `../..` to support /// tests run from `packages/flutter_tools`. /// 3. Platform script is package URI scheme, returning the grandparent directory /// of the package config file location from `packages/flutter_tools/.packages`. /// 4. Platform script file path is the snapshot path generated by `bin/flutter`, /// returning the grandparent directory from `bin/cache`. /// 5. Platform script file name is the entrypoint in `packages/flutter_tools/bin/flutter_tools.dart`, /// returning the 4th parent directory. /// 6. The current directory /// /// If an exception is thrown during any of these checks, an error message is /// printed and `.` is returned by default (6). static String defaultFlutterRoot({ required Platform platform, required FileSystem fileSystem, required UserMessages userMessages, }) { String normalize(String path) { return fileSystem.path.normalize(fileSystem.path.absolute(path)); } if (platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) { return normalize(platform.environment[kFlutterRootEnvironmentVariableName]!); } try { if (platform.script.scheme == 'data') { return normalize('../..'); // The tool is running as a test. } final String Function(String) dirname = fileSystem.path.dirname;
if (platform.script.scheme == 'package') { final String packageConfigPath = Uri.parse(platform.packageConfig!).toFilePath( windows: platform.isWindows, ); return normalize(dirname(dirname(dirname(packageConfigPath)))); }
if (platform.script.scheme == 'file') { final String script = platform.script.toFilePath( windows: platform.isWindows, ); if (fileSystem.path.basename(script) == kSnapshotFileName) { return normalize(dirname(dirname(fileSystem.path.dirname(script)))); } if (fileSystem.path.basename(script) == kFlutterToolsScriptFileName) { return normalize(dirname(dirname(dirname(dirname(script))))); } } } on Exception catch (error) { // There is currently no logger attached since this is computed at startup. // ignore: avoid_print print(userMessages.runnerNoRoot('$error')); } return normalize('.'); }
// Whether to cache artifacts for all platforms. Defaults to only caching // artifacts for the current platform. bool includeAllPlatforms = false;
// Names of artifacts which should be cached even if they would normally // be filtered out for the current platform. Set<String>? platformOverrideArtifacts;
// Whether to cache the unsigned mac binaries. Defaults to caching the signed binaries. bool useUnsignedMacBinaries = false;
// Whether the warning printed when a custom artifact URL is used is fatal. bool fatalStorageWarning = true;
static RandomAccessFile? _lock; static bool _lockEnabled = true;
/// Turn off the [lock]/[releaseLock] mechanism. /// /// This is used by the tests since they run simultaneously and all in one /// process and so it would be a mess if they had to use the lock. @visibleForTesting static void disableLocking() { _lockEnabled = false; }
/// Turn on the [lock]/[releaseLock] mechanism. /// /// This is used by the tests. @visibleForTesting static void enableLocking() { _lockEnabled = true; }
/// Check if lock acquired, skipping FLUTTER_ALREADY_LOCKED reentrant checks. /// /// This is used by the tests. @visibleForTesting static bool isLocked() { return _lock != null; }
/// Lock the cache directory. /// /// This happens while required artifacts are updated /// (see [FlutterCommandRunner.runCommand]). /// /// This uses normal POSIX flock semantics. Future<void> lock() async { if (!_lockEnabled) { return; } assert(_lock == null); final File lockFile = _fileSystem.file(_fileSystem.path.join(flutterRoot!, 'bin', 'cache', 'lockfile')); try { _lock = lockFile.openSync(mode: FileMode.write); } on FileSystemException catch (e) { _logger.printError('Failed to open or create the artifact cache lockfile: "$e"'); _logger.printError('Please ensure you have permissions to create or open ${lockFile.path}'); throwToolExit('Failed to open or create the lockfile'); } bool locked = false; bool printed = false; while (!locked) { try { _lock!.lockSync(); locked = true; } on FileSystemException { if (!printed) { _logger.printTrace('Waiting to be able to obtain lock of Flutter binary artifacts directory: ${_lock!.path}'); // This needs to go to stderr to avoid cluttering up stdout if a // parent process is collecting stdout (e.g. when calling "flutter // version --machine"). It's not really a "warning" though, so print it // in grey. Also, make sure that it isn't counted as a warning for // Logger.warningsAreFatal. _logger.printWarning( 'Waiting for another flutter command to release the startup lock...', color: TerminalColor.grey, fatal: false, ); printed = true; } await Future<void>.delayed(const Duration(milliseconds: 50)); } } }
/// Releases the lock. /// /// This happens automatically on startup (see [FlutterCommand.verifyThenRunCommand]) /// after the command's required artifacts are updated. void releaseLock() { if (!_lockEnabled || _lock == null) { return; } _lock!.closeSync(); _lock = null; }
/// Checks if the current process owns the lock for the cache directory at /// this very moment; throws a [StateError] if it doesn't. void checkLockAcquired() { if (_lockEnabled && _lock == null && _platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') { throw StateError( 'The current process does not own the lock for the cache directory. This is a bug in Flutter CLI tools.', ); } }
String get devToolsVersion { if (_devToolsVersion == null) { const String devToolsDirPath = 'dart-sdk/bin/resources/devtools'; final Directory devToolsDir = getCacheDir(devToolsDirPath, shouldCreate: false); if (!devToolsDir.existsSync()) { throw Exception('Could not find directory at ${devToolsDir.path}'); } final String versionFilePath = '${devToolsDir.path}/version.json'; final File versionFile = _fileSystem.file(versionFilePath); if (!versionFile.existsSync()) { throw Exception('Could not find file at $versionFilePath'); } final dynamic data = jsonDecode(versionFile.readAsStringSync()); if (data is! Map<String, Object?>) { throw Exception("Expected object of type 'Map<String, Object?>' but got one of type '${data.runtimeType}'"); } final Object? version = data['version']; if (version == null) { throw Exception('Could not parse DevTools version from $version'); } if (version is! String) { throw Exception("Could not parse DevTools version. Expected object of type 'String', but got one of type '${version.runtimeType}'"); } return _devToolsVersion = version; } return _devToolsVersion!; } String ? _devToolsVersion;
/// The current version of Dart used to build Flutter and run the tool. String get dartSdkVersion { if (_dartSdkVersion == null) { // Make the version string more customer-friendly. // Changes '2.1.0-dev.8.0.flutter-4312ae32' to '2.1.0 (build 2.1.0-dev.8.0 4312ae32)' final String justVersion = _platform.version.split(' ')[0]; _dartSdkVersion = justVersion.replaceFirstMapped(RegExp(r'(\d+\.\d+\.\d+)(.+)'), (Match match) { final String noFlutter = match[2]!.replaceAll('.flutter-', ' '); return '${match[1]} (build ${match[1]}$noFlutter)'; }); } return _dartSdkVersion!; } String? _dartSdkVersion;
/// The current version of Dart used to build Flutter and run the tool. String get dartSdkBuild { if (_dartSdkBuild == null) { // Make the version string more customer-friendly. // Changes '2.1.0-dev.8.0.flutter-4312ae32' to '2.1.0 (build 2.1.0-dev.8.0 4312ae32)' final String justVersion = _platform.version.split(' ')[0]; _dartSdkBuild = justVersion.replaceFirstMapped(RegExp(r'(\d+\.\d+\.\d+)(.+)'), (Match match) { final String noFlutter = match[2]!.replaceAll('.flutter-', ' '); return '${match[1]}$noFlutter'; }); } return _dartSdkBuild!; } String? _dartSdkBuild;
/// The current version of the Flutter engine the flutter tool will download. String get engineRevision { _engineRevision ??= getVersionFor('engine'); if (_engineRevision == null) { throwToolExit('Could not determine engine revision.'); } return _engineRevision!; } String? _engineRevision;
/// The "realm" for the storage URL. /// /// For production artifacts from Engine post-submit and release builds, /// this string will be empty, and the `storageBaseUrl` will be unmodified. /// When non-empty, this string will be appended to the `storageBaseUrl` after /// a '/'. For artifacts generated by Engine presubmits, the realm should be /// "flutter_archives_v2". String get storageRealm { _storageRealm ??= getRealmFor('engine'); if (_storageRealm == null) { throwToolExit('Could not determine engine realm.'); } return _storageRealm!; } String? _storageRealm;
/// The base for URLs that store Flutter engine artifacts that are fetched /// during the installation of the Flutter SDK. /// /// By default the base URL is https://storage.googleapis.com. However, if /// `FLUTTER_STORAGE_BASE_URL` environment variable ([kFlutterStorageBaseUrl]) /// is provided, the environment variable value is returned instead. /// /// See also: /// /// * [cipdBaseUrl], which determines how CIPD artifacts are fetched. /// * [Cache] class-level dartdocs that explain how artifact mirrors work. String get storageBaseUrl { String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; if (overrideUrl == null) { return storageRealm.isEmpty ? 'https://storage.googleapis.com' : 'https://storage.googleapis.com/$storageRealm'; } // verify that this is a valid URI. overrideUrl = storageRealm.isEmpty ? overrideUrl : '$overrideUrl/$storageRealm'; try { Uri.parse(overrideUrl); } on FormatException catch (err) { throwToolExit('"$kFlutterStorageBaseUrl" contains an invalid URL:\n$err'); } _maybeWarnAboutStorageOverride(overrideUrl); return overrideUrl; }
String get realmlessStorageBaseUrl { return storageRealm.isEmpty ? storageBaseUrl : storageBaseUrl.replaceAll('/$storageRealm', ''); }
/// The base for URLs that store Flutter engine artifacts in CIPD. /// /// For some platforms, such as Web and Fuchsia, CIPD artifacts are fetched /// during the installation of the Flutter SDK, in addition to those fetched /// from [storageBaseUrl]. /// /// By default the base URL is https://chrome-infra-packages.appspot.com/dl. /// However, if `FLUTTER_STORAGE_BASE_URL` environment variable is provided /// ([kFlutterStorageBaseUrl]), then the following value is used: /// /// FLUTTER_STORAGE_BASE_URL/flutter_infra_release/cipd /// /// See also: /// /// * [storageBaseUrl], which determines how engine artifacts stored in the /// Google Cloud Storage buckets are fetched. /// * https://chromium.googlesource.com/infra/luci/luci-go/+/refs/heads/main/cipd, /// which contains information about CIPD. /// * [Cache] class-level dartdocs that explain how artifact mirrors work. String get cipdBaseUrl { final String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; if (overrideUrl == null) { return 'https://chrome-infra-packages.appspot.com/dl'; }
final Uri original; try { original = Uri.parse(overrideUrl); } on FormatException catch (err) { throwToolExit('"$kFlutterStorageBaseUrl" contains an invalid URL:\n$err'); }
final String cipdOverride = original.replace( pathSegments: <String>[ ...original.pathSegments, 'flutter_infra_release', 'cipd', ], ).toString(); return cipdOverride; }
bool _hasWarnedAboutStorageOverride = false;
void _maybeWarnAboutStorageOverride(String overrideUrl) { if (_hasWarnedAboutStorageOverride) { return; } _logger.printWarning( 'Flutter assets will be downloaded from $overrideUrl. Make sure you trust this source!', emphasis: true, fatal: false, ); _hasWarnedAboutStorageOverride = true; }
/// Return the top-level directory in the cache; this is `bin/cache`. Directory getRoot() { if (_rootOverride != null) { return _fileSystem.directory(_fileSystem.path.join(_rootOverride.path, 'bin', 'cache')); } else { return _fileSystem.directory(_fileSystem.path.join(flutterRoot!, 'bin', 'cache')); } }
String getHostPlatformArchName() { return _osUtils.hostPlatform.platformName; }
/// Return a directory in the cache dir. For `pkg`, this will return `bin/cache/pkg`. /// /// When [shouldCreate] is true, the cache directory at [name] will be created /// if it does not already exist. Directory getCacheDir(String name, { bool shouldCreate = true }) { final Directory dir = _fileSystem.directory(_fileSystem.path.join(getRoot().path, name)); if (!dir.existsSync() && shouldCreate) { dir.createSync(recursive: true); _osUtils.chmod(dir, '755'); } return dir; }
/// Return the top-level directory for artifact downloads. Directory getDownloadDir() => getCacheDir('downloads');
/// Return the top-level mutable directory in the cache; this is `bin/cache/artifacts`. Directory getCacheArtifacts() => getCacheDir('artifacts');
/// Location of LICENSE file. File getLicenseFile() => _fileSystem.file(_fileSystem.path.join(flutterRoot!, 'LICENSE'));
/// Get a named directory from with the cache's artifact directory; for example, /// `material_fonts` would return `bin/cache/artifacts/material_fonts`. Directory getArtifactDirectory(String name) { return getCacheArtifacts().childDirectory(name); }
MapEntry<String, String> get dyLdLibEntry { if (_dyLdLibEntry != null) { return _dyLdLibEntry!; } final List<String> paths = <String>[]; for (final ArtifactSet artifact in _artifacts) { final Map<String, String> env = artifact.environment; if (!env.containsKey('DYLD_LIBRARY_PATH')) { continue; } final String path = env['DYLD_LIBRARY_PATH']!; if (path.isEmpty) { continue; } paths.add(path); } _dyLdLibEntry = MapEntry<String, String>('DYLD_LIBRARY_PATH', paths.join(':')); return _dyLdLibEntry!; } MapEntry<String, String>? _dyLdLibEntry;
/// The web sdk has to be co-located with the dart-sdk so that they can share source /// code. Directory getWebSdkDirectory() { return getRoot().childDirectory('flutter_web_sdk'); }
String? getVersionFor(String artifactName) { final File versionFile = _fileSystem.file(_fileSystem.path.join( _rootOverride?.path ?? flutterRoot!, 'bin', 'internal', '$artifactName.version', )); return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null; }
String? getRealmFor(String artifactName) { final File realmFile = _fileSystem.file(_fileSystem.path.join( _rootOverride?.path ?? flutterRoot!, 'bin', 'internal', '$artifactName.realm', )); return realmFile.existsSync() ? realmFile.readAsStringSync().trim() : ''; }
/// Delete all stamp files maintained by the cache. void clearStampFiles() { try { getStampFileFor('flutter_tools').deleteSync(); for (final ArtifactSet artifact in _artifacts) { final File file = getStampFileFor(artifact.stampName); ErrorHandlingFileSystem.deleteIfExists(file); } } on FileSystemException catch (err) { _logger.printWarning('Failed to delete some stamp files: $err'); } }
/// Read the stamp for [artifactName]. /// /// If the file is missing or cannot be parsed, returns `null`. String? getStampFor(String artifactName) { final File stampFile = getStampFileFor(artifactName); if (!stampFile.existsSync()) { return null; } try { return stampFile.readAsStringSync().trim(); } on FileSystemException { return null; } }
void setStampFor(String artifactName, String version) { getStampFileFor(artifactName).writeAsStringSync(version); }
File getStampFileFor(String artifactName) { return _fileSystem.file(_fileSystem.path.join(getRoot().path, '$artifactName.stamp')); }
/// Returns `true` if either [entity] is older than the tools stamp or if /// [entity] doesn't exist. bool isOlderThanToolsStamp(FileSystemEntity entity) { final File flutterToolsStamp = getStampFileFor('flutter_tools'); return _fsUtils.isOlderThanReference( entity: entity, referenceFile: flutterToolsStamp, ); }
Future<bool> isUpToDate() async { for (final ArtifactSet artifact in _artifacts) { if (!await artifact.isUpToDate(_fileSystem)) { return false; } } return true; }
/// Update the cache to contain all `requiredArtifacts`. Future<void> updateAll(Set<DevelopmentArtifact> requiredArtifacts, {bool offline = false}) async { if (!_lockEnabled) { return; } for (final ArtifactSet artifact in _artifacts) { if (!requiredArtifacts.contains(artifact.developmentArtifact)) { _logger.printTrace('Artifact $artifact is not required, skipping update.'); continue; } if (await artifact.isUpToDate(_fileSystem)) { continue; } try { await artifact.update(_artifactUpdater, _logger, _fileSystem, _osUtils, offline: offline); } on SocketException catch (e) { if (_hostsBlockedInChina.contains(e.address?.host)) { _logger.printError( 'Failed to retrieve Flutter tool dependencies: ${e.message}.\n' "If you're in China, please see this page: " 'https://flutter.dev/community/china', emphasis: true, ); } rethrow; } } }
Future<bool> areRemoteArtifactsAvailable({ String? engineVersion, bool includeAllPlatforms = true, }) async { final bool includeAllPlatformsState = this.includeAllPlatforms; bool allAvailable = true; this.includeAllPlatforms = includeAllPlatforms; for (final ArtifactSet cachedArtifact in _artifacts) { if (cachedArtifact is EngineCachedArtifact) { allAvailable &= await cachedArtifact.checkForArtifacts(engineVersion); } } this.includeAllPlatforms = includeAllPlatformsState; return allAvailable; }
Future<bool> doesRemoteExist(String message, Uri url) async { final Status status = _logger.startProgress( message, ); bool exists; try { exists = await _net.doesRemoteFileExist(url); } finally { status.stop(); } return exists; }}
/// Representation of a set of artifacts used by the tool.abstract class ArtifactSet { ArtifactSet(this.developmentArtifact);
/// The development artifact. final DevelopmentArtifact developmentArtifact;
/// [true] if the artifact is up to date. Future<bool> isUpToDate(FileSystem fileSystem);
/// The environment variables (if any) required to consume the artifacts. Map<String, String> get environment { return const <String, String>{}; }
/// Updates the artifact. Future<void> update( ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false} );
/// The canonical name of the artifact. String get name;
// The name of the stamp file. Defaults to the same as the // artifact name. String get stampName => name;}
/// An artifact set managed by the cache.abstract class CachedArtifact extends ArtifactSet { CachedArtifact( this.name, this.cache, DevelopmentArtifact developmentArtifact, ) : super(developmentArtifact);
final Cache cache;
@override final String name;
@override String get stampName => name;
Directory get location => cache.getArtifactDirectory(name);
String? get version => cache.getVersionFor(name);
// Whether or not to bypass normal platform filtering for this artifact. bool get ignorePlatformFiltering { return cache.includeAllPlatforms || (cache.platformOverrideArtifacts != null && cache.platformOverrideArtifacts!.contains(developmentArtifact.name)); }
@override Future<bool> isUpToDate(FileSystem fileSystem) async { if (!location.existsSync()) { return false; } if (version != cache.getStampFor(stampName)) { return false; } return isUpToDateInner(fileSystem); }
@override Future<void> update( ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false} ) async { if (!location.existsSync()) { try { location.createSync(recursive: true); } on FileSystemException catch (err) { logger.printError(err.toString()); throwToolExit( 'Failed to create directory for flutter cache at ${location.path}. ' 'Flutter may be missing permissions in its cache directory.' ); } } await updateInner(artifactUpdater, fileSystem, operatingSystemUtils); try { if (version == null) { logger.printWarning( 'No known version for the artifact name "$name". ' 'Flutter can continue, but the artifact may be re-downloaded on ' 'subsequent invocations until the problem is resolved.', ); } else { cache.setStampFor(stampName, version!); } } on FileSystemException catch (err) { logger.printWarning( 'The new artifact "$name" was downloaded, but Flutter failed to update ' 'its stamp file, receiving the error "$err". ' 'Flutter can continue, but the artifact may be re-downloaded on ' 'subsequent invocations until the problem is resolved.', ); } artifactUpdater.removeDownloadedFiles(); }
/// Hook method for extra checks for being up-to-date. bool isUpToDateInner(FileSystem fileSystem) => true;
Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, );}
abstract class EngineCachedArtifact extends CachedArtifact { EngineCachedArtifact( this.stampName, Cache cache, DevelopmentArtifact developmentArtifact, ) : super('engine', cache, developmentArtifact);
@override final String stampName;
/// Return a list of (directory path, download URL path) tuples. List<List<String>> getBinaryDirs();
/// A list of cache directory paths to which the LICENSE file should be copied. List<String> getLicenseDirs();
/// A list of the dart package directories to download. List<String> getPackageDirs();
@override bool isUpToDateInner(FileSystem fileSystem) { final Directory pkgDir = cache.getCacheDir('pkg'); for (final String pkgName in getPackageDirs()) { final String pkgPath = fileSystem.path.join(pkgDir.path, pkgName); if (!fileSystem.directory(pkgPath).existsSync()) { return false; } }
for (final List<String> toolsDir in getBinaryDirs()) { final Directory dir = fileSystem.directory(fileSystem.path.join(location.path, toolsDir[0])); if (!dir.existsSync()) { return false; } }
for (final String licenseDir in getLicenseDirs()) { final File file = fileSystem.file(fileSystem.path.join(location.path, licenseDir, 'LICENSE')); if (!file.existsSync()) { return false; } } return true; }
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { final String url = '${cache.storageBaseUrl}/flutter_infra_release/flutter/$version/';
final Directory pkgDir = cache.getCacheDir('pkg'); for (final String pkgName in getPackageDirs()) { await artifactUpdater.downloadZipArchive('Downloading package $pkgName...', Uri.parse('$url$pkgName.zip'), pkgDir); }
for (final List<String> toolsDir in getBinaryDirs()) { final String cacheDir = toolsDir[0]; final String urlPath = toolsDir[1]; final Directory dir = fileSystem.directory(fileSystem.path.join(location.path, cacheDir));
// Avoid printing things like 'Downloading linux-x64 tools...' multiple times. final String friendlyName = urlPath.replaceAll('/artifacts.zip', '').replaceAll('.zip', ''); await artifactUpdater.downloadZipArchive('Downloading $friendlyName tools...', Uri.parse(url + urlPath), dir);
_makeFilesExecutable(dir, operatingSystemUtils);
final File frameworkZip = fileSystem.file(fileSystem.path.join(dir.path, 'FlutterMacOS.framework.zip')); if (frameworkZip.existsSync()) { final Directory framework = fileSystem.directory(fileSystem.path.join(dir.path, 'FlutterMacOS.framework')); ErrorHandlingFileSystem.deleteIfExists(framework, recursive: true); framework.createSync(); operatingSystemUtils.unzip(frameworkZip, framework); } }
final File licenseSource = cache.getLicenseFile(); for (final String licenseDir in getLicenseDirs()) { final String licenseDestinationPath = fileSystem.path.join(location.path, licenseDir, 'LICENSE'); await licenseSource.copy(licenseDestinationPath); } }
Future<bool> checkForArtifacts(String? engineVersion) async { engineVersion ??= version; final String url = '${cache.storageBaseUrl}/flutter_infra_release/flutter/$engineVersion/';
bool exists = false; for (final String pkgName in getPackageDirs()) { exists = await cache.doesRemoteExist('Checking package $pkgName is available...', Uri.parse('$url$pkgName.zip')); if (!exists) { return false; } }
for (final List<String> toolsDir in getBinaryDirs()) { final String cacheDir = toolsDir[0]; final String urlPath = toolsDir[1]; exists = await cache.doesRemoteExist('Checking $cacheDir tools are available...', Uri.parse(url + urlPath)); if (!exists) { return false; } } return true; }
void _makeFilesExecutable(Directory dir, OperatingSystemUtils operatingSystemUtils) { operatingSystemUtils.chmod(dir, 'a+r,a+x'); for (final File file in dir.listSync(recursive: true).whereType<File>()) { final FileStat stat = file.statSync(); final bool isUserExecutable = ((stat.mode >> 6) & 0x1) == 1; if (file.basename == 'flutter_tester' || isUserExecutable) { // Make the file readable and executable by all users. operatingSystemUtils.chmod(file, 'a+r,a+x'); } } }}
/// An API for downloading and un-archiving artifacts, such as engine binaries or/// additional source code.class ArtifactUpdater { ArtifactUpdater({ required OperatingSystemUtils operatingSystemUtils, required Logger logger, required FileSystem fileSystem, required Directory tempStorage, required HttpClient httpClient, required Platform platform, required List<String> allowedBaseUrls, }) : _operatingSystemUtils = operatingSystemUtils, _httpClient = httpClient, _logger = logger, _fileSystem = fileSystem, _tempStorage = tempStorage, _platform = platform, _allowedBaseUrls = allowedBaseUrls;
/// The number of times the artifact updater will repeat the artifact download loop. static const int _kRetryCount = 2;
final Logger _logger; final OperatingSystemUtils _operatingSystemUtils; final FileSystem _fileSystem; final Directory _tempStorage; final HttpClient _httpClient; final Platform _platform;
/// Artifacts should only be downloaded from URLs that use one of these /// prefixes. /// /// [ArtifactUpdater] will issue a warning if an attempt to download from a /// non-compliant URL is made. final List<String> _allowedBaseUrls;
/// Keep track of the files we've downloaded for this execution so we /// can delete them after completion. We don't delete them right after /// extraction in case [update] is interrupted, so we can restart without /// starting from scratch. @visibleForTesting final List<File> downloadedFiles = <File>[];
/// These filenames, should they exist after extracting an archive, should be deleted. static const Set<String> _denylistedBasenames = <String>{'entitlements.txt', 'without_entitlements.txt'}; void _removeDenylistedFiles(Directory directory) { for (final FileSystemEntity entity in directory.listSync(recursive: true)) { if (entity is! File) { continue; } if (_denylistedBasenames.contains(entity.basename)) { entity.deleteSync(); } } }
/// Download a zip archive from the given [url] and unzip it to [location]. Future<void> downloadZipArchive( String message, Uri url, Directory location, ) { return _downloadArchive( message, url, location, _operatingSystemUtils.unzip, ); }
/// Download a gzipped tarball from the given [url] and unpack it to [location]. Future<void> downloadZippedTarball(String message, Uri url, Directory location) { return _downloadArchive( message, url, location, _operatingSystemUtils.unpack, ); }
/// Download an archive from the given [url] and unzip it to [location]. Future<void> _downloadArchive( String message, Uri url, Directory location, void Function(File, Directory) extractor, ) async { final String downloadPath = flattenNameSubdirs(url, _fileSystem); final File tempFile = _createDownloadFile(downloadPath); Status status; int retries = _kRetryCount;
while (retries > 0) { status = _logger.startProgress( message, ); try { _ensureExists(tempFile.parent); if (tempFile.existsSync()) { tempFile.deleteSync(); } await _download(url, tempFile, status);
if (!tempFile.existsSync()) { throw Exception('Did not find downloaded file ${tempFile.path}'); } } on Exception catch (err) { _logger.printTrace(err.toString()); retries -= 1; if (retries == 0) { throwToolExit( 'Failed to download $url. Ensure you have network connectivity and then try again.\n$err', ); } continue; } on ArgumentError catch (error) { final String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl]; if (overrideUrl != null && url.toString().contains(overrideUrl)) { _logger.printError(error.toString()); throwToolExit( 'The value of $kFlutterStorageBaseUrl ($overrideUrl) could not be ' 'parsed as a valid url. Please see https://flutter.dev/community/china ' 'for an example of how to use it.\n' 'Full URL: $url', exitCode: kNetworkProblemExitCode, ); } // This error should not be hit if there was not a storage URL override, allow the // tool to crash. rethrow; } finally { status.stop(); } /// Unzipping multiple file into a directory will not remove old files /// from previous versions that are not present in the new bundle. final Directory destination = location.childDirectory( tempFile.fileSystem.path.basenameWithoutExtension(tempFile.path) ); try { ErrorHandlingFileSystem.deleteIfExists( destination, recursive: true, ); } on FileSystemException catch (error) { // Error that indicates another program has this file open and that it // cannot be deleted. For the cache, this is either the analyzer reading // the sky_engine package or a running flutter_tester device. const int kSharingViolation = 32; if (_platform.isWindows && error.osError?.errorCode == kSharingViolation) { throwToolExit( 'Failed to delete ${destination.path} because the local file/directory is in use ' 'by another process. Try closing any running IDEs or editors and trying ' 'again' ); } } _ensureExists(location);
try { extractor(tempFile, location); } on Exception catch (err) { retries -= 1; if (retries == 0) { throwToolExit( 'Flutter could not download and/or extract $url. Ensure you have ' 'network connectivity and all of the required dependencies listed at ' 'flutter.dev/setup.\nThe original exception was: $err.' ); } _deleteIgnoringErrors(tempFile); continue; } _removeDenylistedFiles(location); return; } }
/// Download bytes from [url], throwing non-200 responses as an exception. /// /// Validates that the md5 of the content bytes matches the provided /// `x-goog-hash` header, if present. This header should contain an md5 hash /// if the download source is Google cloud storage. /// /// See also: /// * https://cloud.google.com/storage/docs/xml-api/reference-headers#xgooghash Future<void> _download(Uri url, File file, Status status) async { final bool isAllowedUrl = _allowedBaseUrls.any((String baseUrl) => url.toString().startsWith(baseUrl));
// In tests make this a hard failure. assert( isAllowedUrl, 'URL not allowed: $url\n' 'Allowed URLs must be based on one of: ${_allowedBaseUrls.join(', ')}', );
// In production, issue a warning but allow the download to proceed. if (!isAllowedUrl) { status.pause(); _logger.printWarning( 'Downloading an artifact that may not be reachable in some environments (e.g. firewalled environments): $url\n' 'This should not have happened. This is likely a Flutter SDK bug. Please file an issue at https://github.com/flutter/flutter/issues/new?template=1_activation.yml' ); status.resume(); }
final HttpClientRequest request = await _httpClient.getUrl(url); final HttpClientResponse response = await request.close(); if (response.statusCode != HttpStatus.ok) { throw Exception(response.statusCode); }
final String? md5Hash = _expectedMd5(response.headers); ByteConversionSink? inputSink; late StreamController<Digest> digests; if (md5Hash != null) { _logger.printTrace('Content $url md5 hash: $md5Hash'); digests = StreamController<Digest>(); inputSink = md5.startChunkedConversion(digests); } final RandomAccessFile randomAccessFile = file.openSync(mode: FileMode.writeOnly); await response.forEach((List<int> chunk) { inputSink?.add(chunk); randomAccessFile.writeFromSync(chunk); }); randomAccessFile.closeSync(); if (inputSink != null) { inputSink.close(); final Digest digest = await digests.stream.last; final String rawDigest = base64.encode(digest.bytes); if (rawDigest != md5Hash) { throw Exception( 'Expected $url to have md5 checksum $md5Hash, but was $rawDigest. This ' 'may indicate a problem with your connection to the Flutter backend servers. ' 'Please re-try the download after confirming that your network connection is ' 'stable.' ); } } }
String? _expectedMd5(HttpHeaders httpHeaders) { final List<String>? values = httpHeaders['x-goog-hash']; if (values == null) { return null; } String? rawMd5Hash; for (final String value in values) { if (value.startsWith('md5=')) { rawMd5Hash = value; break; } } if (rawMd5Hash == null) { return null; } final List<String> segments = rawMd5Hash.split('md5='); if (segments.length < 2) { return null; } final String md5Hash = segments[1]; if (md5Hash.isEmpty) { return null; } return md5Hash; }
/// Create a temporary file and invoke [onTemporaryFile] with the file as /// argument, then add the temporary file to the [downloadedFiles]. File _createDownloadFile(String name) { final File tempFile = _fileSystem.file(_fileSystem.path.join(_tempStorage.path, name)); downloadedFiles.add(tempFile); return tempFile; }
/// Create the given [directory] and parents, as necessary. void _ensureExists(Directory directory) { if (!directory.existsSync()) { directory.createSync(recursive: true); } }
/// Clear any zip/gzip files downloaded. void removeDownloadedFiles() { for (final File file in downloadedFiles) { if (!file.existsSync()) { continue; } try { file.deleteSync(); } on FileSystemException catch (e) { _logger.printWarning('Failed to delete "${file.path}". Please delete manually. $e'); continue; } for (Directory directory = file.parent; directory.absolute.path != _tempStorage.absolute.path; directory = directory.parent) { // Handle race condition when the directory is deleted before this step if (!directory.existsSync()) { break; } if (directory.listSync().isNotEmpty) { break; } _deleteIgnoringErrors(directory); } } }
static void _deleteIgnoringErrors(FileSystemEntity entity) { if (!entity.existsSync()) { return; } try { entity.deleteSync(); } on FileSystemException { // Ignore errors. } }}
@visibleForTestingString flattenNameSubdirs(Uri url, FileSystem fileSystem) { final List<String> pieces = <String>[url.host, ...url.pathSegments]; final Iterable<String> convertedPieces = pieces.map<String>(_flattenNameNoSubdirs); return fileSystem.path.joinAll(convertedPieces);}
/// Given a name containing slashes, colons, and backslashes, expand it into/// something that doesn't.String _flattenNameNoSubdirs(String fileName) { final List<int> replacedCodeUnits = <int>[ for (final int codeUnit in fileName.codeUnits) ..._flattenNameSubstitutions[codeUnit] ?? <int>[codeUnit], ]; return String.fromCharCodes(replacedCodeUnits);}
// Many characters are problematic in filenames, especially on Windows.final Map<int, List<int>> _flattenNameSubstitutions = <int, List<int>>{ r'@'.codeUnitAt(0): '@@'.codeUnits, r'/'.codeUnitAt(0): '@s@'.codeUnits, r'\'.codeUnitAt(0): '@bs@'.codeUnits, r':'.codeUnitAt(0): '@c@'.codeUnits, r'%'.codeUnitAt(0): '@per@'.codeUnits, r'*'.codeUnitAt(0): '@ast@'.codeUnits, r'<'.codeUnitAt(0): '@lt@'.codeUnits, r'>'.codeUnitAt(0): '@gt@'.codeUnits, r'"'.codeUnitAt(0): '@q@'.codeUnits, r'|'.codeUnitAt(0): '@pip@'.codeUnits, r'?'.codeUnitAt(0): '@ques@'.codeUnits,};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125// 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:pub_semver/pub_semver.dart';
import 'base/logger.dart';import 'build_info.dart';import 'cmake_project.dart';
/// Extracts the `BINARY_NAME` from a project's CMake file.////// Returns `null` if it cannot be found.String? getCmakeExecutableName(CmakeBasedProject project) { if (!project.cmakeFile.existsSync()) { return null; } final RegExp nameSetPattern = RegExp(r'^\s*set\(BINARY_NAME\s*"(.*)"\s*\)\s*$'); for (final String line in project.cmakeFile.readAsLinesSync()) { final RegExpMatch? match = nameSetPattern.firstMatch(line); if (match != null) { return match.group(1); } } return null;}
String _escapeBackslashes(String s) { return s.replaceAll(r'\', r'\\');}
String _determineVersionString(CmakeBasedProject project, BuildInfo buildInfo) { // Prefer the build arguments for version information. final String buildName = buildInfo.buildName ?? project.parent.manifest.buildName ?? '1.0.0'; final String? buildNumber = buildInfo.buildName != null ? buildInfo.buildNumber : (buildInfo.buildNumber ?? project.parent.manifest.buildNumber);
return buildNumber != null ? '$buildName+$buildNumber' : buildName;}
Version _determineVersion(CmakeBasedProject project, BuildInfo buildInfo, Logger logger) { final String version = _determineVersionString(project, buildInfo); try { return Version.parse(version); } on FormatException { logger.printWarning('Warning: could not parse version $version, defaulting to 1.0.0.');
return Version(1, 0, 0); }}
/// Attempts to map a Dart version's build identifier (the part after a +) into/// a single integer. Returns null for complex build identifiers like `foo` or `1.2`.int? _tryDetermineBuildVersion(Version version) { if (version.build.isEmpty) { return 0; }
if (version.build.length != 1) { return null; }
final Object buildIdentifier = version.build.first; return buildIdentifier is int ? buildIdentifier : null;}
/// Writes a generated CMake configuration file for [project], including/// variables expected by the build template and an environment variable list/// for calling back into Flutter.void writeGeneratedCmakeConfig( String flutterRoot, CmakeBasedProject project, BuildInfo buildInfo, Map<String, String> environment, Logger logger,) { // Only a limited set of variables are needed by the CMake files themselves, // the rest are put into a list to pass to the re-entrant build step. final String escapedFlutterRoot = _escapeBackslashes(flutterRoot); final String escapedProjectDir = _escapeBackslashes(project.parent.directory.path);
final Version version = _determineVersion(project, buildInfo, logger); final int? buildVersion = _tryDetermineBuildVersion(version);
// Since complex Dart build identifiers cannot be converted into integers, // different Dart versions may be converted into the same Windows numeric version. // Warn the user as some Windows installers, like MSI, don't update files if their versions are equal. if (buildVersion == null && project is WindowsProject) { final String buildIdentifier = version.build.join('.'); logger.printWarning( 'Warning: build identifier $buildIdentifier in version $version is not numeric ' 'and cannot be converted into a Windows build version number. Defaulting to 0.\n' 'This may cause issues with Windows installers.' ); }
final StringBuffer buffer = StringBuffer('''# Generated code do not commit.file(TO_CMAKE_PATH "$escapedFlutterRoot" FLUTTER_ROOT)file(TO_CMAKE_PATH "$escapedProjectDir" PROJECT_DIR)
set(FLUTTER_VERSION "$version" PARENT_SCOPE)set(FLUTTER_VERSION_MAJOR ${version.major} PARENT_SCOPE)set(FLUTTER_VERSION_MINOR ${version.minor} PARENT_SCOPE)set(FLUTTER_VERSION_PATCH ${version.patch} PARENT_SCOPE)set(FLUTTER_VERSION_BUILD ${buildVersion ?? 0} PARENT_SCOPE)
# Environment variables to pass to tool_backend.shlist(APPEND FLUTTER_TOOL_ENVIRONMENT "FLUTTER_ROOT=$escapedFlutterRoot" "PROJECT_DIR=$escapedProjectDir"'''); environment.forEach((String key, String value) { final String configValue = _escapeBackslashes(value); buffer.writeln(' "$key=$configValue"'); }); buffer.writeln(')');
project.generatedCmakeConfigFile ..createSync(recursive: true) ..writeAsStringSync(buffer.toString());}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144// 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 'base/file_system.dart';import 'base/utils.dart';import 'platform_plugins.dart';import 'project.dart';
/// Represents a CMake-based sub-project.////// This defines interfaces common to Windows and Linux projects.abstract class CmakeBasedProject { /// The parent of this project. FlutterProject get parent;
/// Whether the subproject (either Windows or Linux) exists in the Flutter project. bool existsSync();
/// The native project CMake specification. File get cmakeFile;
/// Contains definitions for the Flutter library and the tool. File get managedCmakeFile;
/// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for /// the build. File get generatedCmakeConfigFile;
/// Included CMake with rules and variables for plugin builds. File get generatedPluginCmakeFile;
/// The directory to write plugin symlinks. Directory get pluginSymlinkDirectory;}
/// The Windows sub project.class WindowsProject extends FlutterProjectPlatform implements CmakeBasedProject { WindowsProject.fromFlutter(this.parent);
@override final FlutterProject parent;
@override String get pluginConfigKey => WindowsPlugin.kConfigKey;
String get _childDirectory => 'windows';
@override bool existsSync() => _editableDirectory.existsSync() && cmakeFile.existsSync();
@override File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt');
@override File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt');
@override File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake');
@override File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake');
/// The native entrypoint's CMake specification. File get runnerCmakeFile => runnerDirectory.childFile('CMakeLists.txt');
/// The native entrypoint's file that adds Flutter to the window. File get runnerFlutterWindowFile => runnerDirectory.childFile('flutter_window.cpp');
/// The native entrypoint's resource file. Used to configure things /// like the application icon, name, and version. File get runnerResourceFile => runnerDirectory.childFile('Runner.rc');
@override Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks');
Directory get _editableDirectory => parent.directory.childDirectory(_childDirectory);
/// The directory in the project that is managed by Flutter. As much as /// possible, files that are edited by Flutter tooling after initial project /// creation should live here. Directory get managedDirectory => _editableDirectory.childDirectory('flutter');
/// The subdirectory of [managedDirectory] that contains files that are /// generated on the fly. All generated files that are not intended to be /// checked in should live here. Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');
/// The directory in the project that is owned by the app. As much as /// possible, Flutter tooling should not edit files in this directory after /// initial project creation. Directory get runnerDirectory => _editableDirectory.childDirectory('runner');
Future<void> ensureReadyForPlatformSpecificTooling() async {}}
/// The Linux sub project.class LinuxProject extends FlutterProjectPlatform implements CmakeBasedProject { LinuxProject.fromFlutter(this.parent);
@override final FlutterProject parent;
@override String get pluginConfigKey => LinuxPlugin.kConfigKey;
static final RegExp _applicationIdPattern = RegExp(r'''^\s*set\s*\(\s*APPLICATION_ID\s*"(.*)"\s*\)\s*$''');
Directory get _editableDirectory => parent.directory.childDirectory('linux');
/// The directory in the project that is managed by Flutter. As much as /// possible, files that are edited by Flutter tooling after initial project /// creation should live here. Directory get managedDirectory => _editableDirectory.childDirectory('flutter');
/// The subdirectory of [managedDirectory] that contains files that are /// generated on the fly. All generated files that are not intended to be /// checked in should live here. Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');
@override bool existsSync() => _editableDirectory.existsSync();
@override File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt');
@override File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt');
@override File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake');
@override File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake');
@override Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks');
Future<void> ensureReadyForPlatformSpecificTooling() async {}
String? get applicationId { return firstMatchInFile(cmakeFile, _applicationIdPattern)?.group(1); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082// 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:typed_data';
import 'package:meta/meta.dart';import 'package:package_config/package_config.dart';import 'package:process/process.dart';import 'package:usage/uuid/uuid.dart';
import 'artifacts.dart';import 'base/common.dart';import 'base/file_system.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/platform.dart';import 'build_info.dart';import 'convert.dart';
/// Opt-in changes to the dart compilers.const List<String> kDartCompilerExperiments = <String>[];
/// The target model describes the set of core libraries that are available within/// the SDK.class TargetModel { /// Parse a [TargetModel] from a raw string. /// /// Throws an exception if passed a value other than 'flutter', /// 'flutter_runner', 'vm', or 'dartdevc'. factory TargetModel(String rawValue) { switch (rawValue) { case 'flutter': return flutter; case 'flutter_runner': return flutterRunner; case 'vm': return vm; case 'dartdevc': return dartdevc; } throw Exception('Unexpected target model $rawValue'); }
const TargetModel._(this._value);
/// The Flutter patched Dart SDK. static const TargetModel flutter = TargetModel._('flutter');
/// The Fuchsia patched SDK. static const TargetModel flutterRunner = TargetModel._('flutter_runner');
/// The Dart VM. static const TargetModel vm = TargetModel._('vm');
/// The development compiler for JavaScript. static const TargetModel dartdevc = TargetModel._('dartdevc');
final String _value;
@override String toString() => _value;}
class CompilerOutput { const CompilerOutput(this.outputFilename, this.errorCount, this.sources, {this.expressionData});
final String outputFilename; final int errorCount; final List<Uri> sources;
/// This field is only non-null for expression compilation requests. final Uint8List? expressionData;}
enum StdoutState { CollectDiagnostic, CollectDependencies }
/// Handles stdin/stdout communication with the frontend server.class StdoutHandler { StdoutHandler({ required Logger logger, required FileSystem fileSystem, }) : _logger = logger, _fileSystem = fileSystem { reset(); }
final Logger _logger; final FileSystem _fileSystem;
String? boundaryKey; StdoutState state = StdoutState.CollectDiagnostic; Completer<CompilerOutput?>? compilerOutput; final List<Uri> sources = <Uri>[];
bool _suppressCompilerMessages = false; bool _expectSources = true; bool _readFile = false;
void handler(String message) { const String kResultPrefix = 'result '; if (boundaryKey == null && message.startsWith(kResultPrefix)) { boundaryKey = message.substring(kResultPrefix.length); return; } final String? messageBoundaryKey = boundaryKey; if (messageBoundaryKey != null && message.startsWith(messageBoundaryKey)) { if (_expectSources) { if (state == StdoutState.CollectDiagnostic) { state = StdoutState.CollectDependencies; return; } } if (message.length <= messageBoundaryKey.length) { compilerOutput?.complete(); return; } final int spaceDelimiter = message.lastIndexOf(' '); final String fileName = message.substring(messageBoundaryKey.length + 1, spaceDelimiter); final int errorCount = int.parse(message.substring(spaceDelimiter + 1).trim()); Uint8List? expressionData; if (_readFile) { expressionData = _fileSystem.file(fileName).readAsBytesSync(); } final CompilerOutput output = CompilerOutput( fileName, errorCount, sources, expressionData: expressionData, ); compilerOutput?.complete(output); return; } if (state == StdoutState.CollectDiagnostic) { if (!_suppressCompilerMessages) { _logger.printError(message); } else { _logger.printTrace(message); } } else { assert(state == StdoutState.CollectDependencies); switch (message[0]) { case '+': sources.add(Uri.parse(message.substring(1))); case '-': sources.remove(Uri.parse(message.substring(1))); default: _logger.printTrace('Unexpected prefix for $message uri - ignoring'); } } }
// This is needed to get ready to process next compilation result output, // with its own boundary key and new completer. void reset({ bool suppressCompilerMessages = false, bool expectSources = true, bool readFile = false }) { boundaryKey = null; compilerOutput = Completer<CompilerOutput?>(); _suppressCompilerMessages = suppressCompilerMessages; _expectSources = expectSources; _readFile = readFile; state = StdoutState.CollectDiagnostic; }}
/// List the preconfigured build options for a given build mode.List<String> buildModeOptions(BuildMode mode, List<String> dartDefines) => switch (mode) { BuildMode.debug => <String>[ // These checks allow the CLI to override the value of this define for unit // testing the framework. if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) '-Ddart.vm.profile=false', if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) '-Ddart.vm.product=false', '--enable-asserts', ], BuildMode.profile => <String>[ // These checks allow the CLI to override the value of this define for // benchmarks with most timeline traces disabled. if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) '-Ddart.vm.profile=true', if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) '-Ddart.vm.product=false', ...kDartCompilerExperiments, ], BuildMode.release => <String>[ '-Ddart.vm.profile=false', '-Ddart.vm.product=true', ...kDartCompilerExperiments, ], _ => throw Exception('Unknown BuildMode: $mode') };
/// A compiler interface for producing single (non-incremental) kernel files.class KernelCompiler { KernelCompiler({ required FileSystem fileSystem, required Logger logger, required ProcessManager processManager, required Artifacts artifacts, required List<String> fileSystemRoots, String? fileSystemScheme, @visibleForTesting StdoutHandler? stdoutHandler, }) : _logger = logger, _fileSystem = fileSystem, _artifacts = artifacts, _processManager = processManager, _fileSystemScheme = fileSystemScheme, _fileSystemRoots = fileSystemRoots, _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem);
final FileSystem _fileSystem; final Artifacts _artifacts; final ProcessManager _processManager; final Logger _logger; final String? _fileSystemScheme; final List<String> _fileSystemRoots; final StdoutHandler _stdoutHandler;
Future<CompilerOutput?> compile({ required String sdkRoot, String? mainPath, String? outputFilePath, String? depFilePath, TargetModel targetModel = TargetModel.flutter, bool linkPlatformKernelIn = false, bool aot = false, String? frontendServerStarterPath, List<String>? extraFrontEndOptions, List<String>? fileSystemRoots, String? fileSystemScheme, String? initializeFromDill, String? platformDill, Directory? buildDir, String? targetOS, bool checkDartPluginRegistry = false, required String? packagesPath, required BuildMode buildMode, required bool trackWidgetCreation, required List<String> dartDefines, required PackageConfig packageConfig, String? nativeAssets, }) async { final TargetPlatform? platform = targetModel == TargetModel.dartdevc ? TargetPlatform.web_javascript : null; // This is a URI, not a file path, so the forward slash is correct even on Windows. if (!sdkRoot.endsWith('/')) { sdkRoot = '$sdkRoot/'; } String? mainUri; final File mainFile = _fileSystem.file(mainPath); final Uri mainFileUri = mainFile.uri; if (packagesPath != null) { mainUri = packageConfig.toPackageUri(mainFileUri)?.toString(); } mainUri ??= toMultiRootPath(mainFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\'); if (outputFilePath != null && !_fileSystem.isFileSync(outputFilePath)) { _fileSystem.file(outputFilePath).createSync(recursive: true); }
// Check if there's a Dart plugin registrant. // This is contained in the file `dart_plugin_registrant.dart` under `.dart_tools/flutter_build/`. final File? dartPluginRegistrant = checkDartPluginRegistry ? buildDir?.parent.childFile('dart_plugin_registrant.dart') : null;
String? dartPluginRegistrantUri; if (dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { final Uri dartPluginRegistrantFileUri = dartPluginRegistrant.uri; dartPluginRegistrantUri = packageConfig.toPackageUri(dartPluginRegistrantFileUri)?.toString() ?? toMultiRootPath(dartPluginRegistrantFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\'); }
final List<String> commandToStartFrontendServer; if (frontendServerStarterPath != null && frontendServerStarterPath.isNotEmpty) { final String engineDartPath = _artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform); if (!_processManager.canRun(engineDartPath)) { throwToolExit('Unable to find Dart binary at $engineDartPath'); } commandToStartFrontendServer = <String>[ engineDartPath, '--disable-dart-dev', frontendServerStarterPath, ]; } else { final String engineDartAotRuntimePath = _artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform); if (!_processManager.canRun(engineDartAotRuntimePath)) { throwToolExit('Unable to find dartaotruntime binary at $engineDartAotRuntimePath'); } commandToStartFrontendServer = <String>[ engineDartAotRuntimePath, '--disable-dart-dev', _artifacts.getArtifactPath( Artifact.frontendServerSnapshotForEngineDartSdk, platform: platform, ), ]; }
final List<String> command = commandToStartFrontendServer + <String>[ '--sdk-root', sdkRoot, '--target=$targetModel', '--no-print-incremental-dependencies', for (final Object dartDefine in dartDefines) '-D$dartDefine', ...buildModeOptions(buildMode, dartDefines), if (trackWidgetCreation) '--track-widget-creation', if (!linkPlatformKernelIn) '--no-link-platform', if (aot) ...<String>[ '--aot', '--tfa', // The --target-os flag only makes sense for whole program compilation. if (targetOS != null) ...<String>[ '--target-os', targetOS, ], ], if (packagesPath != null) ...<String>[ '--packages', packagesPath, ], if (outputFilePath != null) ...<String>[ '--output-dill', outputFilePath, ], if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) ...<String>[ '--depfile', depFilePath, ], if (fileSystemRoots != null) for (final String root in fileSystemRoots) ...<String>[ '--filesystem-root', root, ], if (fileSystemScheme != null) ...<String>[ '--filesystem-scheme', fileSystemScheme, ], if (initializeFromDill != null) ...<String>[ '--incremental', '--initialize-from-dill', initializeFromDill, ], if (platformDill != null) ...<String>[ '--platform', platformDill, ], if (dartPluginRegistrantUri != null) ...<String>[ '--source', dartPluginRegistrantUri, '--source', 'package:flutter/src/dart_plugin_registrant.dart', '-Dflutter.dart_plugin_registrant=$dartPluginRegistrantUri', ], if (nativeAssets != null) ...<String>[ '--native-assets', nativeAssets, ], // See: https://github.com/flutter/flutter/issues/103994 '--verbosity=error', ...?extraFrontEndOptions, mainUri, ];
_logger.printTrace(command.join(' ')); final Process server = await _processManager.start(command);
server.stderr .transform<String>(utf8.decoder) .listen(_logger.printError); server.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(_stdoutHandler.handler); final int exitCode = await server.exitCode; if (exitCode == 0) { return _stdoutHandler.compilerOutput?.future; } return null; }}
/// Class that allows to serialize compilation requests to the compiler.abstract class _CompilationRequest { _CompilationRequest(this.completer);
Completer<CompilerOutput?> completer;
Future<CompilerOutput?> _run(DefaultResidentCompiler compiler);
Future<void> run(DefaultResidentCompiler compiler) async { completer.complete(await _run(compiler)); }}
class _RecompileRequest extends _CompilationRequest { _RecompileRequest( super.completer, this.mainUri, this.invalidatedFiles, this.outputPath, this.packageConfig, this.suppressErrors, { this.additionalSourceUri, this.nativeAssetsYamlUri, });
Uri mainUri; List<Uri>? invalidatedFiles; String outputPath; PackageConfig packageConfig; bool suppressErrors; final Uri? additionalSourceUri; final Uri? nativeAssetsYamlUri;
@override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._recompile(this);}
class _CompileExpressionRequest extends _CompilationRequest { _CompileExpressionRequest( super.completer, this.expression, this.definitions, this.definitionTypes, this.typeDefinitions, this.typeBounds, this.typeDefaults, this.libraryUri, this.klass, this.method, this.isStatic, );
String expression; List<String>? definitions; List<String>? definitionTypes; List<String>? typeDefinitions; List<String>? typeBounds; List<String>? typeDefaults; String? libraryUri; String? klass; String? method; bool isStatic;
@override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._compileExpression(this);}
class _CompileExpressionToJsRequest extends _CompilationRequest { _CompileExpressionToJsRequest( super.completer, this.libraryUri, this.line, this.column, this.jsModules, this.jsFrameValues, this.moduleName, this.expression, );
final String? libraryUri; final int line; final int column; final Map<String, String>? jsModules; final Map<String, String>? jsFrameValues; final String? moduleName; final String? expression;
@override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._compileExpressionToJs(this);}
class _RejectRequest extends _CompilationRequest { _RejectRequest(super.completer);
@override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._reject();}
/// Wrapper around incremental frontend server compiler, that communicates with/// server via stdin/stdout.////// The wrapper is intended to stay resident in memory as user changes, reloads,/// restarts the Flutter app.abstract class ResidentCompiler { factory ResidentCompiler(String sdkRoot, { required BuildMode buildMode, required Logger logger, required ProcessManager processManager, required Artifacts artifacts, required Platform platform, required FileSystem fileSystem, bool testCompilation, bool trackWidgetCreation, String packagesPath, List<String> fileSystemRoots, String? fileSystemScheme, String initializeFromDill, bool assumeInitializeFromDillUpToDate, TargetModel targetModel, bool unsafePackageSerialization, String? frontendServerStarterPath, List<String> extraFrontEndOptions, String platformDill, List<String>? dartDefines, String librariesSpec, }) = DefaultResidentCompiler;
// TODO(zanderso): find a better way to configure additional file system // roots from the runner. // See: https://github.com/flutter/flutter/issues/50494 void addFileSystemRoot(String root);
/// If invoked for the first time, it compiles Dart script identified by /// [mainPath], [invalidatedFiles] list is ignored. /// On successive runs [invalidatedFiles] indicates which files need to be /// recompiled. If [mainPath] is [null], previously used [mainPath] entry /// point that is used for recompilation. /// Binary file name is returned if compilation was successful, otherwise /// null is returned. /// /// If [checkDartPluginRegistry] is true, it is the caller's responsibility /// to ensure that the generated registrant file has been updated such that /// it is wrapping [mainUri]. Future<CompilerOutput?> recompile( Uri mainUri, List<Uri>? invalidatedFiles, { required String outputPath, required PackageConfig packageConfig, required FileSystem fs, String? projectRootPath, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant, Uri? nativeAssetsYaml, });
Future<CompilerOutput?> compileExpression( String expression, List<String>? definitions, List<String>? definitionTypes, List<String>? typeDefinitions, List<String>? typeBounds, List<String>? typeDefaults, String? libraryUri, String? klass, String? method, bool isStatic, );
/// Compiles [expression] in [libraryUri] at [line]:[column] to JavaScript /// in [moduleName]. /// /// Values listed in [jsFrameValues] are substituted for their names in the /// [expression]. /// /// Ensures that all [jsModules] are loaded and accessible inside the /// expression. /// /// Example values of parameters: /// [moduleName] is of the form '/packages/hello_world_main.dart' /// [jsFrameValues] is a map from js variable name to its primitive value /// or another variable name, for example /// { 'x': '1', 'y': 'y', 'o': 'null' } /// [jsModules] is a map from variable name to the module name, where /// variable name is the name originally used in JavaScript to contain the /// module object, for example: /// { 'dart':'dart_sdk', 'main': '/packages/hello_world_main.dart' } /// Returns a [CompilerOutput] including the name of the file containing the /// compilation result and a number of errors. Future<CompilerOutput?> compileExpressionToJs( String libraryUri, int line, int column, Map<String, String> jsModules, Map<String, String> jsFrameValues, String moduleName, String expression, );
/// Should be invoked when results of compilation are accepted by the client. /// /// Either [accept] or [reject] should be called after every [recompile] call. void accept();
/// Should be invoked when results of compilation are rejected by the client. /// /// Either [accept] or [reject] should be called after every [recompile] call. Future<CompilerOutput?> reject();
/// Should be invoked when frontend server compiler should forget what was /// accepted previously so that next call to [recompile] produces complete /// kernel file. void reset();
Future<Object> shutdown();}
@visibleForTestingclass DefaultResidentCompiler implements ResidentCompiler { DefaultResidentCompiler( String sdkRoot, { required this.buildMode, required Logger logger, required ProcessManager processManager, required this.artifacts, required Platform platform, required FileSystem fileSystem, this.testCompilation = false, this.trackWidgetCreation = true, this.packagesPath, List<String> fileSystemRoots = const <String>[], this.fileSystemScheme, this.initializeFromDill, this.assumeInitializeFromDillUpToDate = false, this.targetModel = TargetModel.flutter, this.unsafePackageSerialization = false, this.frontendServerStarterPath, this.extraFrontEndOptions, this.platformDill, List<String>? dartDefines, this.librariesSpec, @visibleForTesting StdoutHandler? stdoutHandler, }) : _logger = logger, _processManager = processManager, _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem), _platform = platform, dartDefines = dartDefines ?? const <String>[], // This is a URI, not a file path, so the forward slash is correct even on Windows. sdkRoot = sdkRoot.endsWith('/') ? sdkRoot : '$sdkRoot/', // Make a copy, we might need to modify it later. fileSystemRoots = List<String>.from(fileSystemRoots);
final Logger _logger; final ProcessManager _processManager; final Artifacts artifacts; final Platform _platform;
final bool testCompilation; final BuildMode buildMode; final bool trackWidgetCreation; final String? packagesPath; final TargetModel targetModel; final List<String> fileSystemRoots; final String? fileSystemScheme; final String? initializeFromDill; final bool assumeInitializeFromDillUpToDate; final bool unsafePackageSerialization; final String? frontendServerStarterPath; final List<String>? extraFrontEndOptions; final List<String> dartDefines; final String? librariesSpec;
@override void addFileSystemRoot(String root) { fileSystemRoots.add(root); }
/// The path to the root of the Dart SDK used to compile. /// /// This is used to resolve the [platformDill]. final String sdkRoot;
/// The path to the platform dill file. /// /// This does not need to be provided for the normal Flutter workflow. final String? platformDill;
Process? _server; final StdoutHandler _stdoutHandler; bool _compileRequestNeedsConfirmation = false;
final StreamController<_CompilationRequest> _controller = StreamController<_CompilationRequest>();
@override Future<CompilerOutput?> recompile( Uri mainUri, List<Uri>? invalidatedFiles, { required String outputPath, required PackageConfig packageConfig, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant, String? projectRootPath, FileSystem? fs, Uri? nativeAssetsYaml, }) async { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } Uri? additionalSourceUri; // `dart_plugin_registrant.dart` contains the Dart plugin registry. if (checkDartPluginRegistry && dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { additionalSourceUri = dartPluginRegistrant.uri; } final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add(_RecompileRequest( completer, mainUri, invalidatedFiles, outputPath, packageConfig, suppressErrors, additionalSourceUri: additionalSourceUri, nativeAssetsYamlUri: nativeAssetsYaml, )); return completer.future; }
Future<CompilerOutput?> _recompile(_RecompileRequest request) async { _stdoutHandler.reset(); _compileRequestNeedsConfirmation = true; _stdoutHandler._suppressCompilerMessages = request.suppressErrors;
final String mainUri = request.packageConfig.toPackageUri(request.mainUri)?.toString() ?? toMultiRootPath(request.mainUri, fileSystemScheme, fileSystemRoots, _platform.isWindows);
String? additionalSourceUri; if (request.additionalSourceUri != null) { additionalSourceUri = request.packageConfig.toPackageUri(request.additionalSourceUri!)?.toString() ?? toMultiRootPath(request.additionalSourceUri!, fileSystemScheme, fileSystemRoots, _platform.isWindows); }
final String? nativeAssets = request.nativeAssetsYamlUri?.toString(); final Process? server = _server; if (server == null) { return _compile( mainUri, request.outputPath, additionalSourceUri: additionalSourceUri, nativeAssetsUri: nativeAssets, ); } final String inputKey = Uuid().generateV4();
if (nativeAssets != null && nativeAssets.isNotEmpty) { server.stdin.writeln('native-assets $nativeAssets'); _logger.printTrace('<- native-assets $nativeAssets'); } server.stdin.writeln('recompile $mainUri $inputKey'); _logger.printTrace('<- recompile $mainUri $inputKey'); final List<Uri>? invalidatedFiles = request.invalidatedFiles; if (invalidatedFiles != null) { for (final Uri fileUri in invalidatedFiles) { String message; if (fileUri.scheme == 'package') { message = fileUri.toString(); } else { message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots, _platform.isWindows); } server.stdin.writeln(message); _logger.printTrace(message); } } server.stdin.writeln(inputKey); _logger.printTrace('<- $inputKey');
return _stdoutHandler.compilerOutput?.future; }
final List<_CompilationRequest> _compilationQueue = <_CompilationRequest>[];
Future<void> _handleCompilationRequest(_CompilationRequest request) async { final bool isEmpty = _compilationQueue.isEmpty; _compilationQueue.add(request); // Only trigger processing if queue was empty - i.e. no other requests // are currently being processed. This effectively enforces "one // compilation request at a time". if (isEmpty) { while (_compilationQueue.isNotEmpty) { final _CompilationRequest request = _compilationQueue.first; await request.run(this); _compilationQueue.removeAt(0); } } }
Future<CompilerOutput?> _compile( String scriptUri, String? outputPath, { String? additionalSourceUri, String? nativeAssetsUri, }) async { final TargetPlatform? platform = (targetModel == TargetModel.dartdevc) ? TargetPlatform.web_javascript : null; late final List<String> commandToStartFrontendServer; if (frontendServerStarterPath != null && frontendServerStarterPath!.isNotEmpty) { commandToStartFrontendServer = <String>[ artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform), '--disable-dart-dev', frontendServerStarterPath!, ]; } else { commandToStartFrontendServer = <String>[ artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform), '--disable-dart-dev', artifacts.getArtifactPath( Artifact.frontendServerSnapshotForEngineDartSdk, platform: platform, ), ]; }
final List<String> command = commandToStartFrontendServer + <String>[ '--sdk-root', sdkRoot, '--incremental', if (testCompilation) '--no-print-incremental-dependencies', '--target=$targetModel', // TODO(annagrin): remove once this becomes the default behavior // in the frontend_server. // https://github.com/flutter/flutter/issues/59902 '--experimental-emit-debug-metadata', for (final Object dartDefine in dartDefines) '-D$dartDefine', if (outputPath != null) ...<String>[ '--output-dill', outputPath, ], // If we have a platform dill, we don't need to pass the libraries spec, // since the information is embedded in the .dill file. if (librariesSpec != null && platformDill == null) ...<String>[ '--libraries-spec', librariesSpec!, ], if (packagesPath != null) ...<String>[ '--packages', packagesPath!, ], ...buildModeOptions(buildMode, dartDefines), if (trackWidgetCreation) '--track-widget-creation', for (final String root in fileSystemRoots) ...<String>[ '--filesystem-root', root, ], if (fileSystemScheme != null) ...<String>[ '--filesystem-scheme', fileSystemScheme!, ], if (initializeFromDill != null) ...<String>[ '--initialize-from-dill', initializeFromDill!, ], if (assumeInitializeFromDillUpToDate) '--assume-initialize-from-dill-up-to-date', if (additionalSourceUri != null) ...<String>[ '--source', additionalSourceUri, '--source', 'package:flutter/src/dart_plugin_registrant.dart', '-Dflutter.dart_plugin_registrant=$additionalSourceUri', ], if (nativeAssetsUri != null) ...<String>[ '--native-assets', nativeAssetsUri, ], if (platformDill != null) ...<String>[ '--platform', platformDill!, ], if (unsafePackageSerialization) '--unsafe-package-serialization', // See: https://github.com/flutter/flutter/issues/103994 '--verbosity=error', ...?extraFrontEndOptions, ]; _logger.printTrace(command.join(' ')); _server = await _processManager.start(command); _server?.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen( _stdoutHandler.handler, onDone: () { // when outputFilename future is not completed, but stdout is closed // process has died unexpectedly. if (_stdoutHandler.compilerOutput?.isCompleted == false) { _stdoutHandler.compilerOutput?.complete(); throwToolExit('the Dart compiler exited unexpectedly.'); } });
_server?.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(_logger.printError);
unawaited(_server?.exitCode.then((int code) { if (code != 0) { throwToolExit('the Dart compiler exited unexpectedly.'); } }));
if (nativeAssetsUri != null && nativeAssetsUri.isNotEmpty) { _server?.stdin.writeln('native-assets $nativeAssetsUri'); _logger.printTrace('<- native-assets $nativeAssetsUri'); }
_server?.stdin.writeln('compile $scriptUri'); _logger.printTrace('<- compile $scriptUri');
return _stdoutHandler.compilerOutput?.future; }
@override Future<CompilerOutput?> compileExpression( String expression, List<String>? definitions, List<String>? definitionTypes, List<String>? typeDefinitions, List<String>? typeBounds, List<String>? typeDefaults, String? libraryUri, String? klass, String? method, bool isStatic, ) async { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); }
final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); final _CompileExpressionRequest request = _CompileExpressionRequest( completer, expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, libraryUri, klass, method, isStatic); _controller.add(request); return completer.future; }
Future<CompilerOutput?> _compileExpression(_CompileExpressionRequest request) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false, readFile: true);
// 'compile-expression' should be invoked after compiler has been started, // program was compiled. final Process? server = _server; if (server == null) { return null; }
final String inputKey = Uuid().generateV4(); server.stdin ..writeln('compile-expression $inputKey') ..writeln(request.expression); request.definitions?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.definitionTypes?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeDefinitions?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeBounds?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeDefaults?.forEach(server.stdin.writeln); server.stdin ..writeln(inputKey) ..writeln(request.libraryUri ?? '') ..writeln(request.klass ?? '') ..writeln(request.method ?? '') ..writeln(request.isStatic);
return _stdoutHandler.compilerOutput?.future; }
@override Future<CompilerOutput?> compileExpressionToJs( String libraryUri, int line, int column, Map<String, String> jsModules, Map<String, String> jsFrameValues, String moduleName, String expression, ) { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); }
final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add( _CompileExpressionToJsRequest( completer, libraryUri, line, column, jsModules, jsFrameValues, moduleName, expression) ); return completer.future; }
Future<CompilerOutput?> _compileExpressionToJs(_CompileExpressionToJsRequest request) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false);
// 'compile-expression-to-js' should be invoked after compiler has been started, // program was compiled. final Process? server = _server; if (server == null) { return null; }
final String inputKey = Uuid().generateV4(); server.stdin ..writeln('compile-expression-to-js $inputKey') ..writeln(request.libraryUri ?? '') ..writeln(request.line) ..writeln(request.column); request.jsModules?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); server.stdin.writeln(inputKey); request.jsFrameValues?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); server.stdin ..writeln(inputKey) ..writeln(request.moduleName ?? '') ..writeln(request.expression ?? '');
return _stdoutHandler.compilerOutput?.future; }
@override void accept() { if (_compileRequestNeedsConfirmation) { _server?.stdin.writeln('accept'); _logger.printTrace('<- accept'); } _compileRequestNeedsConfirmation = false; }
@override Future<CompilerOutput?> reject() { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); }
final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add(_RejectRequest(completer)); return completer.future; }
Future<CompilerOutput?> _reject() async { if (!_compileRequestNeedsConfirmation) { return Future<CompilerOutput?>.value(); } _stdoutHandler.reset(expectSources: false); _server?.stdin.writeln('reject'); _logger.printTrace('<- reject'); _compileRequestNeedsConfirmation = false; return _stdoutHandler.compilerOutput?.future; }
@override void reset() { _server?.stdin.writeln('reset'); _logger.printTrace('<- reset'); }
@override Future<Object> shutdown() async { // Server was never successfully created. final Process? server = _server; if (server == null) { return 0; } _logger.printTrace('killing pid ${server.pid}'); server.kill(); return server.exitCode; }}
/// Convert a file URI into a multi-root scheme URI if provided, otherwise/// return unmodified.@visibleForTestingString toMultiRootPath(Uri fileUri, String? scheme, List<String> fileSystemRoots, bool windows) { if (scheme == null || fileSystemRoots.isEmpty || fileUri.scheme != 'file') { return fileUri.toString(); } final String filePath = fileUri.toFilePath(windows: windows); for (final String fileSystemRoot in fileSystemRoots) { if (filePath.startsWith(fileSystemRoot)) { return '$scheme://${filePath.substring(fileSystemRoot.length)}'; } } return fileUri.toString();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400// 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:process/process.dart';import 'package:unified_analytics/unified_analytics.dart';
import 'android/android_builder.dart';import 'android/android_sdk.dart';import 'android/android_studio.dart';import 'android/android_workflow.dart';import 'android/gradle.dart';import 'android/gradle_utils.dart';import 'android/java.dart';import 'application_package.dart';import 'artifacts.dart';import 'asset.dart';import 'base/config.dart';import 'base/context.dart';import 'base/error_handling_io.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/os.dart';import 'base/process.dart';import 'base/terminal.dart';import 'base/time.dart';import 'base/user_messages.dart';import 'build_system/build_system.dart';import 'cache.dart';import 'custom_devices/custom_devices_config.dart';import 'dart/pub.dart';import 'devfs.dart';import 'device.dart';import 'devtools_launcher.dart';import 'doctor.dart';import 'emulator.dart';import 'features.dart';import 'flutter_application_package.dart';import 'flutter_cache.dart';import 'flutter_device_manager.dart';import 'flutter_features.dart';import 'fuchsia/fuchsia_device.dart' show FuchsiaDeviceTools;import 'fuchsia/fuchsia_sdk.dart' show FuchsiaArtifacts, FuchsiaSdk;import 'fuchsia/fuchsia_workflow.dart' show FuchsiaWorkflow, fuchsiaWorkflow;import 'globals.dart' as globals;import 'ios/ios_workflow.dart';import 'ios/iproxy.dart';import 'ios/simulators.dart';import 'ios/xcodeproj.dart';import 'macos/cocoapods.dart';import 'macos/cocoapods_validator.dart';import 'macos/macos_workflow.dart';import 'macos/xcdevice.dart';import 'macos/xcode.dart';import 'mdns_discovery.dart';import 'persistent_tool_state.dart';import 'reporting/crash_reporting.dart';import 'reporting/first_run.dart';import 'reporting/reporting.dart';import 'reporting/unified_analytics.dart';import 'resident_runner.dart';import 'run_hot.dart';import 'runner/local_engine.dart';import 'version.dart';import 'web/workflow.dart';import 'windows/visual_studio.dart';import 'windows/visual_studio_validator.dart';import 'windows/windows_workflow.dart';
Future<T> runInContext<T>( FutureOr<T> Function() runner, { Map<Type, Generator>? overrides,}) async {
// Wrap runner with any asynchronous initialization that should run with the // overrides and callbacks. late bool runningOnBot; FutureOr<T> runnerWrapper() async { runningOnBot = await globals.isRunningOnBot; return runner(); }
// TODO(ianh): We should split this into two, one for tests (which should be // in test/), and one for production (which should be in executable.dart). return context.run<T>( name: 'global fallbacks', body: runnerWrapper, overrides: overrides, fallbacks: <Type, Generator>{ Analytics: () => getAnalytics( runningOnBot: runningOnBot, flutterVersion: globals.flutterVersion, environment: globals.platform.environment, clientIde: globals.platform.environment['FLUTTER_HOST'], config: globals.config, ), AndroidBuilder: () => AndroidGradleBuilder( java: globals.java, logger: globals.logger, processManager: globals.processManager, fileSystem: globals.fs, artifacts: globals.artifacts!, usage: globals.flutterUsage, analytics: globals.analytics, gradleUtils: globals.gradleUtils!, platform: globals.platform, androidStudio: globals.androidStudio, ), AndroidLicenseValidator: () => AndroidLicenseValidator( platform: globals.platform, userMessages: globals.userMessages, processManager: globals.processManager, java: globals.java, androidSdk: globals.androidSdk, logger: globals.logger, stdio: globals.stdio, ), AndroidSdk: AndroidSdk.locateAndroidSdk, AndroidStudio: AndroidStudio.latestValid, AndroidValidator: () => AndroidValidator( java: globals.java, androidSdk: globals.androidSdk, logger: globals.logger, platform: globals.platform, userMessages: globals.userMessages, ), AndroidWorkflow: () => AndroidWorkflow( androidSdk: globals.androidSdk, featureFlags: featureFlags, ), ApplicationPackageFactory: () => FlutterApplicationPackageFactory( userMessages: globals.userMessages, processManager: globals.processManager, logger: globals.logger, fileSystem: globals.fs, androidSdk: globals.androidSdk, ), Artifacts: () => CachedArtifacts( fileSystem: globals.fs, cache: globals.cache, platform: globals.platform, operatingSystemUtils: globals.os, ), AssetBundleFactory: () { return AssetBundleFactory.defaultInstance( logger: globals.logger, fileSystem: globals.fs, platform: globals.platform, ); }, BuildSystem: () => FlutterBuildSystem( fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, ), Cache: () => FlutterCache( fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, osUtils: globals.os, projectFactory: globals.projectFactory, ), CocoaPods: () => CocoaPods( fileSystem: globals.fs, processManager: globals.processManager, logger: globals.logger, platform: globals.platform, xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, usage: globals.flutterUsage, analytics: globals.analytics, ), CocoaPodsValidator: () => CocoaPodsValidator( globals.cocoaPods!, globals.userMessages, ), Config: () => Config( Config.kFlutterSettings, fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, ), CustomDevicesConfig: () => CustomDevicesConfig( fileSystem: globals.fs, logger: globals.logger, platform: globals.platform ), CrashReporter: () => CrashReporter( fileSystem: globals.fs, logger: globals.logger, flutterProjectFactory: globals.projectFactory, ), DevFSConfig: () => DevFSConfig(), DeviceManager: () => FlutterDeviceManager( logger: globals.logger, processManager: globals.processManager, platform: globals.platform, androidSdk: globals.androidSdk, iosSimulatorUtils: globals.iosSimulatorUtils!, featureFlags: featureFlags, fileSystem: globals.fs, iosWorkflow: globals.iosWorkflow!, artifacts: globals.artifacts!, flutterVersion: globals.flutterVersion, androidWorkflow: androidWorkflow!, fuchsiaWorkflow: fuchsiaWorkflow!, xcDevice: globals.xcdevice!, userMessages: globals.userMessages, windowsWorkflow: windowsWorkflow!, macOSWorkflow: MacOSWorkflow( platform: globals.platform, featureFlags: featureFlags, ), fuchsiaSdk: globals.fuchsiaSdk!, operatingSystemUtils: globals.os, customDevicesConfig: globals.customDevicesConfig, ), DevtoolsLauncher: () => DevtoolsServerLauncher( processManager: globals.processManager, dartExecutable: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), logger: globals.logger, botDetector: globals.botDetector, ), Doctor: () => Doctor( logger: globals.logger, clock: globals.systemClock, ), DoctorValidatorsProvider: () => DoctorValidatorsProvider.defaultInstance, EmulatorManager: () => EmulatorManager( java: globals.java, androidSdk: globals.androidSdk, processManager: globals.processManager, logger: globals.logger, fileSystem: globals.fs, androidWorkflow: androidWorkflow!, ), FeatureFlags: () => FlutterFeatureFlags( flutterVersion: globals.flutterVersion, config: globals.config, platform: globals.platform, ), FlutterVersion: () => FlutterVersion( fs: globals.fs, flutterRoot: Cache.flutterRoot!, ), FuchsiaArtifacts: () => FuchsiaArtifacts.find(), FuchsiaDeviceTools: () => FuchsiaDeviceTools(), FuchsiaSdk: () => FuchsiaSdk(), FuchsiaWorkflow: () => FuchsiaWorkflow( featureFlags: featureFlags, platform: globals.platform, fuchsiaArtifacts: globals.fuchsiaArtifacts!, ), GradleUtils: () => GradleUtils( operatingSystemUtils: globals.os, logger: globals.logger, platform: globals.platform, cache: globals.cache, ), HotRunnerConfig: () => HotRunnerConfig(), IOSSimulatorUtils: () => IOSSimulatorUtils( logger: globals.logger, processManager: globals.processManager, xcode: globals.xcode!, ), IOSWorkflow: () => IOSWorkflow( featureFlags: featureFlags, xcode: globals.xcode!, platform: globals.platform, ), Java: () => Java.find( config: globals.config, androidStudio: globals.androidStudio, logger: globals.logger, fileSystem: globals.fs, platform: globals.platform, processManager: globals.processManager ), LocalEngineLocator: () => LocalEngineLocator( userMessages: userMessages, logger: globals.logger, platform: globals.platform, fileSystem: globals.fs, flutterRoot: Cache.flutterRoot!, ), Logger: () => globals.platform.isWindows ? WindowsStdoutLogger( terminal: globals.terminal, stdio: globals.stdio, outputPreferences: globals.outputPreferences, ) : StdoutLogger( terminal: globals.terminal, stdio: globals.stdio, outputPreferences: globals.outputPreferences, ), MacOSWorkflow: () => MacOSWorkflow( featureFlags: featureFlags, platform: globals.platform, ), MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery( logger: globals.logger, flutterUsage: globals.flutterUsage, analytics: globals.analytics, ), OperatingSystemUtils: () => OperatingSystemUtils( fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, processManager: globals.processManager, ), OutputPreferences: () => OutputPreferences( wrapText: globals.stdio.hasTerminal, showColor: globals.platform.stdoutSupportsAnsi, stdio: globals.stdio, ), PersistentToolState: () => PersistentToolState( fileSystem: globals.fs, logger: globals.logger, platform: globals.platform, ), ProcessInfo: () => ProcessInfo(globals.fs), ProcessManager: () => ErrorHandlingProcessManager( delegate: const LocalProcessManager(), platform: globals.platform, ), ProcessUtils: () => ProcessUtils( processManager: globals.processManager, logger: globals.logger, ), Pub: () => Pub( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, botDetector: globals.botDetector, platform: globals.platform, usage: globals.flutterUsage, ), Stdio: () => Stdio(), SystemClock: () => const SystemClock(), Usage: () => Usage( runningOnBot: runningOnBot, firstRunMessenger: FirstRunMessenger(persistentToolState: globals.persistentToolState!), ), UserMessages: () => UserMessages(), VisualStudioValidator: () => VisualStudioValidator( userMessages: globals.userMessages, visualStudio: VisualStudio( fileSystem: globals.fs, platform: globals.platform, logger: globals.logger, processManager: globals.processManager, ) ), WebWorkflow: () => WebWorkflow( featureFlags: featureFlags, platform: globals.platform, ), WindowsWorkflow: () => WindowsWorkflow( featureFlags: featureFlags, platform: globals.platform, ), Xcode: () => Xcode( logger: globals.logger, processManager: globals.processManager, platform: globals.platform, fileSystem: globals.fs, xcodeProjectInterpreter: globals.xcodeProjectInterpreter!, userMessages: globals.userMessages, ), XCDevice: () => XCDevice( processManager: globals.processManager, logger: globals.logger, artifacts: globals.artifacts!, cache: globals.cache, platform: globals.platform, xcode: globals.xcode!, iproxy: IProxy( iproxyPath: globals.artifacts!.getHostArtifact( HostArtifact.iproxy, ).path, logger: globals.logger, processManager: globals.processManager, dyLdLibEntry: globals.cache.dyLdLibEntry, ), fileSystem: globals.fs, analytics: globals.analytics, ), XcodeProjectInterpreter: () => XcodeProjectInterpreter( logger: globals.logger, processManager: globals.processManager, platform: globals.platform, fileSystem: globals.fs, usage: globals.flutterUsage, analytics: globals.analytics, ), }, );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081// 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.
// Hide the original utf8 [Codec] so that we can export our own implementation// which adds additional error handling.import 'dart:convert' hide utf8;import 'dart:convert' as cnv show Utf8Decoder, utf8;
import 'package:meta/meta.dart';
import 'base/common.dart';export 'dart:convert' hide Utf8Codec, Utf8Decoder, utf8;
/// The original utf8 encoding for testing overrides only.////// Attempting to use the flutter tool utf8 decoder will surface an analyzer/// warning that overrides cannot change the default value of a named/// parameter.@visibleForTestingconst Encoding utf8ForTesting = cnv.utf8;
/// A [Codec] which reports malformed bytes when decoding.////// Occasionally people end up in a situation where we try to decode bytes/// that aren't UTF-8 and we're not quite sure how this is happening./// This tells people to report a bug when they see this.class Utf8Codec extends Encoding { const Utf8Codec({this.reportErrors = true});
final bool reportErrors;
@override Converter<List<int>, String> get decoder => reportErrors ? const Utf8Decoder() : const Utf8Decoder(reportErrors: false);
@override Converter<String, List<int>> get encoder => cnv.utf8.encoder;
@override String get name => cnv.utf8.name;}
const Encoding utf8 = Utf8Codec();
class Utf8Decoder extends Converter<List<int>, String> { const Utf8Decoder({this.reportErrors = true});
static const cnv.Utf8Decoder _systemDecoder = cnv.Utf8Decoder(allowMalformed: true);
final bool reportErrors;
@override String convert(List<int> input, [int start = 0, int? end]) { final String result = _systemDecoder.convert(input, start, end); // Finding a Unicode replacement character indicates that the input // was malformed. if (reportErrors && result.contains('\u{FFFD}')) { throwToolExit( 'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found while decoding string: $result. ' 'The Flutter team would greatly appreciate if you could file a bug explaining ' 'exactly what you were doing when this happened:\n' 'https://github.com/flutter/flutter/issues/new/choose\n' 'The source bytes were:\n$input\n\n'); } return result; }
@override ByteConversionSink startChunkedConversion(Sink<String> sink) => _systemDecoder.startChunkedConversion(sink);
@override Stream<String> bind(Stream<List<int>> stream) => _systemDecoder.bind(stream);
@override Converter<List<int>, T> fuse<T>(Converter<String, T> other) => _systemDecoder.fuse(other);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378// 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:typed_data';
import 'package:meta/meta.dart';
import 'base/common.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/utils.dart';import 'convert.dart';
/// A single message passed through the [DaemonConnection].class DaemonMessage { DaemonMessage(this.data, [this.binary]);
/// Content of the JSON message in the message. final Map<String, Object?> data;
/// Stream of the binary content of the message. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary;}
/// Data of an event passed through the [DaemonConnection].class DaemonEventData { DaemonEventData(this.eventName, this.data, [this.binary]);
/// The name of the event. final String eventName;
/// The data of the event. final Object? data;
/// Stream of the binary content of the event. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary;}
const String _binaryLengthKey = '_binaryLength';
enum _InputStreamParseState { json, binary,}
/// Converts a binary stream to a stream of [DaemonMessage].////// The daemon JSON-RPC protocol is defined as follows: every single line of/// text that starts with `[{` and ends with `}]` will be parsed as a JSON/// message. The array should contain only one single object which contains the/// message data.////// If the JSON object contains the key [_binaryLengthKey] with an integer/// value (will be referred to as N), the following N bytes after the newline/// character will contain the binary part of the message.@visibleForTestingclass DaemonInputStreamConverter { DaemonInputStreamConverter(this.inputStream) { // Lazily listen to the input stream. _controller.onListen = () { final StreamSubscription<List<int>> subscription = inputStream.listen((List<int> chunk) { _processChunk(chunk); }, onError: (Object error, StackTrace stackTrace) { _controller.addError(error, stackTrace); }, onDone: () { unawaited(_controller.close()); });
_controller.onCancel = subscription.cancel; // We should not handle onPause or onResume. When the stream is paused, we // still need to read from the input stream. }; }
final Stream<List<int>> inputStream;
final StreamController<DaemonMessage> _controller = StreamController<DaemonMessage>(); Stream<DaemonMessage> get convertedStream => _controller.stream;
// Internal states /// The current parse state, whether we are expecting JSON or binary data. _InputStreamParseState state = _InputStreamParseState.json;
/// The binary stream that is being transferred. late StreamController<List<int>> currentBinaryStream;
/// Remaining length in bytes that have to be sent to the binary stream. int remainingBinaryLength = 0;
/// Buffer to hold the current line of input data. final BytesBuilder bytesBuilder = BytesBuilder(copy: false);
// Processes a single chunk received in the input stream. void _processChunk(List<int> chunk) {
int start = 0; while (start < chunk.length) { if (state == _InputStreamParseState.json) { start += _processChunkInJsonMode(chunk, start); } else if (state == _InputStreamParseState.binary) { final int bytesSent = _addBinaryChunk(chunk, start, remainingBinaryLength); start += bytesSent; remainingBinaryLength -= bytesSent;
if (remainingBinaryLength <= 0) { assert(remainingBinaryLength == 0);
unawaited(currentBinaryStream.close()); state = _InputStreamParseState.json; } } } }
/// Processes a chunk in JSON mode, and returns the number of bytes processed. int _processChunkInJsonMode(List<int> chunk, int start) { const int LF = 10; // The '\n' character
// Search for newline character. final int indexOfNewLine = chunk.indexOf(LF, start); if (indexOfNewLine < 0) { bytesBuilder.add(chunk.sublist(start)); return chunk.length - start; }
bytesBuilder.add(chunk.sublist(start, indexOfNewLine + 1));
// Process chunk here final Uint8List combinedChunk = bytesBuilder.takeBytes(); String jsonString = utf8.decode(combinedChunk).trim(); if (jsonString.startsWith('[{') && jsonString.endsWith('}]')) { jsonString = jsonString.substring(1, jsonString.length - 1); final Map<String, Object?>? value = castStringKeyedMap(json.decode(jsonString)); if (value != null) { // Check if we need to consume another binary blob. if (value[_binaryLengthKey] != null) { remainingBinaryLength = value[_binaryLengthKey]! as int; currentBinaryStream = StreamController<List<int>>(); state = _InputStreamParseState.binary; _controller.add(DaemonMessage(value, currentBinaryStream.stream)); } else { _controller.add(DaemonMessage(value)); } } }
return indexOfNewLine + 1 - start; }
int _addBinaryChunk(List<int> chunk, int start, int maximumSizeToRead) { if (start == 0 && chunk.length <= remainingBinaryLength) { currentBinaryStream.add(chunk); return chunk.length; } else { final int chunkRemainingLength = chunk.length - start; final int sizeToRead = chunkRemainingLength < remainingBinaryLength ? chunkRemainingLength : remainingBinaryLength; currentBinaryStream.add(chunk.sublist(start, start + sizeToRead)); return sizeToRead; } }}
/// A stream that a [DaemonConnection] uses to communicate with each other.class DaemonStreams { DaemonStreams( Stream<List<int>> rawInputStream, StreamSink<List<int>> outputSink, { required Logger logger, }) : _outputSink = outputSink, inputStream = DaemonInputStreamConverter(rawInputStream).convertedStream, _logger = logger;
/// Creates a [DaemonStreams] that uses stdin and stdout as the underlying streams. DaemonStreams.fromStdio(Stdio stdio, { required Logger logger }) : this(stdio.stdin, stdio.stdout, logger: logger);
/// Creates a [DaemonStreams] that uses [Socket] as the underlying streams. DaemonStreams.fromSocket(Socket socket, { required Logger logger }) : this(socket, socket, logger: logger);
/// Connects to a server and creates a [DaemonStreams] from the connection as the underlying streams. factory DaemonStreams.connect(String host, int port, { required Logger logger }) { final Future<Socket> socketFuture = Socket.connect(host, port); final StreamController<List<int>> inputStreamController = StreamController<List<int>>(); final StreamController<List<int>> outputStreamController = StreamController<List<int>>(); socketFuture.then((Socket socket) { inputStreamController.addStream(socket); socket.addStream(outputStreamController.stream); }).onError((Object error, StackTrace stackTrace) { logger.printError('Socket error: $error'); logger.printTrace('$stackTrace'); // Propagate the error to the streams. inputStreamController.addError(error, stackTrace); unawaited(outputStreamController.close()); }); return DaemonStreams(inputStreamController.stream, outputStreamController.sink, logger: logger); }
final StreamSink<List<int>> _outputSink; final Logger _logger;
/// Stream that contains input to the [DaemonConnection]. final Stream<DaemonMessage> inputStream;
/// Outputs a message through the connection. void send(Map<String, Object?> message, [ List<int>? binary ]) { try { if (binary != null) { message[_binaryLengthKey] = binary.length; } _outputSink.add(utf8.encode('[${json.encode(message)}]\n')); if (binary != null) { _outputSink.add(binary); } } on StateError catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } on IOException catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } }
/// Cleans up any resources used. Future<void> dispose() async { unawaited(_outputSink.close()); }}
/// Connection between a flutter daemon and a client.class DaemonConnection { DaemonConnection({ required DaemonStreams daemonStreams, required Logger logger, }): _logger = logger, _daemonStreams = daemonStreams { _commandSubscription = daemonStreams.inputStream.listen( _handleMessage, onError: (Object error, StackTrace stackTrace) { // We have to listen for on error otherwise the error on the socket // will end up in the Zone error handler. // Do nothing here and let the stream close handlers handle shutting // down the daemon. } ); }
final DaemonStreams _daemonStreams;
final Logger _logger;
late final StreamSubscription<DaemonMessage> _commandSubscription;
int _outgoingRequestId = 0; final Map<String, Completer<Object?>> _outgoingRequestCompleters = <String, Completer<Object?>>{};
final StreamController<DaemonEventData> _events = StreamController<DaemonEventData>.broadcast(); final StreamController<DaemonMessage> _incomingCommands = StreamController<DaemonMessage>();
/// A stream that contains all the incoming requests. Stream<DaemonMessage> get incomingCommands => _incomingCommands.stream;
/// Listens to the event with the event name [eventToListen]. Stream<DaemonEventData> listenToEvent(String eventToListen) { return _events.stream .where((DaemonEventData event) => event.eventName == eventToListen); }
/// Sends a request to the other end of the connection. /// /// Returns a [Future] that resolves with the content. Future<Object?> sendRequest(String method, [Object? params, List<int>? binary]) async { final String id = '${++_outgoingRequestId}'; final Completer<Object?> completer = Completer<Object?>(); _outgoingRequestCompleters[id] = completer; final Map<String, Object?> data = <String, Object?>{ 'id': id, 'method': method, if (params != null) 'params': params, }; _logger.printTrace('-> Sending to daemon, id = $id, method = $method'); _daemonStreams.send(data, binary); return completer.future; }
/// Sends a response to the other end of the connection. void sendResponse(Object id, [Object? result]) { _daemonStreams.send(<String, Object?>{ 'id': id, if (result != null) 'result': result, }); }
/// Sends an error response to the other end of the connection. void sendErrorResponse(Object id, Object? error, StackTrace trace) { _daemonStreams.send(<String, Object?>{ 'id': id, 'error': error, 'trace': '$trace', }); }
/// Sends an event to the client. void sendEvent(String name, [ Object? params, List<int>? binary ]) { _daemonStreams.send(<String, Object?>{ 'event': name, if (params != null) 'params': params, }, binary); }
/// Handles the input from the stream. /// /// There are three kinds of data: Request, Response, Event. /// /// Request: /// {"id": <Object>. "method": <String>, "params": <optional, Object?>} /// /// Response: /// {"id": <Object>. "result": <optional, Object?>} for a successful response. /// {"id": <Object>. "error": <Object>, "stackTrace": <String>} for an error response. /// /// Event: /// {"event": <String>. "params": <optional, Object?>} void _handleMessage(DaemonMessage message) { final Map<String, Object?> data = message.data; if (data['id'] != null) { if (data['method'] == null) { // This is a response to previously sent request. final String id = data['id']! as String; if (data['error'] != null) { // This is an error response. _logger.printTrace('<- Error response received from daemon, id = $id'); final Object error = data['error']!; final String stackTrace = data['stackTrace'] as String? ?? ''; _outgoingRequestCompleters.remove(id)?.completeError(error, StackTrace.fromString(stackTrace)); } else { _logger.printTrace('<- Response received from daemon, id = $id'); final Object? result = data['result']; _outgoingRequestCompleters.remove(id)?.complete(result); } } else { _incomingCommands.add(message); } } else if (data['event'] != null) { // This is an event _logger.printTrace('<- Event received: ${data['event']}'); final Object? eventName = data['event']; if (eventName is String) { _events.add(DaemonEventData( eventName, data['params'], message.binary, )); } else { throwToolExit('event name received is not string!'); } } else { _logger.printError('Unknown data received from daemon'); } }
/// Cleans up any resources used in the connection. Future<void> dispose() async { await _commandSubscription.cancel(); await _daemonStreams.dispose(); unawaited(_events.close()); unawaited(_incomingCommands.close()); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071// 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:collection';
/// Parsing the output of "dart pub deps --json"////// expected structure: {"name": "package name", "source": "hosted", "dependencies": [...]}class DartDependencyPackage { DartDependencyPackage({ required this.name, required this.version, required this.source, required this.dependencies, });
factory DartDependencyPackage.fromHashMap(dynamic packageInfo) { String name = ''; String version = ''; String source = ''; List<dynamic> dependencies = <dynamic>[];
if (packageInfo is LinkedHashMap) { final LinkedHashMap<String, dynamic> info = packageInfo as LinkedHashMap<String, dynamic>; if (info.containsKey('name')) { name = info['name'] as String; } if (info.containsKey('version')) { version = info['version'] as String; } if (info.containsKey('source')) { source = info['source'] as String; } if (info.containsKey('dependencies')) { dependencies = info['dependencies'] as List<dynamic>; } } return DartDependencyPackage( name: name, version: version, source: source, dependencies: dependencies.map((dynamic e) => e.toString()).toList(), ); }
final String name; final String version; final String source; final List<String> dependencies;
}
class DartPubJson { DartPubJson(this._json); final LinkedHashMap<String, dynamic> _json; final List<DartDependencyPackage> _packages = <DartDependencyPackage>[];
List<DartDependencyPackage> get packages { if (_packages.isNotEmpty) { return _packages; } if (_json.containsKey('packages')) { final List<dynamic> packagesInfo = _json['packages'] as List<dynamic>; for (final dynamic info in packagesInfo) { _packages.add(DartDependencyPackage.fromHashMap(info)); } } return _packages; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353// 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:process/process.dart';
import 'application_package.dart';import 'base/file_system.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/os.dart';import 'build_info.dart';import 'convert.dart';import 'devfs.dart';import 'device.dart';import 'device_port_forwarder.dart';import 'protocol_discovery.dart';
/// A partial implementation of Device for desktop-class devices to inherit/// from, containing implementations that are common to all desktop devices.abstract class DesktopDevice extends Device { DesktopDevice(super.id, { required PlatformType super.platformType, required super.ephemeral, required Logger logger, required ProcessManager processManager, required FileSystem fileSystem, required OperatingSystemUtils operatingSystemUtils, }) : _logger = logger, _processManager = processManager, _fileSystem = fileSystem, _operatingSystemUtils = operatingSystemUtils, super( category: Category.desktop, );
final Logger _logger; final ProcessManager _processManager; final FileSystem _fileSystem; final OperatingSystemUtils _operatingSystemUtils; final Set<Process> _runningProcesses = <Process>{}; final DesktopLogReader _deviceLogReader = DesktopLogReader();
@override DevFSWriter createDevFSWriter(ApplicationPackage? app, String? userIdentifier) { return LocalDevFSWriter(fileSystem: _fileSystem); }
// Since the host and target devices are the same, no work needs to be done // to install the application. @override Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, }) async => true;
// Since the host and target devices are the same, no work needs to be done // to install the application. @override Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => true;
// Since the host and target devices are the same, no work needs to be done // to install the application. @override Future<bool> installApp( ApplicationPackage app, { String? userIdentifier, }) async => true;
// Since the host and target devices are the same, no work needs to be done // to uninstall the application. @override Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }) async => true;
@override Future<bool> get isLocalEmulator async => false;
@override Future<String?> get emulatorId async => null;
@override DevicePortForwarder get portForwarder => const NoOpDevicePortForwarder();
@override Future<String> get sdkNameAndVersion async => _operatingSystemUtils.name;
@override bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;
@override DeviceLogReader getLogReader({ ApplicationPackage? app, bool includePastLogs = false, }) { assert(!includePastLogs, 'Past log reading not supported on desktop.'); return _deviceLogReader; }
@override void clearLogs() {}
@override Future<LaunchResult> startApp( ApplicationPackage package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, dynamic> platformArgs = const <String, dynamic>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, }) async { if (!prebuiltApplication) { await buildForDevice( buildInfo: debuggingOptions.buildInfo, mainPath: mainPath, ); }
// Ensure that the executable is locatable. final BuildInfo buildInfo = debuggingOptions.buildInfo; final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; final String? executable = executablePathForDevice(package, buildInfo); if (executable == null) { _logger.printError('Unable to find executable to run'); return LaunchResult.failed(); }
Process process; final List<String> command = <String>[ executable, ...debuggingOptions.dartEntrypointArgs, ]; try { process = await _processManager.start( command, environment: _computeEnvironment(debuggingOptions, traceStartup, route), ); } on ProcessException catch (e) { _logger.printError('Unable to start executable "${command.join(' ')}": $e'); rethrow; } _runningProcesses.add(process); unawaited(process.exitCode.then((_) => _runningProcesses.remove(process)));
_deviceLogReader.initializeProcess(process); if (debuggingOptions.buildInfo.isRelease) { return LaunchResult.succeeded(); } final ProtocolDiscovery vmServiceDiscovery = ProtocolDiscovery.vmService(_deviceLogReader, devicePort: debuggingOptions.deviceVmServicePort, hostPort: debuggingOptions.hostVmServicePort, ipv6: ipv6, logger: _logger, ); try { final Uri? vmServiceUri = await vmServiceDiscovery.uri; if (vmServiceUri != null) { onAttached(package, buildInfo, process); return LaunchResult.succeeded(vmServiceUri: vmServiceUri); } _logger.printError( 'Error waiting for a debug connection: ' 'The log reader stopped unexpectedly, or never started.', ); } on Exception catch (error) { _logger.printError('Error waiting for a debug connection: $error'); } finally { await vmServiceDiscovery.cancel(); } return LaunchResult.failed(); }
@override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { bool succeeded = true; // Walk a copy of _runningProcesses, since the exit handler removes from the // set. for (final Process process in Set<Process>.of(_runningProcesses)) { succeeded &= _processManager.killPid(process.pid); } return succeeded; }
@override Future<void> dispose() async { await portForwarder.dispose(); }
/// Builds the current project for this device, with the given options. Future<void> buildForDevice({ required BuildInfo buildInfo, String? mainPath, });
/// Returns the path to the executable to run for [package] on this device for /// the given [buildMode]. String? executablePathForDevice(ApplicationPackage package, BuildInfo buildInfo);
/// Called after a process is attached, allowing any device-specific extra /// steps to be run. void onAttached(ApplicationPackage package, BuildInfo buildInfo, Process process) {}
/// Computes a set of environment variables used to pass debugging information /// to the engine without interfering with application level command line /// arguments. /// /// The format of the environment variables is: /// * FLUTTER_ENGINE_SWITCHES to the number of switches. /// * FLUTTER_ENGINE_SWITCH_<N> (indexing from 1) to the individual switches. Map<String, String> _computeEnvironment(DebuggingOptions debuggingOptions, bool traceStartup, String? route) { int flags = 0; final Map<String, String> environment = <String, String>{};
void addFlag(String value) { flags += 1; environment['FLUTTER_ENGINE_SWITCH_$flags'] = value; } void finish() { environment['FLUTTER_ENGINE_SWITCHES'] = flags.toString(); }
addFlag('enable-dart-profiling=true');
if (traceStartup) { addFlag('trace-startup=true'); } if (route != null) { addFlag('route=$route'); } if (debuggingOptions.enableSoftwareRendering) { addFlag('enable-software-rendering=true'); } if (debuggingOptions.skiaDeterministicRendering) { addFlag('skia-deterministic-rendering=true'); } if (debuggingOptions.traceSkia) { addFlag('trace-skia=true'); } if (debuggingOptions.traceAllowlist != null) { addFlag('trace-allowlist=${debuggingOptions.traceAllowlist}'); } if (debuggingOptions.traceSkiaAllowlist != null) { addFlag('trace-skia-allowlist=${debuggingOptions.traceSkiaAllowlist}'); } if (debuggingOptions.traceSystrace) { addFlag('trace-systrace=true'); } if (debuggingOptions.traceToFile != null) { addFlag('trace-to-file=${debuggingOptions.traceToFile}'); } if (debuggingOptions.endlessTraceBuffer) { addFlag('endless-trace-buffer=true'); } if (debuggingOptions.dumpSkpOnShaderCompilation) { addFlag('dump-skp-on-shader-compilation=true'); } if (debuggingOptions.cacheSkSL) { addFlag('cache-sksl=true'); } if (debuggingOptions.purgePersistentCache) { addFlag('purge-persistent-cache=true'); } switch (debuggingOptions.enableImpeller) { case ImpellerStatus.enabled: addFlag('enable-impeller=true'); case ImpellerStatus.disabled: case ImpellerStatus.platformDefault: addFlag('enable-impeller=false'); } // Options only supported when there is a VM Service connection between the // tool and the device, usually in debug or profile mode. if (debuggingOptions.debuggingEnabled) { if (debuggingOptions.deviceVmServicePort != null) { addFlag('vm-service-port=${debuggingOptions.deviceVmServicePort}'); } if (debuggingOptions.buildInfo.isDebug) { addFlag('enable-checked-mode=true'); addFlag('verify-entry-points=true'); } if (debuggingOptions.startPaused) { addFlag('start-paused=true'); } if (debuggingOptions.disableServiceAuthCodes) { addFlag('disable-service-auth-codes=true'); } final String dartVmFlags = computeDartVmFlags(debuggingOptions); if (dartVmFlags.isNotEmpty) { addFlag('dart-flags=$dartVmFlags'); } if (debuggingOptions.useTestFonts) { addFlag('use-test-fonts=true'); } if (debuggingOptions.verboseSystemLogs) { addFlag('verbose-logging=true'); } } finish(); return environment; }}
/// A log reader for desktop applications that delegates to a [Process] stdout/// and stderr streams.class DesktopLogReader extends DeviceLogReader { final StreamController<List<int>> _inputController = StreamController<List<int>>.broadcast();
/// Begin listening to the stdout and stderr streams of the provided [process]. void initializeProcess(Process process) { final StreamSubscription<List<int>> stdoutSub = process.stdout.listen( _inputController.add, ); final StreamSubscription<List<int>> stderrSub = process.stderr.listen( _inputController.add, ); final Future<void> stdioFuture = Future.wait<void>(<Future<void>>[ stdoutSub.asFuture<void>(), stderrSub.asFuture<void>(), ]); process.exitCode.whenComplete(() async { // Wait for output to be fully processed. await stdioFuture; // The streams have already completed, so waiting for the stream // cancellation to complete is not needed. unawaited(stdoutSub.cancel()); unawaited(stderrSub.cancel()); await _inputController.close(); }); }
@override Stream<String> get logLines { return _inputController.stream .transform(utf8.decoder) .transform(const LineSplitter()); }
@override String get name => 'desktop';
@override void dispose() { // Nothing to dispose. }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768// 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:package_config/package_config.dart';import 'package:vm_service/vm_service.dart' as vm_service;
import 'asset.dart';import 'base/context.dart';import 'base/file_system.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/net.dart';import 'base/os.dart';import 'build_info.dart';import 'build_system/targets/scene_importer.dart';import 'build_system/targets/shader_compiler.dart';import 'compile.dart';import 'convert.dart' show base64, utf8;import 'vmservice.dart';
const String _kFontManifest = 'FontManifest.json';
class DevFSConfig { /// Should DevFS assume that symlink targets are stable? bool cacheSymlinks = false; /// Should DevFS assume that there are no symlinks to directories? bool noDirectorySymlinks = false;}
DevFSConfig? get devFSConfig => context.get<DevFSConfig>();
/// Common superclass for content copied to the device.abstract class DevFSContent { /// Return true if this is the first time this method is called /// or if the entry has been modified since this method was last called. bool get isModified;
/// Return true if this is the first time this method is called /// or if the entry has been modified after the given time /// or if the given time is null. bool isModifiedAfter(DateTime time);
int get size;
Future<List<int>> contentsAsBytes();
Stream<List<int>> contentsAsStream();
Stream<List<int>> contentsAsCompressedStream( OperatingSystemUtils osUtils, ) { return osUtils.gzipLevel1Stream(contentsAsStream()); }}
// File content to be copied to the device.class DevFSFileContent extends DevFSContent { DevFSFileContent(this.file);
final FileSystemEntity file; File? _linkTarget; FileStat? _fileStat;
File _getFile() { final File? linkTarget = _linkTarget; if (linkTarget != null) { return linkTarget; } if (file is Link) { // The link target. return file.fileSystem.file(file.resolveSymbolicLinksSync()); } return file as File; }
void _stat() { final File? linkTarget = _linkTarget; if (linkTarget != null) { // Stat the cached symlink target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _linkTarget = null; } else { _fileStat = fileStat; return; } } final FileStat fileStat = file.statSync(); _fileStat = fileStat.type == FileSystemEntityType.notFound ? null : fileStat; if (_fileStat != null && _fileStat?.type == FileSystemEntityType.link) { // Resolve, stat, and maybe cache the symlink target. final String resolved = file.resolveSymbolicLinksSync(); final File linkTarget = file.fileSystem.file(resolved); // Stat the link target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _fileStat = null; _linkTarget = null; } else if (devFSConfig?.cacheSymlinks ?? false) { _linkTarget = linkTarget; } } }
@override bool get isModified { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(oldFileStat.modified); }
@override bool isModifiedAfter(DateTime time) { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(time); }
@override int get size { if (_fileStat == null) { _stat(); } // Can still be null if the file wasn't found. return _fileStat?.size ?? 0; }
@override Future<List<int>> contentsAsBytes() async => _getFile().readAsBytes();
@override Stream<List<int>> contentsAsStream() => _getFile().openRead();}
/// Byte content to be copied to the device.class DevFSByteContent extends DevFSContent { DevFSByteContent(this._bytes);
List<int> _bytes;
bool _isModified = true; DateTime _modificationTime = DateTime.now();
List<int> get bytes => _bytes;
set bytes(List<int> value) { _bytes = value; _isModified = true; _modificationTime = DateTime.now(); }
/// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; }
@override bool isModifiedAfter(DateTime time) { return _modificationTime.isAfter(time); }
@override int get size => _bytes.length;
@override Future<List<int>> contentsAsBytes() async => _bytes;
@override Stream<List<int>> contentsAsStream() => Stream<List<int>>.fromIterable(<List<int>>[_bytes]);}
/// String content to be copied to the device.class DevFSStringContent extends DevFSByteContent { DevFSStringContent(String string) : _string = string, super(utf8.encode(string));
String _string;
String get string => _string;
set string(String value) { _string = value; super.bytes = utf8.encode(_string); }
@override set bytes(List<int> value) { string = utf8.decode(value); }}
/// A string compressing DevFSContent.////// A specialized DevFSContent similar to DevFSByteContent where the contents/// are the compressed bytes of a string. Its difference is that the original/// uncompressed string can be compared with directly without the indirection/// of a compute-expensive uncompress/decode and compress/encode to compare/// the strings.////// The `hintString` parameter is a zlib dictionary hinting mechanism to suggest/// the most common string occurrences to potentially assist with compression.class DevFSStringCompressingBytesContent extends DevFSContent { DevFSStringCompressingBytesContent(this._string, { String? hintString }) : _compressor = ZLibEncoder( dictionary: hintString == null ? null : utf8.encode(hintString), gzip: true, level: 9, );
final String _string; final ZLibEncoder _compressor; final DateTime _modificationTime = DateTime.now();
bool _isModified = true;
late final List<int> bytes = _compressor.convert(utf8.encode(_string));
/// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; }
@override bool isModifiedAfter(DateTime time) { return _modificationTime.isAfter(time); }
@override int get size => bytes.length;
@override Future<List<int>> contentsAsBytes() async => bytes;
@override Stream<List<int>> contentsAsStream() => Stream<List<int>>.value(bytes);
/// This checks the source string with another string. bool equals(String string) => _string == string;}
class DevFSException implements Exception { DevFSException(this.message, [this.error, this.stackTrace]); final String message; final dynamic error; final StackTrace? stackTrace;
@override String toString() => 'DevFSException($message, $error, $stackTrace)';}
/// Interface responsible for syncing asset files to a development device.abstract class DevFSWriter { /// Write the assets in [entries] to the target device. /// /// The keys of the map are relative from the [baseUri]. /// /// Throws a [DevFSException] if the process fails to complete. Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, DevFSWriter parent);}
class _DevFSHttpWriter implements DevFSWriter { _DevFSHttpWriter( this.fsName, FlutterVmService serviceProtocol, { required OperatingSystemUtils osUtils, required HttpClient httpClient, required Logger logger, Duration? uploadRetryThrottle, }) : httpAddress = serviceProtocol.httpAddress, _client = httpClient, _osUtils = osUtils, _uploadRetryThrottle = uploadRetryThrottle, _logger = logger;
final HttpClient _client; final OperatingSystemUtils _osUtils; final Logger _logger; final Duration? _uploadRetryThrottle;
final String fsName; final Uri? httpAddress;
// 3 was chosen to try to limit the variance in the time it takes to execute // `await request.close()` since there is a known bug in Dart where it doesn't // always return a status code in response to a PUT request: // https://github.com/dart-lang/sdk/issues/43525. static const int kMaxInFlight = 3;
int _inFlight = 0; late Map<Uri, DevFSContent> _outstanding; late Completer<void> _completer;
@override Future<void> write(Map<Uri, DevFSContent> entries, Uri devFSBase, [DevFSWriter? parent]) async { try { _client.maxConnectionsPerHost = kMaxInFlight; _completer = Completer<void>(); _outstanding = Map<Uri, DevFSContent>.of(entries); _scheduleWrites(); await _completer.future; } on SocketException catch (socketException, stackTrace) { _logger.printTrace('DevFS sync failed. Lost connection to device: $socketException'); throw DevFSException('Lost connection to device.', socketException, stackTrace); } on Exception catch (exception, stackTrace) { _logger.printError('Could not update files on device: $exception'); throw DevFSException('Sync failed', exception, stackTrace); } }
void _scheduleWrites() { while ((_inFlight < kMaxInFlight) && (!_completer.isCompleted) && _outstanding.isNotEmpty) { final Uri deviceUri = _outstanding.keys.first; final DevFSContent content = _outstanding.remove(deviceUri)!; _startWrite(deviceUri, content, retry: 10); _inFlight += 1; } if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) { _completer.complete(); } }
Future<void> _startWrite( Uri deviceUri, DevFSContent content, { int retry = 0, }) async { while (true) { try { final HttpClientRequest request = await _client.putUrl(httpAddress!); request.headers.removeAll(HttpHeaders.acceptEncodingHeader); request.headers.add('dev_fs_name', fsName); request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri'))); final Stream<List<int>> contents = content.contentsAsCompressedStream( _osUtils, ); await request.addStream(contents); // Once the bug in Dart is solved we can remove the timeout // (https://github.com/dart-lang/sdk/issues/43525). try { final HttpClientResponse response = await request.close().timeout( const Duration(seconds: 60)); response.listen((_) {}, onError: (dynamic error) { _logger.printTrace('error: $error'); }, cancelOnError: true, ); } on TimeoutException { request.abort(); // This should throw "HttpException: Request has been aborted". await request.done; // Just to be safe we rethrow the TimeoutException. rethrow; } break; } on Exception catch (error, trace) { if (!_completer.isCompleted) { _logger.printTrace('Error writing "$deviceUri" to DevFS: $error'); if (retry > 0) { retry--; _logger.printTrace('trying again in a few - $retry more attempts left'); await Future<void>.delayed(_uploadRetryThrottle ?? const Duration(milliseconds: 500)); continue; } _completer.completeError(error, trace); } } } _inFlight -= 1; _scheduleWrites(); }}
// Basic statistics for DevFS update operation.class UpdateFSReport { UpdateFSReport({ bool success = false, int invalidatedSourcesCount = 0, int syncedBytes = 0, int scannedSourcesCount = 0, Duration compileDuration = Duration.zero, Duration transferDuration = Duration.zero, Duration findInvalidatedDuration = Duration.zero, }) : _success = success, _invalidatedSourcesCount = invalidatedSourcesCount, _syncedBytes = syncedBytes, _scannedSourcesCount = scannedSourcesCount, _compileDuration = compileDuration, _transferDuration = transferDuration, _findInvalidatedDuration = findInvalidatedDuration;
bool get success => _success; int get invalidatedSourcesCount => _invalidatedSourcesCount; int get syncedBytes => _syncedBytes; int get scannedSourcesCount => _scannedSourcesCount; Duration get compileDuration => _compileDuration; Duration get transferDuration => _transferDuration; Duration get findInvalidatedDuration => _findInvalidatedDuration;
bool _success; int _invalidatedSourcesCount; int _syncedBytes; int _scannedSourcesCount; Duration _compileDuration; Duration _transferDuration; Duration _findInvalidatedDuration;
void incorporateResults(UpdateFSReport report) { if (!report._success) { _success = false; } _invalidatedSourcesCount += report._invalidatedSourcesCount; _syncedBytes += report._syncedBytes; _scannedSourcesCount += report._scannedSourcesCount; _compileDuration += report._compileDuration; _transferDuration += report._transferDuration; _findInvalidatedDuration += report._findInvalidatedDuration; }}
class DevFS { /// Create a [DevFS] named [fsName] for the local files in [rootDirectory]. /// /// Failed uploads are retried after [uploadRetryThrottle] duration, defaults to 500ms. DevFS( FlutterVmService serviceProtocol, this.fsName, this.rootDirectory, { required OperatingSystemUtils osUtils, required Logger logger, required FileSystem fileSystem, HttpClient? httpClient, Duration? uploadRetryThrottle, StopwatchFactory stopwatchFactory = const StopwatchFactory(), }) : _vmService = serviceProtocol, _logger = logger, _fileSystem = fileSystem, _httpWriter = _DevFSHttpWriter( fsName, serviceProtocol, osUtils: osUtils, logger: logger, uploadRetryThrottle: uploadRetryThrottle, httpClient: httpClient ?? ((context.get<HttpClientFactory>() == null) ? HttpClient() : context.get<HttpClientFactory>()!())), _stopwatchFactory = stopwatchFactory;
final FlutterVmService _vmService; final _DevFSHttpWriter _httpWriter; final Logger _logger; final FileSystem _fileSystem; final StopwatchFactory _stopwatchFactory;
final String fsName; final Directory? rootDirectory; final Set<String> assetPathsToEvict = <String>{}; final Set<String> shaderPathsToEvict = <String>{}; final Set<String> scenePathsToEvict = <String>{};
// A flag to indicate whether we have called `setAssetDirectory` on the target device. bool hasSetAssetDirectory = false;
/// Whether the font manifest was uploaded during [update]. bool didUpdateFontManifest = false;
List<Uri> sources = <Uri>[]; DateTime? lastCompiled; DateTime? _previousCompiled; PackageConfig? lastPackageConfig;
Uri? _baseUri; Uri? get baseUri => _baseUri;
Uri deviceUriToHostUri(Uri deviceUri) { final String deviceUriString = deviceUri.toString(); final String baseUriString = baseUri.toString(); if (deviceUriString.startsWith(baseUriString)) { final String deviceUriSuffix = deviceUriString.substring(baseUriString.length); return rootDirectory!.uri.resolve(deviceUriSuffix); } return deviceUri; }
Future<Uri> create() async { _logger.printTrace('DevFS: Creating new filesystem on the device ($_baseUri)'); try { final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } on vm_service.RPCError catch (rpcException) { if (rpcException.code == RPCErrorCodes.kServiceDisappeared) { // This can happen if the device has been disconnected, so translate to // a DevFSException, which the caller will handle. throw DevFSException('Service disconnected', rpcException); } // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h if (rpcException.code != 1001) { // Other RPCErrors are unexpected. Rethrow so it will hit crash // logging. rethrow; } _logger.printTrace('DevFS: Creating failed. Destroying and trying again'); await destroy(); final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)'); return _baseUri!; }
Future<void> destroy() async { _logger.printTrace('DevFS: Deleting filesystem on the device ($_baseUri)'); await _vmService.deleteDevFS(fsName); _logger.printTrace('DevFS: Deleted filesystem on the device ($_baseUri)'); }
/// Mark the [lastCompiled] time to the previous successful compile. /// /// Sometimes a hot reload will be rejected by the VM due to a change in the /// structure of the code not supporting the hot reload. In these cases, /// the best resolution is a hot restart. However, the resident runner /// will not recognize this file as having been changed since the delta /// will already have been accepted. Instead, reset the compile time so /// that the last updated files are included in subsequent compilations until /// a reload is accepted. void resetLastCompiled() { lastCompiled = _previousCompiled; }
/// Updates files on the device. /// /// Returns the number of bytes synced. Future<UpdateFSReport> update({ required Uri mainUri, required ResidentCompiler generator, required bool trackWidgetCreation, required String pathToReload, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, required String dillOutputPath, required DevelopmentShaderCompiler shaderCompiler, DevelopmentSceneImporter? sceneImporter, DevFSWriter? devFSWriter, String? target, AssetBundle? bundle, DateTime? firstBuildTime, bool bundleFirstUpload = false, bool fullRestart = false, String? projectRootPath, File? dartPluginRegistrant, }) async { final DateTime candidateCompileTime = DateTime.now(); didUpdateFontManifest = false; lastPackageConfig = packageConfig;
// Update modified files final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{}; final List<Future<void>> pendingAssetBuilds = <Future<void>>[]; bool assetBuildFailed = false; int syncedBytes = 0; if (fullRestart) { generator.reset(); } // On a full restart, or on an initial compile for the attach based workflow, // this will produce a full dill. Subsequent invocations will produce incremental // dill files that depend on the invalidated files. _logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files');
// Await the compiler response after checking if the bundle is updated. This allows the file // stating to be done while waiting for the frontend_server response. final Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start(); final Future<CompilerOutput?> pendingCompilerOutput = generator.recompile( mainUri, invalidatedFiles, outputPath: dillOutputPath, fs: _fileSystem, projectRootPath: projectRootPath, packageConfig: packageConfig, checkDartPluginRegistry: true, // The entry point is assumed not to have changed. dartPluginRegistrant: dartPluginRegistrant, ).then((CompilerOutput? result) { compileTimer.stop(); return result; });
if (bundle != null) { // Mark processing of bundle started for testability of starting the compile // before processing bundle. _logger.printTrace('Processing bundle.'); // await null to give time for telling the compiler to compile. await null;
// The tool writes the assets into the AssetBundle working dir so that they // are in the same location in DevFS and the iOS simulator. final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory()); final String assetDirectory = getAssetBuildDirectory(); bundle.entries.forEach((String archivePath, DevFSContent content) { // If the content is backed by a real file, isModified will file stat and return true if // it was modified since the last time this was called. if (!content.isModified || bundleFirstUpload) { return; } // Modified shaders must be recompiled per-target platform. final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath)); if (deviceUri.path.startsWith(assetBuildDirPrefix)) { archivePath = deviceUri.path.substring(assetBuildDirPrefix.length); } // If the font manifest is updated, mark this as true so the hot runner // can invoke a service extension to force the engine to reload fonts. if (archivePath == _kFontManifest) { didUpdateFontManifest = true; }
switch (bundle.entryKinds[archivePath]) { case AssetKind.shader: final Future<DevFSContent?> pending = shaderCompiler.recompileShader(content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { shaderPathsToEvict.add(archivePath); } }); case AssetKind.model: if (sceneImporter == null) { break; } final Future<DevFSContent?> pending = sceneImporter.reimportScene(content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { scenePathsToEvict.add(archivePath); } }); case AssetKind.regular: case AssetKind.font: case null: dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { assetPathsToEvict.add(archivePath); } } });
// Mark processing of bundle done for testability of starting the compile // before processing bundle. _logger.printTrace('Bundle processing done.'); } final CompilerOutput? compilerOutput = await pendingCompilerOutput; if (compilerOutput == null || compilerOutput.errorCount > 0) { return UpdateFSReport(); } // Only update the last compiled time if we successfully compiled. _previousCompiled = lastCompiled; lastCompiled = candidateCompileTime; // list of sources that needs to be monitored are in [compilerOutput.sources] sources = compilerOutput.sources; // // Don't send full kernel file that would overwrite what VM already // started loading from. if (!bundleFirstUpload) { final String compiledBinary = compilerOutput.outputFilename; if (compiledBinary.isNotEmpty) { final Uri entryUri = _fileSystem.path.toUri(pathToReload); final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary)); syncedBytes += content.size; dirtyEntries[entryUri] = content; } } _logger.printTrace('Updating files.'); final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start();
await Future.wait(pendingAssetBuilds); if (assetBuildFailed) { return UpdateFSReport(); }
if (dirtyEntries.isNotEmpty) { await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter); } transferTimer.stop(); _logger.printTrace('DevFS: Sync finished'); return UpdateFSReport( success: true, syncedBytes: syncedBytes, invalidatedSourcesCount: invalidatedFiles.length, compileDuration: compileTimer.elapsed, transferDuration: transferTimer.elapsed, ); }
/// Converts a platform-specific file path to a platform-independent URL path. String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/';}
/// An implementation of a devFS writer which copies physical files for devices/// running on the same host.////// DevFS entries which correspond to physical files are copied using [File.copySync],/// while entries that correspond to arbitrary string/byte values are written from/// memory.////// Requires that the file system is the same for both the tool and application.class LocalDevFSWriter implements DevFSWriter { LocalDevFSWriter({ required FileSystem fileSystem, }) : _fileSystem = fileSystem;
final FileSystem _fileSystem;
@override Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, [DevFSWriter? parent]) async { try { for (final MapEntry<Uri, DevFSContent> entry in entries.entries) { final Uri uri = entry.key; final DevFSContent devFSContent = entry.value; final File destination = _fileSystem.file(baseUri.resolveUri(uri)); if (!destination.parent.existsSync()) { destination.parent.createSync(recursive: true); } if (devFSContent is DevFSFileContent) { final File content = devFSContent.file as File; content.copySync(destination.path); continue; } destination.writeAsBytesSync(await devFSContent.contentsAsBytes()); } } on FileSystemException catch (err) { throw DevFSException(err.toString()); } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400// 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:math' as math;
import 'package:meta/meta.dart';
import 'application_package.dart';import 'base/context.dart';import 'base/dds.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/utils.dart';import 'build_info.dart';import 'devfs.dart';import 'device_port_forwarder.dart';import 'project.dart';import 'vmservice.dart';
DeviceManager? get deviceManager => context.get<DeviceManager>();
/// A description of the kind of workflow the device supports.enum Category { web._('web'), desktop._('desktop'), mobile._('mobile');
const Category._(this.value);
final String value;
@override String toString() => value;
static Category? fromString(String category) { return const <String, Category>{ 'web': web, 'desktop': desktop, 'mobile': mobile, }[category]; }}
/// The platform sub-folder that a device type supports.enum PlatformType { web, android, ios, linux, macos, windows, fuchsia, custom, windowsPreview;
@override String toString() => name;
static PlatformType? fromString(String platformType) => values.asNameMap()[platformType];}
/// A discovery mechanism for flutter-supported development devices.abstract class DeviceManager { DeviceManager({ required Logger logger, }) : _logger = logger;
final Logger _logger;
/// Constructing DeviceManagers is cheap; they only do expensive work if some /// of their methods are called. List<DeviceDiscovery> get deviceDiscoverers;
String? _specifiedDeviceId;
/// A user-specified device ID. String? get specifiedDeviceId { if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') { return null; } return _specifiedDeviceId; }
set specifiedDeviceId(String? id) { _specifiedDeviceId = id; }
/// A minimum duration to use when discovering wireless iOS devices. static const Duration minimumWirelessDeviceDiscoveryTimeout = Duration( seconds: 5, );
/// True when the user has specified a single specific device. bool get hasSpecifiedDeviceId => specifiedDeviceId != null;
/// True when the user has specified all devices by setting /// specifiedDeviceId = 'all'. bool get hasSpecifiedAllDevices => _specifiedDeviceId == 'all';
/// Get devices filtered by [filter] that match the given device id/name. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. /// /// If an exact match is found, return it immediately. Otherwise wait for all /// discoverers to complete and return any partial matches. Future<List<Device>> getDevicesById( String deviceId, { DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter();
final String lowerDeviceId = deviceId.toLowerCase(); bool exactlyMatchesDeviceId(Device device) => device.id.toLowerCase() == lowerDeviceId || device.name.toLowerCase() == lowerDeviceId; bool startsWithDeviceId(Device device) => device.id.toLowerCase().startsWith(lowerDeviceId) || device.name.toLowerCase().startsWith(lowerDeviceId);
// Some discoverers have hard-coded device IDs and return quickly, and others // shell out to other processes and can take longer. // If an ID was specified, first check if it was a "well-known" device id. final Set<String> wellKnownIds = _platformDiscoverers .expand((DeviceDiscovery discovery) => discovery.wellKnownIds) .toSet(); final bool hasWellKnownId = hasSpecifiedDeviceId && wellKnownIds.contains(specifiedDeviceId);
// Process discoverers as they can return results, so if an exact match is // found quickly, we don't wait for all the discoverers to complete. final List<Device> prefixMatches = <Device>[]; final Completer<Device> exactMatchCompleter = Completer<Device>(); final List<Future<List<Device>?>> futureDevices = <Future<List<Device>?>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) if (!hasWellKnownId || discoverer.wellKnownIds.contains(specifiedDeviceId)) discoverer .devices(filter: filter) .then((List<Device> devices) { for (final Device device in devices) { if (exactlyMatchesDeviceId(device)) { exactMatchCompleter.complete(device); return null; } if (startsWithDeviceId(device)) { prefixMatches.add(device); } } return null; }, onError: (dynamic error, StackTrace stackTrace) { // Return matches from other discoverers even if one fails. _logger.printTrace('Ignored error discovering $deviceId: $error'); }), ];
// Wait for an exact match, or for all discoverers to return results. await Future.any<Object>(<Future<Object>>[ exactMatchCompleter.future, Future.wait<List<Device>?>(futureDevices), ]);
if (exactMatchCompleter.isCompleted) { return <Device>[await exactMatchCompleter.future]; } return prefixMatches; }
/// Returns a list of devices filtered by the user-specified device /// id/name (if applicable) and [filter]. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. Future<List<Device>> getDevices({ DeviceDiscoveryFilter? filter, }) { filter ??= DeviceDiscoveryFilter(); final String? id = specifiedDeviceId; if (id == null) { return getAllDevices(filter: filter); } return getDevicesById(id, filter: filter); }
Iterable<DeviceDiscovery> get _platformDiscoverers { return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform); }
/// Returns a list of devices filtered by [filter]. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. Future<List<Device>> getAllDevices({ DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter(); final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) discoverer.devices(filter: filter), ]);
return devices.expand<Device>((List<Device> deviceList) => deviceList).toList(); }
/// Returns a list of devices filtered by [filter]. Discards existing cache of devices. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. /// /// Search for devices to populate the cache for no longer than [timeout]. Future<List<Device>> refreshAllDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter(); final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) discoverer.discoverDevices(filter: filter, timeout: timeout), ]);
return devices.expand<Device>((List<Device> deviceList) => deviceList).toList(); }
/// Discard existing cache of discoverers that are known to take longer to /// discover wireless devices. /// /// Then, search for devices for those discoverers to populate the cache for /// no longer than [timeout]. Future<void> refreshExtendedWirelessDeviceDiscoverers({ Duration? timeout, DeviceDiscoveryFilter? filter, }) async { await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) if (discoverer.requiresExtendedWirelessDeviceDiscovery) discoverer.discoverDevices(timeout: timeout) ]); }
/// Whether we're capable of listing any devices given the current environment configuration. bool get canListAnything { return _platformDiscoverers.any((DeviceDiscovery discoverer) => discoverer.canListAnything); }
/// Get diagnostics about issues with any connected devices. Future<List<String>> getDeviceDiagnostics() async { return <String>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) ...await discoverer.getDiagnostics(), ]; }
/// Determines how to filter devices. /// /// By default, filters to only include devices that are supported by Flutter. /// /// If the user has not specified a device, filters to only include devices /// that are supported by Flutter and supported by the project. /// /// If the user has specified `--device all`, filters to only include devices /// that are supported by Flutter, supported by the project, and supported for `all`. /// /// If [includeDevicesUnsupportedByProject] is true, all devices will be /// considered supported by the project, regardless of user specifications. /// /// This also exists to allow the check to be overridden for google3 clients. DeviceDiscoverySupportFilter deviceSupportFilter({ bool includeDevicesUnsupportedByProject = false, }) { FlutterProject? flutterProject; if (!includeDevicesUnsupportedByProject) { flutterProject = FlutterProject.current(); } if (hasSpecifiedAllDevices) { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll( flutterProject: flutterProject, ); } else if (!hasSpecifiedDeviceId) { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject( flutterProject: flutterProject, ); } else { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter(); } }
/// If the user did not specify to run all or a specific device, then attempt /// to prioritize ephemeral devices. /// /// If there is not exactly one ephemeral device return null. /// /// For example, if the user only typed 'flutter run' and both an Android /// device and desktop device are available, choose the Android device. /// /// Note: ephemeral is nullable for device types where this is not well /// defined. Device? getSingleEphemeralDevice(List<Device> devices){ if (!hasSpecifiedDeviceId) { try { return devices.singleWhere((Device device) => device.ephemeral); } on StateError { return null; } } return null; }}
/// A class for determining how to filter devices based on if they are supported.class DeviceDiscoverySupportFilter { /// Filter devices to only include those supported by Flutter. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter() : _excludeDevicesNotSupportedByProject = false, _excludeDevicesNotSupportedByAll = false, _flutterProject = null;
/// Filter devices to only include those supported by Flutter and the /// provided [flutterProject]. /// /// If [flutterProject] is null, all devices will be considered supported by /// the project. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject({ required FlutterProject? flutterProject, }) : _flutterProject = flutterProject, _excludeDevicesNotSupportedByProject = true, _excludeDevicesNotSupportedByAll = false;
/// Filter devices to only include those supported by Flutter, the provided /// [flutterProject], and `--device all`. /// /// If [flutterProject] is null, all devices will be considered supported by /// the project. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll({ required FlutterProject? flutterProject, }) : _flutterProject = flutterProject, _excludeDevicesNotSupportedByProject = true, _excludeDevicesNotSupportedByAll = true;
final FlutterProject? _flutterProject; final bool _excludeDevicesNotSupportedByProject; final bool _excludeDevicesNotSupportedByAll;
Future<bool> matchesRequirements(Device device) async { final bool meetsSupportByFlutterRequirement = device.isSupported(); final bool meetsSupportForProjectRequirement = !_excludeDevicesNotSupportedByProject || isDeviceSupportedForProject(device); final bool meetsSupportForAllRequirement = !_excludeDevicesNotSupportedByAll || await isDeviceSupportedForAll(device);
return meetsSupportByFlutterRequirement && meetsSupportForProjectRequirement && meetsSupportForAllRequirement; }
/// User has specified `--device all`. /// /// Always remove web and fuchsia devices from `all`. This setting /// currently requires devices to share a frontend_server and resident /// runner instance. Both web and fuchsia require differently configured /// compilers, and web requires an entirely different resident runner. Future<bool> isDeviceSupportedForAll(Device device) async { final TargetPlatform devicePlatform = await device.targetPlatform; return device.isSupported() && devicePlatform != TargetPlatform.fuchsia_arm64 && devicePlatform != TargetPlatform.fuchsia_x64 && devicePlatform != TargetPlatform.web_javascript && isDeviceSupportedForProject(device); }
/// Returns whether the device is supported for the project. /// /// A device can be supported by Flutter but not supported for the project /// (e.g. when the user has removed the iOS directory from their project). /// /// This also exists to allow the check to be overridden for google3 clients. If /// [_flutterProject] is null then return true. bool isDeviceSupportedForProject(Device device) { if (!device.isSupported()) { return false; } if (_flutterProject == null) { return true; } return device.isSupportedForProject(_flutterProject); }}
/// A class for filtering devices.////// If [excludeDisconnected] is true, only devices detected as connected will be included.////// If [supportFilter] is provided, only devices matching the requirements will be included.////// If [deviceConnectionInterface] is provided, only devices matching the DeviceConnectionInterface will be included.class DeviceDiscoveryFilter { DeviceDiscoveryFilter({ this.excludeDisconnected = true, this.supportFilter, this.deviceConnectionInterface, });
final bool excludeDisconnected; final DeviceDiscoverySupportFilter? supportFilter; final DeviceConnectionInterface? deviceConnectionInterface;
Future<bool> matchesRequirements(Device device) async { final DeviceDiscoverySupportFilter? localSupportFilter = supportFilter;
final bool meetsConnectionRequirement = !excludeDisconnected || device.isConnected; final bool meetsSupportRequirements = localSupportFilter == null || (await localSupportFilter.matchesRequirements(device)); final bool meetsConnectionInterfaceRequirement = matchesDeviceConnectionInterface(device, deviceConnectionInterface);
return meetsConnectionRequirement && meetsSupportRequirements && meetsConnectionInterfaceRequirement; }
Future<List<Device>> filterDevices(List<Device> devices) async { devices = <Device>[ for (final Device device in devices) if (await matchesRequirements(device)) device, ]; return devices; }
bool matchesDeviceConnectionInterface( Device device, DeviceConnectionInterface? deviceConnectionInterface, ) { if (deviceConnectionInterface == null) { return true; } return device.connectionInterface == deviceConnectionInterface; }}
/// An abstract class to discover and enumerate a specific type of devices.abstract class DeviceDiscovery { bool get supportsPlatform;
/// Whether this device discovery is capable of listing any devices given the /// current environment configuration. bool get canListAnything;
/// Whether this device discovery is known to take longer to discover /// wireless devices. bool get requiresExtendedWirelessDeviceDiscovery => false;
/// Return all connected devices, cached on subsequent calls. Future<List<Device>> devices({DeviceDiscoveryFilter? filter});
/// Return all connected devices. Discards existing cache of devices. Future<List<Device>> discoverDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, });
/// Gets a list of diagnostic messages pertaining to issues with any connected /// devices (will be an empty list if there are no issues). Future<List<String>> getDiagnostics() => Future<List<String>>.value(<String>[]);
/// Hard-coded device IDs that the discoverer can produce. /// /// These values are used by the device discovery to determine if it can /// short-circuit the other detectors if a specific ID is provided. If a /// discoverer has no valid fixed IDs, these should be left empty. /// /// For example, 'windows' or 'linux'. List<String> get wellKnownIds;}
/// A [DeviceDiscovery] implementation that uses polling to discover device adds/// and removals.abstract class PollingDeviceDiscovery extends DeviceDiscovery { PollingDeviceDiscovery(this.name);
static const Duration _pollingInterval = Duration(seconds: 4); static const Duration _pollingTimeout = Duration(seconds: 30);
final String name;
@protected @visibleForTesting ItemListNotifier<Device>? deviceNotifier;
Timer? _timer;
Future<List<Device>> pollingGetDevices({Duration? timeout});
void startPolling() { if (_timer == null) { deviceNotifier ??= ItemListNotifier<Device>(); // Make initial population the default, fast polling timeout. _timer = _initTimer(null, initialCall: true); } }
Timer _initTimer(Duration? pollingTimeout, {bool initialCall = false}) { // Poll for devices immediately on the initial call for faster initial population. return Timer(initialCall ? Duration.zero : _pollingInterval, () async { try { final List<Device> devices = await pollingGetDevices(timeout: pollingTimeout); deviceNotifier!.updateWithNewList(devices); } on TimeoutException { // Do nothing on a timeout. } // Subsequent timeouts after initial population should wait longer. _timer = _initTimer(_pollingTimeout); }); }
void stopPolling() { _timer?.cancel(); _timer = null; }
/// Get devices from cache filtered by [filter]. /// /// If the cache is empty, populate the cache. /// /// If [filter] is null, it may return devices that are not connected. @override Future<List<Device>> devices({DeviceDiscoveryFilter? filter}) { return _populateDevices(filter: filter); }
/// Empty the cache and repopulate it before getting devices from cache filtered by [filter]. /// /// Search for devices to populate the cache for no longer than [timeout]. /// /// If [filter] is null, it may return devices that are not connected. @override Future<List<Device>> discoverDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }) { return _populateDevices(timeout: timeout, filter: filter, resetCache: true); }
/// Get devices from cache filtered by [filter]. /// /// If the cache is empty or [resetCache] is true, populate the cache. /// /// Search for devices to populate the cache for no longer than [timeout]. Future<List<Device>> _populateDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, bool resetCache = false, }) async { if (deviceNotifier == null || resetCache) { final List<Device> devices = await pollingGetDevices(timeout: timeout); // If the cache was populated while the polling was ongoing, do not // overwrite the cache unless it's explicitly refreshing the cache. if (resetCache) { deviceNotifier = ItemListNotifier<Device>.from(devices); } else { deviceNotifier ??= ItemListNotifier<Device>.from(devices); } }
// If a filter is provided, filter cache to only return devices matching. if (filter != null) { return filter.filterDevices(deviceNotifier!.items); } return deviceNotifier!.items; }
Stream<Device> get onAdded { deviceNotifier ??= ItemListNotifier<Device>(); return deviceNotifier!.onAdded; }
Stream<Device> get onRemoved { deviceNotifier ??= ItemListNotifier<Device>(); return deviceNotifier!.onRemoved; }
void dispose() => stopPolling();
@override String toString() => '$name device discovery';}
/// How a device is connected.enum DeviceConnectionInterface { attached, wireless,}
/// A device is a physical hardware that can run a Flutter application.////// This may correspond to a connected iOS or Android device, or represent/// the host operating system in the case of Flutter Desktop.abstract class Device { Device(this.id, { required this.category, required this.platformType, required this.ephemeral, });
final String id;
/// The [Category] for this device type. final Category? category;
/// The [PlatformType] for this device. final PlatformType? platformType;
/// Whether this is an ephemeral device. final bool ephemeral;
bool get isConnected => true;
DeviceConnectionInterface get connectionInterface => DeviceConnectionInterface.attached;
bool get isWirelesslyConnected => connectionInterface == DeviceConnectionInterface.wireless;
String get name;
bool get supportsStartPaused => true;
/// Whether it is an emulated device running on localhost. /// /// This may return `true` for certain physical Android devices, and is /// generally only a best effort guess. Future<bool> get isLocalEmulator;
/// The unique identifier for the emulator that corresponds to this device, or /// null if it is not an emulator. /// /// The ID returned matches that in the output of `flutter emulators`. Fetching /// this name may require connecting to the device and if an error occurs null /// will be returned. Future<String?> get emulatorId;
/// Whether this device can run the provided [buildMode]. /// /// For example, some emulator architectures cannot run profile or /// release builds. FutureOr<bool> supportsRuntimeMode(BuildMode buildMode) => true;
/// Whether the device is a simulator on a platform which supports hardware rendering. // This is soft-deprecated since the logic is not correct expect for iOS simulators. Future<bool> get supportsHardwareRendering async { return true; }
/// Whether the device is supported for the current project directory. bool isSupportedForProject(FlutterProject flutterProject);
/// Check if a version of the given app is already installed. /// /// Specify [userIdentifier] to check if installed for a particular user (Android only). Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, });
/// Check if the latest build of the [app] is already installed. Future<bool> isLatestBuildInstalled(ApplicationPackage app);
/// Install an app package on the current device. /// /// Specify [userIdentifier] to install for a particular user (Android only). Future<bool> installApp( ApplicationPackage app, { String? userIdentifier, });
/// Uninstall an app package from the current device. /// /// Specify [userIdentifier] to uninstall for a particular user, /// defaults to all users (Android only). Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, });
/// Check if the device is supported by Flutter. bool isSupported();
// String meant to be displayed to the user indicating if the device is // supported by Flutter, and, if not, why. String supportMessage() => isSupported() ? 'Supported' : 'Unsupported';
/// The device's platform. Future<TargetPlatform> get targetPlatform;
/// Platform name for display only. Future<String> get targetPlatformDisplayName async => getNameForTargetPlatform(await targetPlatform);
Future<String> get sdkNameAndVersion;
/// Create a platform-specific [DevFSWriter] for the given [app], or /// null if the device does not support them. /// /// For example, the desktop device classes can use a writer which /// copies the files across the local file system. DevFSWriter? createDevFSWriter( ApplicationPackage? app, String? userIdentifier, ) { return null; }
/// Get a log reader for this device. /// /// If `app` is specified, this will return a log reader specific to that /// application. Otherwise, a global log reader will be returned. /// /// If `includePastLogs` is true and the device type supports it, the log /// reader will also include log messages from before the invocation time. /// Defaults to false. FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false, });
/// Get the port forwarder for this device. DevicePortForwarder? get portForwarder;
/// Get the DDS instance for this device. final DartDevelopmentService dds = DartDevelopmentService();
/// Clear the device's logs. void clearLogs();
/// Start an app package on the current device. /// /// [platformArgs] allows callers to pass platform-specific arguments to the /// start call. The build mode is not used by all platforms. Future<LaunchResult> startApp( covariant ApplicationPackage? package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, });
/// Whether this device implements support for hot reload. bool get supportsHotReload => true;
/// Whether this device implements support for hot restart. bool get supportsHotRestart => true;
/// Whether Flutter applications running on this device can be terminated /// from the VM Service. bool get supportsFlutterExit => true;
/// Whether the device supports taking screenshots of a running flutter /// application. bool get supportsScreenshot => false;
/// Whether the device supports the '--fast-start' development mode. bool get supportsFastStart => false;
/// Whether the Flavors feature ('--flavor') is supported for this device. bool get supportsFlavors => false;
/// Stop an app package on the current device. /// /// Specify [userIdentifier] to stop app installed to a profile (Android only). Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, });
/// Query the current application memory usage.. /// /// If the device does not support this callback, an empty map /// is returned. Future<MemoryInfo> queryMemoryInfo() { return Future<MemoryInfo>.value(const MemoryInfo.empty()); }
Future<void> takeScreenshot(File outputFile) => Future<void>.error('unimplemented');
@nonVirtual @override // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode => id.hashCode;
@nonVirtual @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is Device && other.id == id; }
@override String toString() => name;
static Future<List<String>> descriptions(List<Device> devices) async { if (devices.isEmpty) { return const <String>[]; }
// Extract device information final List<List<String>> table = <List<String>>[]; for (final Device device in devices) { String supportIndicator = device.isSupported() ? '' : ' (unsupported)'; final TargetPlatform targetPlatform = await device.targetPlatform; if (await device.isLocalEmulator) { final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator'; supportIndicator += ' ($type)'; } table.add(<String>[ '${device.name} (${device.category})', device.id, await device.targetPlatformDisplayName, '${await device.sdkNameAndVersion}$supportIndicator', ]); }
// Calculate column widths final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i); List<int> widths = indices.map<int>((int i) => 0).toList(); for (final List<String> row in table) { widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList(); }
// Join columns into lines of text return <String>[ for (final List<String> row in table) indices.map<String>((int i) => row[i].padRight(widths[i])).followedBy(<String>[row.last]).join(' • '), ]; }
static Future<void> printDevices(List<Device> devices, Logger logger, { String prefix = '' }) async { for (final String line in await descriptions(devices)) { logger.printStatus('$prefix$line'); } }
static List<String> devicesPlatformTypes(List<Device> devices) { return devices .map( (Device d) => d.platformType.toString(), ).toSet().toList()..sort(); }
/// Convert the Device object to a JSON representation suitable for serialization. Future<Map<String, Object>> toJson() async { final bool isLocalEmu = await isLocalEmulator; return <String, Object>{ 'name': name, 'id': id, 'isSupported': isSupported(), 'targetPlatform': getNameForTargetPlatform(await targetPlatform), 'emulator': isLocalEmu, 'sdk': await sdkNameAndVersion, 'capabilities': <String, Object>{ 'hotReload': supportsHotReload, 'hotRestart': supportsHotRestart, 'screenshot': supportsScreenshot, 'fastStart': supportsFastStart, 'flutterExit': supportsFlutterExit, 'hardwareRendering': isLocalEmu && await supportsHardwareRendering, 'startPaused': supportsStartPaused, }, }; }
/// Clean up resources allocated by device. /// /// For example log readers or port forwarders. Future<void> dispose();}
/// Information about an application's memory usage.abstract class MemoryInfo { /// Const constructor to allow subclasses to be const. const MemoryInfo();
/// Create a [MemoryInfo] object with no information. const factory MemoryInfo.empty() = _NoMemoryInfo;
/// Convert the object to a JSON representation suitable for serialization. Map<String, Object> toJson();}
class _NoMemoryInfo implements MemoryInfo { const _NoMemoryInfo();
@override Map<String, Object> toJson() => <String, Object>{};}
enum ImpellerStatus { platformDefault._(null), enabled._(true), disabled._(false);
const ImpellerStatus._(this.asBool);
factory ImpellerStatus.fromBool(bool? b) { if (b == null) { return platformDefault; } return b ? enabled : disabled; }
final bool? asBool;}
class DebuggingOptions { DebuggingOptions.enabled( this.buildInfo, { this.startPaused = false, this.disableServiceAuthCodes = false, this.enableDds = true, this.cacheStartupProfile = false, this.dartEntrypointArgs = const <String>[], this.dartFlags = '', this.enableSoftwareRendering = false, this.skiaDeterministicRendering = false, this.traceSkia = false, this.traceAllowlist, this.traceSkiaAllowlist, this.traceSystrace = false, this.traceToFile, this.endlessTraceBuffer = false, this.dumpSkpOnShaderCompilation = false, this.cacheSkSL = false, this.purgePersistentCache = false, this.useTestFonts = false, this.verboseSystemLogs = false, this.hostVmServicePort, this.disablePortPublication = false, this.deviceVmServicePort, this.ddsPort, this.devToolsServerAddress, this.hostname, this.port, this.tlsCertPath, this.tlsCertKeyPath, this.webEnableExposeUrl, this.webUseSseForDebugProxy = true, this.webUseSseForDebugBackend = true, this.webUseSseForInjectedClient = true, this.webRunHeadless = false, this.webBrowserDebugPort, this.webBrowserFlags = const <String>[], this.webEnableExpressionEvaluation = false, this.webHeaders = const <String, String>{}, this.webLaunchUrl, this.vmserviceOutFile, this.fastStart = false, this.nullAssertions = false, this.nativeNullAssertions = false, this.enableImpeller = ImpellerStatus.platformDefault, this.enableVulkanValidation = false, this.uninstallFirst = false, this.serveObservatory = false, this.enableDartProfiling = true, this.enableEmbedderApi = false, this.usingCISystem = false, }) : debuggingEnabled = true;
DebuggingOptions.disabled(this.buildInfo, { this.dartEntrypointArgs = const <String>[], this.port, this.hostname, this.tlsCertPath, this.tlsCertKeyPath, this.webEnableExposeUrl, this.webUseSseForDebugProxy = true, this.webUseSseForDebugBackend = true, this.webUseSseForInjectedClient = true, this.webRunHeadless = false, this.webBrowserDebugPort, this.webBrowserFlags = const <String>[], this.webLaunchUrl, this.webHeaders = const <String, String>{}, this.cacheSkSL = false, this.traceAllowlist, this.enableImpeller = ImpellerStatus.platformDefault, this.enableVulkanValidation = false, this.uninstallFirst = false, this.enableDartProfiling = true, this.enableEmbedderApi = false, this.usingCISystem = false, }) : debuggingEnabled = false, useTestFonts = false, startPaused = false, dartFlags = '', disableServiceAuthCodes = false, enableDds = true, cacheStartupProfile = false, enableSoftwareRendering = false, skiaDeterministicRendering = false, traceSkia = false, traceSkiaAllowlist = null, traceSystrace = false, traceToFile = null, endlessTraceBuffer = false, dumpSkpOnShaderCompilation = false, purgePersistentCache = false, verboseSystemLogs = false, hostVmServicePort = null, disablePortPublication = false, deviceVmServicePort = null, ddsPort = null, devToolsServerAddress = null, vmserviceOutFile = null, fastStart = false, webEnableExpressionEvaluation = false, nullAssertions = false, nativeNullAssertions = false, serveObservatory = false;
DebuggingOptions._({ required this.buildInfo, required this.debuggingEnabled, required this.startPaused, required this.dartFlags, required this.dartEntrypointArgs, required this.disableServiceAuthCodes, required this.enableDds, required this.cacheStartupProfile, required this.enableSoftwareRendering, required this.skiaDeterministicRendering, required this.traceSkia, required this.traceAllowlist, required this.traceSkiaAllowlist, required this.traceSystrace, required this.traceToFile, required this.endlessTraceBuffer, required this.dumpSkpOnShaderCompilation, required this.cacheSkSL, required this.purgePersistentCache, required this.useTestFonts, required this.verboseSystemLogs, required this.hostVmServicePort, required this.deviceVmServicePort, required this.disablePortPublication, required this.ddsPort, required this.devToolsServerAddress, required this.port, required this.hostname, required this.tlsCertPath, required this.tlsCertKeyPath, required this.webEnableExposeUrl, required this.webUseSseForDebugProxy, required this.webUseSseForDebugBackend, required this.webUseSseForInjectedClient, required this.webRunHeadless, required this.webBrowserDebugPort, required this.webBrowserFlags, required this.webEnableExpressionEvaluation, required this.webHeaders, required this.webLaunchUrl, required this.vmserviceOutFile, required this.fastStart, required this.nullAssertions, required this.nativeNullAssertions, required this.enableImpeller, required this.enableVulkanValidation, required this.uninstallFirst, required this.serveObservatory, required this.enableDartProfiling, required this.enableEmbedderApi, required this.usingCISystem, });
final bool debuggingEnabled;
final BuildInfo buildInfo; final bool startPaused; final String dartFlags; final List<String> dartEntrypointArgs; final bool disableServiceAuthCodes; final bool enableDds; final bool cacheStartupProfile; final bool enableSoftwareRendering; final bool skiaDeterministicRendering; final bool traceSkia; final String? traceAllowlist; final String? traceSkiaAllowlist; final bool traceSystrace; final String? traceToFile; final bool endlessTraceBuffer; final bool dumpSkpOnShaderCompilation; final bool cacheSkSL; final bool purgePersistentCache; final bool useTestFonts; final bool verboseSystemLogs; final int? hostVmServicePort; final int? deviceVmServicePort; final bool disablePortPublication; final int? ddsPort; final Uri? devToolsServerAddress; final String? port; final String? hostname; final String? tlsCertPath; final String? tlsCertKeyPath; final bool? webEnableExposeUrl; final bool webUseSseForDebugProxy; final bool webUseSseForDebugBackend; final bool webUseSseForInjectedClient; final ImpellerStatus enableImpeller; final bool enableVulkanValidation; final bool serveObservatory; final bool enableDartProfiling; final bool enableEmbedderApi; final bool usingCISystem;
/// Whether the tool should try to uninstall a previously installed version of the app. /// /// This is not implemented for every platform. final bool uninstallFirst;
/// Whether to run the browser in headless mode. /// /// Some CI environments do not provide a display and fail to launch the /// browser with full graphics stack. Some browsers provide a special /// "headless" mode that runs the browser with no graphics. final bool webRunHeadless;
/// The port the browser should use for its debugging protocol. final int? webBrowserDebugPort;
/// Arbitrary browser flags. final List<String> webBrowserFlags;
/// Enable expression evaluation for web target. final bool webEnableExpressionEvaluation;
/// Allow developers to customize the browser's launch URL final String? webLaunchUrl;
/// Allow developers to add custom headers to web server final Map<String, String> webHeaders;
/// A file where the VM Service URL should be written after the application is started. final String? vmserviceOutFile; final bool fastStart;
final bool nullAssertions;
/// Additional null runtime checks inserted for web applications. /// /// See also: /// * https://github.com/dart-lang/sdk/blob/main/sdk/lib/html/doc/NATIVE_NULL_ASSERTIONS.md final bool nativeNullAssertions;
List<String> getIOSLaunchArguments( EnvironmentType environmentType, String? route, Map<String, Object?> platformArgs, { bool ipv6 = false, DeviceConnectionInterface interfaceType = DeviceConnectionInterface.attached, bool isCoreDevice = false, }) { final String dartVmFlags = computeDartVmFlags(this); return <String>[ if (enableDartProfiling) '--enable-dart-profiling', if (disableServiceAuthCodes) '--disable-service-auth-codes', if (disablePortPublication) '--disable-vm-service-publication', if (startPaused) '--start-paused', // Wrap dart flags in quotes for physical devices if (environmentType == EnvironmentType.physical && dartVmFlags.isNotEmpty) '--dart-flags="$dartVmFlags"', if (environmentType == EnvironmentType.simulator && dartVmFlags.isNotEmpty) '--dart-flags=$dartVmFlags', if (useTestFonts) '--use-test-fonts', // Core Devices (iOS 17 devices) are debugged through Xcode so don't // include these flags, which are used to check if the app was launched // via Flutter CLI and `ios-deploy`. if (debuggingEnabled && !isCoreDevice) ...<String>[ '--enable-checked-mode', '--verify-entry-points', ], if (enableSoftwareRendering) '--enable-software-rendering', if (traceSystrace) '--trace-systrace', if (traceToFile != null) '--trace-to-file="$traceToFile"', if (skiaDeterministicRendering) '--skia-deterministic-rendering', if (traceSkia) '--trace-skia', if (traceAllowlist != null) '--trace-allowlist="$traceAllowlist"', if (traceSkiaAllowlist != null) '--trace-skia-allowlist="$traceSkiaAllowlist"', if (endlessTraceBuffer) '--endless-trace-buffer', if (dumpSkpOnShaderCompilation) '--dump-skp-on-shader-compilation', if (verboseSystemLogs) '--verbose-logging', if (cacheSkSL) '--cache-sksl', if (purgePersistentCache) '--purge-persistent-cache', if (route != null) '--route=$route', if (platformArgs['trace-startup'] as bool? ?? false) '--trace-startup', if (enableImpeller == ImpellerStatus.enabled) '--enable-impeller=true', if (enableImpeller == ImpellerStatus.disabled) '--enable-impeller=false', if (environmentType == EnvironmentType.physical && deviceVmServicePort != null) '--vm-service-port=$deviceVmServicePort', // The simulator "device" is actually on the host machine so no ports will be forwarded. // Use the suggested host port. if (environmentType == EnvironmentType.simulator && hostVmServicePort != null) '--vm-service-port=$hostVmServicePort', // Tell the VM service to listen on all interfaces, don't restrict to the loopback. if (interfaceType == DeviceConnectionInterface.wireless) '--vm-service-host=${ipv6 ? '::0' : '0.0.0.0'}', if (enableEmbedderApi) '--enable-embedder-api', ]; }
Map<String, Object?> toJson() => <String, Object?>{ 'debuggingEnabled': debuggingEnabled, 'startPaused': startPaused, 'dartFlags': dartFlags, 'dartEntrypointArgs': dartEntrypointArgs, 'disableServiceAuthCodes': disableServiceAuthCodes, 'enableDds': enableDds, 'cacheStartupProfile': cacheStartupProfile, 'enableSoftwareRendering': enableSoftwareRendering, 'skiaDeterministicRendering': skiaDeterministicRendering, 'traceSkia': traceSkia, 'traceAllowlist': traceAllowlist, 'traceSkiaAllowlist': traceSkiaAllowlist, 'traceSystrace': traceSystrace, 'traceToFile': traceToFile, 'endlessTraceBuffer': endlessTraceBuffer, 'dumpSkpOnShaderCompilation': dumpSkpOnShaderCompilation, 'cacheSkSL': cacheSkSL, 'purgePersistentCache': purgePersistentCache, 'useTestFonts': useTestFonts, 'verboseSystemLogs': verboseSystemLogs, 'hostVmServicePort': hostVmServicePort, 'deviceVmServicePort': deviceVmServicePort, 'disablePortPublication': disablePortPublication, 'ddsPort': ddsPort, 'devToolsServerAddress': devToolsServerAddress.toString(), 'port': port, 'hostname': hostname, 'tlsCertPath': tlsCertPath, 'tlsCertKeyPath': tlsCertKeyPath, 'webEnableExposeUrl': webEnableExposeUrl, 'webUseSseForDebugProxy': webUseSseForDebugProxy, 'webUseSseForDebugBackend': webUseSseForDebugBackend, 'webUseSseForInjectedClient': webUseSseForInjectedClient, 'webRunHeadless': webRunHeadless, 'webBrowserDebugPort': webBrowserDebugPort, 'webBrowserFlags': webBrowserFlags, 'webEnableExpressionEvaluation': webEnableExpressionEvaluation, 'webLaunchUrl': webLaunchUrl, 'webHeaders': webHeaders, 'vmserviceOutFile': vmserviceOutFile, 'fastStart': fastStart, 'nullAssertions': nullAssertions, 'nativeNullAssertions': nativeNullAssertions, 'enableImpeller': enableImpeller.asBool, 'enableVulkanValidation': enableVulkanValidation, 'serveObservatory': serveObservatory, 'enableDartProfiling': enableDartProfiling, 'enableEmbedderApi': enableEmbedderApi, 'usingCISystem': usingCISystem, };
static DebuggingOptions fromJson(Map<String, Object?> json, BuildInfo buildInfo) => DebuggingOptions._( buildInfo: buildInfo, debuggingEnabled: json['debuggingEnabled']! as bool, startPaused: json['startPaused']! as bool, dartFlags: json['dartFlags']! as String, dartEntrypointArgs: (json['dartEntrypointArgs']! as List<dynamic>).cast<String>(), disableServiceAuthCodes: json['disableServiceAuthCodes']! as bool, enableDds: json['enableDds']! as bool, cacheStartupProfile: json['cacheStartupProfile']! as bool, enableSoftwareRendering: json['enableSoftwareRendering']! as bool, skiaDeterministicRendering: json['skiaDeterministicRendering']! as bool, traceSkia: json['traceSkia']! as bool, traceAllowlist: json['traceAllowlist'] as String?, traceSkiaAllowlist: json['traceSkiaAllowlist'] as String?, traceSystrace: json['traceSystrace']! as bool, traceToFile: json['traceToFile'] as String?, endlessTraceBuffer: json['endlessTraceBuffer']! as bool, dumpSkpOnShaderCompilation: json['dumpSkpOnShaderCompilation']! as bool, cacheSkSL: json['cacheSkSL']! as bool, purgePersistentCache: json['purgePersistentCache']! as bool, useTestFonts: json['useTestFonts']! as bool, verboseSystemLogs: json['verboseSystemLogs']! as bool, hostVmServicePort: json['hostVmServicePort'] as int? , deviceVmServicePort: json['deviceVmServicePort'] as int?, disablePortPublication: json['disablePortPublication']! as bool, ddsPort: json['ddsPort'] as int?, devToolsServerAddress: json['devToolsServerAddress'] != null ? Uri.parse(json['devToolsServerAddress']! as String) : null, port: json['port'] as String?, hostname: json['hostname'] as String?, tlsCertPath: json['tlsCertPath'] as String?, tlsCertKeyPath: json['tlsCertKeyPath'] as String?, webEnableExposeUrl: json['webEnableExposeUrl'] as bool?, webUseSseForDebugProxy: json['webUseSseForDebugProxy']! as bool, webUseSseForDebugBackend: json['webUseSseForDebugBackend']! as bool, webUseSseForInjectedClient: json['webUseSseForInjectedClient']! as bool, webRunHeadless: json['webRunHeadless']! as bool, webBrowserDebugPort: json['webBrowserDebugPort'] as int?, webBrowserFlags: (json['webBrowserFlags']! as List<dynamic>).cast<String>(), webEnableExpressionEvaluation: json['webEnableExpressionEvaluation']! as bool, webHeaders: (json['webHeaders']! as Map<dynamic, dynamic>).cast<String, String>(), webLaunchUrl: json['webLaunchUrl'] as String?, vmserviceOutFile: json['vmserviceOutFile'] as String?, fastStart: json['fastStart']! as bool, nullAssertions: json['nullAssertions']! as bool, nativeNullAssertions: json['nativeNullAssertions']! as bool, enableImpeller: ImpellerStatus.fromBool(json['enableImpeller'] as bool?), enableVulkanValidation: (json['enableVulkanValidation'] as bool?) ?? false, uninstallFirst: (json['uninstallFirst'] as bool?) ?? false, serveObservatory: (json['serveObservatory'] as bool?) ?? false, enableDartProfiling: (json['enableDartProfiling'] as bool?) ?? true, enableEmbedderApi: (json['enableEmbedderApi'] as bool?) ?? false, usingCISystem: (json['usingCISystem'] as bool?) ?? false, );}
class LaunchResult { LaunchResult.succeeded({ Uri? vmServiceUri, Uri? observatoryUri }) : started = true, vmServiceUri = vmServiceUri ?? observatoryUri;
LaunchResult.failed() : started = false, vmServiceUri = null;
bool get hasVmService => vmServiceUri != null;
final bool started; final Uri? vmServiceUri;
@override String toString() { final StringBuffer buf = StringBuffer('started=$started'); if (vmServiceUri != null) { buf.write(', vmService=$vmServiceUri'); } return buf.toString(); }}
/// Read the log for a particular device.abstract class DeviceLogReader { String get name;
/// A broadcast stream where each element in the string is a line of log output. Stream<String> get logLines;
/// Some logs can be obtained from a VM service stream. /// Set this after the VM services are connected. FlutterVmService? connectedVMService;
@override String toString() => name;
/// Process ID of the app on the device. int? appPid;
// Clean up resources allocated by log reader e.g. subprocesses void dispose();}
/// Describes an app running on the device.class DiscoveredApp { DiscoveredApp(this.id, this.vmServicePort); final String id; final int vmServicePort;}
// An empty device log readerclass NoOpDeviceLogReader implements DeviceLogReader { NoOpDeviceLogReader(String? nameOrNull) : name = nameOrNull ?? '';
@override final String name;
@override int? appPid;
@override FlutterVmService? connectedVMService;
@override Stream<String> get logLines => const Stream<String>.empty();
@override void dispose() { }}
/// Append --null_assertions to any existing Dart VM flags if/// [debuggingOptions.nullAssertions] is true.String computeDartVmFlags(DebuggingOptions debuggingOptions) { return <String>[ if (debuggingOptions.dartFlags.isNotEmpty) debuggingOptions.dartFlags, if (debuggingOptions.nullAssertions) '--null_assertions', ].join(',');}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// 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 'base/io.dart';
class ForwardedPort { ForwardedPort(this.hostPort, this.devicePort) : context = null; ForwardedPort.withContext(this.hostPort, this.devicePort, this.context);
final int hostPort; final int devicePort; final Process? context;
@override String toString() => 'ForwardedPort HOST:$hostPort to DEVICE:$devicePort';
/// Kill subprocess (if present) used in forwarding. void dispose() { if (context != null) { context!.kill(); } }}
/// Forward ports from the host machine to the device.abstract class DevicePortForwarder { /// Returns a Future that completes with the current list of forwarded /// ports for this device. List<ForwardedPort> get forwardedPorts;
/// Forward [hostPort] on the host to [devicePort] on the device. /// If [hostPort] is null or zero, will auto select a host port. /// Returns a Future that completes with the host port. Future<int> forward(int devicePort, { int? hostPort });
/// Stops forwarding [forwardedPort]. Future<void> unforward(ForwardedPort forwardedPort);
/// Cleanup allocated resources, like [forwardedPorts]. Future<void> dispose();}
// A port forwarder which does not support forwarding ports.class NoOpDevicePortForwarder implements DevicePortForwarder { const NoOpDevicePortForwarder();
@override Future<int> forward(int devicePort, { int? hostPort }) async => devicePort;
@override List<ForwardedPort> get forwardedPorts => <ForwardedPort>[];
@override Future<void> unforward(ForwardedPort forwardedPort) async { }
@override Future<void> dispose() async { }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110// Copyright 2014 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
import 'dart:async';
import 'package:async/async.dart';
import 'base/logger.dart';import 'device.dart';import 'device_port_forwarder.dart';import 'mdns_discovery.dart';import 'protocol_discovery.dart';
/// Discovers the VM service uri on a device, and forwards the port to the host.////// This is mainly used during a `flutter attach`.abstract class VMServiceDiscoveryForAttach { VMServiceDiscoveryForAttach();
/// The discovered VM service URis. /// /// Port forwarding is only attempted when this is invoked, for each VM /// Service URI in the stream. Stream<Uri> get uris;}
/// An implementation of [VMServiceDiscoveryForAttach] that uses log scanning/// for the discovery.class LogScanningVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { LogScanningVMServiceDiscoveryForAttach( Future<DeviceLogReader> logReader, { DevicePortForwarder? portForwarder, int? hostPort, int? devicePort, required bool ipv6, required Logger logger, }) { _protocolDiscovery = (() async => ProtocolDiscovery.vmService( await logReader, portForwarder: portForwarder, ipv6: ipv6, devicePort: devicePort, hostPort: hostPort, logger: logger, ))(); }
late final Future<ProtocolDiscovery> _protocolDiscovery;
@override Stream<Uri> get uris { final StreamController<Uri> controller = StreamController<Uri>(); _protocolDiscovery.then( (ProtocolDiscovery protocolDiscovery) async { await controller.addStream(protocolDiscovery.uris); await controller.close(); }, onError: (Object error) => controller.addError(error), ); return controller.stream; }}
/// An implementation of [VMServiceDiscoveryForAttach] that uses mdns for the/// discovery.class MdnsVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { MdnsVMServiceDiscoveryForAttach({ required this.device, this.appId, required this.usesIpv6, required this.useDeviceIPAsHost, this.deviceVmservicePort, this.hostVmservicePort, });
final Device device; final String? appId; final bool usesIpv6; final bool useDeviceIPAsHost; final int? deviceVmservicePort; final int? hostVmservicePort;
@override Stream<Uri> get uris { final Future<Uri?> mDNSDiscoveryFuture = MDnsVmServiceDiscovery.instance!.getVMServiceUriForAttach( appId, device, usesIpv6: usesIpv6, useDeviceIPAsHost: useDeviceIPAsHost, deviceVmservicePort: deviceVmservicePort, hostVmservicePort: hostVmservicePort, );
return Stream<Uri?>.fromFuture(mDNSDiscoveryFuture).where((Uri? uri) => uri != null).cast<Uri>().asBroadcastStream(); }}
/// An implementation of [VMServiceDiscoveryForAttach] that delegates to other/// [VMServiceDiscoveryForAttach] instances for discovery.class DelegateVMServiceDiscoveryForAttach extends VMServiceDiscoveryForAttach { DelegateVMServiceDiscoveryForAttach(this.delegates);
final List<VMServiceDiscoveryForAttach> delegates;
@override Stream<Uri> get uris => StreamGroup.merge<Uri>( delegates.map((VMServiceDiscoveryForAttach delegate) => delegate.uris));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111// 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:meta/meta.dart';import 'package:process/process.dart';
import 'base/bot_detector.dart';import 'base/common.dart';import 'base/io.dart' as io;import 'base/logger.dart';import 'convert.dart';import 'resident_runner.dart';
/// An implementation of the devtools launcher that uses `pub global activate` to/// start a server instance.class DevtoolsServerLauncher extends DevtoolsLauncher { DevtoolsServerLauncher({ required ProcessManager processManager, required String dartExecutable, required Logger logger, required BotDetector botDetector, }) : _processManager = processManager, _dartExecutable = dartExecutable, _logger = logger, _botDetector = botDetector;
final ProcessManager _processManager; final String _dartExecutable; final Logger _logger; final BotDetector _botDetector; final Completer<void> _processStartCompleter = Completer<void>();
io.Process? _devToolsProcess; bool _devToolsProcessKilled = false; @visibleForTesting Future<void>? devToolsProcessExit;
static final RegExp _serveDevToolsPattern = RegExp(r'Serving DevTools at ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+?)\.?$');
@override Future<void> get processStart => _processStartCompleter.future;
@override Future<void> launch(Uri? vmServiceUri, {List<String>? additionalArguments}) async { // Place this entire method in a try/catch that swallows exceptions because // this method is guaranteed not to return a Future that throws. try { _devToolsProcess = await _processManager.start(<String>[ _dartExecutable, 'devtools', '--no-launch-browser', if (vmServiceUri != null) '--vm-uri=$vmServiceUri', ...?additionalArguments, ]); _processStartCompleter.complete(); final Completer<Uri> completer = Completer<Uri>(); _devToolsProcess!.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { final Match? match = _serveDevToolsPattern.firstMatch(line); if (match != null) { final String url = match[1]!; completer.complete(Uri.parse(url)); } }); _devToolsProcess!.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .listen(_logger.printError);
final bool runningOnBot = await _botDetector.isRunningOnBot; devToolsProcessExit = _devToolsProcess!.exitCode.then( (int exitCode) { if (!_devToolsProcessKilled && runningOnBot) { throwToolExit('DevTools process failed: exitCode=$exitCode'); } } );
devToolsUrl = await completer.future; } on Exception catch (e, st) { _logger.printError('Failed to launch DevTools: $e', stackTrace: st); } }
@override Future<DevToolsServerAddress?> serve() async { if (activeDevToolsServer == null) { await launch(null); } return activeDevToolsServer; }
@override Future<void> close() async { if (devToolsUrl != null) { devToolsUrl = null; } if (_devToolsProcess != null) { _devToolsProcessKilled = true; _devToolsProcess!.kill(); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806// 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:meta/meta.dart';import 'package:process/process.dart';import 'package:unified_analytics/unified_analytics.dart';
import 'android/android_studio_validator.dart';import 'android/android_workflow.dart';import 'artifacts.dart';import 'base/async_guard.dart';import 'base/context.dart';import 'base/file_system.dart';import 'base/io.dart';import 'base/logger.dart';import 'base/net.dart';import 'base/os.dart';import 'base/platform.dart';import 'base/terminal.dart';import 'base/time.dart';import 'base/user_messages.dart';import 'base/utils.dart';import 'cache.dart';import 'custom_devices/custom_device_workflow.dart';import 'device.dart';import 'doctor_validator.dart';import 'features.dart';import 'fuchsia/fuchsia_workflow.dart';import 'globals.dart' as globals;import 'http_host_validator.dart';import 'intellij/intellij_validator.dart';import 'linux/linux_doctor.dart';import 'linux/linux_workflow.dart';import 'macos/macos_workflow.dart';import 'macos/xcode_validator.dart';import 'proxy_validator.dart';import 'reporting/reporting.dart';import 'tester/flutter_tester.dart';import 'version.dart';import 'vscode/vscode_validator.dart';import 'web/chrome.dart';import 'web/web_validator.dart';import 'web/workflow.dart';import 'windows/visual_studio_validator.dart';import 'windows/windows_version_validator.dart';import 'windows/windows_workflow.dart';
abstract class DoctorValidatorsProvider { // Allow tests to construct a [_DefaultDoctorValidatorsProvider] with explicit // [FeatureFlags]. factory DoctorValidatorsProvider.test({ Platform? platform, Logger? logger, required FeatureFlags featureFlags, }) { return _DefaultDoctorValidatorsProvider( featureFlags: featureFlags, platform: platform ?? FakePlatform(), logger: logger ?? BufferLogger.test(), ); } /// The singleton instance, pulled from the [AppContext]. static DoctorValidatorsProvider get _instance => context.get<DoctorValidatorsProvider>()!;
static final DoctorValidatorsProvider defaultInstance = _DefaultDoctorValidatorsProvider( logger: globals.logger, platform: globals.platform, featureFlags: featureFlags, );
List<DoctorValidator> get validators; List<Workflow> get workflows;}
class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider { _DefaultDoctorValidatorsProvider({ required this.platform, required this.featureFlags, required Logger logger, }) : _logger = logger;
List<DoctorValidator>? _validators; List<Workflow>? _workflows; final Platform platform; final FeatureFlags featureFlags; final Logger _logger;
late final LinuxWorkflow linuxWorkflow = LinuxWorkflow( platform: platform, featureFlags: featureFlags, );
late final WebWorkflow webWorkflow = WebWorkflow( platform: platform, featureFlags: featureFlags, );
late final MacOSWorkflow macOSWorkflow = MacOSWorkflow( platform: platform, featureFlags: featureFlags, );
late final CustomDeviceWorkflow customDeviceWorkflow = CustomDeviceWorkflow( featureFlags: featureFlags, );
@override List<DoctorValidator> get validators { if (_validators != null) { return _validators!; }
final List<DoctorValidator> ideValidators = <DoctorValidator>[ if (androidWorkflow!.appliesToHostPlatform) ...AndroidStudioValidator.allValidators(globals.config, platform, globals.fs, globals.userMessages), ...IntelliJValidator.installedValidators( fileSystem: globals.fs, platform: platform, userMessages: userMessages, plistParser: globals.plistParser, processManager: globals.processManager, logger: _logger, ), ...VsCodeValidator.installedValidators(globals.fs, platform, globals.processManager), ]; final ProxyValidator proxyValidator = ProxyValidator(platform: platform); _validators = <DoctorValidator>[ FlutterValidator( fileSystem: globals.fs, platform: globals.platform, flutterVersion: () => globals.flutterVersion.fetchTagsAndGetVersion(clock: globals.systemClock), devToolsVersion: () => globals.cache.devToolsVersion, processManager: globals.processManager, userMessages: userMessages, artifacts: globals.artifacts!, flutterRoot: () => Cache.flutterRoot!, operatingSystemUtils: globals.os, ), if (platform.isWindows) WindowsVersionValidator( operatingSystemUtils: globals.os, ), if (androidWorkflow!.appliesToHostPlatform) GroupedValidator(<DoctorValidator>[androidValidator!, androidLicenseValidator!]), if (globals.iosWorkflow!.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform) GroupedValidator(<DoctorValidator>[ XcodeValidator( xcode: globals.xcode!, userMessages: userMessages, iosSimulatorUtils: globals.iosSimulatorUtils!, ), globals.cocoapodsValidator!, ]), if (webWorkflow.appliesToHostPlatform) ChromeValidator( chromiumLauncher: ChromiumLauncher( browserFinder: findChromeExecutable, fileSystem: globals.fs, operatingSystemUtils: globals.os, platform: globals.platform, processManager: globals.processManager, logger: globals.logger, ), platform: globals.platform, ), if (linuxWorkflow.appliesToHostPlatform) LinuxDoctorValidator( processManager: globals.processManager, userMessages: userMessages, ), if (windowsWorkflow!.appliesToHostPlatform) visualStudioValidator!, if (ideValidators.isNotEmpty) ...ideValidators else NoIdeValidator(), if (proxyValidator.shouldShow) proxyValidator, if (globals.deviceManager?.canListAnything ?? false) DeviceValidator( deviceManager: globals.deviceManager, userMessages: globals.userMessages, ), HttpHostValidator( platform: globals.platform, featureFlags: featureFlags, httpClient: globals.httpClientFactory?.call() ?? HttpClient(), ), ]; return _validators!; }
@override List<Workflow> get workflows { if (_workflows == null) { _workflows = <Workflow>[];
if (globals.iosWorkflow!.appliesToHostPlatform) { _workflows!.add(globals.iosWorkflow!); }
if (androidWorkflow?.appliesToHostPlatform ?? false) { _workflows!.add(androidWorkflow!); }
if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) { _workflows!.add(fuchsiaWorkflow!); }
if (linuxWorkflow.appliesToHostPlatform) { _workflows!.add(linuxWorkflow); }
if (macOSWorkflow.appliesToHostPlatform) { _workflows!.add(macOSWorkflow); }
if (windowsWorkflow?.appliesToHostPlatform ?? false) { _workflows!.add(windowsWorkflow!); }
if (webWorkflow.appliesToHostPlatform) { _workflows!.add(webWorkflow); }
if (customDeviceWorkflow.appliesToHostPlatform) { _workflows!.add(customDeviceWorkflow); } } return _workflows!; }}
class Doctor { Doctor({ required Logger logger, required SystemClock clock, Analytics? analytics, }) : _logger = logger, _clock = clock, _analytics = analytics ?? globals.analytics;
final Logger _logger; final SystemClock _clock; final Analytics _analytics;
List<DoctorValidator> get validators { return DoctorValidatorsProvider._instance.validators; }
/// Return a list of [ValidatorTask] objects and starts validation on all /// objects in [validators]. List<ValidatorTask> startValidatorTasks() => <ValidatorTask>[ for (final DoctorValidator validator in validators) ValidatorTask( validator, // We use an asyncGuard() here to be absolutely certain that // DoctorValidators do not result in an uncaught exception. Since the // Future returned by the asyncGuard() is not awaited, we pass an // onError callback to it and translate errors into ValidationResults. asyncGuard<ValidationResult>( () { final Completer<ValidationResult> timeoutCompleter = Completer<ValidationResult>(); final Timer timer = Timer(doctorDuration, () { timeoutCompleter.completeError( Exception('${validator.title} exceeded maximum allowed duration of $doctorDuration'), ); }); final Future<ValidationResult> validatorFuture = validator.validate(); return Future.any<ValidationResult>(<Future<ValidationResult>>[ validatorFuture, // This future can only complete with an error timeoutCompleter.future, ]).then((ValidationResult result) async { timer.cancel(); return result; }); }, onError: (Object exception, StackTrace stackTrace) { return ValidationResult.crash(exception, stackTrace); }, ), ), ];
List<Workflow> get workflows { return DoctorValidatorsProvider._instance.workflows; }
/// Print a summary of the state of the tooling, as well as how to get more info. Future<void> summary() async { _logger.printStatus(await _summaryText()); }
Future<String> _summaryText() async { final StringBuffer buffer = StringBuffer();
bool missingComponent = false; bool sawACrash = false;
for (final DoctorValidator validator in validators) { final StringBuffer lineBuffer = StringBuffer(); ValidationResult result; try { result = await asyncGuard<ValidationResult>(() => validator.validate()); } on Exception catch (exception) { // We're generating a summary, so drop the stack trace. result = ValidationResult.crash(exception); } lineBuffer.write('${result.coloredLeadingBox} ${validator.title}: '); switch (result.type) { case ValidationType.crash: lineBuffer.write('the doctor check crashed without a result.'); sawACrash = true; case ValidationType.missing: lineBuffer.write('is not installed.'); case ValidationType.partial: lineBuffer.write('is partially installed; more components are available.'); case ValidationType.notAvailable: lineBuffer.write('is not available.'); case ValidationType.success: lineBuffer.write('is fully installed.'); }
if (result.statusInfo != null) { lineBuffer.write(' (${result.statusInfo})'); }
buffer.write(wrapText( lineBuffer.toString(), hangingIndent: result.leadingBox.length + 1, columnWidth: globals.outputPreferences.wrapColumn, shouldWrap: globals.outputPreferences.wrapText, )); buffer.writeln();
if (result.type != ValidationType.success) { missingComponent = true; } }
if (sawACrash) { buffer.writeln(); buffer.writeln('Run "flutter doctor" for information about why a doctor check crashed.'); }
if (missingComponent) { buffer.writeln(); buffer.writeln('Run "flutter doctor" for information about installing additional components.'); }
return buffer.toString(); }
Future<bool> checkRemoteArtifacts(String engineRevision) async { return globals.cache.areRemoteArtifactsAvailable(engineVersion: engineRevision); }
/// Maximum allowed duration for an entire validator to take. /// /// This should only ever be reached if a process is stuck. // Reduce this to under 5 minutes to diagnose: // https://github.com/flutter/flutter/issues/111686 static const Duration doctorDuration = Duration(minutes: 4, seconds: 30);
/// Print information about the state of installed tooling. /// /// To exclude personally identifiable information like device names and /// paths, set [showPii] to false. Future<bool> diagnose({ bool androidLicenses = false, bool verbose = true, AndroidLicenseValidator? androidLicenseValidator, bool showPii = true, List<ValidatorTask>? startedValidatorTasks, bool sendEvent = true, }) async { final bool showColor = globals.terminal.supportsColor; if (androidLicenses && androidLicenseValidator != null) { return androidLicenseValidator.runLicenseManager(); }
if (!verbose) { _logger.printStatus('Doctor summary (to see all details, run flutter doctor -v):'); } bool doctorResult = true; int issues = 0;
// This timestamp will be used on the backend of GA4 to group each of the events that // were sent for each doctor validator and its result final int analyticsTimestamp = _clock.now().millisecondsSinceEpoch;
for (final ValidatorTask validatorTask in startedValidatorTasks ?? startValidatorTasks()) { final DoctorValidator validator = validatorTask.validator; final Status status = _logger.startSpinner( timeout: validator.slowWarningDuration, slowWarningCallback: () => validator.slowWarning, ); ValidationResult result; try { result = await validatorTask.result; status.stop(); } on Exception catch (exception, stackTrace) { result = ValidationResult.crash(exception, stackTrace); status.cancel(); }
switch (result.type) { case ValidationType.crash: doctorResult = false; issues += 1; case ValidationType.missing: doctorResult = false; issues += 1; case ValidationType.partial: case ValidationType.notAvailable: issues += 1; case ValidationType.success: break; } if (sendEvent) { if (validator is GroupedValidator) { for (int i = 0; i < validator.subValidators.length; i++) { final DoctorValidator subValidator = validator.subValidators[i];
// Ensure that all of the subvalidators in the group have // a corresponding subresult incase a validator crashed final ValidationResult subResult; try { subResult = validator.subResults[i]; } on RangeError { continue; }
_analytics.send(Event.doctorValidatorResult( validatorName: subValidator.title, result: subResult.typeStr, statusInfo: subResult.statusInfo, partOfGroupedValidator: true, doctorInvocationId: analyticsTimestamp, )); } } else { _analytics.send(Event.doctorValidatorResult( validatorName: validator.title, result: result.typeStr, statusInfo: result.statusInfo, partOfGroupedValidator: false, doctorInvocationId: analyticsTimestamp, )); } // TODO(eliasyishak): remove this after migrating from package:usage DoctorResultEvent(validator: validator, result: result).send(); }
final String leadingBox = showColor ? result.coloredLeadingBox : result.leadingBox; if (result.statusInfo != null) { _logger.printStatus('$leadingBox ${validator.title} (${result.statusInfo})', hangingIndent: result.leadingBox.length + 1); } else { _logger.printStatus('$leadingBox ${validator.title}', hangingIndent: result.leadingBox.length + 1); }
for (final ValidationMessage message in result.messages) { if (!message.isInformation || verbose) { int hangingIndent = 2; int indent = 4; final String indicator = showColor ? message.coloredIndicator : message.indicator; for (final String line in '$indicator ${showPii ? message.message : message.piiStrippedMessage}'.split('\n')) { _logger.printStatus(line, hangingIndent: hangingIndent, indent: indent, emphasis: true); // Only do hanging indent for the first line. hangingIndent = 0; indent = 6; } if (message.contextUrl != null) { _logger.printStatus('🔨 ${message.contextUrl}', hangingIndent: hangingIndent, indent: indent, emphasis: true); } } } if (verbose) { _logger.printStatus(''); } }
// Make sure there's always one line before the summary even when not verbose. if (!verbose) { _logger.printStatus(''); }
if (issues > 0) { _logger.printStatus('${showColor ? globals.terminal.color('!', TerminalColor.yellow) : '!'}' ' Doctor found issues in $issues categor${issues > 1 ? "ies" : "y"}.', hangingIndent: 2); } else { _logger.printStatus('${showColor ? globals.terminal.color('•', TerminalColor.green) : '•'}' ' No issues found!', hangingIndent: 2); }
return doctorResult; }
bool get canListAnything => workflows.any((Workflow workflow) => workflow.canListDevices);
bool get canLaunchAnything { if (FlutterTesterDevices.showFlutterTesterDevice) { return true; } return workflows.any((Workflow workflow) => workflow.canLaunchDevices); }}
/// A validator that checks the version of Flutter, as well as some auxiliary information/// such as the pub or Flutter cache overrides.////// This is primarily useful for diagnosing issues on Github bug reports by displaying/// specific commit information.class FlutterValidator extends DoctorValidator { FlutterValidator({ required Platform platform, required FlutterVersion Function() flutterVersion, required String Function() devToolsVersion, required UserMessages userMessages, required FileSystem fileSystem, required Artifacts artifacts, required ProcessManager processManager, required String Function() flutterRoot, required OperatingSystemUtils operatingSystemUtils, }) : _flutterVersion = flutterVersion, _devToolsVersion = devToolsVersion, _platform = platform, _userMessages = userMessages, _fileSystem = fileSystem, _artifacts = artifacts, _processManager = processManager, _flutterRoot = flutterRoot, _operatingSystemUtils = operatingSystemUtils, super('Flutter');
final Platform _platform; final FlutterVersion Function() _flutterVersion; final String Function() _devToolsVersion; final String Function() _flutterRoot; final UserMessages _userMessages; final FileSystem _fileSystem; final Artifacts _artifacts; final ProcessManager _processManager; final OperatingSystemUtils _operatingSystemUtils;
@override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; String? versionChannel; String? frameworkVersion;
try { final FlutterVersion version = _flutterVersion(); final String? gitUrl = _platform.environment['FLUTTER_GIT_URL']; versionChannel = version.channel; frameworkVersion = version.frameworkVersion;
final String flutterRoot = _flutterRoot(); messages.add(_getFlutterVersionMessage(frameworkVersion, versionChannel, flutterRoot));
_validateRequiredBinaries(flutterRoot).forEach(messages.add); messages.add(_getFlutterUpstreamMessage(version)); if (gitUrl != null) { messages.add(ValidationMessage(_userMessages.flutterGitUrl(gitUrl))); } messages.add(ValidationMessage(_userMessages.flutterRevision( version.frameworkRevisionShort, version.frameworkAge, version.frameworkCommitDate, ))); messages.add(ValidationMessage(_userMessages.engineRevision(version.engineRevisionShort))); messages.add(ValidationMessage(_userMessages.dartRevision(version.dartSdkVersion))); messages.add(ValidationMessage(_userMessages.devToolsVersion(_devToolsVersion()))); final String? pubUrl = _platform.environment[kPubDevOverride]; if (pubUrl != null) { messages.add(ValidationMessage(_userMessages.pubMirrorURL(pubUrl))); } final String? storageBaseUrl = _platform.environment[kFlutterStorageBaseUrl]; if (storageBaseUrl != null) { messages.add(ValidationMessage(_userMessages.flutterMirrorURL(storageBaseUrl))); } } on VersionCheckError catch (e) { messages.add(ValidationMessage.error(e.message)); }
// Check that the binaries we downloaded for this platform actually run on it. // If the binaries are not downloaded (because android is not enabled), then do // not run this check. final String genSnapshotPath = _artifacts.getArtifactPath(Artifact.genSnapshot); if (_fileSystem.file(genSnapshotPath).existsSync() && !_genSnapshotRuns(genSnapshotPath)) { final StringBuffer buffer = StringBuffer(); buffer.writeln(_userMessages.flutterBinariesDoNotRun); if (_platform.isLinux) { buffer.writeln(_userMessages.flutterBinariesLinuxRepairCommands); } else if (_platform.isMacOS && _operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm64) { buffer.writeln('Flutter requires the Rosetta translation environment on ARM Macs. Try running:'); buffer.writeln(' sudo softwareupdate --install-rosetta --agree-to-license'); } messages.add(ValidationMessage.error(buffer.toString())); }
ValidationType valid; if (messages.every((ValidationMessage message) => message.isInformation)) { valid = ValidationType.success; } else { // The issues for this validator stem from broken git configuration of the local install; // in that case, make it clear that it is fine to continue, but freshness check/upgrades // won't be supported. valid = ValidationType.partial; messages.add( ValidationMessage(_userMessages.flutterValidatorErrorIntentional), ); }
return ValidationResult( valid, messages, statusInfo: _userMessages.flutterStatusInfo( versionChannel, frameworkVersion, _operatingSystemUtils.name, _platform.localeName, ), ); }
ValidationMessage _getFlutterVersionMessage(String frameworkVersion, String versionChannel, String flutterRoot) { String flutterVersionMessage = _userMessages.flutterVersion(frameworkVersion, versionChannel, flutterRoot);
// The tool sets the channel as kUserBranch, if the current branch is on a // "detached HEAD" state, doesn't have an upstream, or is on a user branch, // and sets the frameworkVersion as "0.0.0-unknown" if "git describe" on // HEAD doesn't produce an expected format to be parsed for the frameworkVersion. if (versionChannel != kUserBranch && frameworkVersion != '0.0.0-unknown') { return ValidationMessage(flutterVersionMessage); } if (versionChannel == kUserBranch) { flutterVersionMessage = '$flutterVersionMessage\n${_userMessages.flutterUnknownChannel}'; } if (frameworkVersion == '0.0.0-unknown') { flutterVersionMessage = '$flutterVersionMessage\n${_userMessages.flutterUnknownVersion}'; } return ValidationMessage.hint(flutterVersionMessage); }
List<ValidationMessage> _validateRequiredBinaries(String flutterRoot) { final ValidationMessage? flutterWarning = _validateSdkBinary('flutter', flutterRoot); final ValidationMessage? dartWarning = _validateSdkBinary('dart', flutterRoot); return <ValidationMessage>[ if (flutterWarning != null) flutterWarning, if (dartWarning != null) dartWarning, ]; }
/// Return a warning if the provided [binary] on the user's path does not /// resolve within the Flutter SDK. ValidationMessage? _validateSdkBinary(String binary, String flutterRoot) { final String flutterBinDir = _fileSystem.path.join(flutterRoot, 'bin');
final File? flutterBin = _operatingSystemUtils.which(binary); if (flutterBin == null) { return ValidationMessage.hint( 'The $binary binary is not on your path. Consider adding ' '$flutterBinDir to your path.', ); } final String resolvedFlutterPath = flutterBin.resolveSymbolicLinksSync(); if (!_filePathContainsDirPath(flutterRoot, resolvedFlutterPath)) { final String hint = 'Warning: `$binary` on your path resolves to ' '$resolvedFlutterPath, which is not inside your current Flutter ' 'SDK checkout at $flutterRoot. Consider adding $flutterBinDir to ' 'the front of your path.'; return ValidationMessage.hint(hint); } return null; }
bool _filePathContainsDirPath(String directory, String file) { // calling .canonicalize() will normalize for alphabetic case and path // separators return _fileSystem.path.canonicalize(file) .startsWith(_fileSystem.path.canonicalize(directory) + _fileSystem.path.separator); }
ValidationMessage _getFlutterUpstreamMessage(FlutterVersion version) { final String? repositoryUrl = version.repositoryUrl; final VersionCheckError? upstreamValidationError = VersionUpstreamValidator(version: version, platform: _platform).run();
// VersionUpstreamValidator can produce an error if repositoryUrl is null if (upstreamValidationError != null) { final String errorMessage = upstreamValidationError.message; if (errorMessage.contains('could not determine the remote upstream which is being tracked')) { return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUnknown); } // At this point, repositoryUrl must not be null if (errorMessage.contains('Flutter SDK is tracking a non-standard remote')) { return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUrlNonStandard(repositoryUrl!)); } if (errorMessage.contains('Either remove "FLUTTER_GIT_URL" from the environment or set it to')){ return ValidationMessage.hint(_userMessages.flutterUpstreamRepositoryUrlEnvMismatch(repositoryUrl!)); } } return ValidationMessage(_userMessages.flutterUpstreamRepositoryUrl(repositoryUrl!)); }
bool _genSnapshotRuns(String genSnapshotPath) { const int kExpectedExitCode = 255; try { return _processManager.runSync(<String>[genSnapshotPath]).exitCode == kExpectedExitCode; } on Exception { return false; } }}
class DeviceValidator extends DoctorValidator { // TODO(jmagman): Make required once g3 rolls and is updated. DeviceValidator({ DeviceManager? deviceManager, UserMessages? userMessages, }) : _deviceManager = deviceManager ?? globals.deviceManager!, _userMessages = userMessages ?? globals.userMessages, super('Connected device');
final DeviceManager _deviceManager; final UserMessages _userMessages;
@override String get slowWarning => 'Scanning for devices is taking a long time...';
@override Future<ValidationResult> validate() async { final List<Device> devices = await _deviceManager.refreshAllDevices( timeout: DeviceManager.minimumWirelessDeviceDiscoveryTimeout, ); List<ValidationMessage> installedMessages = <ValidationMessage>[]; if (devices.isNotEmpty) { installedMessages = (await Device.descriptions(devices)) .map<ValidationMessage>((String msg) => ValidationMessage(msg)).toList(); }
List<ValidationMessage> diagnosticMessages = <ValidationMessage>[]; final List<String> diagnostics = await _deviceManager.getDeviceDiagnostics(); if (diagnostics.isNotEmpty) { diagnosticMessages = diagnostics.map<ValidationMessage>((String message) => ValidationMessage.hint(message)).toList(); } else if (devices.isEmpty) { diagnosticMessages = <ValidationMessage>[ValidationMessage.hint(_userMessages.devicesMissing)]; }
if (devices.isEmpty) { return ValidationResult(ValidationType.notAvailable, diagnosticMessages); } else if (diagnostics.isNotEmpty) { installedMessages.addAll(diagnosticMessages); return ValidationResult( ValidationType.success, installedMessages, statusInfo: _userMessages.devicesAvailable(devices.length) ); } else { return ValidationResult( ValidationType.success, installedMessages, statusInfo: _userMessages.devicesAvailable(devices.length) ); } }}
/// Wrapper for doctor to run multiple times with PII and without, running the validators only once.class DoctorText { DoctorText( BufferLogger logger, { SystemClock? clock, @visibleForTesting Doctor? doctor, }) : _doctor = doctor ?? Doctor(logger: logger, clock: clock ?? globals.systemClock), _logger = logger;
final BufferLogger _logger; final Doctor _doctor; bool _sendDoctorEvent = true;
late final Future<String> text = _runDiagnosis(true); late final Future<String> piiStrippedText = _runDiagnosis(false);
// Start the validator tasks only once. late final List<ValidatorTask> _validatorTasks = _doctor.startValidatorTasks();
Future<String> _runDiagnosis(bool showPii) async { try { await _doctor.diagnose(startedValidatorTasks: _validatorTasks, showPii: showPii, sendEvent: _sendDoctorEvent); // Do not send the doctor event a second time. _sendDoctorEvent = false; final String text = _logger.statusText; _logger.clear(); return text; } on Exception catch (error, trace) { return 'encountered exception: $error\n\n${trace.toString().trim()}\n'; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314// 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:meta/meta.dart';
import 'base/async_guard.dart';import 'base/terminal.dart';import 'globals.dart' as globals;
class ValidatorTask { ValidatorTask(this.validator, this.result); final DoctorValidator validator; final Future<ValidationResult> result;}
/// A series of tools and required install steps for a target platform (iOS or Android).abstract class Workflow { const Workflow();
/// Whether the workflow applies to this platform (as in, should we ever try and use it). bool get appliesToHostPlatform;
/// Are we functional enough to list devices? bool get canListDevices;
/// Could this thing launch *something*? It may still have minor issues. bool get canLaunchDevices;
/// Are we functional enough to list emulators? bool get canListEmulators;}
enum ValidationType { crash, missing, partial, notAvailable, success,}
enum ValidationMessageType { error, hint, information,}
abstract class DoctorValidator { const DoctorValidator(this.title);
/// This is displayed in the CLI. final String title;
String get slowWarning => 'This is taking an unexpectedly long time...';
static const Duration _slowWarningDuration = Duration(seconds: 10);
/// Duration before the spinner should display [slowWarning]. Duration get slowWarningDuration => _slowWarningDuration;
Future<ValidationResult> validate();}
/// A validator that runs other [DoctorValidator]s and combines their output/// into a single [ValidationResult]. It uses the title of the first validator/// passed to the constructor and reports the statusInfo of the first validator/// that provides one. Other titles and statusInfo strings are discarded.class GroupedValidator extends DoctorValidator { GroupedValidator(this.subValidators) : super(subValidators[0].title);
final List<DoctorValidator> subValidators;
List<ValidationResult> _subResults = <ValidationResult>[];
/// Sub-validator results. /// /// To avoid losing information when results are merged, the sub-results are /// cached on this field when they are available. The results are in the same /// order as the sub-validator list. List<ValidationResult> get subResults => _subResults;
@override String get slowWarning => _currentSlowWarning; String _currentSlowWarning = 'Initializing...';
@override Future<ValidationResult> validate() async { final List<ValidatorTask> tasks = <ValidatorTask>[ for (final DoctorValidator validator in subValidators) ValidatorTask( validator, asyncGuard<ValidationResult>(() => validator.validate()), ), ];
final List<ValidationResult> results = <ValidationResult>[]; for (final ValidatorTask subValidator in tasks) { _currentSlowWarning = subValidator.validator.slowWarning; try { results.add(await subValidator.result); } on Exception catch (exception, stackTrace) { results.add(ValidationResult.crash(exception, stackTrace)); } } _currentSlowWarning = 'Merging results...'; return _mergeValidationResults(results); }
ValidationResult _mergeValidationResults(List<ValidationResult> results) { assert(results.isNotEmpty, 'Validation results should not be empty'); _subResults = results; ValidationType mergedType = results[0].type; final List<ValidationMessage> mergedMessages = <ValidationMessage>[]; String? statusInfo;
for (final ValidationResult result in results) { statusInfo ??= result.statusInfo; switch (result.type) { case ValidationType.success: if (mergedType == ValidationType.missing) { mergedType = ValidationType.partial; } case ValidationType.notAvailable: case ValidationType.partial: mergedType = ValidationType.partial; case ValidationType.crash: case ValidationType.missing: if (mergedType == ValidationType.success) { mergedType = ValidationType.partial; } } mergedMessages.addAll(result.messages); }
return ValidationResult(mergedType, mergedMessages, statusInfo: statusInfo); }}
@immutableclass ValidationResult { /// [ValidationResult.type] should only equal [ValidationResult.success] /// if no [messages] are hints or errors. const ValidationResult(this.type, this.messages, { this.statusInfo });
factory ValidationResult.crash(Object error, [StackTrace? stackTrace]) { return ValidationResult(ValidationType.crash, <ValidationMessage>[ const ValidationMessage.error( 'Due to an error, the doctor check did not complete. ' 'If the error message below is not helpful, ' 'please let us know about this issue at https://github.com/flutter/flutter/issues.'), ValidationMessage.error('$error'), if (stackTrace != null) // Stacktrace is informational. Printed in verbose mode only. ValidationMessage('$stackTrace'), ], statusInfo: 'the doctor check crashed'); }
final ValidationType type; // A short message about the status. final String? statusInfo; final List<ValidationMessage> messages;
String get leadingBox { switch (type) { case ValidationType.crash: return '[☠]'; case ValidationType.missing: return '[✗]'; case ValidationType.success: return '[✓]'; case ValidationType.notAvailable: case ValidationType.partial: return '[!]'; } }
String get coloredLeadingBox { switch (type) { case ValidationType.crash: return globals.terminal.color(leadingBox, TerminalColor.red); case ValidationType.missing: return globals.terminal.color(leadingBox, TerminalColor.red); case ValidationType.success: return globals.terminal.color(leadingBox, TerminalColor.green); case ValidationType.notAvailable: case ValidationType.partial: return globals.terminal.color(leadingBox, TerminalColor.yellow); } }
/// The string representation of the type. String get typeStr { switch (type) { case ValidationType.crash: return 'crash'; case ValidationType.missing: return 'missing'; case ValidationType.success: return 'installed'; case ValidationType.notAvailable: return 'notAvailable'; case ValidationType.partial: return 'partial'; } }
@override String toString() { return '$runtimeType($type, $messages, $statusInfo)'; }}
/// A status line for the flutter doctor validation to display.////// The [message] is required and represents either an informational statement/// about the particular doctor validation that passed, or more context/// on the cause and/or solution to the validation failure.@immutableclass ValidationMessage { /// Create a validation message with information for a passing validator. /// /// By default this is not displayed unless the doctor is run in /// verbose mode. /// /// The [contextUrl] may be supplied to link to external resources. This /// is displayed after the informative message in verbose modes. const ValidationMessage(this.message, { this.contextUrl, String? piiStrippedMessage }) : type = ValidationMessageType.information, piiStrippedMessage = piiStrippedMessage ?? message;
/// Create a validation message with information for a failing validator. const ValidationMessage.error(this.message, { String? piiStrippedMessage }) : type = ValidationMessageType.error, piiStrippedMessage = piiStrippedMessage ?? message, contextUrl = null;
/// Create a validation message with information for a partially failing /// validator. const ValidationMessage.hint(this.message, { String? piiStrippedMessage }) : type = ValidationMessageType.hint, piiStrippedMessage = piiStrippedMessage ?? message, contextUrl = null;
final ValidationMessageType type; final String? contextUrl; final String message; /// Optional message with PII stripped, to show instead of [message]. final String piiStrippedMessage;
bool get isError => type == ValidationMessageType.error;
bool get isHint => type == ValidationMessageType.hint;
bool get isInformation => type == ValidationMessageType.information;
String get indicator { switch (type) { case ValidationMessageType.error: return '✗'; case ValidationMessageType.hint: return '!'; case ValidationMessageType.information: return '•'; } }
String get coloredIndicator { switch (type) { case ValidationMessageType.error: return globals.terminal.color(indicator, TerminalColor.red); case ValidationMessageType.hint: return globals.terminal.color(indicator, TerminalColor.yellow); case ValidationMessageType.information: return globals.terminal.color(indicator, TerminalColor.green); } }
@override String toString() => message;
@override bool operator ==(Object other) { return other is ValidationMessage && other.message == message && other.type == type && other.contextUrl == contextUrl; }
@override int get hashCode => Object.hash(type, message, contextUrl);}
class NoIdeValidator extends DoctorValidator { NoIdeValidator() : super('Flutter IDE Support');
@override Future<ValidationResult> validate() async { return ValidationResult( // Info hint to user they do not have a supported IDE installed ValidationType.notAvailable, globals.userMessages.noIdeInstallationInfo.map((String ideInfo) => ValidationMessage(ideInfo)).toList(), statusInfo: globals.userMessages.noIdeStatusInfo, ); }}
class ValidatorWithResult extends DoctorValidator { ValidatorWithResult(super.title, this.result);
final ValidationResult result;
@override Future<ValidationResult> validate() async => result;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337// 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:math' as math;
import 'package:meta/meta.dart';import 'package:process/process.dart';
import 'android/android_emulator.dart';import 'android/android_sdk.dart';import 'android/android_workflow.dart';import 'android/java.dart';import 'base/context.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/process.dart';import 'device.dart';import 'ios/ios_emulators.dart';
EmulatorManager? get emulatorManager => context.get<EmulatorManager>();
/// A class to get all available emulators.class EmulatorManager { EmulatorManager({ required Java? java, AndroidSdk? androidSdk, required Logger logger, required ProcessManager processManager, required AndroidWorkflow androidWorkflow, required FileSystem fileSystem, }) : _java = java, _androidSdk = androidSdk, _processUtils = ProcessUtils(logger: logger, processManager: processManager), _androidEmulators = AndroidEmulators( androidSdk: androidSdk, logger: logger, processManager: processManager, fileSystem: fileSystem, androidWorkflow: androidWorkflow ) { _emulatorDiscoverers.add(_androidEmulators); }
final Java? _java; final AndroidSdk? _androidSdk; final AndroidEmulators _androidEmulators; final ProcessUtils _processUtils;
// Constructing EmulatorManager is cheap; they only do expensive work if some // of their methods are called. final List<EmulatorDiscovery> _emulatorDiscoverers = <EmulatorDiscovery>[ IOSEmulators(), ];
Future<List<Emulator>> getEmulatorsMatching(String searchText) async { final List<Emulator> emulators = await getAllAvailableEmulators(); searchText = searchText.toLowerCase(); bool exactlyMatchesEmulatorId(Emulator emulator) => emulator.id.toLowerCase() == searchText || emulator.name.toLowerCase() == searchText; bool startsWithEmulatorId(Emulator emulator) => emulator.id.toLowerCase().startsWith(searchText) || emulator.name.toLowerCase().startsWith(searchText);
Emulator? exactMatch; for (final Emulator emulator in emulators) { if (exactlyMatchesEmulatorId(emulator)) { exactMatch = emulator; break; } } if (exactMatch != null) { return <Emulator>[exactMatch]; }
// Match on a id or name starting with [emulatorId]. return emulators.where(startsWithEmulatorId).toList(); }
Iterable<EmulatorDiscovery> get _platformDiscoverers { return _emulatorDiscoverers.where((EmulatorDiscovery discoverer) => discoverer.supportsPlatform); }
/// Return the list of all available emulators. Future<List<Emulator>> getAllAvailableEmulators() async { final List<Emulator> emulators = <Emulator>[]; await Future.forEach<EmulatorDiscovery>(_platformDiscoverers, (EmulatorDiscovery discoverer) async { emulators.addAll(await discoverer.emulators); }); return emulators; }
/// Return the list of all available emulators. Future<CreateEmulatorResult> createEmulator({ String? name }) async { if (name == null || name.isEmpty) { const String autoName = 'flutter_emulator'; // Don't use getEmulatorsMatching here, as it will only return one // if there's an exact match and we need all those with this prefix // so we can keep adding suffixes until we miss. final List<Emulator> all = await getAllAvailableEmulators(); final Set<String> takenNames = all .map<String>((Emulator e) => e.id) .where((String id) => id.startsWith(autoName)) .toSet(); int suffix = 1; name = autoName; while (takenNames.contains(name)) { name = '${autoName}_${++suffix}'; } } final String emulatorName = name!; final String? avdManagerPath = _androidSdk?.avdManagerPath; if (avdManagerPath == null || !_androidEmulators.canLaunchAnything) { return CreateEmulatorResult(emulatorName, success: false, error: 'avdmanager is missing from the Android SDK' ); }
final String? device = await _getPreferredAvailableDevice(avdManagerPath); if (device == null) { return CreateEmulatorResult(emulatorName, success: false, error: 'No device definitions are available'); }
final String? sdkId = await _getPreferredSdkId(avdManagerPath); if (sdkId == null) { return CreateEmulatorResult(emulatorName, success: false, error: 'No suitable Android AVD system images are available. You may need to install these' ' using sdkmanager, for example:\n' ' sdkmanager "system-images;android-27;google_apis_playstore;x86"'); }
// Cleans up error output from avdmanager to make it more suitable to show // to flutter users. Specifically: // - Removes lines that say "null" (!) // - Removes lines that tell the user to use '--force' to overwrite emulators String? cleanError(String? error) { if (error == null || error.trim() == '') { return null; } return error .split('\n') .where((String l) => l.trim() != 'null') .where((String l) => l.trim() != 'Use --force if you want to replace it.') .join('\n') .trim(); } final RunResult runResult = await _processUtils.run(<String>[ avdManagerPath, 'create', 'avd', '-n', emulatorName, '-k', sdkId, '-d', device, ], environment: _java?.environment, ); return CreateEmulatorResult( emulatorName, success: runResult.exitCode == 0, output: runResult.stdout, error: cleanError(runResult.stderr), ); }
static const List<String> preferredDevices = <String>[ 'pixel', 'pixel_xl', ];
Future<String?> _getPreferredAvailableDevice(String avdManagerPath) async { final List<String> args = <String>[ avdManagerPath, 'list', 'device', '-c', ]; final RunResult runResult = await _processUtils.run(args, environment: _java?.environment); if (runResult.exitCode != 0) { return null; }
final List<String> availableDevices = runResult.stdout .split('\n') .where((String l) => preferredDevices.contains(l.trim())) .toList();
for (final String device in preferredDevices) { if (availableDevices.contains(device)) { return device; } } return null; }
static final RegExp _androidApiVersion = RegExp(r';android-(\d+);');
Future<String?> _getPreferredSdkId(String avdManagerPath) async { // It seems that to get the available list of images, we need to send a // request to create without the image and it'll provide us a list :-( final List<String> args = <String>[ avdManagerPath, 'create', 'avd', '-n', 'temp', ]; final RunResult runResult = await _processUtils.run(args, environment: _java?.environment);
// Get the list of IDs that match our criteria final List<String> availableIDs = runResult.stderr .split('\n') .where((String l) => _androidApiVersion.hasMatch(l)) .where((String l) => l.contains('system-images')) .where((String l) => l.contains('google_apis_playstore')) .toList();
final List<int> availableApiVersions = availableIDs .map<String>((String id) => _androidApiVersion.firstMatch(id)!.group(1)!) .map<int>((String apiVersion) => int.parse(apiVersion)) .toList();
// Get the highest Android API version or whats left final int apiVersion = availableApiVersions.isNotEmpty ? availableApiVersions.reduce(math.max) : -1; // Don't match below
// We're out of preferences, we just have to return the first one with the high // API version. for (final String id in availableIDs) { if (id.contains(';android-$apiVersion;')) { return id; } } return null; }
/// Whether we're capable of listing any emulators given the current environment configuration. bool get canListAnything { return _platformDiscoverers.any((EmulatorDiscovery discoverer) => discoverer.canListAnything); }}
/// An abstract class to discover and enumerate a specific type of emulators.abstract class EmulatorDiscovery { bool get supportsPlatform;
/// Whether this emulator discovery is capable of listing any emulators. bool get canListAnything;
/// Whether this emulator discovery is capable of launching new emulators. bool get canLaunchAnything;
Future<List<Emulator>> get emulators;}
@immutableabstract class Emulator { const Emulator(this.id, this.hasConfig);
final String id; final bool hasConfig; String get name; String? get manufacturer; Category get category; PlatformType get platformType;
@override int get hashCode => id.hashCode;
@override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is Emulator && other.id == id; }
Future<void> launch({bool coldBoot});
@override String toString() => name;
static List<String> descriptions(List<Emulator> emulators) { if (emulators.isEmpty) { return <String>[]; }
// Extract emulators information final List<List<String>> table = <List<String>>[ for (final Emulator emulator in emulators) <String>[ emulator.id, emulator.name, emulator.manufacturer ?? '', emulator.platformType.toString(), ], ];
// Calculate column widths final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i); List<int> widths = indices.map<int>((int i) => 0).toList(); for (final List<String> row in table) { widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList(); }
// Join columns into lines of text final RegExp whiteSpaceAndDots = RegExp(r'[•\s]+$'); return table .map<String>((List<String> row) { return indices .map<String>((int i) => row[i].padRight(widths[i])) .followedBy(<String>[row.last]) .join(' • '); }) .map<String>((String line) => line.replaceAll(whiteSpaceAndDots, '')) .toList(); }
static void printEmulators(List<Emulator> emulators, Logger logger) { descriptions(emulators).forEach(logger.printStatus); }}
class CreateEmulatorResult { CreateEmulatorResult(this.emulatorName, {required this.success, this.output, this.error});
final bool success; final String emulatorName; final String? output; final String? error;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316// 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 'base/context.dart';
/// The current [FeatureFlags] implementation.FeatureFlags get featureFlags => context.get<FeatureFlags>()!;
/// The interface used to determine if a particular [Feature] is enabled.////// The rest of the tools code should use this class instead of looking up/// features directly. To facilitate rolls to google3 and other clients, all/// flags should be provided with a default implementation here. Clients that/// use this class should extent instead of implement, so that new flags are/// picked up automatically.abstract class FeatureFlags { /// const constructor so that subclasses can be const. const FeatureFlags();
/// Whether flutter desktop for linux is enabled. bool get isLinuxEnabled => false;
/// Whether flutter desktop for macOS is enabled. bool get isMacOSEnabled => false;
/// Whether flutter web is enabled. bool get isWebEnabled => false;
/// Whether flutter desktop for Windows is enabled. bool get isWindowsEnabled => false;
/// Whether android is enabled. bool get isAndroidEnabled => true;
/// Whether iOS is enabled. bool get isIOSEnabled => true;
/// Whether fuchsia is enabled. bool get isFuchsiaEnabled => true;
/// Whether custom devices are enabled. bool get areCustomDevicesEnabled => false;
/// Whether WebAssembly compilation for Flutter Web is enabled. bool get isFlutterWebWasmEnabled => false;
/// Whether animations are used in the command line interface. bool get isCliAnimationEnabled => true;
/// Whether native assets compilation and bundling is enabled. bool get isNativeAssetsEnabled => false;
/// Whether native assets compilation and bundling is enabled. bool get isPreviewDeviceEnabled => true;
/// Whether a particular feature is enabled for the current channel. /// /// Prefer using one of the specific getters above instead of this API. bool isEnabled(Feature feature);}
/// All current Flutter feature flags.const List<Feature> allFeatures = <Feature>[ flutterWebFeature, flutterLinuxDesktopFeature, flutterMacOSDesktopFeature, flutterWindowsDesktopFeature, flutterAndroidFeature, flutterIOSFeature, flutterFuchsiaFeature, flutterCustomDevicesFeature, flutterWebWasm, cliAnimation, nativeAssets, previewDevice,];
/// All current Flutter feature flags that can be configured.////// [Feature.configSetting] is not `null`.Iterable<Feature> get allConfigurableFeatures => allFeatures.where((Feature feature) => feature.configSetting != null);
/// The [Feature] for flutter web.const Feature flutterWebFeature = Feature.fullyEnabled( name: 'Flutter for web', configSetting: 'enable-web', environmentOverride: 'FLUTTER_WEB',);
/// The [Feature] for macOS desktop.const Feature flutterMacOSDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on macOS', configSetting: 'enable-macos-desktop', environmentOverride: 'FLUTTER_MACOS',);
/// The [Feature] for Linux desktop.const Feature flutterLinuxDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on Linux', configSetting: 'enable-linux-desktop', environmentOverride: 'FLUTTER_LINUX',);
/// The [Feature] for Windows desktop.const Feature flutterWindowsDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on Windows', configSetting: 'enable-windows-desktop', environmentOverride: 'FLUTTER_WINDOWS',);
/// The [Feature] for Android devices.const Feature flutterAndroidFeature = Feature.fullyEnabled( name: 'Flutter for Android', configSetting: 'enable-android',);
/// The [Feature] for iOS devices.const Feature flutterIOSFeature = Feature.fullyEnabled( name: 'Flutter for iOS', configSetting: 'enable-ios',);
/// The [Feature] for Fuchsia support.const Feature flutterFuchsiaFeature = Feature( name: 'Flutter for Fuchsia', configSetting: 'enable-fuchsia', environmentOverride: 'FLUTTER_FUCHSIA', master: FeatureChannelSetting( available: true, ),);
const Feature flutterCustomDevicesFeature = Feature( name: 'early support for custom device types', configSetting: 'enable-custom-devices', environmentOverride: 'FLUTTER_CUSTOM_DEVICES', master: FeatureChannelSetting( available: true, ), beta: FeatureChannelSetting( available: true, ), stable: FeatureChannelSetting( available: true, ),);
/// Enabling WebAssembly compilation from `flutter build web`const Feature flutterWebWasm = Feature( name: 'WebAssembly compilation from flutter build web', environmentOverride: 'FLUTTER_WEB_WASM', master: FeatureChannelSetting( available: true, enabledByDefault: true, ),);
const String kCliAnimationsFeatureName = 'cli-animations';
/// The [Feature] for CLI animations.////// The TERM environment variable set to "dumb" turns this off.const Feature cliAnimation = Feature.fullyEnabled( name: 'animations in the command line interface', configSetting: kCliAnimationsFeatureName,);
/// Enable native assets compilation and bundling.const Feature nativeAssets = Feature( name: 'native assets compilation and bundling', configSetting: 'enable-native-assets', environmentOverride: 'FLUTTER_NATIVE_ASSETS', master: FeatureChannelSetting( available: true, ),);
/// Enable Flutter preview prebuilt device.const Feature previewDevice = Feature( name: 'Flutter preview prebuilt device', configSetting: 'enable-flutter-preview', environmentOverride: 'FLUTTER_PREVIEW_DEVICE', master: FeatureChannelSetting( available: true, ), beta: FeatureChannelSetting( available: true, ),);
/// A [Feature] is a process for conditionally enabling tool features.////// All settings are optional, and if not provided will generally default to/// a "safe" value, such as being off.////// The top level feature settings can be provided to apply to all channels./// Otherwise, more specific settings take precedence over higher level/// settings.class Feature { /// Creates a [Feature]. const Feature({ required this.name, this.environmentOverride, this.configSetting, this.extraHelpText, this.master = const FeatureChannelSetting(), this.beta = const FeatureChannelSetting(), this.stable = const FeatureChannelSetting() });
/// Creates a [Feature] that is fully enabled across channels. const Feature.fullyEnabled( {required this.name, this.environmentOverride, this.configSetting, this.extraHelpText}) : master = const FeatureChannelSetting( available: true, enabledByDefault: true, ), beta = const FeatureChannelSetting( available: true, enabledByDefault: true, ), stable = const FeatureChannelSetting( available: true, enabledByDefault: true, );
/// The user visible name for this feature. final String name;
/// The settings for the master branch and other unknown channels. final FeatureChannelSetting master;
/// The settings for the beta branch. final FeatureChannelSetting beta;
/// The settings for the stable branch. final FeatureChannelSetting stable;
/// The name of an environment variable that can override the setting. /// /// The environment variable needs to be set to the value 'true'. This is /// only intended for usage by CI and not as an advertised method to enable /// a feature. /// /// If not provided, defaults to `null` meaning there is no override. final String? environmentOverride;
/// The name of a setting that can be used to enable this feature. /// /// If not provided, defaults to `null` meaning there is no config setting. final String? configSetting;
/// Additional text to add to the end of the help message. /// /// If not provided, defaults to `null` meaning there is no additional text. final String? extraHelpText;
/// A help message for the `flutter config` command, or null if unsupported. String? generateHelpMessage() { if (configSetting == null) { return null; } final StringBuffer buffer = StringBuffer('Enable or disable $name.'); final List<String> channels = <String>[ if (master.available) 'master', if (beta.available) 'beta', if (stable.available) 'stable', ]; // Add channel info for settings only on some channels. if (channels.length == 1) { buffer.write('\nThis setting applies only to the ${channels.single} channel.'); } else if (channels.length == 2) { buffer.write('\nThis setting applies only to the ${channels.join(' and ')} channels.'); } if (extraHelpText != null) { buffer.write(' $extraHelpText'); } return buffer.toString(); }
/// Retrieve the correct setting for the provided `channel`. FeatureChannelSetting getSettingForChannel(String channel) { switch (channel) { case 'stable': return stable; case 'beta': return beta; case 'master': default: return master; } }}
/// A description of the conditions to enable a feature for a particular channel.class FeatureChannelSetting { const FeatureChannelSetting({ this.available = false, this.enabledByDefault = false, });
/// Whether the feature is available on this channel. /// /// If not provided, defaults to `false`. This implies that the feature /// cannot be enabled even by the settings below. final bool available;
/// Whether the feature is enabled by default. /// /// If not provided, defaults to `false`. final bool enabledByDefault;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111// 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:process/process.dart';
import 'android/android_sdk.dart';import 'android/application_package.dart';import 'application_package.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/process.dart';import 'base/user_messages.dart';import 'build_info.dart';import 'fuchsia/application_package.dart';import 'globals.dart' as globals;import 'ios/application_package.dart';import 'linux/application_package.dart';import 'macos/application_package.dart';import 'project.dart';import 'tester/flutter_tester.dart';import 'web/web_device.dart';import 'windows/application_package.dart';
/// A package factory that supports all Flutter target platforms.class FlutterApplicationPackageFactory extends ApplicationPackageFactory { FlutterApplicationPackageFactory({ required AndroidSdk? androidSdk, required ProcessManager processManager, required Logger logger, required UserMessages userMessages, required FileSystem fileSystem, }) : _androidSdk = androidSdk, _processManager = processManager, _logger = logger, _userMessages = userMessages, _fileSystem = fileSystem, _processUtils = ProcessUtils(logger: logger, processManager: processManager);
final AndroidSdk? _androidSdk; final ProcessManager _processManager; final Logger _logger; final ProcessUtils _processUtils; final UserMessages _userMessages; final FileSystem _fileSystem;
@override Future<ApplicationPackage?> getPackageForPlatform( TargetPlatform platform, { BuildInfo? buildInfo, File? applicationBinary, }) async { switch (platform) { case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: if (applicationBinary == null) { return AndroidApk.fromAndroidProject( FlutterProject.current().android, processManager: _processManager, processUtils: _processUtils, logger: _logger, androidSdk: _androidSdk, userMessages: _userMessages, fileSystem: _fileSystem, buildInfo: buildInfo, ); } return AndroidApk.fromApk( applicationBinary, processManager: _processManager, logger: _logger, androidSdk: _androidSdk!, userMessages: _userMessages, processUtils: _processUtils, ); case TargetPlatform.ios: return applicationBinary == null ? await IOSApp.fromIosProject(FlutterProject.current().ios, buildInfo) : IOSApp.fromPrebuiltApp(applicationBinary); case TargetPlatform.tester: return FlutterTesterApp.fromCurrentDirectory(globals.fs); case TargetPlatform.darwin: return applicationBinary == null ? MacOSApp.fromMacOSProject(FlutterProject.current().macos) : MacOSApp.fromPrebuiltApp(applicationBinary); case TargetPlatform.web_javascript: if (!FlutterProject.current().web.existsSync()) { return null; } return WebApplicationPackage(FlutterProject.current()); case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: return applicationBinary == null ? LinuxApp.fromLinuxProject(FlutterProject.current().linux) : LinuxApp.fromPrebuiltApp(applicationBinary); case TargetPlatform.windows_x64: return applicationBinary == null ? WindowsApp.fromWindowsProject(FlutterProject.current().windows) : WindowsApp.fromPrebuiltApp(applicationBinary); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: return applicationBinary == null ? FuchsiaApp.fromFuchsiaProject(FlutterProject.current().fuchsia) : FuchsiaApp.fromPrebuiltApp(applicationBinary); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918// 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:meta/meta.dart';import 'package:package_config/package_config.dart';
import 'android/java.dart';import 'base/common.dart';import 'base/error_handling_io.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/os.dart' show OperatingSystemUtils;import 'base/platform.dart';import 'base/process.dart';import 'cache.dart';import 'dart/package_map.dart';import 'dart/pub.dart';import 'globals.dart' as globals;import 'project.dart';
/// An implementation of the [Cache] which provides all of Flutter's default artifacts.class FlutterCache extends Cache { /// [rootOverride] is configurable for testing. /// [artifacts] is configurable for testing. FlutterCache({ required Logger logger, required super.fileSystem, required Platform platform, required super.osUtils, required FlutterProjectFactory projectFactory, }) : super(logger: logger, platform: platform, artifacts: <ArtifactSet>[]) { registerArtifact(MaterialFonts(this)); registerArtifact(GradleWrapper(this)); registerArtifact(AndroidGenSnapshotArtifacts(this, platform: platform)); registerArtifact(AndroidInternalBuildArtifacts(this)); registerArtifact(IOSEngineArtifacts(this, platform: platform)); registerArtifact(FlutterWebSdk(this)); registerArtifact(LegacyCanvasKitRemover(this)); registerArtifact(FlutterSdk(this, platform: platform)); registerArtifact(WindowsEngineArtifacts(this, platform: platform)); registerArtifact(MacOSEngineArtifacts(this, platform: platform)); registerArtifact(LinuxEngineArtifacts(this, platform: platform)); registerArtifact(LinuxFuchsiaSDKArtifacts(this, platform: platform)); registerArtifact(MacOSFuchsiaSDKArtifacts(this, platform: platform)); registerArtifact(FlutterRunnerSDKArtifacts(this, platform: platform)); registerArtifact(FlutterRunnerDebugSymbols(this, platform: platform)); for (final String artifactName in IosUsbArtifacts.artifactNames) { registerArtifact(IosUsbArtifacts(artifactName, this, platform: platform)); } registerArtifact(FontSubsetArtifacts(this, platform: platform)); registerArtifact(PubDependencies( logger: logger, // flutter root and pub must be lazily initialized to avoid accessing // before the version is determined. flutterRoot: () => Cache.flutterRoot!, pub: () => pub, projectFactory: projectFactory, )); }}
/// Ensures that the source files for all of the dependencies for the/// flutter_tool are present.////// This does not handle cases where the source files are modified or the/// directory contents are incomplete.class PubDependencies extends ArtifactSet { PubDependencies({ // Needs to be lazy to avoid reading from the cache before the root is initialized. required String Function() flutterRoot, required Logger logger, required Pub Function() pub, required FlutterProjectFactory projectFactory, }) : _logger = logger, _flutterRoot = flutterRoot, _pub = pub, _projectFactory = projectFactory, super(DevelopmentArtifact.universal);
final String Function() _flutterRoot; final Logger _logger; final Pub Function() _pub; final FlutterProjectFactory _projectFactory;
@override Future<bool> isUpToDate( FileSystem fileSystem, ) async { final File toolPackageConfig = fileSystem.file( fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools', '.dart_tool', 'package_config.json'), ); if (!toolPackageConfig.existsSync()) { return false; } final PackageConfig packageConfig = await loadPackageConfigWithLogging( toolPackageConfig, logger: _logger, throwOnError: false, ); if (packageConfig == PackageConfig.empty) { return false; } for (final Package package in packageConfig.packages) { if (!fileSystem.directory(package.root).childFile('pubspec.yaml').existsSync()) { return false; } } return true; }
@override String get name => 'pub_dependencies';
@override Future<void> update( ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false} ) async { await _pub().get( context: PubContext.pubGet, project: _projectFactory.fromDirectory( fileSystem.directory(fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools')) ), offline: offline, outputMode: PubOutputMode.none, ); }}
/// A cached artifact containing fonts used for Material Design.class MaterialFonts extends CachedArtifact { MaterialFonts(Cache cache) : super( 'material_fonts', cache, DevelopmentArtifact.universal, );
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { final Uri archiveUri = _toStorageUri(version!); return artifactUpdater.downloadZipArchive('Downloading Material fonts...', archiveUri, location); }
Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path');}
/// A cached artifact containing the web dart:ui sources, platform dill files,/// and libraries.json.////// This SDK references code within the regular Dart sdk to reduce download size.class FlutterWebSdk extends CachedArtifact { FlutterWebSdk(Cache cache) : super( 'flutter_web_sdk', cache, DevelopmentArtifact.web, );
@override Directory get location => cache.getWebSdkDirectory();
@override String? get version => cache.getVersionFor('engine');
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { final Uri url = Uri.parse('${cache.storageBaseUrl}/flutter_infra_release/flutter/$version/flutter-web-sdk.zip'); ErrorHandlingFileSystem.deleteIfExists(location, recursive: true); await artifactUpdater.downloadZipArchive('Downloading Web SDK...', url, location); }}
// In previous builds, CanvasKit artifacts were stored in a different location// than they are now. Leaving those old artifacts in the cache confuses the// in-memory filesystem that the web runner uses, so this artifact will evict// them from our cache if they are there.class LegacyCanvasKitRemover extends ArtifactSet { LegacyCanvasKitRemover(this.cache) : super(DevelopmentArtifact.web);
final Cache cache;
@override String get name => 'legacy_canvaskit_remover';
Directory _getLegacyCanvasKitDirectory(FileSystem fileSystem) => fileSystem.directory(fileSystem.path.join( cache.getRoot().path, 'canvaskit', ));
@override Future<bool> isUpToDate(FileSystem fileSystem) async => !(await _getLegacyCanvasKitDirectory(fileSystem).exists());
@override Future<void> update( ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false} ) => _getLegacyCanvasKitDirectory(fileSystem).delete(recursive: true);}
/// A cached artifact containing the dart:ui source code.class FlutterSdk extends EngineCachedArtifact { FlutterSdk(Cache cache, { required Platform platform, }) : _platform = platform, super( 'flutter_sdk', cache, DevelopmentArtifact.universal, );
final Platform _platform;
@override List<String> getPackageDirs() => const <String>['sky_engine'];
@override List<List<String>> getBinaryDirs() { // Currently only Linux supports both arm64 and x64. final String arch = cache.getHostPlatformArchName(); return <List<String>>[ <String>['common', 'flutter_patched_sdk.zip'], <String>['common', 'flutter_patched_sdk_product.zip'], if (cache.includeAllPlatforms) ...<List<String>>[ <String>['windows-x64', 'windows-x64/artifacts.zip'], <String>['linux-$arch', 'linux-$arch/artifacts.zip'], <String>['darwin-x64', 'darwin-$arch/artifacts.zip'], ] else if (_platform.isWindows) <String>['windows-x64', 'windows-x64/artifacts.zip'] else if (_platform.isMacOS) <String>['darwin-x64', 'darwin-$arch/artifacts.zip'] else if (_platform.isLinux) <String>['linux-$arch', 'linux-$arch/artifacts.zip'], ]; }
@override List<String> getLicenseDirs() => const <String>[];}
class MacOSEngineArtifacts extends EngineCachedArtifact { MacOSEngineArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super( 'macos-sdk', cache, DevelopmentArtifact.macOS, );
final Platform _platform;
@override List<String> getPackageDirs() => const <String>[];
@override List<List<String>> getBinaryDirs() { if (_platform.isMacOS || ignorePlatformFiltering) { return _macOSDesktopBinaryDirs; } return const <List<String>>[]; }
@override List<String> getLicenseDirs() => const <String>[];}
/// Artifacts required for desktop Windows builds.class WindowsEngineArtifacts extends EngineCachedArtifact { WindowsEngineArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super( 'windows-sdk', cache, DevelopmentArtifact.windows, );
final Platform _platform;
@override List<String> getPackageDirs() => const <String>[];
@override List<List<String>> getBinaryDirs() { if (_platform.isWindows || ignorePlatformFiltering) { return _windowsDesktopBinaryDirs; } return const <List<String>>[]; }
@override List<String> getLicenseDirs() => const <String>[];}
/// Artifacts required for desktop Linux builds.class LinuxEngineArtifacts extends EngineCachedArtifact { LinuxEngineArtifacts(Cache cache, { required Platform platform }) : _platform = platform, super( 'linux-sdk', cache, DevelopmentArtifact.linux, );
final Platform _platform;
@override List<String> getPackageDirs() => const <String>[];
@override List<List<String>> getBinaryDirs() { if (_platform.isLinux || ignorePlatformFiltering) { final String arch = cache.getHostPlatformArchName(); return <List<String>>[ <String>['linux-$arch', 'linux-$arch-debug/linux-$arch-flutter-gtk.zip'], <String>['linux-$arch-profile', 'linux-$arch-profile/linux-$arch-flutter-gtk.zip'], <String>['linux-$arch-release', 'linux-$arch-release/linux-$arch-flutter-gtk.zip'], ]; } return const <List<String>>[]; }
@override List<String> getLicenseDirs() => const <String>[];}
/// The artifact used to generate snapshots for Android builds.class AndroidGenSnapshotArtifacts extends EngineCachedArtifact { AndroidGenSnapshotArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super( 'android-sdk', cache, DevelopmentArtifact.androidGenSnapshot, );
final Platform _platform;
@override List<String> getPackageDirs() => const <String>[];
@override List<List<String>> getBinaryDirs() { return <List<String>>[ if (cache.includeAllPlatforms) ...<List<String>>[ ..._osxBinaryDirs, ..._linuxBinaryDirs, ..._windowsBinaryDirs, ..._dartSdks, ] else if (_platform.isWindows) ..._windowsBinaryDirs else if (_platform.isMacOS) ..._osxBinaryDirs else if (_platform.isLinux) ..._linuxBinaryDirs, ]; }
@override List<String> getLicenseDirs() { return <String>[]; }}
/// A cached artifact containing the Maven dependencies used to build Android projects.////// This is a no-op if the android SDK is not available.////// Set [Java] to `null` to indicate that no Java/JDK installation could be found.class AndroidMavenArtifacts extends ArtifactSet { AndroidMavenArtifacts(this.cache, { required Java? java, required Platform platform, }) : _java = java, _platform = platform, super(DevelopmentArtifact.androidMaven);
final Java? _java; final Platform _platform; final Cache cache;
@override Future<void> update( ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false} ) async { // TODO(andrewkolos): Should this really be no-op if the Android SDK // is unavailable? https://github.com/flutter/flutter/issues/127848 if (globals.androidSdk == null) { return; } final Directory tempDir = cache.getRoot().createTempSync('flutter_gradle_wrapper.'); globals.gradleUtils?.injectGradleWrapperIfNeeded(tempDir);
final Status status = logger.startProgress('Downloading Android Maven dependencies...'); final File gradle = tempDir.childFile( _platform.isWindows ? 'gradlew.bat' : 'gradlew', ); try { final String gradleExecutable = gradle.absolute.path; final String flutterSdk = globals.fsUtils.escapePath(Cache.flutterRoot!); final RunResult processResult = await globals.processUtils.run( <String>[ gradleExecutable, '-b', globals.fs.path.join(flutterSdk, 'packages', 'flutter_tools', 'gradle', 'resolve_dependencies.gradle'), '--project-cache-dir', tempDir.path, 'resolveDependencies', ], environment: _java?.environment, ); if (processResult.exitCode != 0) { logger.printError('Failed to download the Android dependencies'); } } finally { status.stop(); tempDir.deleteSync(recursive: true); globals.androidSdk?.reinitialize(); } }
@override Future<bool> isUpToDate(FileSystem fileSystem) async { // The dependencies are downloaded and cached by Gradle. // The tool doesn't know if the dependencies are already cached at this point. // Therefore, call Gradle to figure this out. return false; }
@override String get name => 'android-maven-artifacts';}
/// Artifacts used for internal builds. The flutter tool builds Android projects/// using the artifacts cached by [AndroidMavenArtifacts].class AndroidInternalBuildArtifacts extends EngineCachedArtifact { AndroidInternalBuildArtifacts(Cache cache) : super( 'android-internal-build-artifacts', cache, DevelopmentArtifact.androidInternalBuild, );
@override List<String> getPackageDirs() => const <String>[];
@override List<List<String>> getBinaryDirs() { return _androidBinaryDirs; }
@override List<String> getLicenseDirs() { return <String>[]; }}
class IOSEngineArtifacts extends EngineCachedArtifact { IOSEngineArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super( 'ios-sdk', cache, DevelopmentArtifact.iOS, );
final Platform _platform;
@override List<List<String>> getBinaryDirs() { return <List<String>>[ if (_platform.isMacOS || ignorePlatformFiltering) ..._iosBinaryDirs, ]; }
@override List<String> getLicenseDirs() { if (_platform.isMacOS || ignorePlatformFiltering) { return const <String>['ios', 'ios-profile', 'ios-release']; } return const <String>[]; }
@override List<String> getPackageDirs() { return <String>[]; }}
/// A cached artifact containing Gradle Wrapper scripts and binaries.////// While this is only required for Android, we need to always download it due/// the ensurePlatformSpecificTooling logic.class GradleWrapper extends CachedArtifact { GradleWrapper(Cache cache) : super( 'gradle_wrapper', cache, DevelopmentArtifact.universal, );
List<String> get _gradleScripts => <String>['gradlew', 'gradlew.bat'];
Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path');
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { final Uri archiveUri = _toStorageUri(version!); await artifactUpdater.downloadZippedTarball('Downloading Gradle Wrapper...', archiveUri, location); // Delete property file, allowing templates to provide it. // Remove NOTICE file. Should not be part of the template. final File propertiesFile = fileSystem.file(fileSystem.path.join(location.path, 'gradle', 'wrapper', 'gradle-wrapper.properties')); final File noticeFile = fileSystem.file(fileSystem.path.join(location.path, 'NOTICE')); ErrorHandlingFileSystem.deleteIfExists(propertiesFile); ErrorHandlingFileSystem.deleteIfExists(noticeFile); }
@override bool isUpToDateInner( FileSystem fileSystem, ) { final String gradleWrapper = fileSystem.path.join('gradle', 'wrapper', 'gradle-wrapper.jar'); final Directory wrapperDir = cache.getCacheDir(fileSystem.path.join('artifacts', 'gradle_wrapper')); if (!fileSystem.directory(wrapperDir).existsSync()) { return false; } for (final String scriptName in _gradleScripts) { final File scriptFile = fileSystem.file(fileSystem.path.join(wrapperDir.path, scriptName)); if (!scriptFile.existsSync()) { return false; } } final File gradleWrapperJar = fileSystem.file(fileSystem.path.join(wrapperDir.path, gradleWrapper)); if (!gradleWrapperJar.existsSync()) { return false; } return true; }}
/// Common functionality for pulling Fuchsia SDKs.abstract class _FuchsiaSDKArtifacts extends CachedArtifact { _FuchsiaSDKArtifacts(Cache cache, String platform) : _path = 'fuchsia/sdk/core/$platform-amd64', super( 'fuchsia-$platform', cache, DevelopmentArtifact.fuchsia, );
final String _path;
@override Directory get location => cache.getArtifactDirectory('fuchsia');
Future<void> _doUpdate(ArtifactUpdater artifactUpdater) { final String url = '${cache.cipdBaseUrl}/$_path/+/$version'; return artifactUpdater.downloadZipArchive('Downloading package fuchsia SDK...', Uri.parse(url), location); }}
/// The pre-built flutter runner for Fuchsia development.class FlutterRunnerSDKArtifacts extends CachedArtifact { FlutterRunnerSDKArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super( 'flutter_runner', cache, DevelopmentArtifact.flutterRunner, );
final Platform _platform;
@override Directory get location => cache.getArtifactDirectory('flutter_runner');
@override String? get version => cache.getVersionFor('engine');
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { if (!_platform.isLinux && !_platform.isMacOS) { return; } final String url = '${cache.cipdBaseUrl}/flutter/fuchsia/+/git_revision:$version'; await artifactUpdater.downloadZipArchive('Downloading package flutter runner...', Uri.parse(url), location); }}
/// Implementations of this class can resolve URLs for packages that are versioned.////// See also [CipdArchiveResolver].abstract class VersionedPackageResolver { const VersionedPackageResolver();
/// Returns the URL for the artifact. String resolveUrl(String packageName, String version);}
/// Resolves the CIPD archive URL for a given package and version.class CipdArchiveResolver extends VersionedPackageResolver { const CipdArchiveResolver(this.cache);
final Cache cache;
@override String resolveUrl(String packageName, String version) { return '${cache.cipdBaseUrl}/flutter/$packageName/+/git_revision:$version'; }}
/// The debug symbols for flutter runner for Fuchsia development.class FlutterRunnerDebugSymbols extends CachedArtifact { FlutterRunnerDebugSymbols(Cache cache, { required Platform platform, VersionedPackageResolver? packageResolver, }) : _platform = platform, packageResolver = packageResolver ?? CipdArchiveResolver(cache), super('flutter_runner_debug_symbols', cache, DevelopmentArtifact.flutterRunner);
final VersionedPackageResolver packageResolver; final Platform _platform;
@override Directory get location => cache.getArtifactDirectory(name);
@override String? get version => cache.getVersionFor('engine');
Future<void> _downloadDebugSymbols(String targetArch, ArtifactUpdater artifactUpdater) async { final String packageName = 'fuchsia-debug-symbols-$targetArch'; final String url = packageResolver.resolveUrl(packageName, version!); await artifactUpdater.downloadZipArchive( 'Downloading debug symbols for flutter runner - arch:$targetArch...', Uri.parse(url), location, ); }
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { if (!_platform.isLinux && !_platform.isMacOS) { return; } await _downloadDebugSymbols('x64', artifactUpdater); await _downloadDebugSymbols('arm64', artifactUpdater); }}
/// The Fuchsia core SDK for Linux.class LinuxFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts { LinuxFuchsiaSDKArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super(cache, 'linux');
final Platform _platform;
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { if (!_platform.isLinux) { return; } return _doUpdate(artifactUpdater); }}
/// The Fuchsia core SDK for MacOS.class MacOSFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts { MacOSFuchsiaSDKArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super(cache, 'mac');
final Platform _platform;
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { if (!_platform.isMacOS) { return; } return _doUpdate(artifactUpdater); }}
/// Cached artifacts for font subsetting.class FontSubsetArtifacts extends EngineCachedArtifact { FontSubsetArtifacts(Cache cache, { required Platform platform, }) : _platform = platform, super(artifactName, cache, DevelopmentArtifact.universal);
final Platform _platform;
static const String artifactName = 'font-subset';
@override List<List<String>> getBinaryDirs() { // Currently only Linux supports both arm64 and x64. final String arch = cache.getHostPlatformArchName(); final Map<String, List<String>> artifacts = <String, List<String>> { 'macos': <String>['darwin-x64', 'darwin-$arch/$artifactName.zip'], 'linux': <String>['linux-$arch', 'linux-$arch/$artifactName.zip'], 'windows': <String>['windows-x64', 'windows-x64/$artifactName.zip'], }; if (cache.includeAllPlatforms) { return artifacts.values.toList(); } else { final List<String>? binaryDirs = artifacts[_platform.operatingSystem]; if (binaryDirs == null) { throwToolExit('Unsupported operating system: ${_platform.operatingSystem}'); } return <List<String>>[binaryDirs]; } }
@override List<String> getLicenseDirs() => const <String>[];
@override List<String> getPackageDirs() => const <String>[];}
/// Cached iOS/USB binary artifacts.class IosUsbArtifacts extends CachedArtifact { IosUsbArtifacts(String name, Cache cache, { required Platform platform, }) : _platform = platform, super( name, cache, DevelopmentArtifact.universal, );
final Platform _platform;
static const List<String> artifactNames = <String>[ 'libimobiledevice', 'usbmuxd', 'libplist', 'openssl', 'ios-deploy', ];
// For unknown reasons, users are getting into bad states where libimobiledevice is // downloaded but some executables are missing from the zip. The names here are // used for additional download checks below, so we can re-download if they are // missing. static const Map<String, List<String>> _kExecutables = <String, List<String>>{ 'libimobiledevice': <String>[ 'idevicescreenshot', 'idevicesyslog', ], 'usbmuxd': <String>[ 'iproxy', ], };
@override Map<String, String> get environment { return <String, String>{ 'DYLD_LIBRARY_PATH': cache.getArtifactDirectory(name).path, }; }
@override bool isUpToDateInner(FileSystem fileSystem) { final List<String>? executables =_kExecutables[name]; if (executables == null) { return true; } for (final String executable in executables) { if (!location.childFile(executable).existsSync()) { return false; } } return true; }
@override Future<void> updateInner( ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, ) async { if (!_platform.isMacOS && !ignorePlatformFiltering) { return; } if (location.existsSync()) { location.deleteSync(recursive: true); } await artifactUpdater.downloadZipArchive('Downloading $name...', archiveUri, location); }
@visibleForTesting Uri get archiveUri => Uri.parse( '${cache.realmlessStorageBaseUrl}/flutter_infra_release/' 'ios-usb-dependencies${cache.useUnsignedMacBinaries ? '/unsigned' : ''}' '/$name/$version/$name.zip', );}
// TODO(zanderso): upload debug desktop artifacts to host-debug and// remove from existing host folder.// https://github.com/flutter/flutter/issues/38935const List<List<String>> _windowsDesktopBinaryDirs = <List<String>>[ <String>['windows-x64', 'windows-x64-debug/windows-x64-flutter.zip'], <String>['windows-x64', 'windows-x64/flutter-cpp-client-wrapper.zip'], <String>['windows-x64-profile', 'windows-x64-profile/windows-x64-flutter.zip'], <String>['windows-x64-release', 'windows-x64-release/windows-x64-flutter.zip'],];
const List<List<String>> _macOSDesktopBinaryDirs = <List<String>>[ <String>['darwin-x64', 'darwin-x64/FlutterMacOS.framework.zip'], <String>['darwin-x64', 'darwin-x64/gen_snapshot.zip'], <String>['darwin-x64-profile', 'darwin-x64-profile/FlutterMacOS.framework.zip'], <String>['darwin-x64-profile', 'darwin-x64-profile/artifacts.zip'], <String>['darwin-x64-profile', 'darwin-x64-profile/gen_snapshot.zip'], <String>['darwin-x64-release', 'darwin-x64-release/FlutterMacOS.framework.zip'], <String>['darwin-x64-release', 'darwin-x64-release/artifacts.zip'], <String>['darwin-x64-release', 'darwin-x64-release/gen_snapshot.zip'],];
const List<List<String>> _osxBinaryDirs = <List<String>>[ <String>['android-arm-profile/darwin-x64', 'android-arm-profile/darwin-x64.zip'], <String>['android-arm-release/darwin-x64', 'android-arm-release/darwin-x64.zip'], <String>['android-arm64-profile/darwin-x64', 'android-arm64-profile/darwin-x64.zip'], <String>['android-arm64-release/darwin-x64', 'android-arm64-release/darwin-x64.zip'], <String>['android-x64-profile/darwin-x64', 'android-x64-profile/darwin-x64.zip'], <String>['android-x64-release/darwin-x64', 'android-x64-release/darwin-x64.zip'],];
const List<List<String>> _linuxBinaryDirs = <List<String>>[ <String>['android-arm-profile/linux-x64', 'android-arm-profile/linux-x64.zip'], <String>['android-arm-release/linux-x64', 'android-arm-release/linux-x64.zip'], <String>['android-arm64-profile/linux-x64', 'android-arm64-profile/linux-x64.zip'], <String>['android-arm64-release/linux-x64', 'android-arm64-release/linux-x64.zip'], <String>['android-x64-profile/linux-x64', 'android-x64-profile/linux-x64.zip'], <String>['android-x64-release/linux-x64', 'android-x64-release/linux-x64.zip'],];
const List<List<String>> _windowsBinaryDirs = <List<String>>[ <String>['android-arm-profile/windows-x64', 'android-arm-profile/windows-x64.zip'], <String>['android-arm-release/windows-x64', 'android-arm-release/windows-x64.zip'], <String>['android-arm64-profile/windows-x64', 'android-arm64-profile/windows-x64.zip'], <String>['android-arm64-release/windows-x64', 'android-arm64-release/windows-x64.zip'], <String>['android-x64-profile/windows-x64', 'android-x64-profile/windows-x64.zip'], <String>['android-x64-release/windows-x64', 'android-x64-release/windows-x64.zip'],];
const List<List<String>> _iosBinaryDirs = <List<String>>[ <String>['ios', 'ios/artifacts.zip'], <String>['ios-profile', 'ios-profile/artifacts.zip'], <String>['ios-release', 'ios-release/artifacts.zip'],];
const List<List<String>> _androidBinaryDirs = <List<String>>[ <String>['android-x86', 'android-x86/artifacts.zip'], <String>['android-x64', 'android-x64/artifacts.zip'], <String>['android-arm', 'android-arm/artifacts.zip'], <String>['android-arm-profile', 'android-arm-profile/artifacts.zip'], <String>['android-arm-release', 'android-arm-release/artifacts.zip'], <String>['android-arm64', 'android-arm64/artifacts.zip'], <String>['android-arm64-profile', 'android-arm64-profile/artifacts.zip'], <String>['android-arm64-release', 'android-arm64-release/artifacts.zip'], <String>['android-x64-profile', 'android-x64-profile/artifacts.zip'], <String>['android-x64-release', 'android-x64-release/artifacts.zip'], <String>['android-x86-jit-release', 'android-x86-jit-release/artifacts.zip'],];
const List<List<String>> _dartSdks = <List<String>> [ <String>['darwin-x64', 'dart-sdk-darwin-x64.zip'], <String>['linux-x64', 'dart-sdk-linux-x64.zip'], <String>['windows-x64', 'dart-sdk-windows-x64.zip'],];123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148// 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:process/process.dart';
import 'android/android_device_discovery.dart';import 'android/android_sdk.dart';import 'android/android_workflow.dart';import 'artifacts.dart';import 'base/file_system.dart';import 'base/os.dart';import 'base/platform.dart';import 'base/user_messages.dart';import 'custom_devices/custom_device.dart';import 'custom_devices/custom_devices_config.dart';import 'device.dart';import 'features.dart';import 'fuchsia/fuchsia_device.dart';import 'fuchsia/fuchsia_sdk.dart';import 'fuchsia/fuchsia_workflow.dart';import 'ios/devices.dart';import 'ios/ios_workflow.dart';import 'ios/simulators.dart';import 'linux/linux_device.dart';import 'macos/macos_device.dart';import 'macos/macos_ipad_device.dart';import 'macos/macos_workflow.dart';import 'macos/xcdevice.dart';import 'preview_device.dart';import 'tester/flutter_tester.dart';import 'version.dart';import 'web/web_device.dart';
import 'windows/windows_device.dart';import 'windows/windows_workflow.dart';
/// A provider for all of the device discovery instances.class FlutterDeviceManager extends DeviceManager { FlutterDeviceManager({ required super.logger, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required AndroidSdk? androidSdk, required FeatureFlags featureFlags, required IOSSimulatorUtils iosSimulatorUtils, required XCDevice xcDevice, required AndroidWorkflow androidWorkflow, required IOSWorkflow iosWorkflow, required FuchsiaWorkflow fuchsiaWorkflow, required FlutterVersion flutterVersion, required Artifacts artifacts, required MacOSWorkflow macOSWorkflow, required FuchsiaSdk fuchsiaSdk, required UserMessages userMessages, required OperatingSystemUtils operatingSystemUtils, required WindowsWorkflow windowsWorkflow, required CustomDevicesConfig customDevicesConfig, }) : deviceDiscoverers = <DeviceDiscovery>[ AndroidDevices( logger: logger, androidSdk: androidSdk, androidWorkflow: androidWorkflow, processManager: processManager, fileSystem: fileSystem, platform: platform, userMessages: userMessages, ), IOSDevices( platform: platform, xcdevice: xcDevice, iosWorkflow: iosWorkflow, logger: logger, ), IOSSimulators( iosSimulatorUtils: iosSimulatorUtils, ), FuchsiaDevices( fuchsiaSdk: fuchsiaSdk, logger: logger, fuchsiaWorkflow: fuchsiaWorkflow, platform: platform, ), FlutterTesterDevices( fileSystem: fileSystem, flutterVersion: flutterVersion, processManager: processManager, logger: logger, artifacts: artifacts, ), MacOSDevices( processManager: processManager, macOSWorkflow: macOSWorkflow, logger: logger, platform: platform, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), MacOSDesignedForIPadDevices( processManager: processManager, iosWorkflow: iosWorkflow, logger: logger, platform: platform, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), PreviewDeviceDiscovery( platform: platform, artifacts: artifacts, fileSystem: fileSystem, logger: logger, processManager: processManager, featureFlags: featureFlags, ), LinuxDevices( platform: platform, featureFlags: featureFlags, processManager: processManager, logger: logger, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), WindowsDevices( processManager: processManager, operatingSystemUtils: operatingSystemUtils, logger: logger, fileSystem: fileSystem, windowsWorkflow: windowsWorkflow, ), WebDevices( featureFlags: featureFlags, fileSystem: fileSystem, platform: platform, processManager: processManager, logger: logger, ), CustomDevices( featureFlags: featureFlags, processManager: processManager, logger: logger, config: customDevicesConfig ), ];
@override final List<DeviceDiscovery> deviceDiscoverers;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485// 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 'base/config.dart';import 'base/platform.dart';import 'features.dart';import 'version.dart';
class FlutterFeatureFlags implements FeatureFlags { FlutterFeatureFlags({ required FlutterVersion flutterVersion, required Config config, required Platform platform, }) : _flutterVersion = flutterVersion, _config = config, _platform = platform;
final FlutterVersion _flutterVersion; final Config _config; final Platform _platform;
@override bool get isLinuxEnabled => isEnabled(flutterLinuxDesktopFeature);
@override bool get isMacOSEnabled => isEnabled(flutterMacOSDesktopFeature);
@override bool get isWebEnabled => isEnabled(flutterWebFeature);
@override bool get isWindowsEnabled => isEnabled(flutterWindowsDesktopFeature);
@override bool get isAndroidEnabled => isEnabled(flutterAndroidFeature);
@override bool get isIOSEnabled => isEnabled(flutterIOSFeature);
@override bool get isFuchsiaEnabled => isEnabled(flutterFuchsiaFeature);
@override bool get areCustomDevicesEnabled => isEnabled(flutterCustomDevicesFeature);
@override bool get isFlutterWebWasmEnabled => isEnabled(flutterWebWasm);
@override bool get isCliAnimationEnabled { if (_platform.environment['TERM'] == 'dumb') { return false; } return isEnabled(cliAnimation); }
@override bool get isNativeAssetsEnabled => isEnabled(nativeAssets);
@override bool get isPreviewDeviceEnabled => isEnabled(previewDevice);
@override bool isEnabled(Feature feature) { final String currentChannel = _flutterVersion.channel; final FeatureChannelSetting featureSetting = feature.getSettingForChannel(currentChannel); if (!featureSetting.available) { return false; } bool isEnabled = featureSetting.enabledByDefault; if (feature.configSetting != null) { final bool? configOverride = _config.getValue(feature.configSetting!) as bool?; if (configOverride != null) { isEnabled = configOverride; } } if (feature.environmentOverride != null) { if (_platform.environment[feature.environmentOverride]?.toLowerCase() == 'true') { isEnabled = true; } } return isEnabled; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796// 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:meta/meta.dart';import 'package:pub_semver/pub_semver.dart';import 'package:yaml/yaml.dart';
import 'base/deferred_component.dart';import 'base/file_system.dart';import 'base/logger.dart';import 'base/user_messages.dart';import 'base/utils.dart';import 'plugins.dart';
/// Whether or not Impeller Scene 3D model import is enabled.const bool kIs3dSceneSupported = true;
const Set<String> _kValidPluginPlatforms = <String>{ 'android', 'ios', 'web', 'windows', 'linux', 'macos',};
/// A wrapper around the `flutter` section in the `pubspec.yaml` file.class FlutterManifest { FlutterManifest._({required Logger logger}) : _logger = logger;
/// Returns an empty manifest. factory FlutterManifest.empty({ required Logger logger }) = FlutterManifest._;
/// Returns null on invalid manifest. Returns empty manifest on missing file. static FlutterManifest? createFromPath(String path, { required FileSystem fileSystem, required Logger logger, }) { if (!fileSystem.isFileSync(path)) { return _createFromYaml(null, logger); } final String manifest = fileSystem.file(path).readAsStringSync(); return FlutterManifest.createFromString(manifest, logger: logger); }
/// Returns null on missing or invalid manifest. @visibleForTesting static FlutterManifest? createFromString(String manifest, { required Logger logger }) { return _createFromYaml(loadYaml(manifest), logger); }
static FlutterManifest? _createFromYaml(Object? yamlDocument, Logger logger) { if (yamlDocument != null && !_validate(yamlDocument, logger)) { return null; }
final FlutterManifest pubspec = FlutterManifest._(logger: logger); final Map<Object?, Object?>? yamlMap = yamlDocument as YamlMap?; if (yamlMap != null) { pubspec._descriptor = yamlMap.cast<String, Object?>(); }
final Map<Object?, Object?>? flutterMap = pubspec._descriptor['flutter'] as Map<Object?, Object?>?; if (flutterMap != null) { pubspec._flutterDescriptor = flutterMap.cast<String, Object?>(); }
return pubspec; }
final Logger _logger;
/// A map representation of the entire `pubspec.yaml` file. Map<String, Object?> _descriptor = <String, Object?>{};
/// A map representation of the `flutter` section in the `pubspec.yaml` file. Map<String, Object?> _flutterDescriptor = <String, Object?>{};
Map<String, Object?> get flutterDescriptor => _flutterDescriptor;
/// True if the `pubspec.yaml` file does not exist. bool get isEmpty => _descriptor.isEmpty;
/// The string value of the top-level `name` property in the `pubspec.yaml` file. String get appName => _descriptor['name'] as String? ?? '';
/// Contains the name of the dependencies. /// These are the keys specified in the `dependency` map. Set<String> get dependencies { final YamlMap? dependencies = _descriptor['dependencies'] as YamlMap?; return dependencies != null ? <String>{...dependencies.keys.cast<String>()} : <String>{}; }
// Flag to avoid printing multiple invalid version messages. bool _hasShowInvalidVersionMsg = false;
/// The version String from the `pubspec.yaml` file. /// Can be null if it isn't set or has a wrong format. String? get appVersion { final String? verStr = _descriptor['version']?.toString(); if (verStr == null) { return null; }
Version? version; try { version = Version.parse(verStr); } on Exception { if (!_hasShowInvalidVersionMsg) { _logger.printStatus(userMessages.invalidVersionSettingHintMessage(verStr), emphasis: true); _hasShowInvalidVersionMsg = true; } } return version?.toString(); }
/// The build version name from the `pubspec.yaml` file. /// Can be null if version isn't set or has a wrong format. String? get buildName { final String? version = appVersion; if (version != null && version.contains('+')) { return version.split('+').elementAt(0); } return version; }
/// The build version number from the `pubspec.yaml` file. /// Can be null if version isn't set or has a wrong format. String? get buildNumber { final String? version = appVersion; if (version != null && version.contains('+')) { final String value = version.split('+').elementAt(1); return value; } else { return null; } }
bool get usesMaterialDesign { return _flutterDescriptor['uses-material-design'] as bool? ?? false; }
/// True if this Flutter module should use AndroidX dependencies. /// /// If false the deprecated Android Support library will be used. bool get usesAndroidX { final Object? module = _flutterDescriptor['module']; if (module is YamlMap) { return module['androidX'] == true; } return false; }
/// Any additional license files listed under the `flutter` key. /// /// This is expected to be a list of file paths that should be treated as /// relative to the pubspec in this directory. /// /// For example: /// /// ```yaml /// flutter: /// licenses: /// - assets/foo_license.txt /// ``` List<String> get additionalLicenses { final Object? licenses = _flutterDescriptor['licenses']; if (licenses is YamlList) { return licenses.map((Object? element) => element.toString()).toList(); } return <String>[]; }
/// True if this manifest declares a Flutter module project. /// /// A Flutter project is considered a module when it has a `module:` /// descriptor. A Flutter module project supports integration into an /// existing host app, and has managed platform host code. /// /// Such a project can be created using `flutter create -t module`. bool get isModule => _flutterDescriptor.containsKey('module');
/// True if this manifest declares a Flutter plugin project. /// /// A Flutter project is considered a plugin when it has a `plugin:` /// descriptor. A Flutter plugin project wraps custom Android and/or /// iOS code in a Dart interface for consumption by other Flutter app /// projects. /// /// Such a project can be created using `flutter create -t plugin`. bool get isPlugin => _flutterDescriptor.containsKey('plugin');
/// Returns the Android package declared by this manifest in its /// module or plugin descriptor. Returns null, if there is no /// such declaration. String? get androidPackage { if (isModule) { final Object? module = _flutterDescriptor['module']; if (module is YamlMap) { return module['androidPackage'] as String?; } } final Map<String, Object?>? platforms = supportedPlatforms; if (platforms == null) { // Pre-multi-platform plugin format if (isPlugin) { final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?; return plugin?['androidPackage'] as String?; } return null; } if (platforms.containsKey('android')) { final Object? android = platforms['android']; if (android is YamlMap) { return android['package'] as String?; } } return null; }
/// Returns the deferred components configuration if declared. Returns /// null if no deferred components are declared. late final List<DeferredComponent>? deferredComponents = computeDeferredComponents(); List<DeferredComponent>? computeDeferredComponents() { if (!_flutterDescriptor.containsKey('deferred-components')) { return null; } final List<DeferredComponent> components = <DeferredComponent>[]; final Object? deferredComponents = _flutterDescriptor['deferred-components']; if (deferredComponents is! YamlList) { return components; } for (final Object? component in deferredComponents) { if (component is! YamlMap) { _logger.printError('Expected deferred component manifest to be a map.'); continue; } components.add( DeferredComponent( name: component['name'] as String, libraries: component['libraries'] == null ? <String>[] : (component['libraries'] as List<dynamic>).cast<String>(), assets: _computeAssets(component['assets']), ) ); } return components; }
/// Returns the iOS bundle identifier declared by this manifest in its /// module descriptor. Returns null if there is no such declaration. String? get iosBundleIdentifier { if (isModule) { final Object? module = _flutterDescriptor['module']; if (module is YamlMap) { return module['iosBundleIdentifier'] as String?; } } return null; }
/// Gets the supported platforms. This only supports the new `platforms` format. /// /// If the plugin uses the legacy pubspec format, this method returns null. Map<String, Object?>? get supportedPlatforms { if (isPlugin) { final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?; if (plugin?.containsKey('platforms') ?? false) { final YamlMap? platformsMap = plugin!['platforms'] as YamlMap?; return platformsMap?.value.cast<String, Object?>(); } } return null; }
/// Like [supportedPlatforms], but only returns the valid platforms that are supported in flutter plugins. Map<String, Object?>? get validSupportedPlatforms { final Map<String, Object?>? allPlatforms = supportedPlatforms; if (allPlatforms == null) { return null; } final Map<String, Object?> platforms = <String, Object?>{}..addAll(allPlatforms); platforms.removeWhere((String key, Object? _) => !_kValidPluginPlatforms.contains(key)); if (platforms.isEmpty) { return null; } return platforms; }
List<Map<String, Object?>> get fontsDescriptor { return fonts.map((Font font) => font.descriptor).toList(); }
List<Map<String, Object?>> get _rawFontsDescriptor { final List<Object?>? fontList = _flutterDescriptor['fonts'] as List<Object?>?; return fontList == null ? const <Map<String, Object?>>[] : fontList.map<Map<String, Object?>?>(castStringKeyedMap).whereType<Map<String, Object?>>().toList(); }
late final List<AssetsEntry> assets = _computeAssets(_flutterDescriptor['assets']);
late final List<Font> fonts = _extractFonts();
List<Font> _extractFonts() { if (!_flutterDescriptor.containsKey('fonts')) { return <Font>[]; }
final List<Font> fonts = <Font>[]; for (final Map<String, Object?> fontFamily in _rawFontsDescriptor) { final YamlList? fontFiles = fontFamily['fonts'] as YamlList?; final String? familyName = fontFamily['family'] as String?; if (familyName == null) { _logger.printWarning('Warning: Missing family name for font.', emphasis: true); continue; } if (fontFiles == null) { _logger.printWarning('Warning: No fonts specified for font $familyName', emphasis: true); continue; }
final List<FontAsset> fontAssets = <FontAsset>[]; for (final Map<Object?, Object?> fontFile in fontFiles.cast<Map<Object?, Object?>>()) { final String? asset = fontFile['asset'] as String?; if (asset == null) { _logger.printWarning('Warning: Missing asset in fonts for $familyName', emphasis: true); continue; }
fontAssets.add(FontAsset( Uri.parse(asset), weight: fontFile['weight'] as int?, style: fontFile['style'] as String?, )); } if (fontAssets.isNotEmpty) { fonts.add(Font(familyName, fontAssets)); } } return fonts; }
late final List<Uri> shaders = _extractAssetUris('shaders', 'Shader'); late final List<Uri> models = kIs3dSceneSupported ? _extractAssetUris('models', 'Model') : <Uri>[];
List<Uri> _extractAssetUris(String key, String singularName) { if (!_flutterDescriptor.containsKey(key)) { return <Uri>[]; }
final List<Object?>? items = _flutterDescriptor[key] as List<Object?>?; if (items == null) { return const <Uri>[]; } final List<Uri> results = <Uri>[]; for (final Object? item in items) { if (item is! String || item == '') { _logger.printError('$singularName manifest contains a null or empty uri.'); continue; } try { results.add(Uri(pathSegments: item.split('/'))); } on FormatException { _logger.printError('$singularName manifest contains invalid uri: $item.'); } } return results; }
/// Whether a synthetic flutter_gen package should be generated. /// /// This can be provided to the [Pub] interface to inject a new entry /// into the package_config.json file which points to `.dart_tool/flutter_gen`. /// /// This allows generated source code to be imported using a package /// alias. late final bool generateSyntheticPackage = _computeGenerateSyntheticPackage(); bool _computeGenerateSyntheticPackage() { if (!_flutterDescriptor.containsKey('generate')) { return false; } final Object? value = _flutterDescriptor['generate']; if (value is! bool) { return false; } return value; }}
class Font { Font(this.familyName, this.fontAssets) : assert(fontAssets.isNotEmpty);
final String familyName; final List<FontAsset> fontAssets;
Map<String, Object?> get descriptor { return <String, Object?>{ 'family': familyName, 'fonts': fontAssets.map<Map<String, Object?>>((FontAsset a) => a.descriptor).toList(), }; }
@override String toString() => '$runtimeType(family: $familyName, assets: $fontAssets)';}
class FontAsset { FontAsset(this.assetUri, {this.weight, this.style});
final Uri assetUri; final int? weight; final String? style;
Map<String, Object?> get descriptor { final Map<String, Object?> descriptor = <String, Object?>{}; if (weight != null) { descriptor['weight'] = weight; }
if (style != null) { descriptor['style'] = style; }
descriptor['asset'] = assetUri.path; return descriptor; }
@override String toString() => '$runtimeType(asset: ${assetUri.path}, weight; $weight, style: $style)';}
bool _validate(Object? manifest, Logger logger) { final List<String> errors = <String>[]; if (manifest is! YamlMap) { errors.add('Expected YAML map'); } else { for (final MapEntry<Object?, Object?> kvp in manifest.entries) { if (kvp.key is! String) { errors.add('Expected YAML key to be a string, but got ${kvp.key}.'); continue; } switch (kvp.key as String?) { case 'name': if (kvp.value is! String) { errors.add('Expected "${kvp.key}" to be a string, but got ${kvp.value}.'); } case 'flutter': if (kvp.value == null) { continue; } if (kvp.value is! YamlMap) { errors.add('Expected "${kvp.key}" section to be an object or null, but got ${kvp.value}.'); } else { _validateFlutter(kvp.value as YamlMap?, errors); } default: // additionalProperties are allowed. break; } } }
if (errors.isNotEmpty) { logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); logger.printError(errors.join('\n')); return false; }
return true;}
void _validateFlutter(YamlMap? yaml, List<String> errors) { if (yaml == null) { return; } for (final MapEntry<Object?, Object?> kvp in yaml.entries) { final Object? yamlKey = kvp.key; final Object? yamlValue = kvp.value; if (yamlKey is! String) { errors.add('Expected YAML key to be a string, but got $yamlKey (${yamlValue.runtimeType}).'); continue; } switch (yamlKey) { case 'uses-material-design': if (yamlValue is! bool) { errors.add('Expected "$yamlKey" to be a bool, but got $yamlValue (${yamlValue.runtimeType}).'); } case 'assets': errors.addAll(_validateAssets(yamlValue)); case 'shaders': if (yamlValue is! YamlList) { errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); } else if (yamlValue.isEmpty) { break; } else if (yamlValue[0] is! String) { errors.add( 'Expected "$yamlKey" to be a list of strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', ); } case 'models': if (yamlValue is! YamlList) { errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); } else if (yamlValue.isEmpty) { break; } else if (yamlValue[0] is! String) { errors.add( 'Expected "$yamlKey" to be a list of strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', ); } case 'fonts': if (yamlValue is! YamlList) { errors.add('Expected "$yamlKey" to be a list, but got $yamlValue (${yamlValue.runtimeType}).'); } else if (yamlValue.isEmpty) { break; } else if (yamlValue.first is! YamlMap) { errors.add( 'Expected "$yamlKey" to contain maps, but the first element is $yamlValue (${yamlValue.runtimeType}).', ); } else { _validateFonts(yamlValue, errors); } case 'licenses': if (yamlValue is! YamlList) { errors.add('Expected "$yamlKey" to be a list of files, but got $yamlValue (${yamlValue.runtimeType})'); } else if (yamlValue.isEmpty) { break; } else if (yamlValue.first is! String) { errors.add( 'Expected "$yamlKey" to contain strings, but the first element is $yamlValue (${yamlValue.runtimeType}).', ); } else { _validateListType<String>(yamlValue, errors, '"$yamlKey"', 'files'); } case 'module': if (yamlValue is! YamlMap) { errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).'); break; }
if (yamlValue['androidX'] != null && yamlValue['androidX'] is! bool) { errors.add('The "androidX" value must be a bool if set.'); } if (yamlValue['androidPackage'] != null && yamlValue['androidPackage'] is! String) { errors.add('The "androidPackage" value must be a string if set.'); } if (yamlValue['iosBundleIdentifier'] != null && yamlValue['iosBundleIdentifier'] is! String) { errors.add('The "iosBundleIdentifier" section must be a string if set.'); } case 'plugin': if (yamlValue is! YamlMap) { errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).'); break; } final List<String> pluginErrors = Plugin.validatePluginYaml(yamlValue); errors.addAll(pluginErrors); case 'generate': break; case 'deferred-components': _validateDeferredComponents(kvp, errors); default: errors.add('Unexpected child "$yamlKey" found under "flutter".'); break; } }}
void _validateListType<T>(YamlList yamlList, List<String> errors, String context, String typeAlias) { for (int i = 0; i < yamlList.length; i++) { if (yamlList[i] is! T) { // ignore: avoid_dynamic_calls errors.add('Expected $context to be a list of $typeAlias, but element $i was a ${yamlList[i].runtimeType}'); } }}
void _validateDeferredComponents(MapEntry<Object?, Object?> kvp, List<String> errors) { final Object? yamlList = kvp.value; if (yamlList != null && (yamlList is! YamlList || yamlList[0] is! YamlMap)) { errors.add('Expected "${kvp.key}" to be a list, but got $yamlList (${yamlList.runtimeType}).'); } else if (yamlList is YamlList) { for (int i = 0; i < yamlList.length; i++) { final Object? valueMap = yamlList[i]; if (valueMap is! YamlMap) { // ignore: avoid_dynamic_calls errors.add('Expected the $i element in "${kvp.key}" to be a map, but got ${yamlList[i]} (${yamlList[i].runtimeType}).'); continue; } if (!valueMap.containsKey('name') || valueMap['name'] is! String) { errors.add('Expected the $i element in "${kvp.key}" to have required key "name" of type String'); } if (valueMap.containsKey('libraries')) { final Object? libraries = valueMap['libraries']; if (libraries is! YamlList) { errors.add('Expected "libraries" key in the $i element of "${kvp.key}" to be a list, but got $libraries (${libraries.runtimeType}).'); } else { _validateListType<String>(libraries, errors, '"libraries" key in the $i element of "${kvp.key}"', 'dart library Strings'); } } if (valueMap.containsKey('assets')) { errors.addAll(_validateAssets(valueMap['assets'])); } } }}
List<String> _validateAssets(Object? yaml) { final (_, List<String> errors) = _computeAssetsSafe(yaml); return errors;}
// TODO(andrewkolos): We end up parsing the assets section twice, once during// validation and once when the assets getter is called. We should consider// refactoring this class to parse and store everything in the constructor.// https://github.com/flutter/flutter/issues/139183(List<AssetsEntry>, List<String> errors) _computeAssetsSafe(Object? yaml) { if (yaml == null) { return (const <AssetsEntry>[], const <String>[]); } if (yaml is! YamlList) { final String error = 'Expected "assets" to be a list, but got $yaml (${yaml.runtimeType}).'; return (const <AssetsEntry>[], <String>[error]); } final List<AssetsEntry> results = <AssetsEntry>[]; final List<String> errors = <String>[]; for (final Object? rawAssetEntry in yaml) { final (AssetsEntry? parsed, String? error) = AssetsEntry.parseFromYamlSafe(rawAssetEntry); if (parsed != null) { results.add(parsed); } if (error != null) { errors.add(error); } } return (results, errors);}
List<AssetsEntry> _computeAssets(Object? assetsSection) { final (List<AssetsEntry> result, List<String> errors) = _computeAssetsSafe(assetsSection); if (errors.isNotEmpty) { throw Exception('Uncaught error(s) in assets section: ' '${errors.join('\n')}'); } return result;}
void _validateFonts(YamlList fonts, List<String> errors) { const Set<int> fontWeights = <int>{ 100, 200, 300, 400, 500, 600, 700, 800, 900, }; for (final Object? fontMap in fonts) { if (fontMap is! YamlMap) { errors.add('Unexpected child "$fontMap" found under "fonts". Expected a map.'); continue; } for (final Object? key in fontMap.keys.where((Object? key) => key != 'family' && key != 'fonts')) { errors.add('Unexpected child "$key" found under "fonts".'); } if (fontMap['family'] != null && fontMap['family'] is! String) { errors.add('Font family must either be null or a String.'); } if (fontMap['fonts'] == null) { continue; } else if (fontMap['fonts'] is! YamlList) { errors.add('Expected "fonts" to either be null or a list.'); continue; } for (final Object? fontMapList in fontMap['fonts'] as List<Object?>) { if (fontMapList is! YamlMap) { errors.add('Expected "fonts" to be a list of maps.'); continue; } for (final MapEntry<Object?, Object?> kvp in fontMapList.entries) { final Object? fontKey = kvp.key; if (fontKey is! String) { errors.add('Expected "$fontKey" under "fonts" to be a string.'); } switch (fontKey) { case 'asset': if (kvp.value is! String) { errors.add('Expected font asset ${kvp.value} ((${kvp.value.runtimeType})) to be a string.'); } case 'weight': if (!fontWeights.contains(kvp.value)) { errors.add('Invalid value ${kvp.value} ((${kvp.value.runtimeType})) for font -> weight.'); } case 'style': if (kvp.value != 'normal' && kvp.value != 'italic') { errors.add('Invalid value ${kvp.value} ((${kvp.value.runtimeType})) for font -> style.'); } default: errors.add('Unexpected key $fontKey ((${kvp.value.runtimeType})) under font.'); break; } } } }}
/// Represents an entry under the `assets` section of a pubspec.@immutableclass AssetsEntry { const AssetsEntry({ required this.uri, this.flavors = const <String>[], });
final Uri uri; final List<String> flavors;
static const String _pathKey = 'path'; static const String _flavorKey = 'flavors';
static AssetsEntry? parseFromYaml(Object? yaml) { final (AssetsEntry? value, String? error) = parseFromYamlSafe(yaml); if (error != null) { throw Exception('Unexpected error when parsing assets entry'); } return value!; }
static (AssetsEntry? assetsEntry, String? error) parseFromYamlSafe(Object? yaml) {
(Uri?, String?) tryParseUri(String uri) { try { return (Uri(pathSegments: uri.split('/')), null); } on FormatException { return (null, 'Asset manifest contains invalid uri: $uri.'); } }
if (yaml == null || yaml == '') { return (null, 'Asset manifest contains a null or empty uri.'); }
if (yaml is String) { final (Uri? uri, String? error) = tryParseUri(yaml); return uri == null ? (null, error) : (AssetsEntry(uri: uri), null); }
if (yaml is Map) { if (yaml.keys.isEmpty) { return (null, null); }
final Object? path = yaml[_pathKey]; final Object? flavors = yaml[_flavorKey];
if (path == null || path is! String) { return (null, 'Asset manifest entry is malformed. ' 'Expected asset entry to be either a string or a map ' 'containing a "$_pathKey" entry. Got ${path.runtimeType} instead.'); }
final Uri uri = Uri(pathSegments: path.split('/'));
if (flavors == null) { return (AssetsEntry(uri: uri), null); }
if (flavors is! YamlList) { return(null, 'Asset manifest entry is malformed. ' 'Expected "$_flavorKey" entry to be a list of strings. ' 'Got ${flavors.runtimeType} instead.'); }
final List<String> flavorsListErrors = <String>[]; _validateListType<String>(flavors, flavorsListErrors, 'flavors list of entry "$path"', 'String'); if (flavorsListErrors.isNotEmpty) { return (null, 'Asset manifest entry is malformed. ' 'Expected "$_flavorKey" entry to be a list of strings.\n' '${flavorsListErrors.join('\n')}'); }
final AssetsEntry entry = AssetsEntry( uri: Uri(pathSegments: path.split('/')), flavors: List<String>.from(flavors), );
return (entry, null); }
return (null, 'Assets entry had unexpected shape. ' 'Expected a string or an object. Got ${yaml.runtimeType} instead.'); }
@override bool operator ==(Object other) { if (other is! AssetsEntry) { return false; }
return uri == other.uri && flavors == other.flavors; }
@override int get hashCode => Object.hash(uri.hashCode, flavors.hashCode);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477// 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:meta/meta.dart';import 'package:package_config/package_config.dart';import 'package:path/path.dart' as path; // flutter_ignore: package_path_importimport 'package:pub_semver/pub_semver.dart' as semver;import 'package:yaml/yaml.dart';
import 'android/gradle.dart';import 'base/common.dart';import 'base/error_handling_io.dart';import 'base/file_system.dart';import 'base/os.dart';import 'base/platform.dart';import 'base/template.dart';import 'base/version.dart';import 'cache.dart';import 'convert.dart';import 'dart/language_version.dart';import 'dart/package_map.dart';import 'features.dart';import 'globals.dart' as globals;import 'platform_plugins.dart';import 'plugins.dart';import 'project.dart';
Future<void> _renderTemplateToFile( String template, Object? context, File file, TemplateRenderer templateRenderer,) async { final String renderedTemplate = templateRenderer .renderString(template, context); await file.create(recursive: true); await file.writeAsString(renderedTemplate);}
Future<Plugin?> _pluginFromPackage(String name, Uri packageRoot, Set<String> appDependencies, {FileSystem? fileSystem}) async { final FileSystem fs = fileSystem ?? globals.fs; final File pubspecFile = fs.file(packageRoot.resolve('pubspec.yaml')); if (!pubspecFile.existsSync()) { return null; } Object? pubspec;
try { pubspec = loadYaml(await pubspecFile.readAsString()); } on YamlException catch (err) { globals.printTrace('Failed to parse plugin manifest for $name: $err'); // Do nothing, potentially not a plugin. } if (pubspec == null || pubspec is! YamlMap) { return null; } final Object? flutterConfig = pubspec['flutter']; if (flutterConfig == null || flutterConfig is! YamlMap || !flutterConfig.containsKey('plugin')) { return null; } final String? flutterConstraintText = (pubspec['environment'] as YamlMap?)?['flutter'] as String?; final semver.VersionConstraint? flutterConstraint = flutterConstraintText == null ? null : semver.VersionConstraint.parse(flutterConstraintText); final String packageRootPath = fs.path.fromUri(packageRoot); final YamlMap? dependencies = pubspec['dependencies'] as YamlMap?; globals.printTrace('Found plugin $name at $packageRootPath'); return Plugin.fromYaml( name, packageRootPath, flutterConfig['plugin'] as YamlMap?, flutterConstraint, dependencies == null ? <String>[] : <String>[...dependencies.keys.cast<String>()], fileSystem: fs, appDependencies: appDependencies, );}
Future<List<Plugin>> findPlugins(FlutterProject project, { bool throwOnError = true}) async { final List<Plugin> plugins = <Plugin>[]; final FileSystem fs = project.directory.fileSystem; final String packagesFile = fs.path.join( project.directory.path, '.packages', ); final PackageConfig packageConfig = await loadPackageConfigWithLogging( fs.file(packagesFile), logger: globals.logger, throwOnError: throwOnError, ); for (final Package package in packageConfig.packages) { final Uri packageRoot = package.packageUriRoot.resolve('..'); final Plugin? plugin = await _pluginFromPackage( package.name, packageRoot, project.manifest.dependencies, fileSystem: fs ); if (plugin != null) { plugins.add(plugin); } } return plugins;}
// Key strings for the .flutter-plugins-dependencies file.const String _kFlutterPluginsPluginListKey = 'plugins';const String _kFlutterPluginsNameKey = 'name';const String _kFlutterPluginsPathKey = 'path';const String _kFlutterPluginsDependenciesKey = 'dependencies';const String _kFlutterPluginsHasNativeBuildKey = 'native_build';const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source';
/// Filters [plugins] to those supported by [platformKey].List<Map<String, Object>> _filterPluginsByPlatform(List<Plugin> plugins, String platformKey) { final Iterable<Plugin> platformPlugins = plugins.where((Plugin p) { return p.platforms.containsKey(platformKey); });
final Set<String> pluginNames = platformPlugins.map((Plugin plugin) => plugin.name).toSet(); final List<Map<String, Object>> pluginInfo = <Map<String, Object>>[]; for (final Plugin plugin in platformPlugins) { // This is guaranteed to be non-null due to the `where` filter above. final PluginPlatform platformPlugin = plugin.platforms[platformKey]!; pluginInfo.add(<String, Object>{ _kFlutterPluginsNameKey: plugin.name, _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), if (platformPlugin is DarwinPlugin && (platformPlugin as DarwinPlugin).sharedDarwinSource) _kFlutterPluginsSharedDarwinSource: (platformPlugin as DarwinPlugin).sharedDarwinSource, if (platformPlugin is NativeOrDartPlugin) _kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(), _kFlutterPluginsDependenciesKey: <String>[...plugin.dependencies.where(pluginNames.contains)], }); } return pluginInfo;}
/// Writes the .flutter-plugins-dependencies file based on the list of plugins./// If there aren't any plugins, then the files aren't written to disk. The resulting/// file looks something like this (order of keys is not guaranteed):/// {/// "info": "This is a generated file; do not edit or check into version control.",/// "plugins": {/// "ios": [/// {/// "name": "test",/// "path": "test_path",/// "dependencies": [/// "plugin-a",/// "plugin-b"/// ],/// "native_build": true/// }/// ],/// "android": [],/// "macos": [],/// "linux": [],/// "windows": [],/// "web": []/// },/// "dependencyGraph": [/// {/// "name": "plugin-a",/// "dependencies": [/// "plugin-b",/// "plugin-c"/// ]/// },/// {/// "name": "plugin-b",/// "dependencies": [/// "plugin-c"/// ]/// },/// {/// "name": "plugin-c",/// "dependencies": []/// }/// ],/// "date_created": "1970-01-01 00:00:00.000",/// "version": "0.0.0-unknown"/// }///////// Finally, returns [true] if the plugins list has changed, otherwise returns [false].bool _writeFlutterPluginsList(FlutterProject project, List<Plugin> plugins) { final File pluginsFile = project.flutterPluginsDependenciesFile; if (plugins.isEmpty) { return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); }
final String iosKey = project.ios.pluginConfigKey; final String androidKey = project.android.pluginConfigKey; final String macosKey = project.macos.pluginConfigKey; final String linuxKey = project.linux.pluginConfigKey; final String windowsKey = project.windows.pluginConfigKey; final String webKey = project.web.pluginConfigKey;
final Map<String, Object> pluginsMap = <String, Object>{}; pluginsMap[iosKey] = _filterPluginsByPlatform(plugins, iosKey); pluginsMap[androidKey] = _filterPluginsByPlatform(plugins, androidKey); pluginsMap[macosKey] = _filterPluginsByPlatform(plugins, macosKey); pluginsMap[linuxKey] = _filterPluginsByPlatform(plugins, linuxKey); pluginsMap[windowsKey] = _filterPluginsByPlatform(plugins, windowsKey); pluginsMap[webKey] = _filterPluginsByPlatform(plugins, webKey);
final Map<String, Object> result = <String, Object> {};
result['info'] = 'This is a generated file; do not edit or check into version control.'; result[_kFlutterPluginsPluginListKey] = pluginsMap; /// The dependencyGraph object is kept for backwards compatibility, but /// should be removed once migration is complete. /// https://github.com/flutter/flutter/issues/48918 result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins); result['date_created'] = globals.systemClock.now().toString(); result['version'] = globals.flutterVersion.frameworkVersion;
// Only notify if the plugins list has changed. [date_created] will always be different, // [version] is not relevant for this check. final String? oldPluginsFileStringContent = _readFileContent(pluginsFile); bool pluginsChanged = true; if (oldPluginsFileStringContent != null) { pluginsChanged = oldPluginsFileStringContent.contains(pluginsMap.toString()); } final String pluginFileContent = json.encode(result); pluginsFile.writeAsStringSync(pluginFileContent, flush: true);
return pluginsChanged;}
List<Object?> _createPluginLegacyDependencyGraph(List<Plugin> plugins) { final List<Object> directAppDependencies = <Object>[];
final Set<String> pluginNames = plugins.map((Plugin plugin) => plugin.name).toSet(); for (final Plugin plugin in plugins) { directAppDependencies.add(<String, Object>{ 'name': plugin.name, // Extract the plugin dependencies which happen to be plugins. 'dependencies': <String>[...plugin.dependencies.where(pluginNames.contains)], }); } return directAppDependencies;}
// The .flutter-plugins file will be DEPRECATED in favor of .flutter-plugins-dependencies.// TODO(franciscojma): Remove this method once deprecated.// https://github.com/flutter/flutter/issues/48918///// Writes the .flutter-plugins files based on the list of plugins./// If there aren't any plugins, then the files aren't written to disk.////// Finally, returns [true] if .flutter-plugins has changed, otherwise returns [false].bool _writeFlutterPluginsListLegacy(FlutterProject project, List<Plugin> plugins) { final File pluginsFile = project.flutterPluginsFile; if (plugins.isEmpty) { return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); }
const String info = 'This is a generated file; do not edit or check into version control.'; final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n');
for (final Plugin plugin in plugins) { flutterPluginsBuffer.write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); } final String? oldPluginFileContent = _readFileContent(pluginsFile); final String pluginFileContent = flutterPluginsBuffer.toString(); pluginsFile.writeAsStringSync(pluginFileContent, flush: true);
return oldPluginFileContent != _readFileContent(pluginsFile);}
/// Returns the contents of [File] or [null] if that file does not exist.String? _readFileContent(File file) { return file.existsSync() ? file.readAsStringSync() : null;}
const String _androidPluginRegistryTemplateOldEmbedding = '''package io.flutter.plugins;
import io.flutter.plugin.common.PluginRegistry;{{#methodChannelPlugins}}import {{package}}.{{class}};{{/methodChannelPlugins}}
/** * Generated file. Do not edit. */public final class GeneratedPluginRegistrant { public static void registerWith(PluginRegistry registry) { if (alreadyRegisteredWith(registry)) { return; }{{#methodChannelPlugins}} {{class}}.registerWith(registry.registrarFor("{{package}}.{{class}}"));{{/methodChannelPlugins}} }
private static boolean alreadyRegisteredWith(PluginRegistry registry) { final String key = GeneratedPluginRegistrant.class.getCanonicalName(); if (registry.hasPlugin(key)) { return true; } registry.registrarFor(key); return false; }}''';
const String _androidPluginRegistryTemplateNewEmbedding = '''package io.flutter.plugins;
import androidx.annotation.Keep;import androidx.annotation.NonNull;import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;{{#needsShim}}import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry;{{/needsShim}}
/** * Generated file. Do not edit. * This file is generated by the Flutter tool based on the * plugins that support the Android platform. */@Keeppublic final class GeneratedPluginRegistrant { private static final String TAG = "GeneratedPluginRegistrant"; public static void registerWith(@NonNull FlutterEngine flutterEngine) {{{#needsShim}} ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine);{{/needsShim}}{{#methodChannelPlugins}} {{#supportsEmbeddingV2}} try { flutterEngine.getPlugins().add(new {{package}}.{{class}}()); } catch (Exception e) { Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); } {{/supportsEmbeddingV2}} {{^supportsEmbeddingV2}} {{#supportsEmbeddingV1}} try { {{package}}.{{class}}.registerWith(shimPluginRegistry.registrarFor("{{package}}.{{class}}")); } catch (Exception e) { Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); } {{/supportsEmbeddingV1}} {{/supportsEmbeddingV2}}{{/methodChannelPlugins}} }}''';
List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) { final List<Map<String, Object?>> pluginConfigs = <Map<String, Object?>>[]; for (final Plugin p in plugins) { final PluginPlatform? platformPlugin = p.platforms[type]; if (platformPlugin != null) { pluginConfigs.add(platformPlugin.toMap()); } } return pluginConfigs;}
/// Returns the version of the Android embedding that the current/// [project] is using.AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) { return project.android.getEmbeddingVersion();}
Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, AndroidPlugin.kConfigKey); final List<Map<String, Object?>> androidPlugins = _extractPlatformMaps(methodChannelPlugins, AndroidPlugin.kConfigKey);
final Map<String, Object> templateContext = <String, Object>{ 'methodChannelPlugins': androidPlugins, 'androidX': isAppUsingAndroidX(project.android.hostAppGradleRoot), }; final String javaSourcePath = globals.fs.path.join( project.android.pluginRegistrantHost.path, 'src', 'main', 'java', ); final String registryPath = globals.fs.path.join( javaSourcePath, 'io', 'flutter', 'plugins', 'GeneratedPluginRegistrant.java', ); String templateContent; final AndroidEmbeddingVersion appEmbeddingVersion = _getAndroidEmbeddingVersion(project); switch (appEmbeddingVersion) { case AndroidEmbeddingVersion.v2: templateContext['needsShim'] = false; // If a plugin is using an embedding version older than 2.0 and the app is using 2.0, // then add shim for the old plugins.
final List<String> pluginsUsingV1 = <String>[]; for (final Map<String, Object?> plugin in androidPlugins) { final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false; final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false; if (supportsEmbeddingV1 && !supportsEmbeddingV2) { templateContext['needsShim'] = true; if (plugin['name'] != null) { pluginsUsingV1.add(plugin['name']! as String); } } } if (pluginsUsingV1.length > 1) { globals.printWarning( 'The plugins `${pluginsUsingV1.join(', ')}` use a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to see if these plugins ' 'support the Android V2 embedding. Otherwise, consider removing them since a future release ' 'of Flutter will remove these deprecated APIs.\n' 'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: ' 'https://flutter.dev/go/android-plugin-migration.' ); } else if (pluginsUsingV1.isNotEmpty) { globals.printWarning( 'The plugin `${pluginsUsingV1.first}` uses a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to see if this plugin ' 'supports the Android V2 embedding. Otherwise, consider removing it since a future release ' 'of Flutter will remove these deprecated APIs.\n' 'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: ' 'https://flutter.dev/go/android-plugin-migration.' ); } templateContent = _androidPluginRegistryTemplateNewEmbedding; case AndroidEmbeddingVersion.v1: globals.printWarning( 'This app is using a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to migrate this ' 'app to the V2 embedding.\n' 'Take a look at the docs for migrating an app: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects' ); for (final Map<String, Object?> plugin in androidPlugins) { final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false; final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false; if (!supportsEmbeddingV1 && supportsEmbeddingV2) { throwToolExit( 'The plugin `${plugin['name']}` requires your app to be migrated to ' 'the Android embedding v2. Follow the steps on the migration doc above ' 'and re-run this command.' ); } } templateContent = _androidPluginRegistryTemplateOldEmbedding; } globals.printTrace('Generating $registryPath'); await _renderTemplateToFile( templateContent, templateContext, globals.fs.file(registryPath), globals.templateRenderer, );}
const String _objcPluginRegistryHeaderTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#ifndef GeneratedPluginRegistrant_h#define GeneratedPluginRegistrant_h
#import <{{framework}}/{{framework}}.h>
NS_ASSUME_NONNULL_BEGIN
@interface GeneratedPluginRegistrant : NSObject+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;@end
NS_ASSUME_NONNULL_END#endif /* GeneratedPluginRegistrant_h */''';
const String _objcPluginRegistryImplementationTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#import "GeneratedPluginRegistrant.h"
{{#methodChannelPlugins}}#if __has_include(<{{name}}/{{class}}.h>)#import <{{name}}/{{class}}.h>#else@import {{name}};#endif
{{/methodChannelPlugins}}@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {{{#methodChannelPlugins}} [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]];{{/methodChannelPlugins}}}
@end''';
const String _swiftPluginRegistryTemplate = '''//// Generated file. Do not edit.//
import {{framework}}import Foundation
{{#methodChannelPlugins}}import {{name}}{{/methodChannelPlugins}}
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { {{#methodChannelPlugins}} {{class}}.register(with: registry.registrar(forPlugin: "{{class}}")){{/methodChannelPlugins}}}''';
const String _pluginRegistrantPodspecTemplate = '''## Generated file, do not edit.#
Pod::Spec.new do |s| s.name = 'FlutterPluginRegistrant' s.version = '0.0.1' s.summary = 'Registers plugins with your Flutter app' s.description = <<-DESCDepends on all your plugins, and provides a function to register them. DESC s.homepage = 'https://flutter.dev' s.license = { :type => 'BSD' } s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.{{os}}.deployment_target = '{{deploymentTarget}}' s.source_files = "Classes", "Classes/**/*.{h,m}" s.source = { :path => '.' } s.public_header_files = './Classes/**/*.h' s.static_framework = true s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.dependency '{{framework}}' {{#methodChannelPlugins}} s.dependency '{{name}}' {{/methodChannelPlugins}}end''';
const String _noopDartPluginRegistryTemplate = '''// Flutter web plugin registrant file.//// Generated file. Do not edit.//
// ignore_for_file: type=lint
void registerPlugins() {}''';
const String _dartPluginRegistryTemplate = '''// Flutter web plugin registrant file.//// Generated file. Do not edit.//
// @dart = 2.13// ignore_for_file: type=lint
{{#methodChannelPlugins}}import 'package:{{name}}/{{file}}';{{/methodChannelPlugins}}import 'package:flutter_web_plugins/flutter_web_plugins.dart';
void registerPlugins([final Registrar? pluginRegistrar]) { final Registrar registrar = pluginRegistrar ?? webPluginRegistrar;{{#methodChannelPlugins}} {{class}}.registerWith(registrar);{{/methodChannelPlugins}} registrar.registerMessageHandler();}''';
const String _cppPluginRegistryHeaderTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_''';
const String _cppPluginRegistryImplementationTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#include "generated_plugin_registrant.h"
{{#methodChannelPlugins}}#include <{{name}}/{{filename}}.h>{{/methodChannelPlugins}}
void RegisterPlugins(flutter::PluginRegistry* registry) {{{#methodChannelPlugins}} {{class}}RegisterWithRegistrar( registry->GetRegistrarForPlugin("{{class}}"));{{/methodChannelPlugins}}}''';
const String _linuxPluginRegistryHeaderTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_''';
const String _linuxPluginRegistryImplementationTemplate = '''//// Generated file. Do not edit.//
// clang-format off
#include "generated_plugin_registrant.h"
{{#methodChannelPlugins}}#include <{{name}}/{{filename}}.h>{{/methodChannelPlugins}}
void fl_register_plugins(FlPluginRegistry* registry) {{{#methodChannelPlugins}} g_autoptr(FlPluginRegistrar) {{name}}_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}"); {{filename}}_register_with_registrar({{name}}_registrar);{{/methodChannelPlugins}}}''';
const String _pluginCmakefileTemplate = r'''## Generated file, do not edit.#
list(APPEND FLUTTER_PLUGIN_LIST{{#methodChannelPlugins}} {{name}}{{/methodChannelPlugins}})
list(APPEND FLUTTER_FFI_PLUGIN_LIST{{#ffiPlugins}} {{name}}{{/ffiPlugins}})
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory({{pluginsDir}}/${plugin}/{{os}} plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory({{pluginsDir}}/${ffi_plugin}/{{os}} plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})endforeach(ffi_plugin)''';
const String _dartPluginRegisterWith = r''' try { {{dartClass}}.registerWith(); } catch (err) { print( '`{{pluginName}}` threw an error: $err. ' 'The app may not function as expected until you remove this plugin from pubspec.yaml' ); }''';
// TODO(egarciad): Evaluate merging the web and non-web plugin registry templates.// https://github.com/flutter/flutter/issues/80406const String _dartPluginRegistryForNonWebTemplate = '''//// Generated file. Do not edit.// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.//
// @dart = {{dartLanguageVersion}}
import 'dart:io'; // flutter_ignore: dart_io_import.{{#android}}import 'package:{{pluginName}}/{{pluginName}}.dart';{{/android}}{{#ios}}import 'package:{{pluginName}}/{{pluginName}}.dart';{{/ios}}{{#linux}}import 'package:{{pluginName}}/{{pluginName}}.dart';{{/linux}}{{#macos}}import 'package:{{pluginName}}/{{pluginName}}.dart';{{/macos}}{{#windows}}import 'package:{{pluginName}}/{{pluginName}}.dart';{{/windows}}
@pragma('vm:entry-point')class _PluginRegistrant {
@pragma('vm:entry-point') static void register() { if (Platform.isAndroid) { {{#android}}$_dartPluginRegisterWith {{/android}} } else if (Platform.isIOS) { {{#ios}}$_dartPluginRegisterWith {{/ios}} } else if (Platform.isLinux) { {{#linux}}$_dartPluginRegisterWith {{/linux}} } else if (Platform.isMacOS) { {{#macos}}$_dartPluginRegisterWith {{/macos}} } else if (Platform.isWindows) { {{#windows}}$_dartPluginRegisterWith {{/windows}} } }}''';
Future<void> _writeIOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, IOSPlugin.kConfigKey); final List<Map<String, Object?>> iosPlugins = _extractPlatformMaps(methodChannelPlugins, IOSPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'ios', 'deploymentTarget': '12.0', 'framework': 'Flutter', 'methodChannelPlugins': iosPlugins, }; if (project.isModule) { final Directory registryDirectory = project.ios.pluginRegistrantHost; await _renderTemplateToFile( _pluginRegistrantPodspecTemplate, context, registryDirectory.childFile('FlutterPluginRegistrant.podspec'), globals.templateRenderer, ); } await _renderTemplateToFile( _objcPluginRegistryHeaderTemplate, context, project.ios.pluginRegistrantHeader, globals.templateRenderer, ); await _renderTemplateToFile( _objcPluginRegistryImplementationTemplate, context, project.ios.pluginRegistrantImplementation, globals.templateRenderer, );}
/// The relative path from a project's main CMake file to the plugin symlink/// directory to use in the generated plugin CMake file.////// Because the generated file is checked in, it can't use absolute paths. It is/// designed to be included by the main CMakeLists.txt, so it relative to/// that file, rather than the generated file.String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { final FileSystem fileSystem = project.pluginSymlinkDirectory.fileSystem; final String makefileDirPath = project.cmakeFile.parent.absolute.path; // CMake always uses posix-style path separators, regardless of the platform. final path.Context cmakePathContext = path.Context(style: path.Style.posix); final List<String> relativePathComponents = fileSystem.path.split(fileSystem.path.relative( project.pluginSymlinkDirectory.absolute.path, from: makefileDirPath, )); return cmakePathContext.joinAll(relativePathComponents);}
Future<void> _writeLinuxPluginFiles(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, LinuxPlugin.kConfigKey); final List<Map<String, Object?>> linuxMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, LinuxPlugin.kConfigKey); final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, LinuxPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); final List<Map<String, Object?>> linuxFfiPlugins = _extractPlatformMaps(ffiPlugins, LinuxPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'linux', 'methodChannelPlugins': linuxMethodChannelPlugins, 'ffiPlugins': linuxFfiPlugins, 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux), }; await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context); await _writePluginCmakefile(project.linux.generatedPluginCmakeFile, context, globals.templateRenderer);}
Future<void> _writeLinuxPluginRegistrant(Directory destination, Map<String, Object> templateContext) async { await _renderTemplateToFile( _linuxPluginRegistryHeaderTemplate, templateContext, destination.childFile('generated_plugin_registrant.h'), globals.templateRenderer, ); await _renderTemplateToFile( _linuxPluginRegistryImplementationTemplate, templateContext, destination.childFile('generated_plugin_registrant.cc'), globals.templateRenderer, );}
Future<void> _writePluginCmakefile(File destinationFile, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async { await _renderTemplateToFile( _pluginCmakefileTemplate, templateContext, destinationFile, templateRenderer, );}
Future<void> _writeMacOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, MacOSPlugin.kConfigKey); final List<Map<String, Object?>> macosMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, MacOSPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'macos', 'framework': 'FlutterMacOS', 'methodChannelPlugins': macosMethodChannelPlugins, }; await _renderTemplateToFile( _swiftPluginRegistryTemplate, context, project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'), globals.templateRenderer, );}
/// Filters out any plugins that don't use method channels, and thus shouldn't be added to the native generated registrants.List<Plugin> _filterMethodChannelPlugins(List<Plugin> plugins, String platformKey) { return plugins.where((Plugin element) { final PluginPlatform? plugin = element.platforms[platformKey]; if (plugin == null) { return false; } if (plugin is NativeOrDartPlugin) { return (plugin as NativeOrDartPlugin).hasMethodChannel(); } // Not all platforms have the ability to create Dart-only plugins. Therefore, any plugin that doesn't // implement NativeOrDartPlugin is always native. return true; }).toList();}
/// Filters out Dart-only and method channel plugins.////// FFI plugins do not need native code registration, but their binaries need to be bundled.List<Plugin> _filterFfiPlugins(List<Plugin> plugins, String platformKey) { return plugins.where((Plugin element) { final PluginPlatform? plugin = element.platforms[platformKey]; if (plugin == null) { return false; } if (plugin is NativeOrDartPlugin) { final NativeOrDartPlugin plugin_ = plugin as NativeOrDartPlugin; return plugin_.hasFfi(); } return false; }).toList();}
/// Returns only the plugins with the given platform variant.List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, PluginPlatformVariant variant) { return plugins.where((Plugin element) { final PluginPlatform? platformPlugin = element.platforms[platformKey]; if (platformPlugin == null) { return false; } assert(platformPlugin is VariantPlatformPlugin); return (platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant); }).toList();}
@visibleForTestingFuture<void> writeWindowsPluginFiles( FlutterProject project, List<Plugin> plugins, TemplateRenderer templateRenderer, { Iterable<String>? allowedPlugins,}) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey); if (allowedPlugins != null) { final List<Plugin> disallowedPlugins = methodChannelPlugins .toList() ..removeWhere((Plugin plugin) => allowedPlugins.contains(plugin.name)); if (disallowedPlugins.isNotEmpty) { final StringBuffer buffer = StringBuffer(); buffer.writeln('The Flutter Preview device does not support the following plugins from your pubspec.yaml:'); buffer.writeln(); buffer.writeln(disallowedPlugins.map((Plugin p) => p.name).toList().toString()); buffer.writeln(); buffer.writeln('In order to build a Flutter app with plugins, you must use another target platform,'); buffer.writeln('such as Windows. Type `flutter doctor` into your terminal to see which target platforms'); buffer.writeln('are ready to be used, and how to get required dependencies for other platforms.'); throwToolExit(buffer.toString()); } } final List<Plugin> win32Plugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32); final List<Map<String, Object?>> windowsMethodChannelPlugins = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey); final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); final List<Map<String, Object?>> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'windows', 'methodChannelPlugins': windowsMethodChannelPlugins, 'ffiPlugins': windowsFfiPlugins, 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows), }; await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer); await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer);}
Future<void> _writeCppPluginRegistrant(Directory destination, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async { await _renderTemplateToFile( _cppPluginRegistryHeaderTemplate, templateContext, destination.childFile('generated_plugin_registrant.h'), templateRenderer, ); await _renderTemplateToFile( _cppPluginRegistryImplementationTemplate, templateContext, destination.childFile('generated_plugin_registrant.cc'), templateRenderer, );}
Future<void> _writeWebPluginRegistrant(FlutterProject project, List<Plugin> plugins, Directory destination) async { final List<Map<String, Object?>> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'methodChannelPlugins': webPlugins, };
final File pluginFile = destination.childFile('web_plugin_registrant.dart');
final String template = webPlugins.isEmpty ? _noopDartPluginRegistryTemplate : _dartPluginRegistryTemplate;
await _renderTemplateToFile( template, context, pluginFile, globals.templateRenderer, );}
/// For each platform that uses them, creates symlinks within the platform/// directory to each plugin used on that platform.////// If |force| is true, the symlinks will be recreated, otherwise they will/// be created only if missing.////// This uses [project.flutterPluginsDependenciesFile], so it should only be/// run after [refreshPluginsList] has been run since the last plugin change.void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags? featureFlagsOverride}) { final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags; Map<String, Object?>? platformPlugins; final String? pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile); if (pluginFileContent != null) { final Map<String, Object?>? pluginInfo = json.decode(pluginFileContent) as Map<String, Object?>?; platformPlugins = pluginInfo?[_kFlutterPluginsPluginListKey] as Map<String, Object?>?; } platformPlugins ??= <String, Object?>{};
if (localFeatureFlags.isWindowsEnabled && project.windows.existsSync()) { _createPlatformPluginSymlinks( project.windows.pluginSymlinkDirectory, platformPlugins[project.windows.pluginConfigKey] as List<Object?>?, force: force, ); } if (localFeatureFlags.isLinuxEnabled && project.linux.existsSync()) { _createPlatformPluginSymlinks( project.linux.pluginSymlinkDirectory, platformPlugins[project.linux.pluginConfigKey] as List<Object?>?, force: force, ); }}
/// Handler for symlink failures which provides specific instructions for known/// failure cases.@visibleForTestingvoid handleSymlinkException(FileSystemException e, { required Platform platform, required OperatingSystemUtils os, required String destination, required String source,}) { if (platform.isWindows) { // ERROR_ACCESS_DENIED if (e.osError?.errorCode == 5) { throwToolExit( 'ERROR_ACCESS_DENIED file system exception thrown while trying to ' 'create a symlink from $source to $destination', ); } // ERROR_PRIVILEGE_NOT_HELD, user cannot symlink if (e.osError?.errorCode == 1314) { final String? versionString = RegExp(r'[\d.]+').firstMatch(os.name)?.group(0); final Version? version = Version.parse(versionString); // Windows 10 14972 is the oldest version that allows creating symlinks // just by enabling developer mode; before that it requires running the // terminal as Administrator. // https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/ final String instructions = (version != null && version >= Version(10, 0, 14972)) ? 'Please enable Developer Mode in your system settings. Run\n' ' start ms-settings:developers\n' 'to open settings.' : 'You must build from a terminal run as administrator.'; throwToolExit('Building with plugins requires symlink support.\n\n$instructions'); } // ERROR_INVALID_FUNCTION, trying to link across drives, which is not supported if (e.osError?.errorCode == 1) { throwToolExit( 'Creating symlink from $source to $destination failed with ' 'ERROR_INVALID_FUNCTION. Try moving your Flutter project to the same ' 'drive as your Flutter SDK.', ); } }}
/// Creates [symlinkDirectory] containing symlinks to each plugin listed in [platformPlugins].////// If [force] is true, the directory will be created only if missing.void _createPlatformPluginSymlinks(Directory symlinkDirectory, List<Object?>? platformPlugins, {bool force = false}) { if (force && symlinkDirectory.existsSync()) { // Start fresh to avoid stale links. symlinkDirectory.deleteSync(recursive: true); } symlinkDirectory.createSync(recursive: true); if (platformPlugins == null) { return; } for (final Map<String, Object?> pluginInfo in platformPlugins.cast<Map<String, Object?>>()) { final String name = pluginInfo[_kFlutterPluginsNameKey]! as String; final String path = pluginInfo[_kFlutterPluginsPathKey]! as String; final Link link = symlinkDirectory.childLink(name); if (link.existsSync()) { continue; } try { link.createSync(path); } on FileSystemException catch (e) { handleSymlinkException( e, platform: globals.platform, os: globals.os, destination: 'dest', source: 'source', ); rethrow; } }}
/// Rewrites the `.flutter-plugins` file of [project] based on the plugin/// dependencies declared in `pubspec.yaml`.////// Assumes `pub get` has been executed since last change to `pubspec.yaml`.Future<void> refreshPluginsList( FlutterProject project, { bool iosPlatform = false, bool macOSPlatform = false,}) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); // TODO(franciscojma): Remove once migration is complete. // Write the legacy plugin files to avoid breaking existing apps. final bool legacyChanged = _writeFlutterPluginsListLegacy(project, plugins);
final bool changed = _writeFlutterPluginsList(project, plugins); if (changed || legacyChanged) { createPluginSymlinks(project, force: true); if (iosPlatform) { globals.cocoaPods?.invalidatePodInstallOutput(project.ios); } if (macOSPlatform) { globals.cocoaPods?.invalidatePodInstallOutput(project.macos); } }}
/// Injects plugins found in `pubspec.yaml` into the platform-specific projects/// only at build-time.////// This method is similar to [injectPlugins], but used only for platforms where/// the plugin files are not required when the app is created (currently: Web).////// This method will create files in the temporary flutter build directory/// specified by `destination`.////// In the Web platform, `destination` can point to a real filesystem (`flutter build`)/// or an in-memory filesystem (`flutter run`).////// This method is also used by [WebProject.ensureReadyForPlatformSpecificTooling]/// to inject a copy of the plugin registrant for web into .dart_tool/dartpad so/// dartpad can get the plugin registrant without needing to build the complete/// project. See: https://github.com/dart-lang/dart-services/pull/874Future<void> injectBuildTimePluginFiles( FlutterProject project, { required Directory destination, bool webPlatform = false,}) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); if (webPlatform) { await _writeWebPluginRegistrant(project, plugins, destination); }}
/// Injects plugins found in `pubspec.yaml` into the platform-specific projects.////// The injected files are required by the flutter app as soon as possible, so/// it can be built.////// Files written by this method end up in platform-specific locations that are/// configured by each [FlutterProject] subclass (except for the Web).////// Web tooling uses [injectBuildTimePluginFiles] instead, which places files in the/// current build (temp) directory, and doesn't modify the users' working copy.////// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`.Future<void> injectPlugins( FlutterProject project, { bool androidPlatform = false, bool iosPlatform = false, bool linuxPlatform = false, bool macOSPlatform = false, bool windowsPlatform = false, Iterable<String>? allowedPlugins,}) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); if (androidPlatform) { await _writeAndroidPluginRegistrant(project, plugins); } if (iosPlatform) { await _writeIOSPluginRegistrant(project, plugins); } if (linuxPlatform) { await _writeLinuxPluginFiles(project, plugins); } if (macOSPlatform) { await _writeMacOSPluginRegistrant(project, plugins); } if (windowsPlatform) { await writeWindowsPluginFiles(project, plugins, globals.templateRenderer, allowedPlugins: allowedPlugins); } if (!project.isModule) { final List<XcodeBasedProject> darwinProjects = <XcodeBasedProject>[ if (iosPlatform) project.ios, if (macOSPlatform) project.macos, ]; for (final XcodeBasedProject subproject in darwinProjects) { if (plugins.isNotEmpty) { await globals.cocoaPods?.setupPodfile(subproject); } /// The user may have a custom maintained Podfile that they're running `pod install` /// on themselves. else if (subproject.podfile.existsSync() && subproject.podfileLock.existsSync()) { globals.cocoaPods?.addPodsDependencyToFlutterXcconfig(subproject); } } }}
/// Returns whether the specified Flutter [project] has any plugin dependencies.////// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`.bool hasPlugins(FlutterProject project) { return _readFileContent(project.flutterPluginsFile) != null;}
/// Resolves the platform implementation for Dart-only plugins.////// * If there is only one dependency on a package that implements the/// frontend plugin for the current platform, use that./// * If there is a single direct dependency on a package that implements the/// frontend plugin for the current platform, use that./// * If there is no direct dependency on a package that implements the/// frontend plugin, but there is a default for the current platform,/// use that./// * Else fail.////// For more details, https://flutter.dev/go/federated-plugins.// TODO(stuartmorgan): Expand implementation to apply to all implementations,// not just Dart-only, per the federated plugin spec.List<PluginInterfaceResolution> resolvePlatformImplementation( List<Plugin> plugins, { bool throwOnPluginPubspecError = true,}) { final List<String> platforms = <String>[ AndroidPlugin.kConfigKey, IOSPlugin.kConfigKey, LinuxPlugin.kConfigKey, MacOSPlugin.kConfigKey, WindowsPlugin.kConfigKey, ]; final Map<String, List<PluginInterfaceResolution>> possibleResolutions = <String, List<PluginInterfaceResolution>>{}; final Map<String, String> defaultImplementations = <String, String>{}; // Generates a key for the maps above. String getResolutionKey({required String platform, required String packageName}) { return '$packageName:$platform'; }
bool hasPubspecError = false; for (final Plugin plugin in plugins) { for (final String platform in platforms) { if (plugin.platforms[platform] == null && plugin.defaultPackagePlatforms[platform] == null) { // The plugin doesn't implement this platform. continue; } String? implementsPackage = plugin.implementsPackage; if (implementsPackage == null || implementsPackage.isEmpty) { final String? defaultImplementation = plugin.defaultPackagePlatforms[platform]; final bool hasInlineDartImplementation = plugin.pluginDartClassPlatforms[platform] != null; if (defaultImplementation == null && !hasInlineDartImplementation) { if (throwOnPluginPubspecError) { globals.printError( "Plugin `${plugin.name}` doesn't implement a plugin interface, nor does " 'it specify an implementation in pubspec.yaml.\n\n' 'To set an inline implementation, use:\n' 'flutter:\n' ' plugin:\n' ' platforms:\n' ' $platform:\n' ' $kDartPluginClass: <plugin-class>\n' '\n' 'To set a default implementation, use:\n' 'flutter:\n' ' plugin:\n' ' platforms:\n' ' $platform:\n' ' $kDefaultPackage: <plugin-implementation>\n' '\n' 'To implement an interface, use:\n' 'flutter:\n' ' plugin:\n' ' implements: <plugin-interface>' '\n' ); } hasPubspecError = true; continue; } final String defaultImplementationKey = getResolutionKey(platform: platform, packageName: plugin.name); if (defaultImplementation != null) { defaultImplementations[defaultImplementationKey] = defaultImplementation; continue; } else { // An app-facing package (i.e., one with no 'implements') with an // inline implementation should be its own default implementation. // Desktop platforms originally did not work that way, and enabling // it unconditionally would break existing published plugins, so // only treat it as such if either: // - the platform is not desktop, or // - the plugin requires at least Flutter 2.11 (when this opt-in logic // was added), so that existing plugins continue to work. // See https://github.com/flutter/flutter/issues/87862 for details. final bool isDesktop = platform == 'linux' || platform == 'macos' || platform == 'windows'; final semver.VersionConstraint? flutterConstraint = plugin.flutterConstraint; final semver.Version? minFlutterVersion = flutterConstraint != null && flutterConstraint is semver.VersionRange ? flutterConstraint.min : null; final bool hasMinVersionForImplementsRequirement = minFlutterVersion != null && minFlutterVersion.compareTo(semver.Version(2, 11, 0)) >= 0; if (!isDesktop || hasMinVersionForImplementsRequirement) { implementsPackage = plugin.name; defaultImplementations[defaultImplementationKey] = plugin.name; } else { // If it doesn't meet any of the conditions, it isn't eligible for // auto-registration. continue; } } } // If there's no Dart implementation, there's nothing to register. if (plugin.pluginDartClassPlatforms[platform] == null || plugin.pluginDartClassPlatforms[platform] == 'none') { continue; }
// If it hasn't been skipped, it's a candidate for auto-registration, so // add it as a possible resolution. final String resolutionKey = getResolutionKey(platform: platform, packageName: implementsPackage); if (!possibleResolutions.containsKey(resolutionKey)) { possibleResolutions[resolutionKey] = <PluginInterfaceResolution>[]; } possibleResolutions[resolutionKey]!.add(PluginInterfaceResolution( plugin: plugin, platform: platform, )); } } if (hasPubspecError && throwOnPluginPubspecError) { throwToolExit('Please resolve the errors'); }
// Now resolve all the possible resolutions to a single option for each // plugin, or throw if that's not possible. bool hasResolutionError = false; final List<PluginInterfaceResolution> finalResolution = <PluginInterfaceResolution>[]; for (final MapEntry<String, List<PluginInterfaceResolution>> entry in possibleResolutions.entries) { final List<PluginInterfaceResolution> candidates = entry.value; // If there's only one candidate, use it. if (candidates.length == 1) { finalResolution.add(candidates.first); continue; } // Next, try direct dependencies of the resolving application. final Iterable<PluginInterfaceResolution> directDependencies = candidates.where((PluginInterfaceResolution r) { return r.plugin.isDirectDependency; }); if (directDependencies.isNotEmpty) { if (directDependencies.length > 1) { globals.printError( 'Plugin ${entry.key} has conflicting direct dependency implementations:\n' '${directDependencies.map((PluginInterfaceResolution r) => ' ${r.plugin.name}\n').join()}' 'To fix this issue, remove all but one of these dependencies from pubspec.yaml.\n' ); hasResolutionError = true; } else { finalResolution.add(directDependencies.first); } continue; } // Next, defer to the default implementation if there is one. final String? defaultPackageName = defaultImplementations[entry.key]; if (defaultPackageName != null) { final int defaultIndex = candidates .indexWhere((PluginInterfaceResolution r) => r.plugin.name == defaultPackageName); if (defaultIndex != -1) { finalResolution.add(candidates[defaultIndex]); continue; } } // Otherwise, require an explicit choice. if (candidates.length > 1) { globals.printError( 'Plugin ${entry.key} has multiple possible implementations:\n' '${candidates.map((PluginInterfaceResolution r) => ' ${r.plugin.name}\n').join()}' 'To fix this issue, add one of these dependencies to pubspec.yaml.\n' ); hasResolutionError = true; continue; } } if (hasResolutionError) { throwToolExit('Please resolve the errors'); } return finalResolution;}
/// Generates the Dart plugin registrant, which allows to bind a platform/// implementation of a Dart only plugin to its interface./// The new entrypoint wraps [currentMainUri], adds the [_PluginRegistrant] class,/// and writes the file to [newMainDart].////// [mainFile] is the main entrypoint file. e.g. /<app>/lib/main.dart.////// A successful run will create a new generate_main.dart file or update the existing file./// Throws [ToolExit] if unable to generate the file.////// This method also validates each plugin's pubspec.yaml, but errors are only/// reported if [throwOnPluginPubspecError] is [true].////// For more details, see https://flutter.dev/go/federated-plugins.Future<void> generateMainDartWithPluginRegistrant( FlutterProject rootProject, PackageConfig packageConfig, String currentMainUri, File mainFile, { bool throwOnPluginPubspecError = false,}) async { final List<Plugin> plugins = await findPlugins(rootProject); final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation( plugins, throwOnPluginPubspecError: throwOnPluginPubspecError, ); final LanguageVersion entrypointVersion = determineLanguageVersion( mainFile, packageConfig.packageOf(mainFile.absolute.uri), Cache.flutterRoot!, ); final Map<String, Object> templateContext = <String, Object>{ 'mainEntrypoint': currentMainUri, 'dartLanguageVersion': entrypointVersion.toString(), AndroidPlugin.kConfigKey: <Object?>[], IOSPlugin.kConfigKey: <Object?>[], LinuxPlugin.kConfigKey: <Object?>[], MacOSPlugin.kConfigKey: <Object?>[], WindowsPlugin.kConfigKey: <Object?>[], }; final File newMainDart = rootProject.dartPluginRegistrant; if (resolutions.isEmpty) { try { if (await newMainDart.exists()) { await newMainDart.delete(); } } on FileSystemException catch (error) { globals.printWarning( 'Unable to remove ${newMainDart.path}, received error: $error.\n' 'You might need to run flutter clean.' ); rethrow; } return; } for (final PluginInterfaceResolution resolution in resolutions) { assert(templateContext.containsKey(resolution.platform)); (templateContext[resolution.platform] as List<Object?>?)?.add(resolution.toMap()); } try { await _renderTemplateToFile( _dartPluginRegistryForNonWebTemplate, templateContext, newMainDart, globals.templateRenderer, ); } on FileSystemException catch (error) { globals.printError('Unable to write ${newMainDart.path}, received error: $error'); rethrow; }}novelforge-project/flutter/packages/flutter_tools/lib/src/android/adb.dartAdded+18
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android.dartAdded+7
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_builder.dartAdded+53
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_console.dartAdded+84
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device.dartAdded+1365
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dartAdded+199
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_emulator.dartAdded+232
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_sdk.dartAdded+623
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio.dartAdded+579
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_studio_validator.dartAdded+141
novelforge-project/flutter/packages/flutter_tools/lib/src/android/android_workflow.dartAdded+455
novelforge-project/flutter/packages/flutter_tools/lib/src/android/application_package.dartAdded+431
novelforge-project/flutter/packages/flutter_tools/lib/src/android/build_validation.dartAdded+49
novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_gen_snapshot_validator.dartAdded+342
novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_prebuild_validator.dartAdded+294
novelforge-project/flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dartAdded+223
novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle.dartAdded+1277
novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_errors.dartAdded+750
novelforge-project/flutter/packages/flutter_tools/lib/src/android/gradle_utils.dartAdded+974
novelforge-project/flutter/packages/flutter_tools/lib/src/android/java.dartAdded+247
novelforge-project/flutter/packages/flutter_tools/lib/src/application_package.dartAdded+41
novelforge-project/flutter/packages/flutter_tools/lib/src/artifacts.dartAdded+1468
novelforge-project/flutter/packages/flutter_tools/lib/src/asset.dartAdded+1283
novelforge-project/flutter/packages/flutter_tools/lib/src/build_info.dartAdded+1063
novelforge-project/flutter/packages/flutter_tools/lib/src/bundle.dartAdded+64
novelforge-project/flutter/packages/flutter_tools/lib/src/bundle_builder.dartAdded+217
novelforge-project/flutter/packages/flutter_tools/lib/src/cache.dartAdded+1351
novelforge-project/flutter/packages/flutter_tools/lib/src/cmake.dartAdded+125
novelforge-project/flutter/packages/flutter_tools/lib/src/cmake_project.dartAdded+144
novelforge-project/flutter/packages/flutter_tools/lib/src/compile.dartAdded+1082
novelforge-project/flutter/packages/flutter_tools/lib/src/context_runner.dartAdded+400
novelforge-project/flutter/packages/flutter_tools/lib/src/convert.dartAdded+81
novelforge-project/flutter/packages/flutter_tools/lib/src/daemon.dartAdded+378
novelforge-project/flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dartAdded+71
novelforge-project/flutter/packages/flutter_tools/lib/src/desktop_device.dartAdded+353
novelforge-project/flutter/packages/flutter_tools/lib/src/devfs.dartAdded+768
novelforge-project/flutter/packages/flutter_tools/lib/src/device.dartAdded+1400
novelforge-project/flutter/packages/flutter_tools/lib/src/device_port_forwarder.dartAdded+61
novelforge-project/flutter/packages/flutter_tools/lib/src/device_vm_service_discovery_for_attach.dartAdded+110
novelforge-project/flutter/packages/flutter_tools/lib/src/devtools_launcher.dartAdded+111
novelforge-project/flutter/packages/flutter_tools/lib/src/doctor.dartAdded+806
novelforge-project/flutter/packages/flutter_tools/lib/src/doctor_validator.dartAdded+314
novelforge-project/flutter/packages/flutter_tools/lib/src/emulator.dartAdded+337
novelforge-project/flutter/packages/flutter_tools/lib/src/features.dartAdded+316
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_application_package.dartAdded+111
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_cache.dartAdded+918
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_device_manager.dartAdded+148
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_features.dartAdded+85
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_manifest.dartAdded+796
novelforge-project/flutter/packages/flutter_tools/lib/src/flutter_plugins.dartAdded+1477