build_ios.dart 29.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:typed_data';

7
import 'package:crypto/crypto.dart';
8
import 'package:file/file.dart';
9
import 'package:meta/meta.dart';
10
import 'package:unified_analytics/unified_analytics.dart';
11

12
import '../base/analyze_size.dart';
13
import '../base/common.dart';
14
import '../base/error_handling_io.dart';
15 16
import '../base/logger.dart';
import '../base/process.dart';
17
import '../base/utils.dart';
18
import '../build_info.dart';
19
import '../convert.dart';
20
import '../doctor_validator.dart';
21
import '../globals.dart' as globals;
22
import '../ios/application_package.dart';
23
import '../ios/mac.dart';
24
import '../ios/plist_parser.dart';
25
import '../reporting/reporting.dart';
26
import '../runner/flutter_command.dart';
27
import 'build.dart';
28

xster's avatar
xster committed
29
/// Builds an .app for an iOS app to be used for local testing on an iOS device
30
/// or simulator. Can only be run on a macOS host.
31
class BuildIOSCommand extends _BuildIOSSubCommand {
32 33 34 35 36
  BuildIOSCommand({
    required super.logger,
    required bool verboseHelp,
  }) : super(verboseHelp: verboseHelp) {
    addPublishPort(verboseHelp: verboseHelp);
37
    argParser
38 39 40 41 42
      ..addFlag('config-only',
        help: 'Update the project configuration without performing a build. '
          'This can be used in CI/CD process that create an archive to avoid '
          'performing duplicate work.'
      )
43
      ..addFlag('simulator',
44 45
        help: 'Build for the iOS simulator instead of the device. This changes '
          'the default build mode to debug if otherwise unspecified.',
46
      );
47 48 49 50 51 52
  }

  @override
  final String name = 'ios';

  @override
53
  final String description = 'Build an iOS application bundle (macOS host only).';
54

55 56 57 58
  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.build;

  @override
59
  EnvironmentType get environmentType => boolArg('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
60 61

  @override
62
  bool get configOnly => boolArg('config-only');
63

64
  @override
65
  Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs.directory(xcodeResultOutput).parent;
66 67
}

68 69 70
/// The key that uniquely identifies an image file in an image asset.
/// It consists of (idiom, scale, size?), where size is present for app icon
/// asset, and null for launch image asset.
71
@immutable
72 73
class _ImageAssetFileKey {
  const _ImageAssetFileKey(this.idiom, this.scale, this.size);
74 75 76 77 78

  /// The idiom (iphone or ipad).
  final String idiom;
  /// The scale factor (e.g. 2).
  final int scale;
79 80 81
  /// The logical size in point (e.g. 83.5).
  /// Size is present for app icon, and null for launch image.
  final double? size;
82 83

  @override
84
  int get hashCode => Object.hash(idiom, scale, size);
85 86

  @override
87
  bool operator ==(Object other) => other is _ImageAssetFileKey
88
      && other.idiom == idiom
89 90
      && other.scale == scale
      && other.size == size;
91

92 93
  /// The pixel size based on logical size and scale.
  int? get pixelSize => size == null ? null : (size! * scale).toInt(); // pixel size must be an int.
94 95
}

96 97 98
/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for
/// App Store submission.
///
99 100
/// Can only be run on a macOS host.
class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
101
  BuildIOSArchiveCommand({required super.logger, required super.verboseHelp}) {
102 103 104 105 106 107 108 109 110 111 112 113 114
    argParser.addOption(
      'export-method',
      defaultsTo: 'app-store',
      allowed: <String>['app-store', 'ad-hoc', 'development', 'enterprise'],
      help: 'Specify how the IPA will be distributed.',
      allowedHelp: <String, String>{
        'app-store': 'Upload to the App Store.',
        'ad-hoc': 'Test on designated devices that do not need to be registered with the Apple developer account. '
                  'Requires a distribution certificate.',
        'development': 'Test only on development devices registered with the Apple developer account.',
        'enterprise': 'Distribute an app registered with the Apple Developer Enterprise Program.',
      },
    );
115 116 117 118
    argParser.addOption(
      'export-options-plist',
      valueHelp: 'ExportOptions.plist',
      help:
119
          'Export an IPA with these options. See "xcodebuild -h" for available exportOptionsPlist keys.',
120 121
    );
  }
122 123

  @override
124 125 126 127
  final String name = 'ipa';

