build_ios_framework.dart 20.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
xster's avatar
xster committed
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
// @dart = 2.8

7
import 'package:meta/meta.dart';
xster's avatar
xster committed
8 9 10 11 12

import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
13
import '../base/platform.dart';
xster's avatar
xster committed
14 15 16
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
17
import '../build_system/build_system.dart';
xster's avatar
xster committed
18
import '../build_system/targets/ios.dart';
19
import '../cache.dart';
20
import '../flutter_plugins.dart';
21
import '../globals_null_migrated.dart' as globals;
xster's avatar
xster committed
22 23 24
import '../macos/cocoapod_utils.dart';
import '../project.dart';
import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult;
25
import '../version.dart';
xster's avatar
xster committed
26 27 28 29 30 31 32
import 'build.dart';

/// Produces a .framework for integration into a host iOS app. The .framework
/// contains the Flutter engine and framework code as well as plugins. It can
/// be integrated into plain Xcode projects without using or other package
/// managers.
class BuildIOSFrameworkCommand extends BuildSubCommand {
33 34
  BuildIOSFrameworkCommand({
    FlutterVersion flutterVersion, // Instantiating FlutterVersion kicks off networking, so delay until it's needed, but allow test injection.
35
    @required BuildSystem buildSystem,
36
    @required bool verboseHelp,
37 38
    Cache cache,
    Platform platform
39
  }) : _flutterVersion = flutterVersion,
40
       _buildSystem = buildSystem,
41 42
       _injectedCache = cache,
       _injectedPlatform = platform {
43
    addTreeShakeIconsFlag();
xster's avatar
xster committed
44 45 46
    usesTargetOption();
    usesFlavorOption();
    usesPubOption();
47
    usesDartDefineOption();
48 49
    addSplitDebugInfoOption();
    addDartObfuscationOption();
50
    usesExtraDartFlagOptions(verboseHelp: verboseHelp);
51 52 53
    addNullSafetyModeOptions(hide: !verboseHelp);
    addEnableExperimentation(hide: !verboseHelp);

xster's avatar
xster committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    argParser
      ..addFlag('debug',
        negatable: true,
        defaultsTo: true,
        help: 'Whether to produce a framework for the debug build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('profile',
        negatable: true,
        defaultsTo: true,
        help: 'Whether to produce a framework for the profile build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('release',
        negatable: true,
        defaultsTo: true,
        help: 'Whether to produce a framework for the release build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('universal',
74
        help: '(deprecated) Produce universal frameworks that include all valid architectures.',
75
        negatable: true,
76
        hide: !verboseHelp,
xster's avatar
xster committed
77 78
      )
      ..addFlag('xcframework',
79
        help: 'Produce xcframeworks that include all valid architectures.',
80
        negatable: false,
81
        defaultsTo: true,
82
        hide: !verboseHelp,
xster's avatar
xster committed
83
      )
84
      ..addFlag('cocoapods',
85
        help: 'Produce a Flutter.podspec instead of an engine Flutter.xcframework (recommended if host app uses CocoaPods).',
86
      )
xster's avatar
xster committed
87 88 89 90
      ..addOption('output',
        abbr: 'o',
        valueHelp: 'path/to/directory/',
        help: 'Location to write the frameworks.',
91 92 93
      )
      ..addFlag('force',
        abbr: 'f',
94 95
        help: 'Force Flutter.podspec creation on the master channel. This is only intended for testing the tool itself.',
        hide: !verboseHelp,
xster's avatar
xster committed
96 97 98
      );
  }

99 100
  final BuildSystem _buildSystem;
  BuildSystem get buildSystem => _buildSystem ?? globals.buildSystem;
101 102 103 104 105 106

  Cache get _cache => _injectedCache ?? globals.cache;
  final Cache _injectedCache;

  Platform get _platform => _injectedPlatform ?? globals.platform;
  final Platform _injectedPlatform;
107 108

