build_ios.dart 16 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
import 'package:file/file.dart';
6
import 'package:meta/meta.dart';
7

8
import '../base/analyze_size.dart';
9
import '../base/common.dart';
10 11
import '../base/logger.dart';
import '../base/process.dart';
12
import '../base/utils.dart';
13
import '../build_info.dart';
14
import '../convert.dart';
15
import '../globals.dart' as globals;
16
import '../ios/application_package.dart';
17
import '../ios/mac.dart';
18
import '../runner/flutter_command.dart';
19
import 'build.dart';
20

xster's avatar
xster committed
21
/// Builds an .app for an iOS app to be used for local testing on an iOS device
22
/// or simulator. Can only be run on a macOS host.
23
class BuildIOSCommand extends _BuildIOSSubCommand {
24
  BuildIOSCommand({ required super.verboseHelp }) {
25
    argParser
26 27 28 29 30
      ..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.'
      )
31
      ..addFlag('simulator',
32 33
        help: 'Build for the iOS simulator instead of the device. This changes '
          'the default build mode to debug if otherwise unspecified.',
34
      );
35 36 37 38 39 40
  }

  @override
  final String name = 'ios';

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

43 44 45 46
  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.build;

  @override
47
  EnvironmentType get environmentType => boolArgDeprecated('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
48 49

  @override
50
  bool get configOnly => boolArgDeprecated('config-only');
51

52
  @override
53
  Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs.directory(xcodeResultOutput).parent;
54 55
}

56 57 58
/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for
/// App Store submission.
///
59 60
/// Can only be run on a macOS host.
class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
61
  BuildIOSArchiveCommand({required super.verboseHelp}) {
62 63 64 65 66 67 68 69 70 71 72 73 74
    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.',
      },
    );
75 76 77 78
    argParser.addOption(
      'export-options-plist',
      valueHelp: 'ExportOptions.plist',
      help:
79
          'Export an IPA with these options. See "xcodebuild -h" for available exportOptionsPlist keys.',
80 81
    );
  }
82 83

  @override
84 85 86 87
  final String name = 'ipa';

  @override
  final List<String> aliases = <String>['xcarchive'];
88 89

  @override
90
  final String description = 'Build an iOS archive bundle and IPA for distribution (macOS host only).';
91 92 93 94 95

  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.archive;

  @override
96
  final EnvironmentType environmentType = EnvironmentType.physical;
97 98 99 100

  @override
  final bool configOnly = false;

101
  String? get exportOptionsPlist => stringArgDeprecated('export-options-plist');
102

103 104 105 106 107 108
  @override
  Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs
      .directory(xcodeResultOutput)
      .childDirectory('Products')
      .childDirectory('Applications');

109
  @override
110
  Future<void> validateCommand() async {
111 112
    final String? exportOptions = exportOptionsPlist;
    if (exportOptions != null) {
113
      if (argResults?.wasParsed('export-method') ?? false) {
114 115 116 117 118 119
        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.'
        );
      }
120
      final FileSystemEntityType type = globals.fs.typeSync(exportOptions);
121 122
      if (type == FileSystemEntityType.notFound) {
        throwToolExit(
123
            '"$exportOptions" property list does not exist.');
124 125
      } else if (type != FileSystemEntityType.file) {
        throwToolExit(
126
            '"$exportOptions" is not a file. See "xcodebuild -h" for available keys.');
127 128
      }
    }
129 130 131 132 133
    return super.validateCommand();
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
134
    final BuildInfo buildInfo = await cachedBuildInfo;
135
    displayNullSafetyMode(buildInfo);
136
    final FlutterCommandResult xcarchiveResult = await super.runCommand();
137 138 139

    // xcarchive failed or not at expected location.
    if (xcarchiveResult.exitStatus != ExitStatus.success) {
140 141 142 143 144 145
      globals.printStatus('Skipping IPA.');
      return xcarchiveResult;
    }

    if (!shouldCodesign) {
      globals.printStatus('Codesigning disabled with --no-codesign, skipping IPA.');
146 147 148 149
      return xcarchiveResult;
    }

    // Build IPA from generated xcarchive.
150 151 152
    final BuildableIOSApp app = await buildableIOSApp;
    Status? status;
    RunResult? result;
153 154 155
    final String relativeOutputPath = app.ipaOutputPath;
    final String absoluteOutputPath = globals.fs.path.absolute(relativeOutputPath);
    final String absoluteArchivePath = globals.fs.path.absolute(app.archiveBundleOutputPath);
156
    final String exportMethod = stringArgDeprecated('export-method')!;
