build_ios.dart 12.1 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

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

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

  @override
  final String name = 'ios';

  @override
44
  final String description = 'Build an iOS application bundle (Mac OS X host only).';
45

46 47 48 49
  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.build;

  @override
50
  EnvironmentType get environmentType => boolArg('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
51 52 53 54 55 56

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

  @override
  bool get shouldCodesign => boolArg('codesign');
57 58

  @override
59
  Directory _outputAppDirectory(String xcodeResultOutput) => globals.fs.directory(xcodeResultOutput).parent;
60 61
}

62 63 64
/// Builds an .xcarchive and optionally .ipa for an iOS app to be generated for
/// App Store submission.
///
65 66
/// Can only be run on a macOS host.
class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
67
  BuildIOSArchiveCommand({required bool verboseHelp})
68 69 70 71 72 73 74 75 76
      : 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.',
    );
  }
77 78

  @override
79 80 81 82
  final String name = 'ipa';

  @override
  final List<String> aliases = <String>['xcarchive'];
83 84 85 86 87 88 89 90

  @override
  final String description = 'Build an iOS archive bundle (Mac OS X host only).';

  @override
  final XcodeBuildAction xcodeBuildAction = XcodeBuildAction.archive;

  @override
91
  final EnvironmentType environmentType = EnvironmentType.physical;
92 93 94 95 96 97

  @override
  final bool configOnly = false;

  @override
  final bool shouldCodesign = true;
98

99
  String? get exportOptionsPlist => stringArg('export-options-plist');
100

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

107 108
  @override
  Future<FlutterCommandResult> runCommand() async {
109 110 111
    final String? exportOptions = exportOptionsPlist;
    if (exportOptions != null) {
      final FileSystemEntityType type = globals.fs.typeSync(exportOptions);
112 113
      if (type == FileSystemEntityType.notFound) {
        throwToolExit(
114
            '"$exportOptions" property list does not exist.');
115 116
      } else if (type != FileSystemEntityType.file) {
        throwToolExit(
117
            '"$exportOptions" is not a file. See "xcodebuild -h" for available keys.');
118 119 120
      }
    }
    final FlutterCommandResult xcarchiveResult = await super.runCommand();
121
    final BuildInfo buildInfo = await getBuildInfo();
122
    displayNullSafetyMode(buildInfo);
123

124
    if (exportOptions == null) {
125 126 127 128 129
      return xcarchiveResult;
    }

    // xcarchive failed or not at expected location.
    if (xcarchiveResult.exitStatus != ExitStatus.success) {
130
      globals.printStatus('Skipping IPA');
131 132 133 134
      return xcarchiveResult;
    }

    // Build IPA from generated xcarchive.
135 136 137
    final BuildableIOSApp app = await buildableIOSApp;
    Status? status;
    RunResult? result;
138 139 140 141 142 143
    final String outputPath = globals.fs.path.absolute(app.ipaOutputPath);
    try {
      status = globals.logger.startProgress('Building IPA...');

      result = await globals.processUtils.run(
        <String>[
144
          ...globals.xcode!.xcrunCommand(),
145 146
          'xcodebuild',
          '-exportArchive',
147 148 149 150
          if (shouldCodesign) ...<String>[
            '-allowProvisioningDeviceRegistration',
            '-allowProvisioningUpdates',
          ],
151 152 153 154 155
          '-archivePath',
          globals.fs.path.absolute(app.archiveBundleOutputPath),
          '-exportPath',
          outputPath,
          '-exportOptionsPlist',
156
          globals.fs.path.absolute(exportOptions),
157 158 159
        ],
      );
    } finally {
160
      status?.stop();
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    }

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

177
    globals.printStatus('Built IPA to $outputPath.');
178 179 180

    return FlutterCommandResult.success();
  }
181 182 183
}

abstract class _BuildIOSSubCommand extends BuildSubCommand {
184
  _BuildIOSSubCommand({
185
    required bool verboseHelp
186
  }) : super(verboseHelp: verboseHelp) {
187 188
    addTreeShakeIconsFlag();
    addSplitDebugInfoOption();
189
    addBuildModeFlags(verboseHelp: verboseHelp);
190 191 192 193 194 195 196
    usesTargetOption();
    usesFlavorOption();
    usesPubOption();
    usesBuildNumberOption();
    usesBuildNameOption();
    addDartObfuscationOption();
    usesDartDefineOption();
197
    usesExtraDartFlagOptions(verboseHelp: verboseHelp);
198 199 200 201 202 203 204
    addEnableExperimentation(hide: !verboseHelp);
    addBuildPerformanceFile(hide: !verboseHelp);
    addBundleSkSLPathOption(hide: !verboseHelp);
    addNullSafetyModeOptions(hide: !verboseHelp);
    usesAnalyzeSizeFlag();
  }

205 206 207 208 209
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
    DevelopmentArtifact.iOS,
  };