  FlutterVersion _flutterVersion;
xster's avatar
xster committed
109

110 111 112
  @override
  bool get reportNullSafety => false;

xster's avatar
xster committed
113 114 115 116
  @override
  final String name = 'ios-framework';

  @override
117
  final String description = 'Produces .xcframeworks for a Flutter project '
xster's avatar
xster committed
118 119 120 121 122 123 124 125 126 127
      'and its plugins for integration into existing, plain Xcode projects.\n'
      'This can only be run on macOS hosts.';

  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{
    DevelopmentArtifact.iOS,
  };

  FlutterProject _project;

128
  Future<List<BuildInfo>> getBuildInfos() async {
129
    final List<BuildInfo> buildInfos = <BuildInfo>[];
xster's avatar
xster committed
130

131
    if (boolArg('debug')) {
132
      buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.debug));
xster's avatar
xster committed
133
    }
134
    if (boolArg('profile')) {
135
      buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.profile));
xster's avatar
xster committed
136
    }
137
    if (boolArg('release')) {
138
      buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.release));
xster's avatar
xster committed
139 140
    }

141
    return buildInfos;
xster's avatar
xster committed
142 143 144 145 146 147
  }

  @override
  Future<void> validateCommand() async {
    await super.validateCommand();
    _project = FlutterProject.current();
148
    if (!_platform.isMacOS) {
xster's avatar
xster committed
149 150 151
      throwToolExit('Building frameworks for iOS is only supported on the Mac.');
    }

152
    if (boolArg('universal')) {
153
      throwToolExit('--universal has been deprecated, only XCFrameworks are supported.');
154
    }
155
    if ((await getBuildInfos()).isEmpty) {
xster's avatar
xster committed
156 157 158 159 160 161
      throwToolExit('At least one of "--debug" or "--profile", or "--release" is required.');
    }
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
162
    final String outputArgument = stringArg('output')
163
        ?? globals.fs.path.join(globals.fs.currentDirectory.path, 'build', 'ios', 'framework');
xster's avatar
xster committed
164 165 166 167 168

    if (outputArgument.isEmpty) {
      throwToolExit('--output is required.');
    }

169
    if (!_project.ios.existsSync()) {
170
      throwToolExit('Project does not support iOS');
xster's avatar
xster committed
171 172
    }

173
    final Directory outputDirectory = globals.fs.directory(globals.fs.path.absolute(globals.fs.path.normalize(outputArgument)));
174 175 176
    final List<BuildInfo> buildInfos = await getBuildInfos();
    displayNullSafetyMode(buildInfos.first);
    for (final BuildInfo buildInfo in buildInfos) {
177
      final String productBundleIdentifier = await _project.ios.productBundleIdentifier(buildInfo);
178 179
      globals.printStatus('Building frameworks for $productBundleIdentifier in ${getNameForBuildMode(buildInfo.mode)} mode...');
      final String xcodeBuildConfiguration = toTitleCase(getNameForBuildMode(buildInfo.mode));
xster's avatar
xster committed
180
      final Directory modeDirectory = outputDirectory.childDirectory(xcodeBuildConfiguration);
181 182 183 184

      if (modeDirectory.existsSync()) {
        modeDirectory.deleteSync(recursive: true);
      }
xster's avatar
xster committed
185

186 187
      if (boolArg('cocoapods')) {
        // FlutterVersion.instance kicks off git processing which can sometimes fail, so don't try it until needed.
188
        _flutterVersion ??= globals.flutterVersion;
189
        produceFlutterPodspec(buildInfo.mode, modeDirectory, force: boolArg('force'));
190
      } else {
191
        // Copy Flutter.xcframework.
192
        await _produceFlutterFramework(buildInfo, modeDirectory);
193
      }
xster's avatar
xster committed
194 195

      // Build aot, create module.framework and copy.
196 197 198 199 200 201
      final Directory iPhoneBuildOutput =
          modeDirectory.childDirectory('iphoneos');
      final Directory simulatorBuildOutput =
          modeDirectory.childDirectory('iphonesimulator');
      await _produceAppFramework(
          buildInfo, modeDirectory, iPhoneBuildOutput, simulatorBuildOutput);
xster's avatar
xster committed
202 203

      // Build and copy plugins.
204
      await processPodsIfNeeded(_project.ios, getIosBuildDirectory(), buildInfo.mode);
xster's avatar
xster committed
205
      if (hasPlugins(_project)) {
206
        await _producePlugins(buildInfo.mode, xcodeBuildConfiguration, iPhoneBuildOutput, simulatorBuildOutput, modeDirectory, outputDirectory);
xster's avatar
xster committed
207 208
      }

209
      final Status status = globals.logger.startProgress(
210
        ' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}');
211 212 213 214 215 216 217 218 219 220 221
      try {
        // Delete the intermediaries since they would have been copied into our
        // output frameworks.
        if (iPhoneBuildOutput.existsSync()) {
          iPhoneBuildOutput.deleteSync(recursive: true);
        }
        if (simulatorBuildOutput.existsSync()) {
          simulatorBuildOutput.deleteSync(recursive: true);
        }
      } finally {
        status.stop();
xster's avatar
xster committed
222 223 224
      }
    }

225
    globals.printStatus('Frameworks written to ${outputDirectory.path}.');
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

    if (!_project.isModule && hasPlugins(_project)) {
      // Apps do not generate a FlutterPluginRegistrant.framework. Users will need
      // to copy the GeneratedPluginRegistrant class to their project manually.
      final File pluginRegistrantHeader = _project.ios.pluginRegistrantHeader;
      final File pluginRegistrantImplementation =
          _project.ios.pluginRegistrantImplementation;
      pluginRegistrantHeader.copySync(
          outputDirectory.childFile(pluginRegistrantHeader.basename).path);
      pluginRegistrantImplementation.copySync(outputDirectory
          .childFile(pluginRegistrantImplementation.basename)
          .path);
      globals.printStatus(
          '\nCopy the ${globals.fs.path.basenameWithoutExtension(pluginRegistrantHeader.path)} class into your project.\n'
          'See https://flutter.dev/docs/development/add-to-app/ios/add-flutter-screen#create-a-flutterengine for more information.');
    }

243
    return FlutterCommandResult.success();
xster's avatar
xster committed
244 245
  }