  @override
  final List<String> aliases = <String>['xcarchive'];
128 129

  @override
130
  final String description = 'Build an iOS archive bundle and IPA for distribution (macOS host only).';
131 132 133 134 135

  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.archive;

  @override
136
  final EnvironmentType environmentType = EnvironmentType.physical;
137 138 139 140

  @override
  final bool configOnly = false;

141
  String? get exportOptionsPlist => stringArg('export-options-plist');
142

143 144 145 146 147 148
  @override
  Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs
      .directory(xcodeResultOutput)
      .childDirectory('Products')
      .childDirectory('Applications');

149
  @override
150
  Future<void> validateCommand() async {
151 152
    final String? exportOptions = exportOptionsPlist;
    if (exportOptions != null) {
153
      if (argResults?.wasParsed('export-method') ?? false) {
154 155 156 157 158 159
        throwToolExit(
          '"--export-options-plist" is not compatible with "--export-method". Either use "--export-options-plist" and '
          'a plist describing how the IPA should be exported by Xcode, or use "--export-method" to create a new plist.\n'
          'See "xcodebuild -h" for available exportOptionsPlist keys.'
        );
      }
160
      final FileSystemEntityType type = globals.fs.typeSync(exportOptions);
161 162
      if (type == FileSystemEntityType.notFound) {
        throwToolExit(
163
            '"$exportOptions" property list does not exist.');
164 165
      } else if (type != FileSystemEntityType.file) {
        throwToolExit(
166
            '"$exportOptions" is not a file. See "xcodebuild -h" for available keys.');
167 168
      }
    }
169 170 171
    return super.validateCommand();
  }

172 173 174 175 176 177 178
  // A helper function to parse Contents.json of an image asset into a map,
  // with the key to be _ImageAssetFileKey, and value to be the image file name.
  // Some assets have size (e.g. app icon) and others do not (e.g. launch image).
  Map<_ImageAssetFileKey, String> _parseImageAssetContentsJson(
    String contentsJsonDirName,
    { required bool requiresSize })
  {
179 180
    final Directory contentsJsonDirectory = globals.fs.directory(contentsJsonDirName);
    if (!contentsJsonDirectory.existsSync()) {
181
      return <_ImageAssetFileKey, String>{};
182 183
    }
    final File contentsJsonFile = contentsJsonDirectory.childFile('Contents.json');
184 185 186 187 188
    final Map<String, dynamic> contents = json.decode(contentsJsonFile.readAsStringSync()) as Map<String, dynamic>? ?? <String, dynamic>{};
    final List<dynamic> images = contents['images'] as List<dynamic>? ?? <dynamic>[];
    final Map<String, dynamic> info = contents['info'] as Map<String, dynamic>? ?? <String, dynamic>{};
    if ((info['version'] as int?) != 1) {
      // Skips validation for unknown format.
189
      return <_ImageAssetFileKey, String>{};
190
    }
191

192
    final Map<_ImageAssetFileKey, String> iconInfo = <_ImageAssetFileKey, String>{};
193 194 195 196 197 198 199
    for (final dynamic image in images) {
      final Map<String, dynamic> imageMap = image as Map<String, dynamic>;
      final String? idiom = imageMap['idiom'] as String?;
      final String? size = imageMap['size'] as String?;
      final String? scale = imageMap['scale'] as String?;
      final String? fileName = imageMap['filename'] as String?;

200 201 202 203
      // requiresSize must match the actual presence of size in json.
      if (requiresSize != (size != null)
        || idiom == null || scale == null || fileName == null)
      {
204 205 206
        continue;
      }

207 208 209 210
      final double? parsedSize;
      if (size != null) {
        // for example, "64x64". Parse the width since it is a square.
        final Iterable<double> parsedSizes = size.split('x')
211 212
          .map((String element) => double.tryParse(element))
          .whereType<double>();
213 214 215 216 217 218
        if (parsedSizes.isEmpty) {
          continue;
        }
        parsedSize = parsedSizes.first;
      } else {
        parsedSize = null;
219
      }
220 221 222

      // for example, "3x".
      final Iterable<int> parsedScales = scale.split('x')
223 224
        .map((String element) => int.tryParse(element))
        .whereType<int>();
225 226 227 228
      if (parsedScales.isEmpty) {
        continue;
      }
      final int parsedScale = parsedScales.first;
229
      iconInfo[_ImageAssetFileKey(idiom, parsedScale, parsedSize)] = fileName;
230 231 232 233
    }
    return iconInfo;
  }

234 235 236 237 238 239 240 241 242 243 244 245
  // A helper function to check if an image asset is still using template files.
  bool _isAssetStillUsingTemplateFiles({
    required Map<_ImageAssetFileKey, String> templateImageInfoMap,
    required Map<_ImageAssetFileKey, String> projectImageInfoMap,
    required String templateImageDirName,
    required String projectImageDirName,
  }) {
    return projectImageInfoMap.entries.any((MapEntry<_ImageAssetFileKey, String> entry) {
      final String projectFileName = entry.value;
      final String? templateFileName = templateImageInfoMap[entry.key];
      if (templateFileName == null) {
        return false;
246
      }
247 248 249 250 251 252 253 254 255 256 257
      final File projectFile = globals.fs.file(
          globals.fs.path.join(projectImageDirName, projectFileName));
      final File templateFile = globals.fs.file(
          globals.fs.path.join(templateImageDirName, templateFileName));

      return projectFile.existsSync()
          && templateFile.existsSync()
          && md5.convert(projectFile.readAsBytesSync()) ==
              md5.convert(templateFile.readAsBytesSync());
    });
  }
258

259 260 261 262 263 264 265 266 267 268 269 270
  // A helper function to return a list of image files in an image asset with
  // wrong sizes (as specified in its Contents.json file).
  List<String> _imageFilesWithWrongSize({
    required Map<_ImageAssetFileKey, String> imageInfoMap,
    required String imageDirName,
  }) {
    return imageInfoMap.entries.where((MapEntry<_ImageAssetFileKey, String> entry) {
      final String fileName = entry.value;
      final File imageFile = globals.fs.file(globals.fs.path.join(imageDirName, fileName));
      if (!imageFile.existsSync()) {
        return false;
      }
271 272 273
      // validate image size is correct.
      // PNG file's width is at byte [16, 20), and height is at byte [20, 24), in big endian format.
      // Based on https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_format
274 275 276
      final ByteData imageData = imageFile.readAsBytesSync().buffer.asByteData();
      if (imageData.lengthInBytes < 24) {
        return false;
277
      }
278 279 280 281 282 283 284 285 286
      final int width = imageData.getInt32(16);
      final int height = imageData.getInt32(20);
      // The size must not be null.
      final int expectedSize = entry.key.pixelSize!;
      return width != expectedSize || height != expectedSize;
    })
    .map((MapEntry<_ImageAssetFileKey, String> entry) => entry.value)
    .toList();
  }
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  ValidationResult? _createValidationResult(String title, List<ValidationMessage> messages) {
    if (messages.isEmpty) {
      return null;
    }
    final bool anyInvalid = messages.any((ValidationMessage message) => message.type != ValidationMessageType.information);
    return ValidationResult(
      anyInvalid ? ValidationType.partial : ValidationType.success,
      messages,
      statusInfo: title,
    );
  }

