Add Swift Package Manager as new opt-in feature for iOS and macOS (#146256)

This PR adds initial support for Swift Package Manager (SPM). Users must opt in. Only compatible with Xcode 15+.

Fixes https://github.com/flutter/flutter/issues/146369.

## Included Features

This PR includes the following features:
* Enabling SPM via config 
`flutter config --enable-swift-package-manager`
* Disabling SPM via config (will disable for all projects) 
`flutter config --no-enable-swift-package-manager`
* Disabling SPM via pubspec.yaml (will disable for the specific project)
```
flutter:
  disable-swift-package-manager: true
```
* Migrating existing apps to add SPM integration if using a Flutter plugin with a Package.swift
  * Generates a Swift Package (named `FlutterGeneratedPluginSwiftPackage`) that handles Flutter SPM-compatible plugin dependencies. Generated package is added to the Xcode project.
* Error parsing of common errors that may occur due to using CocoaPods and Swift Package Manager together
* Tool will print warnings when using all Swift Package plugins and encourage you to remove CocoaPods

This PR also converts `integration_test` and `integration_test_macos` plugins to be both Swift Packages and CocoaPod Pods.

## How it Works
The Flutter CLI will generate a Swift Package called `FlutterGeneratedPluginSwiftPackage`, which will have local dependencies on all Swift Package compatible Flutter plugins.  

The `FlutterGeneratedPluginSwiftPackage` package will be added to the Xcode project via altering of the `project.pbxproj`. 

In addition, a "Pre-action" script will be added via altering of the `Runner.xcscheme`. This script will invoke the flutter tool to copy the Flutter/FlutterMacOS framework to the `BUILT_PRODUCTS_DIR` directory before the build starts. This is needed because plugins need to be linked to the Flutter framework and fortunately Swift Package Manager automatically uses `BUILT_PRODUCTS_DIR` as a framework search path.

CocoaPods will continue to run and be used to support non-Swift Package compatible Flutter plugins.

## Not Included Features

It does not include the following (will be added in future PRs):
* Create plugin template
* Create app template
* Add-to-App integration
This commit is contained in:
Victoria Ashworth
2024-04-18 16:12:36 -05:00
committed by GitHub
parent f0fc419a6c
commit 6d19fa3bfa
56 changed files with 10017 additions and 139 deletions

View File

@@ -41,6 +41,9 @@ List<Target> _kDefaultTargets = <Target>[
const DebugMacOSBundleFlutterAssets(),
const ProfileMacOSBundleFlutterAssets(),
const ReleaseMacOSBundleFlutterAssets(),
const DebugUnpackMacOS(),
const ProfileUnpackMacOS(),
const ReleaseUnpackMacOS(),
// Linux targets
const DebugBundleLinuxAssets(TargetPlatform.linux_x64),
const DebugBundleLinuxAssets(TargetPlatform.linux_arm64),
@@ -72,6 +75,9 @@ List<Target> _kDefaultTargets = <Target>[
const DebugIosApplicationBundle(),
const ProfileIosApplicationBundle(),
const ReleaseIosApplicationBundle(),
const DebugUnpackIOS(),
const ProfileUnpackIOS(),
const ReleaseUnpackIOS(),
// Windows targets
const UnpackWindows(TargetPlatform.windows_x64),
const UnpackWindows(TargetPlatform.windows_arm64),

View File

@@ -23,6 +23,7 @@ import '../globals.dart' as globals;
import '../ios/application_package.dart';
import '../ios/mac.dart';
import '../ios/plist_parser.dart';
import '../project.dart';
import '../reporting/reporting.dart';
import '../runner/flutter_command.dart';
import 'build.dart';
@@ -686,7 +687,15 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand {
xcodeBuildResult = result;
if (!result.success) {
await diagnoseXcodeBuildFailure(result, globals.flutterUsage, globals.logger, globals.analytics);
await diagnoseXcodeBuildFailure(
result,
analytics: globals.analytics,
fileSystem: globals.fs,
flutterUsage: globals.flutterUsage,
logger: globals.logger,
platform: SupportedPlatform.ios,
project: app.project.parent,
);
final String presentParticiple = xcodeBuildAction == XcodeBuildAction.build ? 'building' : 'archiving';
throwToolExit('Encountered error while $presentParticiple for $logTarget.');
}

View File

@@ -272,7 +272,12 @@ class BuildIOSFrameworkCommand extends BuildFrameworkCommand {
buildInfo, modeDirectory, iPhoneBuildOutput, simulatorBuildOutput);
// Build and copy plugins.
await processPodsIfNeeded(project.ios, getIosBuildDirectory(), buildInfo.mode);
await processPodsIfNeeded(
project.ios,
getIosBuildDirectory(),
buildInfo.mode,
forceCocoaPodsOnly: true,
);
if (boolArg('plugins') && hasPlugins(project)) {
await _producePlugins(buildInfo.mode, xcodeBuildConfiguration, iPhoneBuildOutput, simulatorBuildOutput, modeDirectory);
}

View File

@@ -94,7 +94,12 @@ class BuildMacOSFrameworkCommand extends BuildFrameworkCommand {
await _produceAppFramework(buildInfo, modeDirectory, buildOutput);
// Build and copy plugins.
await processPodsIfNeeded(project.macos, getMacOSBuildDirectory(), buildInfo.mode);
await processPodsIfNeeded(
project.macos,
getMacOSBuildDirectory(),
buildInfo.mode,
forceCocoaPodsOnly: true,
);
if (boolArg('plugins') && hasPlugins(project)) {
await _producePlugins(xcodeBuildConfiguration, buildOutput, modeDirectory);
}

View File

@@ -51,6 +51,9 @@ abstract class FeatureFlags {
/// Whether native assets compilation and bundling is enabled.
bool get isPreviewDeviceEnabled => true;
/// Whether Swift Package Manager dependency management is enabled.
bool get isSwiftPackageManagerEnabled => false;
/// Whether a particular feature is enabled for the current channel.
///
/// Prefer using one of the specific getters above instead of this API.
@@ -70,6 +73,7 @@ const List<Feature> allFeatures = <Feature>[
cliAnimation,
nativeAssets,
previewDevice,
swiftPackageManager,
];
/// All current Flutter feature flags that can be configured.
@@ -175,6 +179,16 @@ const Feature previewDevice = Feature(
),
);
/// Enable Swift Package Mangaer as a darwin dependency manager.
const Feature swiftPackageManager = Feature(
name: 'support for Swift Package Manager for iOS and macOS',
configSetting: 'enable-swift-package-manager',
environmentOverride: 'SWIFT_PACKAGE_MANAGER',
master: 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

View File

@@ -58,6 +58,9 @@ class FlutterFeatureFlags implements FeatureFlags {
@override
bool get isPreviewDeviceEnabled => isEnabled(previewDevice);
@override
bool get isSwiftPackageManagerEnabled => isEnabled(swiftPackageManager);
@override
bool isEnabled(Feature feature) {
final String currentChannel = _flutterVersion.channel;

View File

@@ -136,6 +136,12 @@ class FlutterManifest {
return _flutterDescriptor['uses-material-design'] as bool? ?? false;
}
/// If true, does not use Swift Package Manager as a dependency manager.
/// CocoaPods will be used instead.
bool get disabledSwiftPackageManager {
return _flutterDescriptor['disable-swift-package-manager'] as bool? ?? false;
}
/// True if this Flutter module should use AndroidX dependencies.
///
/// If false the deprecated Android Support library will be used.
@@ -547,6 +553,10 @@ void _validateFlutter(YamlMap? yaml, List<String> errors) {
break;
case 'deferred-components':
_validateDeferredComponents(kvp, errors);
case 'disable-swift-package-manager':
if (yamlValue is! bool) {
errors.add('Expected "$yamlKey" to be a bool, but got $yamlValue (${yamlValue.runtimeType}).');
}
default:
errors.add('Unexpected child "$yamlKey" found under "flutter".');
break;

View File

@@ -22,6 +22,8 @@ import 'dart/language_version.dart';
import 'dart/package_map.dart';
import 'features.dart';
import 'globals.dart' as globals;
import 'macos/darwin_dependency_management.dart';
import 'macos/swift_package_manager.dart';
import 'platform_plugins.dart';
import 'plugins.dart';
import 'project.dart';
@@ -160,7 +162,11 @@ const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source';
///
///
/// Finally, returns [true] if the plugins list has changed, otherwise returns [false].
bool _writeFlutterPluginsList(FlutterProject project, List<Plugin> plugins) {
bool _writeFlutterPluginsList(
FlutterProject project,
List<Plugin> plugins, {
bool forceCocoaPodsOnly = false,
}) {
final File pluginsFile = project.flutterPluginsDependenciesFile;
if (plugins.isEmpty) {
return ErrorHandlingFileSystem.deleteIfExists(pluginsFile);
@@ -190,6 +196,7 @@ bool _writeFlutterPluginsList(FlutterProject project, List<Plugin> plugins) {
result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins);
result['date_created'] = globals.systemClock.now().toString();
result['version'] = globals.flutterVersion.frameworkVersion;
result['swift_package_manager_enabled'] = !forceCocoaPodsOnly && project.usesSwiftPackageManager;
// Only notify if the plugins list has changed. [date_created] will always be different,
// [version] is not relevant for this check.
@@ -1000,6 +1007,7 @@ Future<void> refreshPluginsList(
FlutterProject project, {
bool iosPlatform = false,
bool macOSPlatform = false,
bool forceCocoaPodsOnly = false,
}) async {
final List<Plugin> plugins = await findPlugins(project);
// Sort the plugins by name to keep ordering stable in generated files.
@@ -1008,8 +1016,12 @@ Future<void> refreshPluginsList(
// 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) {
final bool changed = _writeFlutterPluginsList(
project,
plugins,
forceCocoaPodsOnly: forceCocoaPodsOnly,
);
if (changed || legacyChanged || forceCocoaPodsOnly) {
createPluginSymlinks(project, force: true);
if (iosPlatform) {
globals.cocoaPods?.invalidatePodInstallOutput(project.ios);
@@ -1069,6 +1081,7 @@ Future<void> injectPlugins(
bool macOSPlatform = false,
bool windowsPlatform = false,
Iterable<String>? allowedPlugins,
DarwinDependencyManagement? darwinDependencyManagement,
}) async {
final List<Plugin> plugins = await findPlugins(project);
// Sort the plugins by name to keep ordering stable in generated files.
@@ -1088,20 +1101,27 @@ Future<void> injectPlugins(
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);
}
if (iosPlatform || macOSPlatform) {
final DarwinDependencyManagement darwinDependencyManagerSetup = darwinDependencyManagement ?? DarwinDependencyManagement(
project: project,
plugins: plugins,
cocoapods: globals.cocoaPods!,
swiftPackageManager: SwiftPackageManager(
fileSystem: globals.fs,
templateRenderer: globals.templateRenderer,
),
fileSystem: globals.fs,
logger: globals.logger,
);
if (iosPlatform) {
await darwinDependencyManagerSetup.setUp(
platform: SupportedPlatform.ios,
);
}
if (macOSPlatform) {
await darwinDependencyManagerSetup.setUp(
platform: SupportedPlatform.macos,
);
}
}
}

View File

@@ -496,7 +496,15 @@ class IOSDevice extends Device {
);
if (!buildResult.success) {
_logger.printError('Could not build the precompiled application for the device.');
await diagnoseXcodeBuildFailure(buildResult, globals.flutterUsage, _logger, globals.analytics);
await diagnoseXcodeBuildFailure(
buildResult,
analytics: globals.analytics,
fileSystem: globals.fs,
flutterUsage: globals.flutterUsage,
logger: globals.logger,
platform: SupportedPlatform.ios,
project: package.project.parent,
);
_logger.printError('');
return LaunchResult.failed();
}

View File

@@ -19,12 +19,16 @@ import '../build_info.dart';
import '../cache.dart';
import '../device.dart';
import '../flutter_manifest.dart';
import '../flutter_plugins.dart';
import '../globals.dart' as globals;
import '../macos/cocoapod_utils.dart';
import '../macos/swift_package_manager.dart';
import '../macos/xcode.dart';
import '../migrations/swift_package_manager_integration_migration.dart';
import '../migrations/xcode_project_object_version_migration.dart';
import '../migrations/xcode_script_build_phase_migration.dart';
import '../migrations/xcode_thin_binary_build_phase_input_paths_migration.dart';
import '../plugins.dart';
import '../project.dart';
import '../reporting/reporting.dart';
import 'application_package.dart';
@@ -148,6 +152,8 @@ Future<XcodeBuildResult> buildXcodeProject({
return XcodeBuildResult(success: false);
}
final FlutterProject project = FlutterProject.current();
final List<ProjectMigrator> migrators = <ProjectMigrator>[
RemoveFrameworkLinkAndEmbeddingMigration(app.project, globals.logger, globals.flutterUsage, globals.analytics),
XcodeBuildSystemMigration(app.project, globals.logger),
@@ -160,6 +166,16 @@ Future<XcodeBuildResult> buildXcodeProject({
RemoveBitcodeMigration(app.project, globals.logger),
XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, globals.logger),
UIApplicationMainDeprecationMigration(app.project, globals.logger),
if (project.usesSwiftPackageManager && app.project.flutterPluginSwiftPackageManifest.existsSync())
SwiftPackageManagerIntegrationMigration(
app.project,
SupportedPlatform.ios,
buildInfo,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
logger: globals.logger,
fileSystem: globals.fs,
plistParser: globals.plistParser,
),
];
final ProjectMigration migration = ProjectMigration(migrators);
@@ -245,12 +261,21 @@ Future<XcodeBuildResult> buildXcodeProject({
);
}
final FlutterProject project = FlutterProject.current();
await updateGeneratedXcodeProperties(
project: project,
targetOverride: targetOverride,
buildInfo: buildInfo,
);
if (project.usesSwiftPackageManager) {
final String? iosDeploymentTarget = buildSettings['IPHONEOS_DEPLOYMENT_TARGET'];
if (iosDeploymentTarget != null) {
SwiftPackageManager.updateMinimumDeployment(
platform: SupportedPlatform.ios,
project: project.ios,
deploymentTarget: iosDeploymentTarget,
);
}
}
await processPodsIfNeeded(project.ios, getIosBuildDirectory(), buildInfo.mode);
if (configOnly) {
return XcodeBuildResult(success: true);
@@ -596,11 +621,14 @@ return result.exitCode != 0 &&
}
Future<void> diagnoseXcodeBuildFailure(
XcodeBuildResult result,
Usage flutterUsage,
Logger logger,
Analytics analytics,
) async {
XcodeBuildResult result, {
required Analytics analytics,
required Logger logger,
required FileSystem fileSystem,
required Usage flutterUsage,
required SupportedPlatform platform,
required FlutterProject project,
}) async {
final XcodeBuildExecution? xcodeBuildExecution = result.xcodeBuildExecution;
if (xcodeBuildExecution != null
&& xcodeBuildExecution.environmentType == EnvironmentType.physical
@@ -627,7 +655,14 @@ Future<void> diagnoseXcodeBuildFailure(
}
// Handle errors.
final bool issueDetected = _handleIssues(result.xcResult, logger, xcodeBuildExecution);
final bool issueDetected = await _handleIssues(
result,
xcodeBuildExecution,
project: project,
platform: platform,
logger: logger,
fileSystem: fileSystem,
);
if (!issueDetected && xcodeBuildExecution != null) {
// Fallback to use stdout to detect and print issues.
@@ -728,7 +763,11 @@ bool upgradePbxProjWithFlutterAssets(IosProject project, Logger logger) {
return true;
}
_XCResultIssueHandlingResult _handleXCResultIssue({required XCResultIssue issue, required Logger logger}) {
_XCResultIssueHandlingResult _handleXCResultIssue({
required XCResultIssue issue,
required XcodeBuildResult result,
required Logger logger,
}) {
// Issue summary from xcresult.
final StringBuffer issueSummaryBuffer = StringBuffer();
issueSummaryBuffer.write(issue.subType ?? 'Unknown');
@@ -761,20 +800,61 @@ _XCResultIssueHandlingResult _handleXCResultIssue({required XCResultIssue issue,
if (missingPlatform != null) {
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: false, missingPlatform: missingPlatform);
}
} else if (message.toLowerCase().contains('redefinition of module')) {
final String? duplicateModule = _parseModuleRedefinition(message);
return _XCResultIssueHandlingResult(
requiresProvisioningProfile: false,
hasProvisioningProfileIssue: false,
duplicateModule: duplicateModule,
);
} else if (message.toLowerCase().contains('duplicate symbols')) {
// The message does not contain the plugin name, must parse the stdout.
String? duplicateModule;
if (result.stdout != null) {
duplicateModule = _parseDuplicateSymbols(result.stdout!);
}
return _XCResultIssueHandlingResult(
requiresProvisioningProfile: false,
hasProvisioningProfileIssue: false,
duplicateModule: duplicateModule,
);
} else if (message.toLowerCase().contains('not found')) {
final String? missingModule = _parseMissingModule(message);
if (missingModule != null) {
return _XCResultIssueHandlingResult(
requiresProvisioningProfile: false,
hasProvisioningProfileIssue: false,
missingModule: missingModule,
);
}
}
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: false);
}
// Returns `true` if at least one issue is detected.
bool _handleIssues(XCResult? xcResult, Logger logger, XcodeBuildExecution? xcodeBuildExecution) {
Future<bool> _handleIssues(
XcodeBuildResult result,
XcodeBuildExecution? xcodeBuildExecution, {
required FlutterProject project,
required SupportedPlatform platform,
required Logger logger,
required FileSystem fileSystem,
}) async {
bool requiresProvisioningProfile = false;
bool hasProvisioningProfileIssue = false;
bool issueDetected = false;
String? missingPlatform;
final List<String> duplicateModules = <String>[];
final List<String> missingModules = <String>[];
final XCResult? xcResult = result.xcResult;
if (xcResult != null && xcResult.parseSuccess) {
for (final XCResultIssue issue in xcResult.issues) {
final _XCResultIssueHandlingResult handlingResult = _handleXCResultIssue(issue: issue, logger: logger);
final _XCResultIssueHandlingResult handlingResult = _handleXCResultIssue(
issue: issue,
result: result,
logger: logger,
);
if (handlingResult.hasProvisioningProfileIssue) {
hasProvisioningProfileIssue = true;
}
@@ -782,12 +862,20 @@ bool _handleIssues(XCResult? xcResult, Logger logger, XcodeBuildExecution? xcode
requiresProvisioningProfile = true;
}
missingPlatform = handlingResult.missingPlatform;
if (handlingResult.duplicateModule != null) {
duplicateModules.add(handlingResult.duplicateModule!);
}
if (handlingResult.missingModule != null) {
missingModules.add(handlingResult.missingModule!);
}
issueDetected = true;
}
} else if (xcResult != null) {
globals.printTrace('XCResult parsing error: ${xcResult.parsingErrorMessage}');
}
final XcodeBasedProject xcodeProject = platform == SupportedPlatform.ios ? project.ios : project.macos;
if (requiresProvisioningProfile) {
logger.printError(noProvisioningProfileInstruction, emphasis: true);
} else if ((!issueDetected || hasProvisioningProfileIssue) && _missingDevelopmentTeam(xcodeBuildExecution)) {
@@ -803,11 +891,84 @@ bool _handleIssues(XCResult? xcResult, Logger logger, XcodeBuildExecution? xcode
logger.printError("Also try selecting 'Product > Build' to fix the problem.");
} else if (missingPlatform != null) {
logger.printError(missingPlatformInstructions(missingPlatform), emphasis: true);
} else if (duplicateModules.isNotEmpty) {
final bool usesCocoapods = xcodeProject.podfile.existsSync();
final bool usesSwiftPackageManager = project.usesSwiftPackageManager;
if (usesCocoapods && usesSwiftPackageManager) {
logger.printError(
'Your project uses both CocoaPods and Swift Package Manager, which can '
'cause the above error. It may be caused by there being both a CocoaPod '
'and Swift Package Manager dependency for the following module(s): '
'${duplicateModules.join(', ')}.\n\n'
'You can try to identify which Pod the conflicting module is from by '
'looking at your "ios/Podfile.lock" dependency tree and requesting the '
'author add Swift Package Manager compatibility. See https://stackoverflow.com/a/27955017 '
'to learn more about understanding Podlock dependency tree. \n\n'
'You can also disable Swift Package Manager for the project by adding the '
'following in the project\'s pubspec.yaml under the "flutter" section:\n'
' "disable-swift-package-manager: true"\n',
);
}
} else if (missingModules.isNotEmpty) {
final bool usesCocoapods = xcodeProject.podfile.existsSync();
final bool usesSwiftPackageManager = project.usesSwiftPackageManager;
if (usesCocoapods && !usesSwiftPackageManager) {
final List<String> swiftPackageOnlyPlugins = <String>[];
for (final String module in missingModules) {
if (await _isPluginSwiftPackageOnly(
platform: platform,
project: project,
pluginName: module,
fileSystem: fileSystem,
)) {
swiftPackageOnlyPlugins.add(module);
}
}
if (swiftPackageOnlyPlugins.isNotEmpty) {
logger.printError(
'Your project uses CocoaPods as a dependency manager, but the following '
'plugin(s) only support Swift Package Manager: ${swiftPackageOnlyPlugins.join(', ')}.\n'
'Try enabling Swift Package Manager with "flutter config --enable-swift-package-manager".',
);
}
}
}
return issueDetected;
}
/// Returns true if a Package.swift is found for the plugin and a podspec is not.
Future<bool> _isPluginSwiftPackageOnly({
required SupportedPlatform platform,
required FlutterProject project,
required String pluginName,
required FileSystem fileSystem,
}) async {
final List<Plugin> plugins = await findPlugins(project);
final Plugin? matched = plugins
.where((Plugin plugin) =>
plugin.name.toLowerCase() == pluginName.toLowerCase() &&
plugin.platforms[platform.name] != null)
.firstOrNull;
if (matched == null) {
return false;
}
final String? swiftPackagePath = matched.pluginSwiftPackageManifestPath(
fileSystem,
platform.name,
);
final bool swiftPackageExists = swiftPackagePath != null &&
fileSystem.file(swiftPackagePath).existsSync();
final String? podspecPath = matched.pluginPodspecPath(
fileSystem,
platform.name,
);
final bool podspecExists = podspecPath != null &&
fileSystem.file(podspecPath).existsSync();
return swiftPackageExists && !podspecExists;
}
// Return 'true' a missing development team issue is detected.
bool _missingDevelopmentTeam(XcodeBuildExecution? xcodeBuildExecution) {
// Make sure the user has specified one of:
@@ -852,22 +1013,68 @@ String? _parseMissingPlatform(String message) {
return pattern.firstMatch(message)?.group(1);
}
String? _parseModuleRedefinition(String message) {
// Example: "Redefinition of module 'plugin_1_name'"
final RegExp pattern = RegExp(r"Redefinition of module '(.*?)'");
final RegExpMatch? match = pattern.firstMatch(message);
if (match != null && match.groupCount > 0) {
final String? version = match.group(1);
return version;
}
return null;
}
String? _parseDuplicateSymbols(String message) {
// Example: "duplicate symbol '_$s29plugin_1_name23PluginNamePluginC9setDouble3key5valueySS_SdtF' in:
// /Users/username/path/to/app/build/ios/Debug-iphonesimulator/plugin_1_name/plugin_1_name.framework/plugin_1_name[arm64][5](PluginNamePlugin.o)
final RegExp pattern = RegExp(r'duplicate symbol [\s|\S]*?\/(.*)\.o');
final RegExpMatch? match = pattern.firstMatch(message);
if (match != null && match.groupCount > 0) {
final String? version = match.group(1);
if (version != null) {
return version.split('/').last.split('[').first.split('(').first;
}
return version;
}
return null;
}
String? _parseMissingModule(String message) {
// Example: "Module 'plugin_1_name' not found"
final RegExp pattern = RegExp(r"Module '(.*?)' not found");
final RegExpMatch? match = pattern.firstMatch(message);
if (match != null && match.groupCount > 0) {
final String? version = match.group(1);
return version;
}
return null;
}
// The result of [_handleXCResultIssue].
class _XCResultIssueHandlingResult {
_XCResultIssueHandlingResult({
required this.requiresProvisioningProfile,
required this.hasProvisioningProfileIssue,
this.missingPlatform,
this.duplicateModule,
this.missingModule,
});
// An issue indicates that user didn't provide the provisioning profile.
/// An issue indicates that user didn't provide the provisioning profile.
final bool requiresProvisioningProfile;
// An issue indicates that there is a provisioning profile issue.
/// An issue indicates that there is a provisioning profile issue.
final bool hasProvisioningProfileIssue;
final String? missingPlatform;
/// An issue indicates a module is declared twice, potentially due to being
/// used in both Swift Package Manager and CocoaPods.
final String? duplicateModule;
/// An issue indicates a module was imported but not found, potentially due
/// to it being Swift Package Manager compatible only.
final String? missingModule;
}
const String _kResultBundlePath = 'temporary_xcresult_bundle';

View File

@@ -64,6 +64,35 @@ class PlistParser {
}
}
/// Returns the content, converted to JSON, of the plist file located at
/// [filePath].
///
/// If [filePath] points to a non-existent file or a file that's not a
/// valid property list file, this will return null.
String? plistJsonContent(String filePath) {
if (!_fileSystem.isFileSync(_plutilExecutable)) {
throw const FileNotFoundException(_plutilExecutable);
}
final List<String> args = <String>[
_plutilExecutable,
'-convert',
'json',
'-o',
'-',
filePath,
];
try {
final String jsonContent = _processUtils.runSync(
args,
throwOnError: true,
).stdout.trim();
return jsonContent;
} on ProcessException catch (error) {
_logger.printError('$error');
return null;
}
}
/// Replaces the string key in the given plist file with the given value.
///
/// If the value is null, then the key will be removed.

View File

@@ -571,7 +571,15 @@ class IOSSimulator extends Device {
deviceID: id,
);
if (!buildResult.success) {
await diagnoseXcodeBuildFailure(buildResult, globals.flutterUsage, globals.logger, globals.analytics);
await diagnoseXcodeBuildFailure(
buildResult,
analytics: globals.analytics,
fileSystem: globals.fs,
flutterUsage: globals.flutterUsage,
logger: globals.logger,
platform: SupportedPlatform.ios,
project: app.project.parent,
);
throwToolExit('Could not build the application for the simulator.');
}

View File

@@ -16,6 +16,7 @@ import '../convert.dart';
import '../globals.dart' as globals;
import '../ios/xcode_build_settings.dart';
import '../ios/xcodeproj.dart';
import '../migrations/swift_package_manager_integration_migration.dart';
import '../migrations/xcode_project_object_version_migration.dart';
import '../migrations/xcode_script_build_phase_migration.dart';
import '../migrations/xcode_thin_binary_build_phase_input_paths_migration.dart';
@@ -85,6 +86,16 @@ Future<void> buildMacOS({
XcodeThinBinaryBuildPhaseInputPathsMigration(flutterProject.macos, globals.logger),
FlutterApplicationMigration(flutterProject.macos, globals.logger),
NSApplicationMainDeprecationMigration(flutterProject.macos, globals.logger),
if (flutterProject.usesSwiftPackageManager && flutterProject.macos.flutterPluginSwiftPackageManifest.existsSync())
SwiftPackageManagerIntegrationMigration(
flutterProject.macos,
SupportedPlatform.macos,
buildInfo,
xcodeProjectInterpreter: globals.xcodeProjectInterpreter!,
logger: globals.logger,
fileSystem: globals.fs,
plistParser: globals.plistParser,
),
];
final ProjectMigration migration = ProjectMigration(migrators);
@@ -101,6 +112,11 @@ Future<void> buildMacOS({
targetOverride: targetOverride,
useMacOSConfig: true,
);
// TODO(vashworth): Call `SwiftPackageManager.updateMinimumDeployment`
// using MACOSX_DEPLOYMENT_TARGET once https://github.com/flutter/flutter/issues/146204
// is fixed.
await processPodsIfNeeded(flutterProject.macos, getMacOSBuildDirectory(), buildInfo.mode);
// If the xcfilelists do not exist, create empty version.
if (!flutterProject.macos.inputFileList.existsSync()) {

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../base/error_handling_io.dart';
import '../base/fingerprint.dart';
import '../build_info.dart';
import '../cache.dart';
@@ -14,20 +15,57 @@ import '../project.dart';
Future<void> processPodsIfNeeded(
XcodeBasedProject xcodeProject,
String buildDirectory,
BuildMode buildMode) async {
BuildMode buildMode, {
bool forceCocoaPodsOnly = false,
}) async {
final FlutterProject project = xcodeProject.parent;
// Ensure that the plugin list is up to date, since hasPlugins relies on it.
await refreshPluginsList(project, macOSPlatform: project.macos.existsSync());
if (!(hasPlugins(project) || (project.isModule && xcodeProject.podfile.existsSync()))) {
// When using Swift Package Manager, the Podfile may not exist so if there
// isn't a Podfile, skip processing pods.
if (project.usesSwiftPackageManager && !xcodeProject.podfile.existsSync() && !forceCocoaPodsOnly) {
return;
}
// If the Xcode project, Podfile, or generated xcconfig have changed since
// last run, pods should be updated.
// Ensure that the plugin list is up to date, since hasPlugins relies on it.
await refreshPluginsList(
project,
iosPlatform: project.ios.existsSync(),
macOSPlatform: project.macos.existsSync(),
forceCocoaPodsOnly: forceCocoaPodsOnly,
);
// If there are no plugins and if the project is a not module with an existing
// podfile, skip processing pods
if (!hasPlugins(project) && !(project.isModule && xcodeProject.podfile.existsSync())) {
return;
}
// If forcing the use of only CocoaPods, but the project is using Swift
// Package Manager, print a warning that CocoaPods will be used.
if (forceCocoaPodsOnly && project.usesSwiftPackageManager) {
globals.logger.printWarning(
'Swift Package Manager does not yet support this command. '
'CocoaPods will be used instead.');
// If CocoaPods has been deintegrated, add it back.
if (!xcodeProject.podfile.existsSync()) {
await globals.cocoaPods?.setupPodfile(xcodeProject);
}
// Delete Swift Package Manager manifest to invalidate fingerprinter
ErrorHandlingFileSystem.deleteIfExists(
xcodeProject.flutterPluginSwiftPackageManifest,
);
}
// If the Xcode project, Podfile, generated plugin Swift Package, or podhelper
// have changed since last run, pods should be updated.
final Fingerprinter fingerprinter = Fingerprinter(
fingerprintPath: globals.fs.path.join(buildDirectory, 'pod_inputs.fingerprint'),
paths: <String>[
xcodeProject.xcodeProjectInfoFile.path,
xcodeProject.podfile.path,
if (xcodeProject.flutterPluginSwiftPackageManifest.existsSync())
xcodeProject.flutterPluginSwiftPackageManifest.path,
globals.fs.path.join(
Cache.flutterRoot!,
'packages',

View File

@@ -21,8 +21,8 @@ import '../cache.dart';
import '../ios/xcodeproj.dart';
import '../migrations/cocoapods_script_symlink.dart';
import '../migrations/cocoapods_toolchain_directory_migration.dart';
import '../project.dart';
import '../reporting/reporting.dart';
import '../xcode_project.dart';
const String noCocoaPodsConsequence = '''
CocoaPods is a package manager for iOS or macOS platform code.
@@ -166,6 +166,10 @@ class CocoaPods {
bool dependenciesChanged = true,
}) async {
if (!xcodeProject.podfile.existsSync()) {
// Swift Package Manager doesn't need Podfile, so don't error.
if (xcodeProject.parent.usesSwiftPackageManager) {
return false;
}
throwToolExit('Podfile missing');
}
_warnIfPodfileOutOfDate(xcodeProject);
@@ -258,6 +262,18 @@ class CocoaPods {
addPodsDependencyToFlutterXcconfig(xcodeProject);
return;
}
final File podfileTemplate = await getPodfileTemplate(
xcodeProject,
runnerProject,
);
podfileTemplate.copySync(podfile.path);
addPodsDependencyToFlutterXcconfig(xcodeProject);
}
Future<File> getPodfileTemplate(
XcodeBasedProject xcodeProject,
Directory runnerProject,
) async {
String podfileTemplateName;
if (xcodeProject is MacOSProject) {
podfileTemplateName = 'Podfile-macos';
@@ -268,7 +284,7 @@ class CocoaPods {
)).containsKey('SWIFT_VERSION');
podfileTemplateName = isSwift ? 'Podfile-ios-swift' : 'Podfile-ios-objc';
}
final File podfileTemplate = _fileSystem.file(_fileSystem.path.join(
return _fileSystem.file(_fileSystem.path.join(
Cache.flutterRoot!,
'packages',
'flutter_tools',
@@ -276,8 +292,6 @@ class CocoaPods {
'cocoapods',
podfileTemplateName,
));
podfileTemplate.copySync(podfile.path);
addPodsDependencyToFlutterXcconfig(xcodeProject);
}
/// Ensures all `Flutter/Xxx.xcconfig` files for the given Xcode-based
@@ -287,12 +301,24 @@ class CocoaPods {
_addPodsDependencyToFlutterXcconfig(xcodeProject, 'Release');
}
String includePodsXcconfig(String mode) {
return 'Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
.toLowerCase()}.xcconfig';
}
bool xcconfigIncludesPods(File xcodeConfig) {
if (xcodeConfig.existsSync()) {
final String content = xcodeConfig.readAsStringSync();
return content.contains('Pods/Target Support Files/Pods-');
}
return false;
}
void _addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject, String mode) {
final File file = xcodeProject.xcodeConfigFor(mode);
if (file.existsSync()) {
final String content = file.readAsStringSync();
final String includeFile = 'Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
.toLowerCase()}.xcconfig';
final String includeFile = includePodsXcconfig(mode);
final String include = '#include? "$includeFile"';
if (!content.contains('Pods/Target Support Files/Pods-')) {
file.writeAsStringSync('$include\n$content', flush: true);

View File

@@ -0,0 +1,257 @@
// 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/logger.dart';
import '../plugins.dart';
import '../project.dart';
import 'cocoapods.dart';
import 'swift_package_manager.dart';
/// Flutter has two dependency management solutions for iOS and macOS
/// applications: CocoaPods and Swift Package Manager. They may be used
/// individually or together. This class handles setting up required files and
/// project settings for the dependency manager(s) being used.
class DarwinDependencyManagement {
DarwinDependencyManagement({
required FlutterProject project,
required List<Plugin> plugins,
required CocoaPods cocoapods,
required SwiftPackageManager swiftPackageManager,
required FileSystem fileSystem,
required Logger logger,
}) : _project = project,
_plugins = plugins,
_cocoapods = cocoapods,
_swiftPackageManager = swiftPackageManager,
_fileSystem = fileSystem,
_logger = logger;
final FlutterProject _project;
final List<Plugin> _plugins;
final CocoaPods _cocoapods;
final SwiftPackageManager _swiftPackageManager;
final FileSystem _fileSystem;
final Logger _logger;
/// Generates/updates required files and project settings for Darwin
/// Dependency Managers (CocoaPods and Swift Package Manager). Projects may
/// use only CocoaPods (if no SPM compatible dependencies or SPM has been
/// disabled), only Swift Package Manager (if no CocoaPod dependencies), or
/// both. This only generates files for the manager(s) being used.
///
/// CocoaPods requires a Podfile and certain values in the Flutter xcconfig
/// files.
///
/// Swift Package Manager requires a generated Package.swift and certain
/// settings in the Xcode project's project.pbxproj and xcscheme (done later
/// before build).
Future<void> setUp({
required SupportedPlatform platform,
}) async {
if (platform != SupportedPlatform.ios &&
platform != SupportedPlatform.macos) {
throwToolExit(
'The platform ${platform.name} is incompatible with Darwin Dependency Managers. Only iOS and macOS are allowed.',
);
}
final XcodeBasedProject xcodeProject = platform == SupportedPlatform.ios
? _project.ios
: _project.macos;
if (_project.usesSwiftPackageManager) {
await _swiftPackageManager.generatePluginsSwiftPackage(
_plugins,
platform,
xcodeProject,
);
} else if (xcodeProject.flutterPluginSwiftPackageInProjectSettings) {
// If Swift Package Manager is not enabled but the project is already
// integrated for Swift Package Manager, pass no plugins to the generator.
// This will still generate the required Package.swift, but it will have
// no dependencies.
await _swiftPackageManager.generatePluginsSwiftPackage(
<Plugin>[],
platform,
xcodeProject,
);
}
// Skip updating Podfile if project is a module, since it will use a
// different module-specific Podfile.
if (_project.isModule) {
return;
}
final (:int totalCount, :int swiftPackageCount, :int podCount) = await _evaluatePluginsAndPrintWarnings(
platform: platform,
xcodeProject: xcodeProject,
);
final bool useCocoapods;
if (_project.usesSwiftPackageManager) {
useCocoapods = _usingCocoaPodsPlugin(
pluginCount: totalCount,
swiftPackageCount: swiftPackageCount,
cocoapodCount: podCount,
);
} else {
// When Swift Package Manager is not enabled, set up Podfile if plugins
// is not empty, regardless of if plugins are CocoaPod compatible. This
// is done because `processPodsIfNeeded` uses `hasPlugins` to determine
// whether to run.
useCocoapods = _plugins.isNotEmpty;
}
if (useCocoapods) {
await _cocoapods.setupPodfile(xcodeProject);
}
/// The user may have a custom maintained Podfile that they're running `pod install`
/// on themselves.
else if (xcodeProject.podfile.existsSync() && xcodeProject.podfileLock.existsSync()) {
_cocoapods.addPodsDependencyToFlutterXcconfig(xcodeProject);
}
}
bool _usingCocoaPodsPlugin({
required int pluginCount,
required int swiftPackageCount,
required int cocoapodCount,
}) {
if (_project.usesSwiftPackageManager) {
if (pluginCount == swiftPackageCount) {
return false;
}
}
return cocoapodCount > 0;
}
/// Returns count of total number of plugins, number of Swift Package Manager
/// compatible plugins, and number of CocoaPods compatible plugins. A plugin
/// can be both Swift Package Manager and CocoaPods compatible.
///
/// Prints warnings when using a plugin incompatible with the available Darwin
/// Dependency Manager (Swift Package Manager or CocoaPods).
///
/// Prints message prompting the user to deintegrate CocoaPods if using all
/// Swift Package plugins.
Future<({int totalCount, int swiftPackageCount, int podCount})> _evaluatePluginsAndPrintWarnings({
required SupportedPlatform platform,
required XcodeBasedProject xcodeProject,
}) async {
int pluginCount = 0;
int swiftPackageCount = 0;
int cocoapodCount = 0;
for (final Plugin plugin in _plugins) {
if (plugin.platforms[platform.name] == null) {
continue;
}
final String? swiftPackagePath = plugin.pluginSwiftPackageManifestPath(
_fileSystem,
platform.name,
);
final bool swiftPackageManagerCompatible = swiftPackagePath != null &&
_fileSystem.file(swiftPackagePath).existsSync();
final String? podspecPath = plugin.pluginPodspecPath(
_fileSystem,
platform.name,
);
final bool cocoaPodsCompatible =
podspecPath != null && _fileSystem.file(podspecPath).existsSync();
// If a plugin is missing both a Package.swift and Podspec, it won't be
// included by either Swift Package Manager or Cocoapods. This can happen
// when a plugin doesn't have native platform code.
// For example, image_picker_macos only uses dart code.
if (!swiftPackageManagerCompatible && !cocoaPodsCompatible) {
continue;
}
pluginCount += 1;
if (swiftPackageManagerCompatible) {
swiftPackageCount += 1;
}
if (cocoaPodsCompatible) {
cocoapodCount += 1;
}
// If not using Swift Package Manager and plugin does not have podspec
// but does have a Package.swift, throw an error. Otherwise, it'll error
// when it builds.
if (!_project.usesSwiftPackageManager &&
!cocoaPodsCompatible &&
swiftPackageManagerCompatible) {
throwToolExit(
'Plugin ${plugin.name} is only Swift Package Manager compatible. Try '
'enabling Swift Package Manager by running '
'"flutter config --enable-swift-package-manager" or remove the '
'plugin as a dependency.');
}
}
// Only show warnings to remove CocoaPods if the project is using Swift
// Package Manager, has already been migrated to have SPM integration, and
// all plugins are Swift Packages.
if (_project.usesSwiftPackageManager &&
xcodeProject.flutterPluginSwiftPackageInProjectSettings &&
pluginCount == swiftPackageCount &&
swiftPackageCount != 0) {
final bool podfileExists = xcodeProject.podfile.existsSync();
if (podfileExists) {
// If all plugins are Swift Packages and the Podfile matches the
// default template, recommend pod deintegration.
final File podfileTemplate = await _cocoapods.getPodfileTemplate(
xcodeProject,
xcodeProject.xcodeProject,
);
final String configWarning = '${_podIncludeInConfigWarning(xcodeProject, 'Debug')}'
'${_podIncludeInConfigWarning(xcodeProject, 'Release')}';
if (xcodeProject.podfile.readAsStringSync() ==
podfileTemplate.readAsStringSync()) {
_logger.printWarning(
'All plugins found for ${platform.name} are Swift Packages, but your '
'project still has CocoaPods integration. To remove CocoaPods '
'integration, complete the following steps:\n'
' * In the ${platform.name}/ directory run "pod deintegrate"\n'
' * Also in the ${platform.name}/ directory, delete the Podfile\n'
'$configWarning\n'
"Removing CocoaPods integration will improve the project's build time.");
} else {
// If all plugins are Swift Packages, but the Podfile has custom logic,
// recommend migrating manually.
_logger.printWarning(
'All plugins found for ${platform.name} are Swift Packages, but your '
'project still has CocoaPods integration. Your project uses a '
'non-standard Podfile and will need to be migrated to Swift Package '
'Manager manually. Some steps you may need to complete include:\n'
' * In the ${platform.name}/ directory run "pod deintegrate"\n'
' * Transition any Pod dependencies to Swift Package equivalents. '
'See https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app\n'
' * Transition any custom logic\n'
'$configWarning\n'
"Removing CocoaPods integration will improve the project's build time.");
}
}
}
return (
totalCount: pluginCount,
swiftPackageCount: swiftPackageCount,
podCount: cocoapodCount,
);
}
String _podIncludeInConfigWarning(XcodeBasedProject xcodeProject, String mode) {
final File xcconfigFile = xcodeProject.xcodeConfigFor(mode);
final bool configIncludesPods = _cocoapods.xcconfigIncludesPods(xcconfigFile);
if (configIncludesPods) {
return ' * Remove the include to '
'"${_cocoapods.includePodsXcconfig(mode)}" in your '
'${xcconfigFile.parent.parent.basename}/${xcconfigFile.parent.basename}/${xcconfigFile.basename}\n';
}
return '';
}
}

View File

@@ -0,0 +1,196 @@
// 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/template.dart';
import '../base/version.dart';
import '../plugins.dart';
import '../project.dart';
import 'swift_packages.dart';
/// Swift Package Manager is a dependency management solution for iOS and macOS
/// applications.
///
/// See also:
/// * https://www.swift.org/documentation/package-manager/ - documentation on
/// Swift Package Manager.
/// * https://developer.apple.com/documentation/packagedescription/package -
/// documentation on Swift Package Manager manifest file, Package.swift.
class SwiftPackageManager {
const SwiftPackageManager({
required FileSystem fileSystem,
required TemplateRenderer templateRenderer,
}) : _fileSystem = fileSystem,
_templateRenderer = templateRenderer;
final FileSystem _fileSystem;
final TemplateRenderer _templateRenderer;
static const String _defaultFlutterPluginsSwiftPackageName = 'FlutterGeneratedPluginSwiftPackage';
static final SwiftPackageSupportedPlatform _iosSwiftPackageSupportedPlatform = SwiftPackageSupportedPlatform(
platform: SwiftPackagePlatform.ios,
version: Version(12, 0, null),
);
static final SwiftPackageSupportedPlatform _macosSwiftPackageSupportedPlatform = SwiftPackageSupportedPlatform(
platform: SwiftPackagePlatform.macos,
version: Version(10, 14, null),
);
/// Creates a Swift Package called 'FlutterGeneratedPluginSwiftPackage' that
/// has dependencies on Flutter plugins that are compatible with Swift
/// Package Manager.
Future<void> generatePluginsSwiftPackage(
List<Plugin> plugins,
SupportedPlatform platform,
XcodeBasedProject project,
) async {
_validatePlatform(platform);
final (
List<SwiftPackagePackageDependency> packageDependencies,
List<SwiftPackageTargetDependency> targetDependencies
) = _dependenciesForPlugins(plugins, platform);
// If there aren't any Swift Package plugins and the project hasn't been
// migrated yet, don't generate a Swift package or migrate the app since
// it's not needed. If the project has already been migrated, regenerate
// the Package.swift even if there are no dependencies in case there
// were dependencies previously.
if (packageDependencies.isEmpty && !project.flutterPluginSwiftPackageInProjectSettings) {
return;
}
final SwiftPackageSupportedPlatform swiftSupportedPlatform;
if (platform == SupportedPlatform.ios) {
swiftSupportedPlatform = _iosSwiftPackageSupportedPlatform;
} else {
swiftSupportedPlatform = _macosSwiftPackageSupportedPlatform;
}
// FlutterGeneratedPluginSwiftPackage must be statically linked to ensure
// any dynamic dependencies are linked to Runner and prevent undefined symbols.
final SwiftPackageProduct generatedProduct = SwiftPackageProduct(
name: _defaultFlutterPluginsSwiftPackageName,
targets: <String>[_defaultFlutterPluginsSwiftPackageName],
libraryType: SwiftPackageLibraryType.static,
);
final SwiftPackageTarget generatedTarget = SwiftPackageTarget.defaultTarget(
name: _defaultFlutterPluginsSwiftPackageName,
dependencies: targetDependencies,
);
final SwiftPackage pluginsPackage = SwiftPackage(
manifest: project.flutterPluginSwiftPackageManifest,
name: _defaultFlutterPluginsSwiftPackageName,
platforms: <SwiftPackageSupportedPlatform>[swiftSupportedPlatform],
products: <SwiftPackageProduct>[generatedProduct],
dependencies: packageDependencies,
targets: <SwiftPackageTarget>[generatedTarget],
templateRenderer: _templateRenderer,
);
pluginsPackage.createSwiftPackage();
}
(List<SwiftPackagePackageDependency>, List<SwiftPackageTargetDependency>) _dependenciesForPlugins(
List<Plugin> plugins,
SupportedPlatform platform,
) {
final List<SwiftPackagePackageDependency> packageDependencies =
<SwiftPackagePackageDependency>[];
final List<SwiftPackageTargetDependency> targetDependencies =
<SwiftPackageTargetDependency>[];
for (final Plugin plugin in plugins) {
final String? pluginSwiftPackageManifestPath = plugin.pluginSwiftPackageManifestPath(
_fileSystem,
platform.name,
);
if (plugin.platforms[platform.name] == null ||
pluginSwiftPackageManifestPath == null ||
!_fileSystem.file(pluginSwiftPackageManifestPath).existsSync()) {
continue;
}
packageDependencies.add(SwiftPackagePackageDependency(
name: plugin.name,
path: _fileSystem.file(pluginSwiftPackageManifestPath).parent.path,
));
// The target dependency product name is hyphen separated because it's
// the dependency's library name, which Swift Package Manager will
// automatically use as the CFBundleIdentifier if linked dynamically. The
// CFBundleIdentifier cannot contain underscores.
targetDependencies.add(SwiftPackageTargetDependency.product(
name: plugin.name.replaceAll('_', '-'),
packageName: plugin.name,
));
}
return (packageDependencies, targetDependencies);
}
/// Validates the platform is either iOS or macOS, otherwise throw an error.
static void _validatePlatform(SupportedPlatform platform) {
if (platform != SupportedPlatform.ios &&
platform != SupportedPlatform.macos) {
throwToolExit(
'The platform ${platform.name} is not compatible with Swift Package Manager. '
'Only iOS and macOS are allowed.',
);
}
}
/// If the project's IPHONEOS_DEPLOYMENT_TARGET/MACOSX_DEPLOYMENT_TARGET is
/// higher than the FlutterGeneratedPluginSwiftPackage's default
/// SupportedPlatform, increase the SupportedPlatform to match the project's
/// deployment target.
///
/// This is done for the use case of a plugin requiring a higher iOS/macOS
/// version than FlutterGeneratedPluginSwiftPackage.
///
/// Swift Package Manager emits an error if a dependency isn’t compatible
/// with the top-level package’s deployment version. The deployment target of
/// a package’s dependencies must be lower than or equal to the top-level
/// package’s deployment target version for a particular platform.
///
/// To still be able to use the plugin, the user can increase the Xcode
/// project's iOS/macOS deployment target and this will then increase the
/// deployment target for FlutterGeneratedPluginSwiftPackage.
static void updateMinimumDeployment({
required XcodeBasedProject project,
required SupportedPlatform platform,
required String deploymentTarget,
}) {
final Version? projectDeploymentTargetVersion = Version.parse(deploymentTarget);
final SwiftPackageSupportedPlatform defaultPlatform;
final SwiftPackagePlatform packagePlatform;
if (platform == SupportedPlatform.ios) {
defaultPlatform = _iosSwiftPackageSupportedPlatform;
packagePlatform = SwiftPackagePlatform.ios;
} else {
defaultPlatform = _macosSwiftPackageSupportedPlatform;
packagePlatform = SwiftPackagePlatform.macos;
}
if (projectDeploymentTargetVersion == null ||
projectDeploymentTargetVersion <= defaultPlatform.version ||
!project.flutterPluginSwiftPackageManifest.existsSync()) {
return;
}
final String manifestContents = project.flutterPluginSwiftPackageManifest.readAsStringSync();
final String oldSupportedPlatform = defaultPlatform.format();
final String newSupportedPlatform = SwiftPackageSupportedPlatform(
platform: packagePlatform,
version: projectDeploymentTargetVersion,
).format();
project.flutterPluginSwiftPackageManifest.writeAsStringSync(
manifestContents.replaceFirst(oldSupportedPlatform, newSupportedPlatform),
);
}
}

View File

@@ -0,0 +1,403 @@
// 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/template.dart';
import '../base/version.dart';
/// Swift toolchain version included with Xcode 15.0.
const String minimumSwiftToolchainVersion = '5.9';
const String _swiftPackageTemplate = '''
// swift-tools-version: {{swiftToolsVersion}}
// The swift-tools-version declares the minimum version of Swift required to build this package.
//
// Generated file. Do not edit.
//
import PackageDescription
let package = Package(
name: "{{packageName}}",
{{#platforms}}
platforms: [
{{platforms}}
],
{{/platforms}}
products: [
{{products}}
],
dependencies: [
{{dependencies}}
],
targets: [
{{targets}}
]
)
''';
const String _swiftPackageSourceTemplate = '''
//
// Generated file. Do not edit.
//
''';
const String _singleIndent = ' ';
const String _doubleIndent = '$_singleIndent$_singleIndent';
/// A Swift Package is reusable code that can be shared across projects and
/// with other developers in iOS and macOS applications. A Swift Package
/// requires a Package.swift. This class handles the formatting and creation of
/// a Package.swift.
///
/// See https://developer.apple.com/documentation/packagedescription/package
/// for more information about Swift Packages and Package.swift.
class SwiftPackage {
SwiftPackage({
required File manifest,
required String name,
required List<SwiftPackageSupportedPlatform> platforms,
required List<SwiftPackageProduct> products,
required List<SwiftPackagePackageDependency> dependencies,
required List<SwiftPackageTarget> targets,
required TemplateRenderer templateRenderer,
}) : _manifest = manifest,
_name = name,
_platforms = platforms,
_products = products,
_dependencies = dependencies,
_targets = targets,
_templateRenderer = templateRenderer;
/// [File] for Package.swift.
final File _manifest;
/// The name of the Swift package.
final String _name;
/// The list of minimum versions for platforms supported by the package.
final List<SwiftPackageSupportedPlatform> _platforms;
/// The list of products that this package vends and that clients can use.
final List<SwiftPackageProduct> _products;
/// The list of package dependencies.
final List<SwiftPackagePackageDependency> _dependencies;
/// The list of targets that are part of this package.
final List<SwiftPackageTarget> _targets;
final TemplateRenderer _templateRenderer;
/// Context for the [_swiftPackageTemplate] template.
Map<String, Object> get _templateContext {
return <String, Object>{
'swiftToolsVersion': minimumSwiftToolchainVersion,
'packageName': _name,
// Supported platforms can't be empty, so only include if not null.
'platforms': _formatPlatforms() ?? false,
'products': _formatProducts(),
'dependencies': _formatDependencies(),
'targets': _formatTargets(),
};
}
/// Create a Package.swift using settings from [_templateContext].
void createSwiftPackage() {
// Swift Packages require at least one source file per non-binary target,
// whether it be in Swift or Objective C. If the target does not have any
// files yet, create an empty Swift file.
for (final SwiftPackageTarget target in _targets) {
if (target.targetType == SwiftPackageTargetType.binaryTarget) {
continue;
}
final Directory targetDirectory = _manifest.parent
.childDirectory('Sources')
.childDirectory(target.name);
if (!targetDirectory.existsSync() || targetDirectory.listSync().isEmpty) {
final File requiredSwiftFile = targetDirectory.childFile(
'${target.name}.swift',
);
requiredSwiftFile.createSync(recursive: true);
requiredSwiftFile.writeAsStringSync(_swiftPackageSourceTemplate);
}
}
final String renderedTemplate = _templateRenderer.renderString(
_swiftPackageTemplate,
_templateContext,
);
_manifest.createSync(recursive: true);
_manifest.writeAsStringSync(renderedTemplate);
}
String? _formatPlatforms() {
if (_platforms.isEmpty) {
return null;
}
final List<String> platformStrings = _platforms
.map((SwiftPackageSupportedPlatform platform) => platform.format())
.toList();
return platformStrings.join(',\n$_doubleIndent');
}
String _formatProducts() {
if (_products.isEmpty) {
return '';
}
final List<String> libraries = _products
.map((SwiftPackageProduct product) => product.format())
.toList();
return libraries.join(',\n$_doubleIndent');
}
String _formatDependencies() {
if (_dependencies.isEmpty) {
return '';
}
final List<String> packages = _dependencies
.map((SwiftPackagePackageDependency dependency) => dependency.format())
.toList();
return packages.join(',\n$_doubleIndent');
}
String _formatTargets() {
if (_targets.isEmpty) {
return '';
}
final List<String> targetList =
_targets.map((SwiftPackageTarget target) => target.format()).toList();
return targetList.join(',\n$_doubleIndent');
}
}
enum SwiftPackagePlatform {
ios(name: '.iOS'),
macos(name: '.macOS'),
tvos(name: '.tvOS'),
watchos(name: '.watchOS');
const SwiftPackagePlatform({required this.name});
final String name;
}
/// A platform that the Swift package supports.
///
/// Representation of SupportedPlatform from
/// https://developer.apple.com/documentation/packagedescription/supportedplatform.
class SwiftPackageSupportedPlatform {
SwiftPackageSupportedPlatform({
required this.platform,
required this.version,
});
final SwiftPackagePlatform platform;
final Version version;
String format() {
// platforms: [
// .macOS("10.14"),
// .iOS("12.0"),
// ],
return '${platform.name}("$version")';
}
}
/// Types of library linking.
///
/// Representation of Product.Library.LibraryType from
/// https://developer.apple.com/documentation/packagedescription/product/library/librarytype.
enum SwiftPackageLibraryType {
dynamic(name: '.dynamic'),
static(name: '.static');
const SwiftPackageLibraryType({required this.name});
final String name;
}
/// An externally visible build artifact that's available to clients of the
/// package.
///
/// Representation of Product from
/// https://developer.apple.com/documentation/packagedescription/product.
class SwiftPackageProduct {
SwiftPackageProduct({
required this.name,
required this.targets,
this.libraryType,
});
final String name;
final SwiftPackageLibraryType? libraryType;
final List<String> targets;
String format() {
// products: [
// .library(name: "FlutterGeneratedPluginSwiftPackage", targets: ["FlutterGeneratedPluginSwiftPackage"]),
// .library(name: "FlutterDependenciesPackage", type: .dynamic, targets: ["FlutterDependenciesPackage"]),
// ],
String targetsString = '';
if (targets.isNotEmpty) {
final List<String> quotedTargets =
targets.map((String target) => '"$target"').toList();
targetsString = ', targets: [${quotedTargets.join(', ')}]';
}
String libraryTypeString = '';
if (libraryType != null) {
libraryTypeString = ', type: ${libraryType!.name}';
}
return '.library(name: "$name"$libraryTypeString$targetsString)';
}
}
/// A package dependency of a Swift package.
///
/// Representation of Package.Dependency from
/// https://developer.apple.com/documentation/packagedescription/package/dependency.
class SwiftPackagePackageDependency {
SwiftPackagePackageDependency({
required this.name,
required this.path,
});
final String name;
final String path;
String format() {
// dependencies: [
// .package(name: "image_picker_ios", path: "/path/to/packages/image_picker/image_picker_ios/ios/image_picker_ios"),
// ],
return '.package(name: "$name", path: "$path")';
}
}
/// Type of Target constructor.
///
/// See https://developer.apple.com/documentation/packagedescription/target for
/// more information.
enum SwiftPackageTargetType {
target(name: '.target'),
binaryTarget(name: '.binaryTarget');
const SwiftPackageTargetType({required this.name});
final String name;
}
/// A building block of a Swift Package that contains a set of source files
/// that Swift Package Manager compiles into a module.
///
/// Representation of Target from
/// https://developer.apple.com/documentation/packagedescription/target.
class SwiftPackageTarget {
SwiftPackageTarget.defaultTarget({
required this.name,
this.dependencies,
}) : path = null,
targetType = SwiftPackageTargetType.target;
SwiftPackageTarget.binaryTarget({
required this.name,
required String relativePath,
}) : path = relativePath,
dependencies = null,
targetType = SwiftPackageTargetType.binaryTarget;
final String name;
final String? path;
final List<SwiftPackageTargetDependency>? dependencies;
final SwiftPackageTargetType targetType;
String format() {
// targets: [
// .binaryTarget(
// name: "Flutter",
// path: "Flutter.xcframework"
// ),
// .target(
// name: "FlutterGeneratedPluginSwiftPackage",
// dependencies: [
// .target(name: "Flutter"),
// .product(name: "image_picker_ios", package: "image_picker_ios")
// ]
// ),
// ]
const String targetIndent = _doubleIndent;
const String targetDetailsIndent = '$_doubleIndent$_singleIndent';
final List<String> targetDetails = <String>[];
final String nameString = 'name: "$name"';
targetDetails.add(nameString);
if (path != null) {
final String pathString = 'path: "$path"';
targetDetails.add(pathString);
}
if (dependencies != null && dependencies!.isNotEmpty) {
final List<String> targetDependencies = dependencies!
.map((SwiftPackageTargetDependency dependency) => dependency.format())
.toList();
final String dependenciesString = '''
dependencies: [
${targetDependencies.join(",\n")}
$targetDetailsIndent]''';
targetDetails.add(dependenciesString);
}
return '''
${targetType.name}(
$targetDetailsIndent${targetDetails.join(",\n$targetDetailsIndent")}
$targetIndent)''';
}
}
/// Type of Target.Dependency constructor.
///
/// See https://developer.apple.com/documentation/packagedescription/target/dependency
/// for more information.
enum SwiftPackageTargetDependencyType {
product(name: '.product'),
target(name: '.target');
const SwiftPackageTargetDependencyType({required this.name});
final String name;
}
/// A dependency for the Target on a product from a package dependency or from
/// another Target in the same package.
///
/// Representation of Target.Dependency from
/// https://developer.apple.com/documentation/packagedescription/target/dependency.
class SwiftPackageTargetDependency {
SwiftPackageTargetDependency.product({
required this.name,
required String packageName,
}) : package = packageName,
dependencyType = SwiftPackageTargetDependencyType.product;
SwiftPackageTargetDependency.target({
required this.name,
}) : package = null,
dependencyType = SwiftPackageTargetDependencyType.target;
final String name;
final String? package;
final SwiftPackageTargetDependencyType dependencyType;
String format() {
// dependencies: [
// .target(name: "Flutter"),
// .product(name: "image_picker_ios", package: "image_picker_ios")
// ]
if (dependencyType == SwiftPackageTargetDependencyType.product) {
return '$_doubleIndent$_doubleIndent${dependencyType.name}(name: "$name", package: "$package")';
}
return '$_doubleIndent$_doubleIndent${dependencyType.name}(name: "$name")';
}
}

View File

@@ -397,6 +397,51 @@ class Plugin {
/// Whether this plugin is a direct dependency of the app.
/// If [false], the plugin is a dependency of another plugin.
final bool isDirectDependency;
/// Expected path to the plugin's Package.swift. Returns null if the plugin
/// does not support the [platform] or the [platform] is not iOS or macOS.
String? pluginSwiftPackageManifestPath(
FileSystem fileSystem,
String platform,
) {
final String? platformDirectoryName = _darwinPluginDirectoryName(platform);
if (platformDirectoryName == null) {
return null;
}
return fileSystem.path.join(
path,
platformDirectoryName,
name,
'Package.swift',
);
}
/// Expected path to the plugin's podspec. Returns null if the plugin does
/// not support the [platform] or the [platform] is not iOS or macOS.
String? pluginPodspecPath(FileSystem fileSystem, String platform) {
final String? platformDirectoryName = _darwinPluginDirectoryName(platform);
if (platformDirectoryName == null) {
return null;
}
return fileSystem.path.join(path, platformDirectoryName, '$name.podspec');
}
String? _darwinPluginDirectoryName(String platform) {
final PluginPlatform? platformPlugin = platforms[platform];
if (platformPlugin == null ||
(platform != IOSPlugin.kConfigKey &&
platform != MacOSPlugin.kConfigKey)) {
return null;
}
// iOS and macOS code can be shared in "darwin" directory, otherwise
// respectively in "ios" or "macos" directories.
if (platformPlugin is DarwinPlugin &&
(platformPlugin as DarwinPlugin).sharedDarwinSource) {
return 'darwin';
}
return platform;
}
}
/// Metadata associated with the resolution of a platform interface of a plugin.

View File

@@ -21,6 +21,7 @@ import 'features.dart';
import 'flutter_manifest.dart';
import 'flutter_plugins.dart';
import 'globals.dart' as globals;
import 'macos/xcode.dart';
import 'platform_plugins.dart';
import 'project_validator_result.dart';
import 'template.dart';
@@ -31,14 +32,20 @@ export 'xcode_project.dart';
/// Enum for each officially supported platform.
enum SupportedPlatform {
android,
ios,
linux,
macos,
web,
windows,
fuchsia,
root, // Special platform to represent the root project directory
android(name: 'android'),
ios(name: 'ios'),
linux(name: 'linux'),
macos(name: 'macos'),
web(name: 'web'),
windows(name: 'windows'),
fuchsia(name: 'fuchsia'),
root(name: 'root'); // Special platform to represent the root project directory
const SupportedPlatform({
required this.name,
});
final String name;
}
class FlutterProjectFactory {
@@ -261,6 +268,24 @@ class FlutterProject {
/// True if this project has an example application.
bool get hasExampleApp => _exampleDirectory(directory).existsSync();
/// True if this project doesn't have Swift Package Manager disabled in the
/// pubspec, has either an iOS or macOS platform implementation, is not a
/// module project, Xcode is 15 or greater, and the Swift Package Manager
/// feature is enabled.
bool get usesSwiftPackageManager {
if (!manifest.disabledSwiftPackageManager &&
(ios.existsSync() || macos.existsSync()) &&
!isModule) {
final Xcode? xcode = globals.xcode;
final Version? xcodeVersion = xcode?.currentVersion;
if (xcodeVersion == null || xcodeVersion.major < 15) {
return false;
}
return featureFlags.isSwiftPackageManagerEnabled;
}
return false;
}
/// Returns a list of platform names that are supported by the project.
List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) {
final List<SupportedPlatform> platforms = includeRoot ? <SupportedPlatform>[SupportedPlatform.root] : <SupportedPlatform>[];

View File

@@ -115,6 +115,46 @@ abstract class XcodeBasedProject extends FlutterProjectPlatform {
.childDirectory('Pods')
.childDirectory('Target Support Files')
.childDirectory('Pods-Runner');
/// 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 => hostAppRoot.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 Flutter generated directory for the Swift Package handling plugin
/// dependencies.
Directory get flutterPluginSwiftPackageDirectory => ephemeralDirectory
.childDirectory('Packages')
.childDirectory('FlutterGeneratedPluginSwiftPackage');
/// The Flutter generated Swift Package manifest (Package.swift) for plugin
/// dependencies.
File get flutterPluginSwiftPackageManifest =>
flutterPluginSwiftPackageDirectory.childFile('Package.swift');
/// Checks if FlutterGeneratedPluginSwiftPackage has been added to the
/// project's build settings by checking the contents of the pbxproj.
bool get flutterPluginSwiftPackageInProjectSettings {
return xcodeProjectInfoFile.existsSync() &&
xcodeProjectInfoFile
.readAsStringSync()
.contains('FlutterGeneratedPluginSwiftPackage');
}
Future<XcodeProjectInfo?> projectInfo() async {
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (!xcodeProject.existsSync() || xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) {
return null;
}
return _projectInfo ??= await xcodeProjectInterpreter.getInfo(hostAppRoot.path);
}
XcodeProjectInfo? _projectInfo;
}
/// Represents the iOS sub-project of a Flutter project.
@@ -167,16 +207,16 @@ class IosProject extends XcodeBasedProject {
/// Whether the Flutter application has an iOS project.
bool get exists => hostAppRoot.existsSync();
/// Put generated files here.
Directory get ephemeralDirectory => _flutterLibRoot.childDirectory('Flutter').childDirectory('ephemeral');
@override
Directory get managedDirectory => _flutterLibRoot.childDirectory('Flutter');
@override
File xcodeConfigFor(String mode) => _flutterLibRoot.childDirectory('Flutter').childFile('$mode.xcconfig');
File xcodeConfigFor(String mode) => managedDirectory.childFile('$mode.xcconfig');
@override
File get generatedEnvironmentVariableExportScript => _flutterLibRoot.childDirectory('Flutter').childFile('flutter_export_environment.sh');
File get generatedEnvironmentVariableExportScript => managedDirectory.childFile('flutter_export_environment.sh');
File get appFrameworkInfoPlist => _flutterLibRoot.childDirectory('Flutter').childFile('AppFrameworkInfo.plist');
File get appFrameworkInfoPlist => managedDirectory.childFile('AppFrameworkInfo.plist');
/// The 'AppDelegate.swift' file of the host app. This file might not exist if the app project uses Objective-C.
File get appDelegateSwift => _editableDirectory.childDirectory('Runner').childFile('AppDelegate.swift');
@@ -444,15 +484,6 @@ class IosProject extends XcodeBasedProject {
final Map<XcodeProjectBuildContext, Map<String, String>> _buildSettingsByBuildContext = <XcodeProjectBuildContext, Map<String, String>>{};
Future<XcodeProjectInfo?> projectInfo() async {
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (!xcodeProject.existsSync() || xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) {
return null;
}
return _projectInfo ??= await xcodeProjectInterpreter.getInfo(hostAppRoot.path);
}
XcodeProjectInfo? _projectInfo;
Future<Map<String, String>?> _xcodeProjectBuildSettings(XcodeProjectBuildContext buildContext) async {
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) {
@@ -692,16 +723,6 @@ class MacOSProject extends XcodeBasedProject {
@override
Directory get hostAppRoot => parent.directory.childDirectory('macos');
/// 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 => hostAppRoot.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 xcfilelist used to track the inputs for the Flutter script phase in
/// the Xcode build.
File get inputFileList => ephemeralDirectory.childFile('FlutterInputs.xcfilelist');