246 247 248
  /// Create podspec that will download and unzip remote engine assets so host apps can leverage CocoaPods
  /// vendored framework caching.
  @visibleForTesting
249
  void produceFlutterPodspec(BuildMode mode, Directory modeDirectory, { bool force = false }) {
250
    final Status status = globals.logger.startProgress(' ├─Creating Flutter.podspec...');
251
    try {
252
      final GitTagVersion gitTagVersion = _flutterVersion.gitTagVersion;
253
      if (!force && (gitTagVersion.x == null || gitTagVersion.y == null || gitTagVersion.z == null || gitTagVersion.commits != 0)) {
254
        throwToolExit(
255
            '--cocoapods is only supported on the dev, beta, or stable channels. Detected version is ${_flutterVersion.frameworkVersion}');
256 257 258 259 260 261 262 263
      }

      // Podspecs use semantic versioning, which don't support hotfixes.
      // Fake out a semantic version with major.minor.(patch * 100) + hotfix.
      // A real increasing version is required to prompt CocoaPods to fetch
      // new artifacts when the source URL changes.
      final int minorHotfixVersion = gitTagVersion.z * 100 + (gitTagVersion.hotfix ?? 0);

264
      final File license = _cache.getLicenseFile();
265 266 267 268 269 270 271 272 273
      if (!license.existsSync()) {
        throwToolExit('Could not find license at ${license.path}');
      }
      final String licenseSource = license.readAsStringSync();
      final String artifactsMode = mode == BuildMode.debug ? 'ios' : 'ios-${mode.name}';

      final String podspecContents = '''
Pod::Spec.new do |s|
  s.name                  = 'Flutter'
274
  s.version               = '${gitTagVersion.x}.${gitTagVersion.y}.$minorHotfixVersion' # ${_flutterVersion.frameworkVersion}
275
  s.summary               = 'A UI toolkit for beautiful and fast apps.'
276
  s.description           = <<-DESC
277
Flutter is Google's UI toolkit for building beautiful, fast apps for mobile, web, desktop, and embedded devices from a single codebase.
278 279 280 281
This pod vends the iOS Flutter engine framework. It is compatible with application frameworks created with this version of the engine and tools.
The pod version matches Flutter version major.minor.(patch * 100) + hotfix.
DESC
  s.homepage              = 'https://flutter.dev'
282
  s.license               = { :type => 'BSD', :text => <<-LICENSE
283 284 285 286
$licenseSource
LICENSE
  }
  s.author                = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' }
287
  s.source                = { :http => '${_cache.storageBaseUrl}/flutter_infra_release/flutter/${_cache.engineRevision}/$artifactsMode/artifacts.zip' }
288 289
  s.documentation_url     = 'https://flutter.dev/docs'
  s.platform              = :ios, '8.0'
290
  s.vendored_frameworks   = 'Flutter.xcframework'
291 292 293 294 295 296 297 298 299 300
end
''';

      final File podspec = modeDirectory.childFile('Flutter.podspec')..createSync(recursive: true);
      podspec.writeAsStringSync(podspecContents);
    } finally {
      status.stop();
    }
  }