210
  XcodeBuildAction get xcodeBuildAction;
211
  EnvironmentType get environmentType;
212 213 214
  bool get configOnly;
  bool get shouldCodesign;

215 216 217 218
  late final Future<BuildInfo> cachedBuildInfo = getBuildInfo();

  late final Future<BuildableIOSApp> buildableIOSApp = () async {
    final BuildableIOSApp? app = await applicationPackages?.getPackageForPlatform(
219
      TargetPlatform.ios,
220 221
      buildInfo: await cachedBuildInfo,
    ) as BuildableIOSApp?;
222

223 224 225 226 227
    if (app == null) {
      throwToolExit('Application not configured for iOS');
    }
    return app;
  }();
228

229 230
  Directory _outputAppDirectory(String xcodeResultOutput);

231 232 233
  @override
  bool get supported => globals.platform.isMacOS;

234 235
  @override
  Future<FlutterCommandResult> runCommand() async {
236
    defaultBuildMode = environmentType == EnvironmentType.simulator ? BuildMode.debug : BuildMode.release;
237
    final BuildInfo buildInfo = await cachedBuildInfo;
238

239
    if (!supported) {
240 241
      throwToolExit('Building for iOS is only supported on macOS.');
    }
242
    if (environmentType == EnvironmentType.simulator && !buildInfo.supportsSimulator) {
243
      throwToolExit('${sentenceCase(buildInfo.friendlyModeName)} mode is not supported for simulators.');
244 245 246 247
    }
    if (configOnly && buildInfo.codeSizeDirectory != null) {
      throwToolExit('Cannot analyze code size without performing a full build.');
    }
248
    if (environmentType == EnvironmentType.physical && !shouldCodesign) {
249 250 251 252
      globals.printStatus(
        'Warning: Building for device with codesigning disabled. You will '
        'have to manually codesign before deploying to device.',
      );
253
    }
254

255
    final BuildableIOSApp app = await buildableIOSApp;
256

257
    final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
258
    final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
259 260 261 262 263
    if (xcodeBuildAction == XcodeBuildAction.build) {
      globals.printStatus('Building $app for $logTarget ($typeName)...');
    } else {
      globals.printStatus('Archiving $app...');
    }
264
    final XcodeBuildResult result = await buildXcodeProject(
265
      app: app,
266
      buildInfo: buildInfo,
267
      targetOverride: targetFile,
268
      environmentType: environmentType,
269
      codesign: shouldCodesign,
270
      configOnly: configOnly,
271
      buildAction: xcodeBuildAction,
272
      deviceID: globals.deviceManager?.specifiedDeviceId,
273
    );
274

275
    if (!result.success) {
276
      await diagnoseXcodeBuildFailure(result, globals.flutterUsage, globals.logger);
277 278
      final String presentParticiple = xcodeBuildAction == XcodeBuildAction.build ? 'building' : 'archiving';
      throwToolExit('Encountered error while $presentParticiple for $logTarget.');
279 280
    }

281 282 283 284
    if (buildInfo.codeSizeDirectory != null) {
      final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
        fileSystem: globals.fs,
        logger: globals.logger,
285
        flutterUsage: globals.flutterUsage,
286 287 288 289 290 291 292 293 294
        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');

295 296 297 298 299
      final String? resultOutput = result.output;
      if (resultOutput == null) {
        throwToolExit('Could not find app to analyze code size');
      }
      final Directory outputAppDirectoryCandidate = _outputAppDirectory(resultOutput);
300

301
      Directory? appDirectory;
302 303 304
      if (outputAppDirectoryCandidate.existsSync()) {
        appDirectory = outputAppDirectoryCandidate.listSync()
            .whereType<Directory>()
305
            .where((Directory directory) {
306
          return globals.fs.path.extension(directory.path) == '.app';
307
        }).first;
308 309 310 311
      }
      if (appDirectory == null) {
        throwToolExit('Could not find app to analyze code size in ${outputAppDirectoryCandidate.path}');
      }
312
      final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
313 314 315 316 317 318
        aotSnapshot: aotSnapshot,
        precompilerTrace: precompilerTrace,
        outputDirectory: appDirectory,
        type: 'ios',
      );
      final File outputFile = globals.fsUtils.getUniqueFile(
319 320 321
        globals.fs
          .directory(globals.fsUtils.homeDirPath)
          .childDirectory('.flutter-devtools'), 'ios-code-size-analysis', 'json',
322 323 324 325 326
      )..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}',
      );
327 328 329 330 331 332 333 334

      // 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'
      );
335 336
    }

337
    if (result.output != null) {
338
      globals.printStatus('Built ${result.output}.');
339 340

      return FlutterCommandResult.success();
341
    }
342

343
    return FlutterCommandResult.fail();
344 345
  }
}