  ValidationMessage _createValidationMessage({
    required bool isValid,
    required String message,
  }) {
    // Use "information" type for valid message, and "hint" type for invalid message.
    return isValid ? ValidationMessage(message) : ValidationMessage.hint(message);
  }

  Future<List<ValidationMessage>> _validateIconAssetsAfterArchive() async {
309 310 311 312 313 314 315 316 317
    final BuildableIOSApp app = await buildableIOSApp;

    final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
      app.templateAppIconDirNameForContentsJson,
      requiresSize: true);
    final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
      app.projectAppIconDirName,
      requiresSize: true);

318 319
    final List<ValidationMessage> validationMessages = <ValidationMessage>[];

320 321 322 323 324
    final bool usesTemplate = _isAssetStillUsingTemplateFiles(
      templateImageInfoMap: templateInfoMap,
      projectImageInfoMap: projectInfoMap,
      templateImageDirName: await app.templateAppIconDirNameForImages,
      projectImageDirName: app.projectAppIconDirName);
325

326
    if (usesTemplate) {
327 328 329 330
      validationMessages.add(_createValidationMessage(
        isValid: false,
        message: 'App icon is set to the default placeholder icon. Replace with unique icons.',
      ));
331
    }
332 333 334 335

    final List<String> filesWithWrongSize = _imageFilesWithWrongSize(
      imageInfoMap: projectInfoMap,
      imageDirName: app.projectAppIconDirName);
