From 04657354f5cb483a58d0d9fbeaa1c444c10ccc36 Mon Sep 17 00:00:00 2001 From: Jenn Magder Date: Thu, 22 Oct 2020 13:32:51 -0700 Subject: [PATCH] Build IPA command (#67781) * Build IPA command * xcarchive -> ipa --- .../lib/src/application_package.dart | 7 + .../lib/src/commands/build_ios.dart | 125 ++++++++++++++++-- packages/flutter_tools/lib/src/ios/mac.dart | 2 +- ...carchive_test.dart => build_ipa_test.dart} | 115 ++++++++++++++-- 4 files changed, 226 insertions(+), 23 deletions(-) rename packages/flutter_tools/test/commands.shard/hermetic/{build_xcarchive_test.dart => build_ipa_test.dart} (67%) diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart index 2423edfa6b..4c8d0858e7 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart @@ -385,6 +385,13 @@ class BuildableIOSApp extends IOSApp { String get archiveBundlePath => globals.fs.path.join(getIosBuildDirectory(), 'archive', globals.fs.path.withoutExtension(_hostAppBundleName)); + // The output xcarchive bundle path `build/ios/archive/Runner.xcarchive`. + String get archiveBundleOutputPath => + globals.fs.path.setExtension(archiveBundlePath, '.xcarchive'); + + String get ipaOutputPath => + globals.fs.path.join(getIosBuildDirectory(), 'ipa'); + String _buildAppPath(String type) { return globals.fs.path.join(getIosBuildDirectory(), type, _hostAppBundleName); } diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart index 650e4afac4..f0f7004bb9 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios.dart @@ -8,17 +8,18 @@ import 'package:meta/meta.dart'; import '../application_package.dart'; import '../base/analyze_size.dart'; import '../base/common.dart'; +import '../base/logger.dart'; +import '../base/process.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../convert.dart'; import '../globals.dart' as globals; import '../ios/mac.dart'; -import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; +import '../runner/flutter_command.dart'; import 'build.dart'; /// Builds an .app for an iOS app to be used for local testing on an iOS device -/// or simulator. Can only be run on a macOS host. For producing deployment -/// .ipas, see https://flutter.dev/docs/deployment/ios. +/// or simulator. Can only be run on a macOS host. class BuildIOSCommand extends _BuildIOSSubCommand { BuildIOSCommand({ @required bool verboseHelp }) : super(verboseHelp: verboseHelp) { argParser @@ -56,14 +57,27 @@ class BuildIOSCommand extends _BuildIOSSubCommand { bool get shouldCodesign => boolArg('codesign'); } -/// Builds an .xcarchive for an iOS app to be generated for App Store submission. +/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for +/// App Store submission. +/// /// Can only be run on a macOS host. -/// For producing deployment .ipas, see https://flutter.dev/docs/deployment/ios. class BuildIOSArchiveCommand extends _BuildIOSSubCommand { - BuildIOSArchiveCommand({ @required bool verboseHelp }) : super(verboseHelp: verboseHelp); + BuildIOSArchiveCommand({@required bool verboseHelp}) + : super(verboseHelp: verboseHelp) { + argParser.addOption( + 'export-options-plist', + valueHelp: 'ExportOptions.plist', + // TODO(jmagman): Update help text with link to Flutter docs. + help: + 'Optionally export an IPA with these options. See "xcodebuild -h" for available exportOptionsPlist keys.', + ); + } @override - final String name = 'xcarchive'; + final String name = 'ipa'; + + @override + final List aliases = ['xcarchive']; @override final String description = 'Build an iOS archive bundle (Mac OS X host only).'; @@ -79,6 +93,76 @@ class BuildIOSArchiveCommand extends _BuildIOSSubCommand { @override final bool shouldCodesign = true; + + String get exportOptionsPlist => stringArg('export-options-plist'); + + @override + Future runCommand() async { + if (exportOptionsPlist != null) { + final FileSystemEntityType type = globals.fs.typeSync(exportOptionsPlist); + if (type == FileSystemEntityType.notFound) { + throwToolExit( + '"$exportOptionsPlist" property list does not exist. See "man xcodebuild" for available keys.'); + } else if (type != FileSystemEntityType.file) { + throwToolExit( + '"$exportOptionsPlist" is not a file. See "xcodebuild -h" for available keys.'); + } + } + final FlutterCommandResult xcarchiveResult = await super.runCommand(); + + if (exportOptionsPlist == null) { + return xcarchiveResult; + } + + // xcarchive failed or not at expected location. + if (xcarchiveResult.exitStatus != ExitStatus.success) { + globals.logger.printStatus('Skipping IPA'); + return xcarchiveResult; + } + + // Build IPA from generated xcarchive. + final BuildableIOSApp app = await buildableIOSApp; + Status status; + RunResult result; + final String outputPath = globals.fs.path.absolute(app.ipaOutputPath); + try { + status = globals.logger.startProgress('Building IPA...'); + + result = await globals.processUtils.run( + [ + ...globals.xcode.xcrunCommand(), + 'xcodebuild', + '-exportArchive', + '-archivePath', + globals.fs.path.absolute(app.archiveBundleOutputPath), + '-exportPath', + outputPath, + '-exportOptionsPlist', + globals.fs.path.absolute(exportOptionsPlist), + ], + ); + } finally { + status.stop(); + } + + if (result.exitCode != 0) { + final StringBuffer errorMessage = StringBuffer(); + + // "error:" prefixed lines are the nicely formatted error message, the + // rest is the same message but printed as a IDEFoundationErrorDomain. + // Example: + // error: exportArchive: exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd + // Error Domain=IDEFoundationErrorDomain Code=1 "exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd" ... + LineSplitter.split(result.stderr) + .where((String line) => line.contains('error: ')) + .forEach(errorMessage.writeln); + throwToolExit('Encountered error while building IPA:\n$errorMessage'); + } + + globals.logger.printStatus('Built IPA to $outputPath.'); + + return FlutterCommandResult.success(); + } } abstract class _BuildIOSSubCommand extends BuildSubCommand { @@ -111,10 +195,26 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand { bool get configOnly; bool get shouldCodesign; + BuildInfo get buildInfo { + _buildInfo ??= getBuildInfo(); + return _buildInfo; + } + + BuildInfo _buildInfo; + + Future get buildableIOSApp async { + _buildableIOSApp ??= await applicationPackages.getPackageForPlatform( + TargetPlatform.ios, + buildInfo: buildInfo, + ) as BuildableIOSApp; + return _buildableIOSApp; + } + + BuildableIOSApp _buildableIOSApp; + @override Future runCommand() async { defaultBuildMode = forSimulator ? BuildMode.debug : BuildMode.release; - final BuildInfo buildInfo = getBuildInfo(); if (!globals.platform.isMacOS) { throwToolExit('Building for iOS is only supported on macOS.'); @@ -132,10 +232,7 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand { ); } - final BuildableIOSApp app = await applicationPackages.getPackageForPlatform( - TargetPlatform.ios, - buildInfo: buildInfo, - ) as BuildableIOSApp; + final BuildableIOSApp app = await buildableIOSApp; if (app == null) { throwToolExit('Application not configured for iOS'); @@ -204,8 +301,10 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand { if (result.output != null) { globals.printStatus('Built ${result.output}.'); + + return FlutterCommandResult.success(); } - return FlutterCommandResult.success(); + return FlutterCommandResult.fail(); } } diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index b5154869dd..dc0a5f2e75 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -438,7 +438,7 @@ Future buildXcodeProject({ globals.printError('Build succeeded but the expected app at $expectedOutputDirectory not found'); } } else { - outputDir = '${globals.fs.path.absolute(app.archiveBundlePath)}.xcarchive'; + outputDir = globals.fs.path.absolute(app.archiveBundleOutputPath); if (!globals.fs.isDirectorySync(outputDir)) { globals.printError('Archive succeeded but the expected xcarchive at $outputDir not found'); } diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_xcarchive_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart similarity index 67% rename from packages/flutter_tools/test/commands.shard/hermetic/build_xcarchive_test.dart rename to packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart index 50a636c22f..0355ca50d5 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_xcarchive_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_ipa_test.dart @@ -4,6 +4,7 @@ import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; @@ -45,6 +46,7 @@ final Platform notMacosPlatform = FakePlatform( void main() { FileSystem fileSystem; Usage usage; + BufferLogger logger; setUpAll(() { Cache.disableLocking(); @@ -53,6 +55,7 @@ void main() { setUp(() { fileSystem = MemoryFileSystem.test(); usage = Usage.test(); + logger = BufferLogger.test(); }); // Sets up the minimal mock project files necessary to look like a Flutter project. @@ -110,12 +113,26 @@ void main() { ); } - testUsingContext('xcarchive build fails when there is no ios project', () async { + const FakeCommand exportArchiveCommand = FakeCommand( + command: [ + 'xcrun', + 'xcodebuild', + '-exportArchive', + '-archivePath', + '/build/ios/archive/Runner.xcarchive', + '-exportPath', + '/build/ios/ipa', + '-exportOptionsPlist', + '/ExportOptions.plist' + ], + ); + + testUsingContext('ipa build fails when there is no ios project', () async { final BuildCommand command = BuildCommand(); createCoreMockProjectFiles(); expect(createTestCommandRunner(command).run( - const ['build', 'xcarchive', '--no-pub'] + const ['build', 'ipa', '--no-pub'] ), throwsToolExit(message: 'Application not configured for iOS')); }, overrides: { Platform: () => macosPlatform, @@ -124,7 +141,7 @@ void main() { XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); - testUsingContext('xcarchive build fails on non-macOS platform', () async { + testUsingContext('ipa build fails on non-macOS platform', () async { final BuildCommand command = BuildCommand(); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); @@ -132,7 +149,7 @@ void main() { .createSync(recursive: true); expect(createTestCommandRunner(command).run( - const ['build', 'xcarchive', '--no-pub'] + const ['build', 'ipa', '--no-pub'] ), throwsToolExit()); }, overrides: { Platform: () => notMacosPlatform, @@ -141,12 +158,58 @@ void main() { XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); - testUsingContext('xcarchive build invokes xcode build', () async { + testUsingContext('ipa build fails when export plist does not exist', + () async { + final BuildCommand command = BuildCommand(); + createMinimalMockProjectFiles(); + + await expectToolExitLater( + createTestCommandRunner(command).run([ + 'build', + 'ipa', + '--export-options-plist', + 'bogus.plist', + '--no-pub', + ]), + contains('property list does not exist'), + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + Platform: () => macosPlatform, + XcodeProjectInterpreter: () => + FakeXcodeProjectInterpreterWithBuildSettings(), + }); + + testUsingContext('ipa build fails when export plist is not a file', () async { + final Directory bogus = fileSystem.directory('bogus')..createSync(); + final BuildCommand command = BuildCommand(); + createMinimalMockProjectFiles(); + + await expectToolExitLater( + createTestCommandRunner(command).run([ + 'build', + 'ipa', + '--export-options-plist', + bogus.path, + '--no-pub', + ]), + contains('is not a file.'), + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + Platform: () => macosPlatform, + XcodeProjectInterpreter: () => + FakeXcodeProjectInterpreterWithBuildSettings(), + }); + + testUsingContext('ipa build invokes xcode build', () async { final BuildCommand command = BuildCommand(); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( - const ['build', 'xcarchive', '--no-pub'] + const ['build', 'ipa', '--no-pub'] ); }, overrides: { FileSystem: () => fileSystem, @@ -160,12 +223,12 @@ void main() { XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); - testUsingContext('xcarchive build invokes xcode build with verbosity', () async { + testUsingContext('ipa build invokes xcode build with verbosity', () async { final BuildCommand command = BuildCommand(); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( - const ['build', 'xcarchive', '--no-pub', '-v'] + const ['build', 'ipa', '--no-pub', '-v'] ); }, overrides: { FileSystem: () => fileSystem, @@ -190,7 +253,7 @@ void main() { // Capture Usage.test() events. final StringBuffer buffer = await capturedConsolePrint(() => createTestCommandRunner(command).run( - const ['build', 'xcarchive', '--no-pub', '--analyze-size'] + const ['build', 'ipa', '--no-pub', '--analyze-size'] ) ); @@ -224,4 +287,38 @@ void main() { Usage: () => usage, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); + + testUsingContext('ipa build invokes xcode build export archive', () async { + final String outputPath = + fileSystem.path.absolute(fileSystem.path.join('build', 'ios', 'ipa')); + final File exportOptions = fileSystem.file('ExportOptions.plist') + ..createSync(); + final BuildCommand command = BuildCommand(); + createMinimalMockProjectFiles(); + + await createTestCommandRunner(command).run( + [ + 'build', + 'ipa', + '--no-pub', + '--export-options-plist', + exportOptions.path, + ], + ); + + expect(logger.statusText, contains('Built IPA to $outputPath.')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.list([ + xattrCommand, + armCheckCommand, + setUpMockXcodeBuildHandler(), + setUpMockXcodeBuildHandler(showBuildSettings: true), + exportArchiveCommand, + ]), + Platform: () => macosPlatform, + Logger: () => logger, + XcodeProjectInterpreter: () => + FakeXcodeProjectInterpreterWithBuildSettings(), + }); }