301
  Future<void> _produceFlutterFramework(
302
    BuildInfo buildInfo,
303 304 305
    Directory modeDirectory,
  ) async {
    final Status status = globals.logger.startProgress(
306
      ' ├─Copying Flutter.xcframework...',
307 308
    );
    final String engineCacheFlutterFrameworkDirectory = globals.artifacts.getArtifactPath(
309
      Artifact.flutterXcframework,
310
      platform: TargetPlatform.ios,
311
      mode: buildInfo.mode,
312 313 314 315
    );
    final String flutterFrameworkFileName = globals.fs.path.basename(
      engineCacheFlutterFrameworkDirectory,
    );
316
    final Directory flutterFrameworkCopy = modeDirectory.childDirectory(
317 318
      flutterFrameworkFileName,
    );
319

320
    try {
321
      // Copy xcframework engine cache framework to mode directory.
322
      copyDirectory(
323
        globals.fs.directory(engineCacheFlutterFrameworkDirectory),
324
        flutterFrameworkCopy,
325
      );
326 327
    } finally {
      status.stop();
xster's avatar
xster committed
328 329 330
    }
  }

331 332 333 334 335 336
  Future<void> _produceAppFramework(
    BuildInfo buildInfo,
    Directory outputDirectory,
    Directory iPhoneBuildOutput,
    Directory simulatorBuildOutput,
  ) async {
xster's avatar
xster committed
337 338
    const String appFrameworkName = 'App.framework';

339
    final Status status = globals.logger.startProgress(
340
      ' ├─Building App.xcframework...',
341
    );
342 343
    final List<EnvironmentType> environmentTypes = <EnvironmentType>[
      EnvironmentType.physical,
344
      EnvironmentType.simulator,
345
    ];
346
    final List<Directory> frameworks = <Directory>[];
347

348
    try {
349 350 351 352 353
      for (final EnvironmentType sdkType in environmentTypes) {
        final Directory outputBuildDirectory =
            sdkType == EnvironmentType.physical
                ? iPhoneBuildOutput
                : simulatorBuildOutput;
354 355 356 357 358 359 360 361 362 363 364
        frameworks.add(outputBuildDirectory.childDirectory(appFrameworkName));
        final Environment environment = Environment(
          projectDir: globals.fs.currentDirectory,
          outputDir: outputBuildDirectory,
          buildDir: _project.dartTool.childDirectory('flutter_build'),
          cacheDir: null,
          flutterRootDir: globals.fs.directory(Cache.flutterRoot),
          defines: <String, String>{
            kTargetFile: targetFile,
            kTargetPlatform: getNameForTargetPlatform(TargetPlatform.ios),
            kBitcodeFlag: 'true',
365
            kIosArchs: defaultIOSArchsForEnvironment(sdkType)
366 367 368
                .map(getNameForDarwinArch)
                .join(' '),
            kSdkRoot: await globals.xcode.sdkLocation(sdkType),
369
            ...buildInfo.toBuildSystemEnvironment(),
370 371 372 373 374
          },
          artifacts: globals.artifacts,
          fileSystem: globals.fs,
          logger: globals.logger,
          processManager: globals.processManager,
375
          platform: globals.platform,
376 377 378
          engineVersion: globals.artifacts.isLocalEngine
              ? null
              : globals.flutterVersion.engineRevision,
379
          generateDartPluginRegistry: true,
380
        );
381 382 383 384 385 386 387 388 389
        Target target;
        // Always build debug for simulator.
        if (buildInfo.isDebug || sdkType == EnvironmentType.simulator) {
          target = const DebugIosApplicationBundle();
        } else if (buildInfo.isProfile) {
          target = const ProfileIosApplicationBundle();
        } else {
          target = const ReleaseIosApplicationBundle();
        }
390 391 392 393 394 395
        final BuildResult result = await buildSystem.build(target, environment);
        if (!result.success) {
          for (final ExceptionMeasurement measurement
              in result.exceptions.values) {
            globals.printError(measurement.exception.toString());
          }
396
          throwToolExit('The App.xcframework build failed.');
397 398
        }
      }
399 400 401
    } finally {
      status.stop();
    }
402

403
    await _produceXCFramework(frameworks, 'App', outputDirectory);
xster's avatar
xster committed
404 405 406
  }

  Future<void> _producePlugins(
407
    BuildMode mode,
xster's avatar
xster committed
408 409 410 411 412 413
    String xcodeBuildConfiguration,
    Directory iPhoneBuildOutput,
    Directory simulatorBuildOutput,
    Directory modeDirectory,
    Directory outputDirectory,
  ) async {
414
    final Status status = globals.logger.startProgress(
415 416
      ' ├─Building plugins...'
    );
417
    try {
418 419 420
      final String bitcodeGenerationMode = mode == BuildMode.release ?
          'bitcode' : 'marker'; // In release, force bitcode embedding without archiving.

421
      List<String> pluginsBuildCommand = <String>[
422
        ...globals.xcode.xcrunCommand(),
423 424 425 426 427 428 429
        'xcodebuild',
        '-alltargets',
        '-sdk',
        'iphoneos',
        '-configuration',
        xcodeBuildConfiguration,
        'SYMROOT=${iPhoneBuildOutput.path}',
430
        'BITCODE_GENERATION_MODE=$bitcodeGenerationMode',
431 432
        'ONLY_ACTIVE_ARCH=NO', // No device targeted, so build all valid architectures.
        'BUILD_LIBRARY_FOR_DISTRIBUTION=YES',
433
      ];
xster's avatar
xster committed
434

435
      RunResult buildPluginsResult = await globals.processUtils.run(
436 437 438 439
        pluginsBuildCommand,
        workingDirectory: _project.ios.hostAppRoot.childDirectory('Pods').path,
        allowReentrantFlutter: false,
      );
xster's avatar
xster committed
440

441 442 443
      if (buildPluginsResult.exitCode != 0) {
        throwToolExit('Unable to build plugin frameworks: ${buildPluginsResult.stderr}');
      }
xster's avatar
xster committed
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
      // Always build debug for simulator.
      final String simulatorConfiguration = toTitleCase(getNameForBuildMode(BuildMode.debug));
      pluginsBuildCommand = <String>[
        ...globals.xcode.xcrunCommand(),
        'xcodebuild',
        '-alltargets',
        '-sdk',
        'iphonesimulator',
        '-configuration',
        simulatorConfiguration,
        'SYMROOT=${simulatorBuildOutput.path}',
        'ENABLE_BITCODE=YES', // Support host apps with bitcode enabled.
        'ONLY_ACTIVE_ARCH=NO', // No device targeted, so build all valid architectures.
        'BUILD_LIBRARY_FOR_DISTRIBUTION=YES',
      ];
xster's avatar
xster committed
460

461 462 463 464 465 466 467 468 469 470 471 472
      buildPluginsResult = await globals.processUtils.run(
        pluginsBuildCommand,
        workingDirectory: _project.ios.hostAppRoot
          .childDirectory('Pods')
          .path,
        allowReentrantFlutter: false,
      );

      if (buildPluginsResult.exitCode != 0) {
        throwToolExit(
          'Unable to build plugin frameworks for simulator: ${buildPluginsResult.stderr}',
        );
473 474
      }

475 476 477 478
      final Directory iPhoneBuildConfiguration = iPhoneBuildOutput.childDirectory(
        '$xcodeBuildConfiguration-iphoneos',
      );
      final Directory simulatorBuildConfiguration = simulatorBuildOutput.childDirectory(
479
        '$simulatorConfiguration-iphonesimulator',
480
      );
481

482 483 484 485
      final Iterable<Directory> products = iPhoneBuildConfiguration
        .listSync(followLinks: false)
        .whereType<Directory>();
      for (final Directory builtProduct in products) {
486
        for (final FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) {
487
          final String podFrameworkName = podProduct.basename;
488 489 490 491
          if (globals.fs.path.extension(podFrameworkName) != '.framework') {
            continue;
          }
          final String binaryName = globals.fs.path.basenameWithoutExtension(podFrameworkName);
492

493 494
          final List<Directory> frameworks = <Directory>[
            podProduct as Directory,
495 496 497
            simulatorBuildConfiguration
                .childDirectory(builtProduct.basename)
                .childDirectory(podFrameworkName)
498 499 500
          ];

          await _produceXCFramework(frameworks, binaryName, modeDirectory);
xster's avatar
xster committed
501 502
        }
      }
503 504
    } finally {
      status.stop();
xster's avatar
xster committed
505 506
    }
  }