336

337
    if (filesWithWrongSize.isNotEmpty) {
338 339 340 341
      validationMessages.add(_createValidationMessage(
        isValid: false,
        message: 'App icon is using the incorrect size (e.g. ${filesWithWrongSize.first}).',
      ));
342
    }
343
    return validationMessages;
344 345
  }

346
  Future<List<ValidationMessage>> _validateLaunchImageAssetsAfterArchive() async {
347 348 349 350 351 352 353 354 355
    final BuildableIOSApp app = await buildableIOSApp;

    final Map<_ImageAssetFileKey, String> templateInfoMap = _parseImageAssetContentsJson(
      app.templateLaunchImageDirNameForContentsJson,
      requiresSize: false);
    final Map<_ImageAssetFileKey, String> projectInfoMap = _parseImageAssetContentsJson(
      app.projectLaunchImageDirName,
      requiresSize: false);

356 357
    final List<ValidationMessage> validationMessages = <ValidationMessage>[];

358 359 360 361 362 363 364
    final bool usesTemplate = _isAssetStillUsingTemplateFiles(
      templateImageInfoMap: templateInfoMap,
      projectImageInfoMap: projectInfoMap,
      templateImageDirName: await app.templateLaunchImageDirNameForImages,
      projectImageDirName: app.projectLaunchImageDirName);

    if (usesTemplate) {
365 366 367 368
      validationMessages.add(_createValidationMessage(
        isValid: false,
        message: 'Launch image is set to the default placeholder icon. Replace with unique launch image.',
      ));
369
    }
370 371

    return validationMessages;
372 373
  }

374
  Future<List<ValidationMessage>> _validateXcodeBuildSettingsAfterArchive() async {
375 376 377 378 379 380
    final BuildableIOSApp app = await buildableIOSApp;

    final String plistPath = app.builtInfoPlistPathAfterArchive;

    if (!globals.fs.file(plistPath).existsSync()) {
      globals.printError('Invalid iOS archive. Does not contain Info.plist.');
381
      return <ValidationMessage>[];
382 383 384 385
    }

    final Map<String, String?> xcodeProjectSettingsMap = <String, String?>{};

386 387
    xcodeProjectSettingsMap['Version Number'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleShortVersionStringKey);
    xcodeProjectSettingsMap['Build Number'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleVersionKey);
388 389
    xcodeProjectSettingsMap['Display Name'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleDisplayNameKey)
      ?? globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleNameKey);
390 391
    xcodeProjectSettingsMap['Deployment Target'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kMinimumOSVersionKey);
    xcodeProjectSettingsMap['Bundle Identifier'] = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleIdentifierKey);
392

393 394 395 396 397 398 399 400
    final List<ValidationMessage> validationMessages = xcodeProjectSettingsMap.entries.map((MapEntry<String, String?> entry) {
      final String title = entry.key;
      final String? info = entry.value;
      return _createValidationMessage(
        isValid: info != null,
        message: '$title: ${info ?? "Missing"}',
      );
    }).toList();
401

402 403 404 405 406 407
    final bool hasMissingSettings = xcodeProjectSettingsMap.values.any((String? element) => element == null);
    if (hasMissingSettings) {
      validationMessages.add(_createValidationMessage(
        isValid: false,
        message: 'You must set up the missing app settings.'),
      );
408
    }
409

410 411 412 413 414 415
    final bool usesDefaultBundleIdentifier = xcodeProjectSettingsMap['Bundle Identifier']?.startsWith('com.example') ?? false;
    if (usesDefaultBundleIdentifier) {
      validationMessages.add(_createValidationMessage(
        isValid: false,
        message: 'Your application still contains the default "com.example" bundle identifier.'),
      );
416
    }
417 418

    return validationMessages;
419 420
  }

