build_ios_framework.dart 20.2 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
import 'package:meta/meta.dart';
xster's avatar
xster committed
6 7 8 9 10

import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
11
import '../base/platform.dart';
xster's avatar
xster committed
12 13 14
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
15
import '../build_system/build_system.dart';
xster's avatar
xster committed
16
import '../build_system/targets/ios.dart';
17
import '../cache.dart';
18
import '../flutter_plugins.dart';
19
import '../globals.dart' as globals;
xster's avatar
xster committed
20 21 22
import '../macos/cocoapod_utils.dart';
import '../project.dart';
import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult;
23
import '../version.dart';
xster's avatar
xster committed
24 25 26 27 28 29 30
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 {
31
  BuildIOSFrameworkCommand({
32 33 34 35 36 37 38
    // Instantiating FlutterVersion kicks off networking, so delay until it's needed, but allow test injection.
    @visibleForTesting FlutterVersion? flutterVersion,
    required BuildSystem buildSystem,
    required bool verboseHelp,
    Cache? cache,
    Platform? platform
  }) : _injectedFlutterVersion = flutterVersion,
39
       _buildSystem = buildSystem,
40
       _injectedCache = cache,
41 42
       _injectedPlatform = platform,
       super(verboseHelp: verboseHelp) {
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
    argParser
      ..addFlag('debug',
        defaultsTo: true,
        help: 'Whether to produce a framework for the debug build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('profile',
        defaultsTo: true,
        help: 'Whether to produce a framework for the profile build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('release',
        defaultsTo: true,
        help: 'Whether to produce a framework for the release build configuration. '
              'By default, all build configurations are built.'
      )
      ..addFlag('universal',
71 72
        help: '(deprecated) Produce universal frameworks that include all valid architectures.',
        hide: !verboseHelp,
xster's avatar
xster committed
73 74
      )
      ..addFlag('xcframework',
75
        help: 'Produce xcframeworks that include all valid architectures.',
76
        negatable: false,
77
        defaultsTo: true,
78
        hide: !verboseHelp,
xster's avatar
xster committed
79
      )
80
      ..addFlag('cocoapods',
81
        help: 'Produce a Flutter.podspec instead of an engine Flutter.xcframework (recommended if host app uses CocoaPods).',
82
      )
xster's avatar
xster committed
83 84 85 86
      ..addOption('output',
        abbr: 'o',
        valueHelp: 'path/to/directory/',
        help: 'Location to write the frameworks.',
87 88 89
      )
      ..addFlag('force',
        abbr: 'f',
90 91
        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
92 93 94
      );
  }

95
  final BuildSystem? _buildSystem;
96
  BuildSystem get buildSystem => _buildSystem ?? globals.buildSystem;
97 98

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

  Platform get _platform => _injectedPlatform ?? globals.platform;
102
  final Platform? _injectedPlatform;
103

104 105 106
  // FlutterVersion.instance kicks off git processing which can sometimes fail, so don't try it until needed.
  FlutterVersion get _flutterVersion => _injectedFlutterVersion ?? globals.flutterVersion;
  final FlutterVersion? _injectedFlutterVersion;
xster's avatar
xster committed
107

108 109 110
  @override
  bool get reportNullSafety => false;

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

  @override
115
  final String description = 'Produces .xcframeworks for a Flutter project '
xster's avatar
xster committed
116 117 118 119 120 121 122 123
      '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,
  };

124
  late final FlutterProject _project = FlutterProject.current();
xster's avatar
xster committed
125

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

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

139
    return buildInfos;
xster's avatar
xster committed
140 141
  }

142 143 144
  @override
  bool get supported => _platform.isMacOS;

xster's avatar
xster committed
145 146 147
  @override
  Future<void> validateCommand() async {
    await super.validateCommand();
148
    if (!supported) {
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
      globals.printStatus('Building frameworks for $productBundleIdentifier in ${getNameForBuildMode(buildInfo.mode)} mode...');
179
      final String xcodeBuildConfiguration = sentenceCase(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
      if (boolArg('cocoapods')) {
187
        produceFlutterPodspec(buildInfo.mode, modeDirectory, force: boolArg('force'));
188
      } else {
189
        // Copy Flutter.xcframework.
190
        await _produceFlutterFramework(buildInfo, modeDirectory);
191
      }
xster's avatar
xster committed
192 193

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

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

207
      final Status status = globals.logger.startProgress(
208
        ' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}');
209 210 211 212 213 214 215 216 217 218 219
      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
220 221 222
      }
    }

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

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

241
    return FlutterCommandResult.success();
xster's avatar
xster committed
242 243
  }

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

      // 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.