157 158
    final bool isAppStoreUpload = exportMethod  == 'app-store';
    File? generatedExportPlist;
159
    try {
160 161 162 163 164 165 166
      final String exportMethodDisplayName = isAppStoreUpload ? 'App Store' : exportMethod;
      status = globals.logger.startProgress('Building $exportMethodDisplayName IPA...');
      String? exportOptions = exportOptionsPlist;
      if (exportOptions == null) {
        generatedExportPlist = _createExportPlist();
        exportOptions = generatedExportPlist.path;
      }
167 168 169

      result = await globals.processUtils.run(
        <String>[
170
          ...globals.xcode!.xcrunCommand(),
171 172
          'xcodebuild',
          '-exportArchive',
173 174 175 176
          if (shouldCodesign) ...<String>[
            '-allowProvisioningDeviceRegistration',
            '-allowProvisioningUpdates',
          ],
177
          '-archivePath',
178
          absoluteArchivePath,
179
          '-exportPath',
180
          absoluteOutputPath,
181
          '-exportOptionsPlist',
182
          globals.fs.path.absolute(exportOptions),
183 184 185
        ],
      );
    } finally {
186
      generatedExportPlist?.deleteSync();
187
      status?.stop();
188 189 190 191 192 193 194 195 196 197 198 199 200
    }

    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);
201 202 203 204 205 206 207 208 209

      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();
210 211
    }

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    globals.printStatus('Built IPA to $absoluteOutputPath.');

    if (isAppStoreUpload) {
      globals.printStatus('To upload to the App Store either:');
      globals.printStatus(
        '1. Drag and drop the "$relativeOutputPath/*.ipa" bundle into the Apple Transport macOS app https://apps.apple.com/us/app/transporter/id1450874784',
        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,
      );
    }
229 230 231

    return FlutterCommandResult.success();
  }
232 233 234 235 236 237 238 239 240 241 242 243

  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>
''');

    plistContents.write('''
244
        <string>${stringArgDeprecated('export-method')}</string>
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    ''');
    if (xcodeBuildResult?.xcodeBuildExecution?.buildSettings['ENABLE_BITCODE'] != 'YES') {
      // Bitcode is off by default in Flutter iOS apps.
      plistContents.write('''
    <key>uploadBitcode</key>
        <false/>
    </dict>
</plist>
''');
    } else {
      plistContents.write('''