421 422
  @override
  Future<FlutterCommandResult> runCommand() async {
423 424
    final BuildInfo buildInfo = await cachedBuildInfo;
    displayNullSafetyMode(buildInfo);
425
    final FlutterCommandResult xcarchiveResult = await super.runCommand();
426

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    final List<ValidationResult?> validationResults = <ValidationResult?>[];
    validationResults.add(_createValidationResult(
      'App Settings Validation',
      await _validateXcodeBuildSettingsAfterArchive(),
    ));
    validationResults.add(_createValidationResult(
      'App Icon and Launch Image Assets Validation',
      await _validateIconAssetsAfterArchive() + await _validateLaunchImageAssetsAfterArchive(),
    ));

    for (final ValidationResult result in validationResults.whereType<ValidationResult>()) {
      globals.printStatus('\n${result.coloredLeadingBox} ${result.statusInfo}');
      for (final ValidationMessage message in result.messages) {
        globals.printStatus(
          '${message.coloredIndicator} ${message.message}',
          indent: result.leadingBox.length + 1,
        );
      }
    }
    globals.printStatus('\nTo update the settings, please refer to https://docs.flutter.dev/deployment/ios\n');
447

448 449
    // xcarchive failed or not at expected location.
    if (xcarchiveResult.exitStatus != ExitStatus.success) {
450 451 452 453 454 455
      globals.printStatus('Skipping IPA.');
      return xcarchiveResult;
    }

    if (!shouldCodesign) {
      globals.printStatus('Codesigning disabled with --no-codesign, skipping IPA.');
456 457 458 459
      return xcarchiveResult;
    }

    // Build IPA from generated xcarchive.
460 461 462
    final BuildableIOSApp app = await buildableIOSApp;
    Status? status;
    RunResult? result;
463 464 465
    final String relativeOutputPath = app.ipaOutputPath;
    final String absoluteOutputPath = globals.fs.path.absolute(relativeOutputPath);
    final String absoluteArchivePath = globals.fs.path.absolute(app.archiveBundleOutputPath);
466 467 468 469 470
    String? exportOptions = exportOptionsPlist;
    String? exportMethod = exportOptions != null ?
        globals.plistParser.getValueFromFile<String?>(exportOptions, 'method') : null;
    exportMethod ??= stringArg('export-method')!;
    final bool isAppStoreUpload = exportMethod == 'app-store';
471
    File? generatedExportPlist;
472
    try {
473 474 475 476 477 478
      final String exportMethodDisplayName = isAppStoreUpload ? 'App Store' : exportMethod;
      status = globals.logger.startProgress('Building $exportMethodDisplayName IPA...');
      if (exportOptions == null) {
        generatedExportPlist = _createExportPlist();
        exportOptions = generatedExportPlist.path;
      }
479 480 481

      result = await globals.processUtils.run(
        <String>[
482
          ...globals.xcode!.xcrunCommand(),
483 484
          'xcodebuild',
          '-exportArchive',
485 486 487 488
          if (shouldCodesign) ...<String>[
            '-allowProvisioningDeviceRegistration',
            '-allowProvisioningUpdates',
          ],
489
          '-archivePath',
490
          absoluteArchivePath,
491
          '-exportPath',
492
          absoluteOutputPath,
493
          '-exportOptionsPlist',
494
          globals.fs.path.absolute(exportOptions),
495 496 497
        ],
      );
    } finally {
498 499 500
      if (generatedExportPlist != null) {
        ErrorHandlingFileSystem.deleteIfExists(generatedExportPlist);
      }
501
      status?.stop();
502 503 504 505 506 507 508 509 510 511 512 513 514
    }

    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);
515 516 517 518 519 520 521 522 523

      globals.printError('Encountered error while creating the IPA:');
      globals.printError(errorMessage.toString());
      globals.printError('Try distributing the app in Xcode: "open $absoluteArchivePath"');

      // Even though the IPA step didn't succeed, the xcarchive did.
      // Still count this as success since the user has been instructed about how to
      // recover in Xcode.
      return FlutterCommandResult.success();
524 525
    }

526
    globals.printStatus('Built IPA to $absoluteOutputPath.');
527 528 529 530

    if (isAppStoreUpload) {
      globals.printStatus('To upload to the App Store either:');
      globals.printStatus(
531
        '1. Drag and drop the "$relativeOutputPath/*.ipa" bundle into the Apple Transporter macOS app https://apps.apple.com/us/app/transporter/id1450874784',
532 533 534 535 536 537 538 539 540 541 542
        indent: 4,
      );
      globals.printStatus(
        '2. Run "xcrun altool --upload-app --type ios -f $relativeOutputPath/*.ipa --apiKey your_api_key --apiIssuer your_issuer_id".',
        indent: 4,
      );
      globals.printStatus(
        'See "man altool" for details about how to authenticate with the App Store Connect API key.',
        indent: 7,
      );
    }
543 544 545

    return FlutterCommandResult.success();
  }