260
      final int minorHotfixVersion = (gitTagVersion.z ?? 0) * 100 + (gitTagVersion.hotfix ?? 0);
261

262
      final File license = _cache.getLicenseFile();
263 264 265 266 267 268 269 270 271
      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'
272
  s.version               = '${gitTagVersion.x}.${gitTagVersion.y}.$minorHotfixVersion' # ${_flutterVersion.frameworkVersion}
273
  s.summary               = 'A UI toolkit for beautiful and fast apps.'
274
  s.description           = <<-DESC
275
Flutter is Google's UI toolkit for building beautiful, fast apps for mobile, web, desktop, and embedded devices from a single codebase.
276 277 278 279
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'
280
  s.license               = { :type => 'BSD', :text => <<-LICENSE
281 282 283 284
$licenseSource
LICENSE
  }
  s.author                = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' }
285
  s.source                = { :http => '${_cache.storageBaseUrl}/flutter_infra_release/flutter/${_cache.engineRevision}/$artifactsMode/artifacts.zip' }
286
  s.documentation_url     = 'https://flutter.dev/docs'
287
  s.platform              = :ios, '9.0'
288
  s.vendored_frameworks   = 'Flutter.xcframework'
289 290 291 292 293 294 295 296 297 298
end
''';

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

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

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

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

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

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

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

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

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

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

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

442
      // Always build debug for simulator.
443
      final String simulatorConfiguration = sentenceCase(getNameForBuildMode(BuildMode.debug));
444
      pluginsBuildCommand = <String>[
445
        ...globals.xcode!.xcrunCommand(),
446 447 448 449 450 451 452 453 454 455 456
        '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
457

458 459 460 461 462 463 464 465 466 467 468
      buildPluginsResult = await globals.processUtils.run(
        pluginsBuildCommand,
        workingDirectory: _project.ios.hostAppRoot
          .childDirectory('Pods')
          .path,
      );

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

471 472 473 474
      final Directory iPhoneBuildConfiguration = iPhoneBuildOutput.childDirectory(
        '$xcodeBuildConfiguration-iphoneos',
      );
      final Directory simulatorBuildConfiguration = simulatorBuildOutput.childDirectory(
475
        '$simulatorConfiguration-iphonesimulator',
476
      );
477

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

489 490
          final List<Directory> frameworks = <Directory>[
            podProduct as Directory,
491 492 493
            simulatorBuildConfiguration
                .childDirectory(builtProduct.basename)
                .childDirectory(podFrameworkName)
494 495 496
          ];

          await _produceXCFramework(frameworks, binaryName, modeDirectory);
xster's avatar
xster committed
497 498
        }
      }
499 500
    } finally {
      status.stop();
xster's avatar
xster committed
501 502
    }
  }
503

504 505 506 507 508
  Future<void> _produceXCFramework(Iterable<Directory> frameworks,
      String frameworkBinaryName, Directory outputDirectory) async {
    if (!boolArg('xcframework')) {
      return;
    }
509
    final List<String> xcframeworkCommand = <String>[
510
      ...globals.xcode!.xcrunCommand(),
511 512
      'xcodebuild',
      '-create-xcframework',
513 514
      for (Directory framework in frameworks) ...<String>[
        '-framework',
515 516 517 518 519 520 521 522 523
        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)
524 525 526
      ],
      '-output',
      outputDirectory.childDirectory('$frameworkBinaryName.xcframework').path
527 528
    ];

529
    final RunResult xcframeworkResult = await globals.processUtils.run(
530 531 532 533 534
      xcframeworkCommand,
    );

    if (xcframeworkResult.exitCode != 0) {
      throwToolExit(
535 536 537
          'Unable to create $frameworkBinaryName.xcframework: ${xcframeworkResult.stderr}');
    }
  }
xster's avatar
xster committed
538
}