507

508 509 510 511 512
  Future<void> _produceXCFramework(Iterable<Directory> frameworks,
      String frameworkBinaryName, Directory outputDirectory) async {
    if (!boolArg('xcframework')) {
      return;
    }
513
    final List<String> xcframeworkCommand = <String>[
514
      ...globals.xcode.xcrunCommand(),
515 516
      'xcodebuild',
      '-create-xcframework',
517 518
      for (Directory framework in frameworks) ...<String>[
        '-framework',
519 520 521 522 523 524 525 526 527
        framework.path,
        ...framework.parent
            .listSync()
            .where((FileSystemEntity entity) =>
                entity.basename.endsWith('bcsymbolmap') ||
                entity.basename.endsWith('dSYM'))
            .map((FileSystemEntity entity) =>
                <String>['-debug-symbols', entity.path])
            .expand<String>((List<String> parameter) => parameter)
528 529 530
      ],
      '-output',
      outputDirectory.childDirectory('$frameworkBinaryName.xcframework').path
531 532
    ];

533
    final RunResult xcframeworkResult = await globals.processUtils.run(
534 535 536 537 538 539
      xcframeworkCommand,
      allowReentrantFlutter: false,
    );

    if (xcframeworkResult.exitCode != 0) {
      throwToolExit(
540 541 542
          'Unable to create $frameworkBinaryName.xcframework: ${xcframeworkResult.stderr}');
    }
  }
xster's avatar
xster committed
543
}