546 547 548 549 550 551 552 553 554

  File _createExportPlist() {
    // Create the plist to be passed into xcodebuild -exportOptionsPlist.
    final StringBuffer plistContents = StringBuffer('''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>method</key>
555
        <string>${stringArg('export-method')}</string>
556
        <key>uploadBitcode</key>
557 558 559 560 561 562 563 564 565 566 567
        <false/>
    </dict>
</plist>
''');

    final File tempPlist = globals.fs.systemTempDirectory
        .createTempSync('flutter_build_ios.').childFile('ExportOptions.plist');
    tempPlist.writeAsStringSync(plistContents.toString());

    return tempPlist;
  }
568 569 570
}

abstract class _BuildIOSSubCommand extends BuildSubCommand {
571
  _BuildIOSSubCommand({
572
    required super.logger,
573
    required bool verboseHelp
574
  }) : super(verboseHelp: verboseHelp) {
575 576
    addTreeShakeIconsFlag();
    addSplitDebugInfoOption();
577
    addBuildModeFlags(verboseHelp: verboseHelp);
578 579 580 581 582 583 584
    usesTargetOption();
    usesFlavorOption();
    usesPubOption();
    usesBuildNumberOption();
    usesBuildNameOption();
    addDartObfuscationOption();
    usesDartDefineOption();
585
    usesExtraDartFlagOptions(verboseHelp: verboseHelp);
586 587 588
    addEnableExperimentation(hide: !verboseHelp);
    addBuildPerformanceFile(hide: !verboseHelp);
    addBundleSkSLPathOption(hide: !verboseHelp);
589
    addNullSafetyModeOptions(hide: !verboseHelp);
590
    usesAnalyzeSizeFlag();
591 592 593 594
    argParser.addFlag('codesign',
      defaultsTo: true,
      help: 'Codesign the application bundle (only available on device builds).',
    );
595 596
  }

597 598 599 600 601
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
    DevelopmentArtifact.iOS,
  };

602
  XcodeBuildAction get xcodeBuildAction;
603 604 605 606

  /// The result of the Xcode build command. Null until it finishes.
  @protected
  XcodeBuildResult? xcodeBuildResult;
607

608
  EnvironmentType get environmentType;
609
  bool get configOnly;
610

611
  bool get shouldCodesign => boolArg('codesign');
612

613 614 615 616
  late final Future<BuildInfo> cachedBuildInfo = getBuildInfo();

  late final Future<BuildableIOSApp> buildableIOSApp = () async {
    final BuildableIOSApp? app = await applicationPackages?.getPackageForPlatform(
617
      TargetPlatform.ios,
618 619
      buildInfo: await cachedBuildInfo,
    ) as BuildableIOSApp?;
620

621 622 623 624 625
    if (app == null) {
      throwToolExit('Application not configured for iOS');
    }
    return app;
  }();
626

627 628
  Directory _outputAppDirectory(String xcodeResultOutput);

629 630 631
  @override
  bool get supported => globals.platform.isMacOS;

