1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'dart:typed_data';
6
7import 'package:crypto/crypto.dart';
8import 'package:meta/meta.dart';
9import 'package:unified_analytics/unified_analytics.dart';
10
11import '../base/analyze_size.dart';
12import '../base/common.dart';
13import '../base/error_handling_io.dart';
14import '../base/file_system.dart';
15import '../base/logger.dart';
16import '../base/process.dart';
17import '../base/terminal.dart';
18import '../base/utils.dart';
19import '../base/version.dart';
20import '../build_info.dart';
21import '../convert.dart';
22import '../darwin/darwin.dart';
23import '../doctor_validator.dart';
24import '../globals.dart' as globals;
25import '../ios/application_package.dart';
26import '../ios/mac.dart';
27import '../ios/plist_parser.dart';
28import '../runner/flutter_command.dart';
29import 'build.dart';
30
31/// Builds an .app for an iOS app to be used for local testing on an iOS device
32/// or simulator. Can only be run on a macOS host.
33class BuildIOSCommand extends _BuildIOSSubCommand {
34 BuildIOSCommand({required super.logger, required bool verboseHelp})
35 : super(verboseHelp: verboseHelp) {
36 addPublishPort(verboseHelp: verboseHelp);
37 argParser
38 ..addFlag(
39 'config-only',
40 help:
41 'Update the project configuration without performing a build. '
42 'This can be used in CI/CD process that create an archive to avoid '
43 'performing duplicate work.',
44 )
45 ..addFlag(
46 'simulator',
47 help:
48 'Build for the iOS simulator instead of the device. This changes '
49 'the default build mode to debug if otherwise unspecified.',
50 );
51 }
52
53 @override
54 final name = 'ios';
55
56 @override
57 final description = 'Build an iOS application bundle.';
58
59 @override
60 final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.build;
61
62 @override
63 EnvironmentType get environmentType =>
64 boolArg('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
65
66 @override
67 bool get configOnly => boolArg('config-only');
68
69 @override
70 Directory _outputAppDirectory(String xcodeResultOutput) =>
71 globals.fs.directory(xcodeResultOutput).parent;
72}
73
74/// The key that uniquely identifies an image file in an image asset.
75/// It consists of (idiom, scale, size?), where size is present for app icon
76/// asset, and null for launch image asset.
77@immutable
78class _ImageAssetFileKey {
79 const _ImageAssetFileKey(this.idiom, this.scale, this.size);
80
81 /// The idiom (iphone or ipad).
82 final String idiom;
83
84 /// The scale factor (e.g. 2).
85 final int scale;
86
87 /// The logical size in point (e.g. 83.5).
88 /// Size is present for app icon, and null for launch image.
89 final double? size;
90
91 @override
92 int get hashCode => Object.hash(idiom, scale, size);
93
94 @override
95 bool operator ==(Object other) =>
96 other is _ImageAssetFileKey &&
97 other.idiom == idiom &&
98 other.scale == scale &&
99 other.size == size;
100
101 /// The pixel size based on logical size and scale.
102 int? get pixelSize => size == null ? null : (size! * scale).toInt(); // pixel size must be an int.
103}
104
105/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for
106/// App Store submission.
107///
108/// Can only be run on a macOS host.
109class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
110 BuildIOSArchiveCommand({required super.logger, required super.verboseHelp}) {
111 argParser.addOption(
112 'export-method',
113 defaultsTo: 'app-store',
114 allowed: <String>['app-store', 'ad-hoc', 'development', 'enterprise'],
115 help: 'Specify how the IPA will be distributed.',
116 allowedHelp: <String, String>{
117 'app-store': 'Upload to the App Store.',
118 'ad-hoc':
119 'Test on designated devices that do not need to be registered with the Apple developer account. '
120 'Requires a distribution certificate.',
121 'development':
122 'Test only on development devices registered with the Apple developer account.',
123 'enterprise': 'Distribute an app registered with the Apple Developer Enterprise Program.',
124 },
125 );
126 argParser.addOption(
127 'export-options-plist',
128 valueHelp: 'ExportOptions.plist',
129 help:
130 'Export an IPA with these options. See "xcodebuild -h" for available exportOptionsPlist keys.',
131 );
132 }
133
134 @override
135 final name = 'ipa';
136
137 @override
138 final aliases = <String>['xcarchive'];
139
140 @override
141 final description = 'Build an iOS archive bundle and IPA for distribution.';
142
143 @override
144 final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.archive;
145
146 @override
147 final EnvironmentType environmentType = EnvironmentType.physical;
148
149 @override
150 final configOnly = false;
151
152 String? get exportOptionsPlist => stringArg('export-options-plist');
153
154 @override
155 Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs
156 .directory(xcodeResultOutput)
157 .childDirectory('Products')
158 .childDirectory('Applications');
159
160 @override
161 Future<void> validateCommand() async {
162 final String? exportOptions = exportOptionsPlist;
163 if (exportOptions != null) {
164 if (argResults?.wasParsed('export-method') ?? false) {
165 throwToolExit(
166 '"--export-options-plist" is not compatible with "--export-method". Either use "--export-options-plist" and '
167 'a plist describing how the IPA should be exported by Xcode, or use "--export-method" to create a new plist.\n'
168 'See "xcodebuild -h" for available exportOptionsPlist keys.',
169 );
170 }
171 final FileSystemEntityType type = globals.fs.typeSync(exportOptions);
172 if (type == FileSystemEntityType.notFound) {
173 throwToolExit('"$exportOptions" property list does not exist.');
174 } else if (type != FileSystemEntityType.file) {
175 throwToolExit('"$exportOptions" is not a file. See "xcodebuild -h" for available keys.');
176 }
177 }
178 return super.validateCommand();
179 }
180
181 // A helper function to parse Contents.json of an image asset into a map,
182 // with the key to be _ImageAssetFileKey, and value to be the image file name.
183 // Some assets have size (e.g. app icon) and others do not (e.g. launch image).
184 Map<_ImageAssetFileKey, String> _parseImageAssetContentsJson(
185 String contentsJsonDirName, {
186 required bool requiresSize,
187 }) {
188 final Directory contentsJsonDirectory = globals.fs.directory(contentsJsonDirName);
189 if (!contentsJsonDirectory.existsSync()) {
190 return <_ImageAssetFileKey, String>{};
191 }
192 final File contentsJsonFile = contentsJsonDirectory.childFile('Contents.json');
193 final Map<String, dynamic> contents =
194 json.decode(contentsJsonFile.readAsStringSync()) as Map<String, dynamic>? ??
195 <String, dynamic>{};
196 final List<dynamic> images = contents['images'] as List<dynamic>? ?? <dynamic>[];
197 final Map<String, dynamic> info =
198 contents['info'] as Map<String, dynamic>? ?? <String, dynamic>{};
199 if ((info['version'] as int?) != 1) {
200 // Skips validation for unknown format.
201 return <_ImageAssetFileKey, String>{};
202 }
203
204 final iconInfo = <_ImageAssetFileKey, String>{};
205 for (final dynamic image in images) {
206 final imageMap = image as Map<String, dynamic>;
207 final idiom = imageMap['idiom'] as String?;
208 final size = imageMap['size'] as String?;
209 final scale = imageMap['scale'] as String?;
210 final fileName = imageMap['filename'] as String?;
211
212 // requiresSize must match the actual presence of size in json.
213 if (requiresSize != (size != null) || idiom == null || scale == null || fileName == null) {
214 continue;
215 }
216
217 final double? parsedSize;
218 if (size != null) {
219 // for example, "64x64". Parse the width since it is a square.
220 final Iterable<double> parsedSizes = size
221 .split('x')
222 .map((String element) => double.tryParse(element))
223 .whereType<double>();
224 if (parsedSizes.isEmpty) {
225 continue;
226 }
227 parsedSize = parsedSizes.first;
228 } else {
229 parsedSize = null;
230 }
231
232 // for example, "3x".
233 final Iterable<int> parsedScales = scale
234 .split('x')
235 .map((String element) => int.tryParse(element))
236 .whereType<int>();
237 if (parsedScales.isEmpty) {
238 continue;
239 }
240 final int parsedScale = parsedScales.first;
241 iconInfo[_ImageAssetFileKey(idiom, parsedScale, parsedSize)] = fileName;
242 }
243 return iconInfo;
244 }
245
246 // A helper function to check if an image asset is still using template files.
247 bool _isAssetStillUsingTemplateFiles({
248 required Map<_ImageAssetFileKey, String> templateImageInfoMap,
249 required Map<_ImageAssetFileKey, String> projectImageInfoMap,
250 required String templateImageDirName,
251 required String projectImageDirName,
252 }) {
253 return projectImageInfoMap.entries.any((MapEntry<_ImageAssetFileKey, String> entry) {
254 final String projectFileName = entry.value;
255 final String? templateFileName = templateImageInfoMap[entry.key];
256 if (templateFileName == null) {
257 return false;
258 }
259 final File projectFile = globals.fs.file(
260 globals.fs.path.join(projectImageDirName, projectFileName),
261 );
262 final File templateFile = globals.fs.file(
263 globals.fs.path.join(templateImageDirName, templateFileName),
264 );
265
266 return projectFile.existsSync() &&
267 templateFile.existsSync() &&
268 md5.convert(projectFile.readAsBytesSync()) == md5.convert(templateFile.readAsBytesSync());
269 });
270 }
271
272 // A helper function to return a list of image files in an image asset with
273 // wrong sizes (as specified in its Contents.json file).
274 List<String> _imageFilesWithWrongSize({
275 required Map<_ImageAssetFileKey, String> imageInfoMap,
276 required String imageDirName,
277 }) {
278 return imageInfoMap.entries
279 .where((MapEntry<_ImageAssetFileKey, String> entry) {
280 final String fileName = entry.value;
281 final File imageFile = globals.fs.file(globals.fs.path.join(imageDirName, fileName));
282 if (!imageFile.existsSync()) {
283 return false;
284 }
285 // validate image size is correct.
286 // PNG file's width is at byte [16, 20), and height is at byte [20, 24), in big endian format.
287 // Based on https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_format
288 final ByteData imageData = imageFile.readAsBytesSync().buffer.asByteData();
289 if (imageData.lengthInBytes < 24) {
290 return false;
291 }
292 final int width = imageData.getInt32(16);
293 final int height = imageData.getInt32(20);
294 // The size must not be null.
295 final int expectedSize = entry.key.pixelSize!;
296 return width != expectedSize || height != expectedSize;
297 })
298 .map((MapEntry<_ImageAssetFileKey, String> entry) => entry.value)
299 .toList();
300 }
301
302 ValidationResult? _createValidationResult(String title, List<ValidationMessage> messages) {
303 if (messages.isEmpty) {
304 return null;
305 }
306 final bool anyInvalid = messages.any(
307 (ValidationMessage message) => message.type != ValidationMessageType.information,
308 );
309 return ValidationResult(
310 anyInvalid ? ValidationType.partial : ValidationType.success,
311 messages,
312 statusInfo: title,
313 );
314 }
315
316 ValidationMessage _createValidationMessage({required bool isValid, required String message}) {
317 // Use "information" type for valid message, and "hint" type for invalid message.
318 return isValid ? ValidationMessage(message) : ValidationMessage.hint(message);
319 }
320
321 Future<List<ValidationMessage>> _validateIconAssetsAfterArchive() async {
322 final BuildableIOSApp app = await buildableIOSApp;
323
324 final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
325 app.templateAppIconDirNameForContentsJson,
326 requiresSize: true,
327 );
328 final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
329 app.projectAppIconDirName,
330 requiresSize: true,
331 );
332
333 final validationMessages = <ValidationMessage>[];
334
335 final bool usesTemplate = _isAssetStillUsingTemplateFiles(
336 templateImageInfoMap: templateInfoMap,
337 projectImageInfoMap: projectInfoMap,
338 templateImageDirName: await app.templateAppIconDirNameForImages,
339 projectImageDirName: app.projectAppIconDirName,
340 );
341
342 if (usesTemplate) {
343 validationMessages.add(
344 _createValidationMessage(
345 isValid: false,
346 message: 'App icon is set to the default placeholder icon. Replace with unique icons.',
347 ),
348 );
349 }
350
351 final List<String> filesWithWrongSize = _imageFilesWithWrongSize(
352 imageInfoMap: projectInfoMap,
353 imageDirName: app.projectAppIconDirName,
354 );
355
356 if (filesWithWrongSize.isNotEmpty) {
357 validationMessages.add(
358 _createValidationMessage(
359 isValid: false,
360 message: 'App icon is using the incorrect size (e.g. ${filesWithWrongSize.first}).',
361 ),
362 );
363 }
364 return validationMessages;
365 }
366
367 Future<List<ValidationMessage>> _validateLaunchImageAssetsAfterArchive() async {
368 final BuildableIOSApp app = await buildableIOSApp;
369
370 final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
371 app.templateLaunchImageDirNameForContentsJson,
372 requiresSize: false,
373 );
374 final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
375 app.projectLaunchImageDirName,
376 requiresSize: false,
377 );
378
379 final validationMessages = <ValidationMessage>[];
380
381 final bool usesTemplate = _isAssetStillUsingTemplateFiles(
382 templateImageInfoMap: templateInfoMap,
383 projectImageInfoMap: projectInfoMap,
384 templateImageDirName: await app.templateLaunchImageDirNameForImages,
385 projectImageDirName: app.projectLaunchImageDirName,
386 );
387
388 if (usesTemplate) {
389 validationMessages.add(
390 _createValidationMessage(
391 isValid: false,
392 message:
393 'Launch image is set to the default placeholder icon. Replace with unique launch image.',
394 ),
395 );
396 }
397
398 return validationMessages;
399 }
400
401 Future<List<ValidationMessage>> _validateXcodeBuildSettingsAfterArchive() async {
402 final BuildableIOSApp app = await buildableIOSApp;
403
404 final String plistPath = app.builtInfoPlistPathAfterArchive;
405
406 if (!globals.fs.file(plistPath).existsSync()) {
407 globals.printError('Invalid iOS archive. Does not contain Info.plist.');
408 return <ValidationMessage>[];
409 }
410
411 final xcodeProjectSettingsMap = <String, String?>{};
412
413 xcodeProjectSettingsMap['Version Number'] = globals.plistParser.getValueFromFile<String>(
414 plistPath,
415 PlistParser.kCFBundleShortVersionStringKey,
416 );
417 xcodeProjectSettingsMap['Build Number'] = globals.plistParser.getValueFromFile<String>(
418 plistPath,
419 PlistParser.kCFBundleVersionKey,
420 );
421 xcodeProjectSettingsMap['Display Name'] =
422 globals.plistParser.getValueFromFile<String>(
423 plistPath,
424 PlistParser.kCFBundleDisplayNameKey,
425 ) ??
426 globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleNameKey);
427 xcodeProjectSettingsMap['Deployment Target'] = globals.plistParser.getValueFromFile<String>(
428 plistPath,
429 PlistParser.kMinimumOSVersionKey,
430 );
431 xcodeProjectSettingsMap['Bundle Identifier'] = globals.plistParser.getValueFromFile<String>(
432 plistPath,
433 PlistParser.kCFBundleIdentifierKey,
434 );
435
436 final List<ValidationMessage> validationMessages = xcodeProjectSettingsMap.entries.map((
437 MapEntry<String, String?> entry,
438 ) {
439 final String title = entry.key;
440 final String? info = entry.value;
441 return _createValidationMessage(
442 isValid: info != null,
443 message: '$title: ${info ?? "Missing"}',
444 );
445 }).toList();
446
447 final bool hasMissingSettings = xcodeProjectSettingsMap.values.any(
448 (String? element) => element == null,
449 );
450 if (hasMissingSettings) {
451 validationMessages.add(
452 _createValidationMessage(
453 isValid: false,
454 message: 'You must set up the missing app settings.',
455 ),
456 );
457 }
458
459 final bool usesDefaultBundleIdentifier =
460 xcodeProjectSettingsMap['Bundle Identifier']?.startsWith('com.example') ?? false;
461 if (usesDefaultBundleIdentifier) {
462 validationMessages.add(
463 _createValidationMessage(
464 isValid: false,
465 message: 'Your application still contains the default "com.example" bundle identifier.',
466 ),
467 );
468 }
469
470 return validationMessages;
471 }
472
473 @override
474 Future<FlutterCommandResult> runCommand() async {
475 final BuildInfo buildInfo = await cachedBuildInfo;
476 final FlutterCommandResult xcarchiveResult = await super.runCommand();
477
478 final validationResults = <ValidationResult?>[];
479 validationResults.add(
480 _createValidationResult(
481 'App Settings Validation',
482 await _validateXcodeBuildSettingsAfterArchive(),
483 ),
484 );
485 validationResults.add(
486 _createValidationResult(
487 'App Icon and Launch Image Assets Validation',
488 await _validateIconAssetsAfterArchive() + await _validateLaunchImageAssetsAfterArchive(),
489 ),
490 );
491
492 for (final ValidationResult result in validationResults.whereType<ValidationResult>()) {
493 globals.printStatus('\n${result.coloredLeadingBox} ${result.statusInfo}');
494 for (final ValidationMessage message in result.messages) {
495 globals.printStatus(
496 '${message.coloredIndicator} ${message.message}',
497 indent: result.leadingBox.length + 1,
498 );
499 }
500 }
501 globals.printStatus(
502 '\nTo update the settings, please refer to https://flutter.dev/to/ios-deploy\n',
503 );
504
505 // xcarchive failed or not at expected location.
506 if (xcarchiveResult.exitStatus != ExitStatus.success) {
507 globals.printStatus('Skipping IPA.');
508 return xcarchiveResult;
509 }
510
511 if (!shouldCodesign) {
512 globals.printStatus('Codesigning disabled with --no-codesign, skipping IPA.');
513 return xcarchiveResult;
514 }
515
516 // Build IPA from generated xcarchive.
517 final BuildableIOSApp app = await buildableIOSApp;
518 Status? status;
519 RunResult? result;
520 final String relativeOutputPath = app.ipaOutputPath;
521 final String absoluteOutputPath = globals.fs.path.absolute(relativeOutputPath);
522 final String absoluteArchivePath = globals.fs.path.absolute(app.archiveBundleOutputPath);
523 String? exportOptions = exportOptionsPlist;
524 String? exportMethod = exportOptions != null
525 ? globals.plistParser.getValueFromFile<String?>(exportOptions, 'method')
526 : null;
527 exportMethod ??= _getVersionAppropriateExportMethod(stringArg('export-method')!);
528 final bool isAppStoreUpload =
529 exportMethod == 'app-store' || exportMethod == 'app-store-connect';
530 File? generatedExportPlist;
531 try {
532 final String exportMethodDisplayName = isAppStoreUpload ? 'App Store' : exportMethod;
533 status = globals.logger.startProgress('Building $exportMethodDisplayName IPA...');
534 if (exportOptions == null) {
535 generatedExportPlist = _createExportPlist(exportMethod);
536 exportOptions = generatedExportPlist.path;
537 }
538
539 result = await globals.processUtils.run(<String>[
540 ...globals.xcode!.xcrunCommand(),
541 'xcodebuild',
542 '-exportArchive',
543 if (shouldCodesign) ...<String>[
544 '-allowProvisioningDeviceRegistration',
545 '-allowProvisioningUpdates',
546 ],
547 '-archivePath',
548 absoluteArchivePath,
549 '-exportPath',
550 absoluteOutputPath,
551 '-exportOptionsPlist',
552 globals.fs.path.absolute(exportOptions),
553 ]);
554 } finally {
555 if (generatedExportPlist != null) {
556 ErrorHandlingFileSystem.deleteIfExists(generatedExportPlist);
557 }
558 status?.stop();
559 }
560
561 if (result.exitCode != 0) {
562 final errorMessage = StringBuffer();
563
564 // "error:" prefixed lines are the nicely formatted error message, the
565 // rest is the same message but printed as a IDEFoundationErrorDomain.
566 // Example:
567 // error: exportArchive: exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd
568 // Error Domain=IDEFoundationErrorDomain Code=1 "exportOptionsPlist error for key 'method': expected one of {app-store, ad-hoc, enterprise, development, validation}, but found developmentasdasd" ...
569 LineSplitter.split(
570 result.stderr,
571 ).where((String line) => line.contains('error: ')).forEach(errorMessage.writeln);
572
573 globals.printError('Encountered error while creating the IPA:');
574 globals.printError(errorMessage.toString());
575
576 final FileSystemEntityType type = globals.fs.typeSync(absoluteArchivePath);
577 globals.printError('Try distributing the app in Xcode:');
578 if (type == FileSystemEntityType.notFound) {
579 globals.printError('open ios/Runner.xcworkspace', indent: 2);
580 } else {
581 globals.printError('open $absoluteArchivePath', indent: 2);
582 }
583
584 // Even though the IPA step didn't succeed, the xcarchive did.
585 // Still count this as success since the user has been instructed about how to
586 // recover in Xcode.
587 return FlutterCommandResult.success();
588 }
589
590 final Directory outputDirectory = globals.fs.directory(absoluteOutputPath);
591 final int? directorySize = globals.os.getDirectorySize(outputDirectory);
592 final appSize = (buildInfo.mode == BuildMode.debug || directorySize == null)
593 ? '' // Don't display the size when building a debug variant.
594 : ' (${getSizeAsPlatformMB(directorySize)})';
595
596 globals.printStatus(
597 '${globals.terminal.successMark} '
598 'Built IPA to ${globals.fs.path.relative(outputDirectory.path)}$appSize',
599 color: TerminalColor.green,
600 );
601
602 if (isAppStoreUpload) {
603 globals.printStatus('To upload to the App Store either:');
604 globals.printStatus(
605 '1. Drag and drop the "$relativeOutputPath/*.ipa" bundle into the Apple Transporter macOS app https://apps.apple.com/us/app/transporter/id1450874784',
606 indent: 4,
607 );
608 globals.printStatus(
609 '2. Run "xcrun altool --upload-app --type ios -f $relativeOutputPath/*.ipa --apiKey your_api_key --apiIssuer your_issuer_id".',
610 indent: 4,
611 );
612 globals.printStatus(
613 'See "man altool" for details about how to authenticate with the App Store Connect API key.',
614 indent: 7,
615 );
616 }
617
618 return FlutterCommandResult.success();
619 }
620
621 File _createExportPlist(String exportMethod) {
622 // Create the plist to be passed into xcodebuild -exportOptionsPlist.
623 final plistContents = StringBuffer('''
624
625//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
626
627
628 method
629 $exportMethod
630 uploadBitcode
631
632
633
634''');
635
636 final File tempPlist = globals.fs.systemTempDirectory
637 .createTempSync('flutter_build_ios.')
638 .childFile('ExportOptions.plist');
639 tempPlist.writeAsStringSync(plistContents.toString());
640
641 return tempPlist;
642 }
643
644 // As of Xcode 15.4, the old export methods 'app-store', 'ad-hoc', and 'development'
645 // are now deprecated. The new equivalents are 'app-store-connect', 'release-testing',
646 // and 'debugging'.
647 String _getVersionAppropriateExportMethod(String method) {
648 final Version? currVersion = globals.xcode!.currentVersion;
649 if (currVersion != null) {
650 if (currVersion >= Version(15, 4, 0)) {
651 switch (method) {
652 case 'app-store':
653 return 'app-store-connect';
654 case 'ad-hoc':
655 return 'release-testing';
656 case 'development':
657 return 'debugging';
658 }
659 }
660 return method;
661 }
662 throwToolExit('Xcode version could not be found.');
663 }
664}
665
666abstract class _BuildIOSSubCommand extends BuildSubCommand {
667 _BuildIOSSubCommand({required super.logger, required bool verboseHelp})
668 : super(verboseHelp: verboseHelp) {
669 addTreeShakeIconsFlag();
670 addSplitDebugInfoOption();
671 addBuildModeFlags(verboseHelp: verboseHelp);
672 usesTargetOption();
673 usesFlavorOption();
674 usesPubOption();
675 usesBuildNumberOption();
676 usesBuildNameOption();
677 addDartObfuscationOption();
678 usesDartDefineOption();
679 usesExtraDartFlagOptions(verboseHelp: verboseHelp);
680 addEnableExperimentation(hide: !verboseHelp);
681 addBuildPerformanceFile(hide: !verboseHelp);
682 usesAnalyzeSizeFlag();
683 argParser.addFlag(
684 'codesign',
685 defaultsTo: true,
686 help: 'Codesign the application bundle (only available on device builds).',
687 );
688 }
689
690 @override
691 Future> get requiredArtifacts async => const {
692 DevelopmentArtifact.iOS,
693 };
694
695 XcodeBuildAction get xcodeBuildAction;
696
697 /// The result of the Xcode build command. Null until it finishes.
698 @protected
699 XcodeBuildResult? xcodeBuildResult;
700
701 EnvironmentType get environmentType;
702 bool get configOnly;
703
704 bool get shouldCodesign => boolArg('codesign');
705
706 late final Future cachedBuildInfo = getBuildInfo();
707
708 late final Future buildableIOSApp = () async {
709 final app =
710 await applicationPackages?.getPackageForPlatform(
711 TargetPlatform.ios,
712 buildInfo: await cachedBuildInfo,
713 )
714 as BuildableIOSApp?;
715
716 if (app == null) {
717 throwToolExit('Application not configured for iOS');
718 }
719 return app;
720 }();
721
722 Directory _outputAppDirectory(String xcodeResultOutput);
723
724 @override
725 bool get supported => globals.platform.isMacOS;
726
727 @override
728 Future runCommand() async {
729 defaultBuildMode = environmentType == EnvironmentType.simulator
730 ? BuildMode.debug
731 : BuildMode.release;
732 final BuildInfo buildInfo = await cachedBuildInfo;
733
734 if (!supported) {
735 throwToolExit('Building for iOS is only supported on macOS.');
736 }
737 if (environmentType == EnvironmentType.simulator && !buildInfo.supportsSimulator) {
738 throwToolExit('${buildInfo.mode.uppercaseName} mode is not supported for simulators.');
739 }
740 if (configOnly && buildInfo.codeSizeDirectory != null) {
741 throwToolExit('Cannot analyze code size without performing a full build.');
742 }
743 if (environmentType == EnvironmentType.physical && !shouldCodesign) {
744 globals.printStatus(
745 'Warning: Building for device with codesigning disabled. You will '
746 'have to manually codesign before deploying to device.',
747 );
748 }
749
750 final BuildableIOSApp app = await buildableIOSApp;
751
752 final logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
753 final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
754 globals.printStatus(switch (xcodeBuildAction) {
755 XcodeBuildAction.build => 'Building $app for $logTarget ($typeName)...',
756 XcodeBuildAction.archive => 'Archiving $app...',
757 });
758 final XcodeBuildResult result = await buildXcodeProject(
759 app: app,
760 buildInfo: buildInfo,
761 targetOverride: targetFile,
762 environmentType: environmentType,
763 codesign: shouldCodesign,
764 configOnly: configOnly,
765 buildAction: xcodeBuildAction,
766 deviceID: globals.deviceManager?.specifiedDeviceId,
767 disablePortPublication:
768 usingCISystem &&
769 xcodeBuildAction == XcodeBuildAction.build &&
770 await disablePortPublication,
771 );
772 xcodeBuildResult = result;
773
774 if (!result.success) {
775 await diagnoseXcodeBuildFailure(
776 result,
777 analytics: globals.analytics,
778 fileSystem: globals.fs,
779 logger: globals.logger,
780 platform: FlutterDarwinPlatform.ios,
781 project: app.project.parent,
782 );
783 final presentParticiple = xcodeBuildAction == XcodeBuildAction.build
784 ? 'building'
785 : 'archiving';
786 throwToolExit('Encountered error while $presentParticiple for $logTarget.');
787 }
788
789 if (buildInfo.codeSizeDirectory != null) {
790 final sizeAnalyzer = SizeAnalyzer(
791 fileSystem: globals.fs,
792 logger: globals.logger,
793 analytics: analytics,
794 appFilenamePattern: 'App',
795 );
796 // Only support 64bit iOS code size analysis.
797 final String arch = DarwinArch.arm64.name;
798 final File aotSnapshot = globals.fs
799 .directory(buildInfo.codeSizeDirectory)
800 .childFile('snapshot.$arch.json');
801 final File precompilerTrace = globals.fs
802 .directory(buildInfo.codeSizeDirectory)
803 .childFile('trace.$arch.json');
804
805 final String? resultOutput = result.output;
806 if (resultOutput == null) {
807 throwToolExit('Could not find app to analyze code size');
808 }
809 final Directory outputAppDirectoryCandidate = _outputAppDirectory(resultOutput);
810
811 Directory? appDirectory;
812 if (outputAppDirectoryCandidate.existsSync()) {
813 appDirectory = outputAppDirectoryCandidate.listSync().whereType().where((
814 Directory directory,
815 ) {
816 return globals.fs.path.extension(directory.path) == '.app';
817 }).first;
818 }
819 if (appDirectory == null) {
820 throwToolExit(
821 'Could not find app to analyze code size in ${outputAppDirectoryCandidate.path}',
822 );
823 }
824 final Map output = await sizeAnalyzer.analyzeAotSnapshot(
825 aotSnapshot: aotSnapshot,
826 precompilerTrace: precompilerTrace,
827 outputDirectory: appDirectory,
828 type: 'ios',
829 );
830 final File outputFile = globals.fsUtils.getUniqueFile(
831 globals.fs.directory(globals.fsUtils.homeDirPath).childDirectory('.flutter-devtools'),
832 'ios-code-size-analysis',
833 'json',
834 )..writeAsStringSync(jsonEncode(output));
835 // This message is used as a sentinel in analyze_apk_size_test.dart
836 globals.printStatus(
837 'A summary of your iOS bundle analysis can be found at: ${outputFile.path}',
838 );
839
840 globals.printStatus(
841 '\nTo analyze your app size in Dart DevTools, run the following command:\n'
842 'dart devtools --appSizeBase=${outputFile.path}',
843 );
844 }
845
846 if (result.output != null) {
847 final Directory outputDirectory = globals.fs.directory(result.output);
848 final int? directorySize = globals.os.getDirectorySize(outputDirectory);
849 final appSize = (buildInfo.mode == BuildMode.debug || directorySize == null)
850 ? '' // Don't display the size when building a debug variant.
851 : ' (${getSizeAsPlatformMB(directorySize)})';
852
853 globals.printStatus(
854 '${globals.terminal.successMark} '
855 'Built ${globals.fs.path.relative(outputDirectory.path)}$appSize',
856 color: TerminalColor.green,
857 );
858
859 // When an app is successfully built, record to analytics whether Impeller
860 // is enabled or disabled. Note that we report the _lack_ of an explicit
861 // flag set as "enabled" because the default is to enable Impeller on iOS.
862 final BuildableIOSApp app = await buildableIOSApp;
863 final String plistPath = app.project.infoPlist.path;
864 final bool? impellerEnabled = globals.plistParser.getValueFromFile(
865 plistPath,
866 PlistParser.kFLTEnableImpellerKey,
867 );
868
869 final buildLabel = impellerEnabled == false
870 ? 'plist-impeller-disabled'
871 : 'plist-impeller-enabled';
872 globals.analytics.send(Event.flutterBuildInfo(label: buildLabel, buildType: 'ios'));
873
874 return FlutterCommandResult.success();
875 }
876
877 return FlutterCommandResult.fail();
878 }
879}
880