</dict>
</plist>
''');
    }

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

    return tempPlist;
  }
267 268 269
}

abstract class _BuildIOSSubCommand extends BuildSubCommand {
270
  _BuildIOSSubCommand({
271
    required bool verboseHelp
272
  }) : super(verboseHelp: verboseHelp) {
273 274
    addTreeShakeIconsFlag();
    addSplitDebugInfoOption();
275
    addBuildModeFlags(verboseHelp: verboseHelp);
276 277 278 279 280 281 282
    usesTargetOption();
    usesFlavorOption();
    usesPubOption();
    usesBuildNumberOption();
    usesBuildNameOption();
    addDartObfuscationOption();
    usesDartDefineOption();
283
    usesExtraDartFlagOptions(verboseHelp: verboseHelp);
284 285 286 287 288
    addEnableExperimentation(hide: !verboseHelp);
    addBuildPerformanceFile(hide: !verboseHelp);
    addBundleSkSLPathOption(hide: !verboseHelp);
    addNullSafetyModeOptions(hide: !verboseHelp);
    usesAnalyzeSizeFlag();
289 290 291 292
    argParser.addFlag('codesign',
      defaultsTo: true,
      help: 'Codesign the application bundle (only available on device builds).',
    );
293 294
  }

295 296 297 298 299
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
    DevelopmentArtifact.iOS,
  };

300
  XcodeBuildAction get xcodeBuildAction;
301 302 303 304

  /// The result of the Xcode build command. Null until it finishes.
  @protected
  XcodeBuildResult? xcodeBuildResult;
305
  EnvironmentType get environmentType;
306
  bool get configOnly;
307

308
  bool get shouldCodesign => boolArgDeprecated('codesign');
309

310 311 312 313
  late final Future<BuildInfo> cachedBuildInfo = getBuildInfo();

  late final Future<BuildableIOSApp> buildableIOSApp = () async {
    final BuildableIOSApp? app = await applicationPackages?.getPackageForPlatform(
314
      TargetPlatform.ios,
315 316
      buildInfo: await cachedBuildInfo,
    ) as BuildableIOSApp?;
317

318 319 320 321 322
    if (app == null) {
      throwToolExit('Application not configured for iOS');
    }
    return app;
  }();
323

324 325
  Directory _outputAppDirectory(String xcodeResultOutput);

326 327 328
  @override
  bool get supported => globals.platform.isMacOS;

329 330
  @override
  Future<FlutterCommandResult> runCommand() async {
331
    defaultBuildMode = environmentType == EnvironmentType.simulator ? BuildMode.debug : BuildMode.release;
332
    final BuildInfo buildInfo = await cachedBuildInfo;
333

334
    if (!supported) {
335 336
      throwToolExit('Building for iOS is only supported on macOS.');
    }
337
    if (environmentType == EnvironmentType.simulator && !buildInfo.supportsSimulator) {
338
      throwToolExit('${sentenceCase(buildInfo.friendlyModeName)} mode is not supported for simulators.');
339 340 341 342
    }
    if (configOnly && buildInfo.codeSizeDirectory != null) {
      throwToolExit('Cannot analyze code size without performing a full build.');
    }
343
    if (environmentType == EnvironmentType.physical && !shouldCodesign) {
344 345 346 347
      globals.printStatus(
        'Warning: Building for device with codesigning disabled. You will '
        'have to manually codesign before deploying to device.',
      );
348
    }
349

350
    final BuildableIOSApp app = await buildableIOSApp;
351

352
    final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
353
    final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
354 355 356 357 358
    if (xcodeBuildAction == XcodeBuildAction.build) {
      globals.printStatus('Building $app for $logTarget ($typeName)...');
    } else {
      globals.printStatus('Archiving $app...');
    }
359
    final XcodeBuildResult result = await buildXcodeProject(
360
      app: app,
361
      buildInfo: buildInfo,
362
      targetOverride: targetFile,
363
      environmentType: environmentType,
364
      codesign: shouldCodesign,
365
      configOnly: configOnly,
366
      buildAction: xcodeBuildAction,
367
      deviceID: globals.deviceManager?.specifiedDeviceId,
368
    );
369
    xcodeBuildResult = result;
370

371
    if (!result.success) {
372
      await diagnoseXcodeBuildFailure(result, globals.flutterUsage, globals.logger);
373 374
      final String presentParticiple = xcodeBuildAction == XcodeBuildAction.build ? 'building' : 'archiving';
      throwToolExit('Encountered error while $presentParticiple for $logTarget.');
375 376
    }

377 378 379 380
    if (buildInfo.codeSizeDirectory != null) {
      final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
        fileSystem: globals.fs,
        logger: globals.logger,
381
        flutterUsage: globals.flutterUsage,
382 383 384 385 386 387 388 389 390
        appFilenamePattern: 'App'
      );
      // Only support 64bit iOS code size analysis.
      final String arch = getNameForDarwinArch(DarwinArch.arm64);
      final File aotSnapshot = globals.fs.directory(buildInfo.codeSizeDirectory)
        .childFile('snapshot.$arch.json');
      final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
        .childFile('trace.$arch.json');

391 392 393 394 395
      final String? resultOutput = result.output;
      if (resultOutput == null) {
        throwToolExit('Could not find app to analyze code size');
      }
      final Directory outputAppDirectoryCandidate = _outputAppDirectory(resultOutput);
396

397
      Directory? appDirectory;
398 399 400
      if (outputAppDirectoryCandidate.existsSync()) {
        appDirectory = outputAppDirectoryCandidate.listSync()
            .whereType<Directory>()
401
            .where((Directory directory) {
402
          return globals.fs.path.extension(directory.path) == '.app';
403
        }).first;
404 405 406 407
      }
      if (appDirectory == null) {
        throwToolExit('Could not find app to analyze code size in ${outputAppDirectoryCandidate.path}');
      }
408
      final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
409 410 411 412 413 414
        aotSnapshot: aotSnapshot,
        precompilerTrace: precompilerTrace,
        outputDirectory: appDirectory,
        type: 'ios',
      );
      final File outputFile = globals.fsUtils.getUniqueFile(
415 416 417
        globals.fs
          .directory(globals.fsUtils.homeDirPath)
          .childDirectory('.flutter-devtools'), 'ios-code-size-analysis', 'json',
418 419 420 421 422
      )..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}',
      );
423 424 425 426 427 428 429 430

      // 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'
        'flutter pub global activate devtools; flutter pub global run devtools '
        '--appSizeBase=$relativeAppSizePath'
      );
431 432
    }

433
    if (result.output != null) {
434
      globals.printStatus('Built ${result.output}.');
435 436

      return FlutterCommandResult.success();
437
    }
438

439
    return FlutterCommandResult.fail();
440 441
  }
}