632 633
  @override
  Future<FlutterCommandResult> runCommand() async {
634
    defaultBuildMode = environmentType == EnvironmentType.simulator ? BuildMode.debug : BuildMode.release;
635
    final BuildInfo buildInfo = await cachedBuildInfo;
636

637
    if (!supported) {
638 639
      throwToolExit('Building for iOS is only supported on macOS.');
    }
640
    if (environmentType == EnvironmentType.simulator && !buildInfo.supportsSimulator) {
641
      throwToolExit('${sentenceCase(buildInfo.friendlyModeName)} mode is not supported for simulators.');
642 643 644 645
    }
    if (configOnly && buildInfo.codeSizeDirectory != null) {
      throwToolExit('Cannot analyze code size without performing a full build.');
    }
646
    if (environmentType == EnvironmentType.physical && !shouldCodesign) {
647 648 649 650
      globals.printStatus(
        'Warning: Building for device with codesigning disabled. You will '
        'have to manually codesign before deploying to device.',
      );
651
    }
652

653
    final BuildableIOSApp app = await buildableIOSApp;
654

655
    final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
656
    final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
657 658 659 660 661
    if (xcodeBuildAction == XcodeBuildAction.build) {
      globals.printStatus('Building $app for $logTarget ($typeName)...');
    } else {
      globals.printStatus('Archiving $app...');
    }
662
    final XcodeBuildResult result = await buildXcodeProject(
663
      app: app,
664
      buildInfo: buildInfo,
665
      targetOverride: targetFile,
666
      environmentType: environmentType,
667
      codesign: shouldCodesign,
668
      configOnly: configOnly,
669
      buildAction: xcodeBuildAction,
670
      deviceID: globals.deviceManager?.specifiedDeviceId,
671 672 673
      disablePortPublication: usingCISystem &&
          xcodeBuildAction == XcodeBuildAction.build &&
          await disablePortPublication,
674
    );
675
    xcodeBuildResult = result;
676

677
    if (!result.success) {
678
      await diagnoseXcodeBuildFailure(result, globals.flutterUsage, globals.logger, globals.analytics);
679 680
      final String presentParticiple = xcodeBuildAction == XcodeBuildAction.build ? 'building' : 'archiving';
      throwToolExit('Encountered error while $presentParticiple for $logTarget.');
681 682
    }

683 684 685 686
    if (buildInfo.codeSizeDirectory != null) {
      final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
        fileSystem: globals.fs,
        logger: globals.logger,
687
        flutterUsage: globals.flutterUsage,
688
        analytics: analytics,
689 690 691
        appFilenamePattern: 'App'
      );
      // Only support 64bit iOS code size analysis.
692
      final String arch = DarwinArch.arm64.name;
693 694 695 696 697
      final File aotSnapshot = globals.fs.directory(buildInfo.codeSizeDirectory)
        .childFile('snapshot.$arch.json');
      final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
        .childFile('trace.$arch.json');

698 699 700 701 702
      final String? resultOutput = result.output;
      if (resultOutput == null) {
        throwToolExit('Could not find app to analyze code size');
      }
      final Directory outputAppDirectoryCandidate = _outputAppDirectory(resultOutput);
703

704
      Directory? appDirectory;
705 706 707
      if (outputAppDirectoryCandidate.existsSync()) {
        appDirectory = outputAppDirectoryCandidate.listSync()
            .whereType<Directory>()
708
            .where((Directory directory) {
709
          return globals.fs.path.extension(directory.path) == '.app';
710
        }).first;
711 712 713 714
      }
      if (appDirectory == null) {
        throwToolExit('Could not find app to analyze code size in ${outputAppDirectoryCandidate.path}');
      }
715
      final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
716 717 718 719 720 721
        aotSnapshot: aotSnapshot,
        precompilerTrace: precompilerTrace,
        outputDirectory: appDirectory,
        type: 'ios',
      );
      final File outputFile = globals.fsUtils.getUniqueFile(
722 723 724
        globals.fs
          .directory(globals.fsUtils.homeDirPath)
          .childDirectory('.flutter-devtools'), 'ios-code-size-analysis', 'json',
725 726 727 728 729
      )..writeAsStringSync(jsonEncode(output));
      // This message is used as a sentinel in analyze_apk_size_test.dart
      globals.printStatus(
        'A summary of your iOS bundle analysis can be found at: ${outputFile.path}',
      );
730 731 732 733 734

      // DevTools expects a file path relative to the .flutter-devtools/ dir.
      final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim();
      globals.printStatus(
        '\nTo analyze your app size in Dart DevTools, run the following command:\n'
735
        'dart devtools --appSizeBase=$relativeAppSizePath'
736
      );
737 738
    }

739
    if (result.output != null) {
740
      globals.printStatus('Built ${result.output}.');
741

742 743 744 745 746 747 748
      // When an app is successfully built, record to analytics whether Impeller
      // is enabled or disabled.
      final BuildableIOSApp app = await buildableIOSApp;
      final String plistPath = app.project.infoPlist.path;
      final bool? impellerEnabled = globals.plistParser.getValueFromFile<bool>(
        plistPath, PlistParser.kFLTEnableImpellerKey,
      );
749 750

      final String buildLabel = impellerEnabled == false
751
          ? 'plist-impeller-disabled'
752 753 754
          : 'plist-impeller-enabled';
      BuildEvent(
        buildLabel,
755 756 757
        type: 'ios',
        flutterUsage: globals.flutterUsage,
      ).send();
758 759 760 761
      globals.analytics.send(Event.flutterBuildInfo(
        label: buildLabel,
        buildType: 'ios',
      ));
762

763
      return FlutterCommandResult.success();
764
    }
765

766
    return FlutterCommandResult.fail();
767 768
  }
}