cocoapods.dart 16.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
// @dart = 2.8

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

import '../base/common.dart';
12
import '../base/error_handling_io.dart';
13 14 15
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
16
import '../base/os.dart';
17
import '../base/platform.dart';
18 19
import '../base/process.dart';
import '../base/version.dart';
20
import '../build_info.dart';
21
import '../cache.dart';
22
import '../ios/xcodeproj.dart';
23
import '../project.dart';
24
import '../reporting/reporting.dart';
25

26
const String noCocoaPodsConsequence = '''
27 28
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
29
  For more info, see https://flutter.dev/platform-plugins''';
30

31 32 33 34
const String unknownCocoaPodsConsequence = '''
  Flutter is unable to determine the installed CocoaPods's version.
  Ensure that the output of 'pod --version' contains only digits and . to be recognized by Flutter.''';

35 36 37
const String brokenCocoaPodsConsequence = '''
  You appear to have CocoaPods installed but it is not working.
  This can happen if the version of Ruby that CocoaPods was installed with is different from the one being used to invoke it.
38
  This can usually be fixed by re-installing CocoaPods.''';
39

40
const String outOfDateFrameworksPodfileConsequence = '''
41 42 43
  This can cause a mismatched version of Flutter to be embedded in your app, which may result in App Store submission rejection or crashes.
  If you have local Podfile edits you would like to keep, see https://github.com/flutter/flutter/issues/24641 for instructions.''';

44
const String outOfDatePluginsPodfileConsequence = '''
45
  This can cause issues if your application depends on plugins that do not support iOS or macOS.
46 47 48
  See https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms for details.
  If you have local Podfile edits you would like to keep, see https://github.com/flutter/flutter/issues/45197 for instructions.''';

49
const String cocoaPodsInstallInstructions = 'see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.';
50

51
const String podfileIosMigrationInstructions = '''
52 53
  rm ios/Podfile''';

54 55 56
const String podfileMacOSMigrationInstructions = '''
  rm macos/Podfile''';

57 58 59 60
/// Result of evaluating the CocoaPods installation.
enum CocoaPodsStatus {
  /// iOS plugins will not work, installation required.
  notInstalled,
61 62
  /// iOS plugins might not work, upgrade recommended.
  unknownVersion,
63 64 65 66 67 68 69
  /// iOS plugins will not work, upgrade required.
  belowMinimumVersion,
  /// iOS plugins may not work in certain situations (Swift, static libraries),
  /// upgrade recommended.
  belowRecommendedVersion,
  /// Everything should be fine.
  recommended,
70 71
  /// iOS plugins will not work, re-install required.
  brokenInstall,
72
}
73

74 75
const Version cocoaPodsMinimumVersion = Version.withText(1, 9, 0, '1.9.0');
const Version cocoaPodsRecommendedVersion = Version.withText(1, 10, 0, '1.10.0');
76

77
/// Cocoapods is a dependency management solution for iOS and macOS applications.
78 79 80 81 82 83 84 85
///
/// Cocoapods is generally installed via ruby gems and interacted with via
/// the `pod` CLI command.
///
/// See also:
///   * https://cocoapods.org/ - the cocoapods website.
///   * https://flutter.dev/docs/get-started/install/macos#deploy-to-ios-devices - instructions for
///     installing iOS/macOS dependencies.
86
class CocoaPods {
87 88 89 90 91 92
  CocoaPods({
    @required FileSystem fileSystem,
    @required ProcessManager processManager,
    @required XcodeProjectInterpreter xcodeProjectInterpreter,
    @required Logger logger,
    @required Platform platform,
93
    @required Usage usage,
94 95 96 97
  }) : _fileSystem = fileSystem,
      _processManager = processManager,
      _xcodeProjectInterpreter = xcodeProjectInterpreter,
      _logger = logger,
98
      _usage = usage,
99
      _processUtils = ProcessUtils(processManager: processManager, logger: logger),
100 101 102 103 104 105
      _operatingSystemUtils = OperatingSystemUtils(
        fileSystem: fileSystem,
        logger: logger,
        platform: platform,
        processManager: processManager,
      );
106 107 108 109

  final FileSystem _fileSystem;
  final ProcessManager _processManager;
  final ProcessUtils _processUtils;
110
  final OperatingSystemUtils _operatingSystemUtils;
111 112
  final XcodeProjectInterpreter _xcodeProjectInterpreter;
  final Logger _logger;
113
  final Usage _usage;
114

115
  Future<String> _versionText;
116

117
  Future<bool> get isInstalled =>
118
    _processUtils.exitsHappy(<String>['which', 'pod']);
119

120
  Future<String> get cocoaPodsVersionText {
121
    _versionText ??= _processUtils.run(
122 123 124 125 126
      <String>['pod', '--version'],
      environment: <String, String>{
        'LANG': 'en_US.UTF-8',
      },
    ).then<String>((RunResult result) {
127 128 129 130
      return result.exitCode == 0 ? result.stdout.trim() : null;
    }, onError: (dynamic _) => null);
    return _versionText;
  }
131

132
  Future<CocoaPodsStatus> get evaluateCocoaPodsInstallation async {
133
    if (!(await isInstalled)) {
134
      return CocoaPodsStatus.notInstalled;
135 136 137 138 139
    }
    final String versionText = await cocoaPodsVersionText;
    if (versionText == null) {
      return CocoaPodsStatus.brokenInstall;
    }
140
    try {
141
      final Version installedVersion = Version.parse(versionText);
142
      if (installedVersion == null) {
143
        return CocoaPodsStatus.unknownVersion;
144
      }
145
      if (installedVersion < cocoaPodsMinimumVersion) {
146
        return CocoaPodsStatus.belowMinimumVersion;
147
      }
148
      if (installedVersion < cocoaPodsRecommendedVersion) {
149
        return CocoaPodsStatus.belowRecommendedVersion;
150 151
      }
      return CocoaPodsStatus.recommended;
152
    } on FormatException {
153
      return CocoaPodsStatus.notInstalled;
154 155 156
    }
  }

157
  Future<bool> processPods({
158
    @required XcodeBasedProject xcodeProject,
159
    @required BuildMode buildMode,
160
    bool dependenciesChanged = true,
161
  }) async {
162
    if (!xcodeProject.podfile.existsSync()) {
163 164
      throwToolExit('Podfile missing');
    }
165
    _warnIfPodfileOutOfDate(xcodeProject);
166
    bool podsProcessed = false;
167 168 169
    if (_shouldRunPodInstall(xcodeProject, dependenciesChanged)) {
      if (!await _checkPodCondition()) {
        throwToolExit('CocoaPods not installed or not in valid state.');
170
      }
171
      await _runPodInstall(xcodeProject, buildMode);
172
      podsProcessed = true;
173
    }
174
    return podsProcessed;
175 176
  }

177
  /// Make sure the CocoaPods tools are in the right states.
178
  Future<bool> _checkPodCondition() async {
179 180 181
    final CocoaPodsStatus installation = await evaluateCocoaPodsInstallation;
    switch (installation) {
      case CocoaPodsStatus.notInstalled:
182
        _logger.printError(
183 184
          'Warning: CocoaPods not installed. Skipping pod install.\n'
          '$noCocoaPodsConsequence\n'
185
          'To install $cocoaPodsInstallInstructions\n',
186 187 188
          emphasis: true,
        );
        return false;
189
      case CocoaPodsStatus.brokenInstall:
190
        _logger.printError(
191 192
          'Warning: CocoaPods is installed but broken. Skipping pod install.\n'
          '$brokenCocoaPodsConsequence\n'
193
          'To re-install $cocoaPodsInstallInstructions\n',
194 195 196
          emphasis: true,
        );
        return false;
197
      case CocoaPodsStatus.unknownVersion:
198
        _logger.printError(
199 200
          'Warning: Unknown CocoaPods version installed.\n'
          '$unknownCocoaPodsConsequence\n'
201
          'To upgrade $cocoaPodsInstallInstructions\n',
202 203 204
          emphasis: true,
        );
        break;
205
      case CocoaPodsStatus.belowMinimumVersion:
206
        _logger.printError(
207 208
          'Warning: CocoaPods minimum required version $cocoaPodsMinimumVersion or greater not installed. Skipping pod install.\n'
          '$noCocoaPodsConsequence\n'
209
          'To upgrade $cocoaPodsInstallInstructions\n',
210 211 212 213
          emphasis: true,
        );
        return false;
      case CocoaPodsStatus.belowRecommendedVersion:
214
        _logger.printError(
215 216
          'Warning: CocoaPods recommended version $cocoaPodsRecommendedVersion or greater not installed.\n'
          'Pods handling may fail on some projects involving plugins.\n'
217
          'To upgrade $cocoaPodsInstallInstructions\n',
218 219 220
          emphasis: true,
        );
        break;
221
      case CocoaPodsStatus.recommended:
222
        break;
223 224 225 226 227
    }

    return true;
  }

228
  /// Ensures the given Xcode-based sub-project of a parent Flutter project
229 230
  /// contains a suitable `Podfile` and that its `Flutter/Xxx.xcconfig` files
  /// include pods configuration.
231
  Future<void> setupPodfile(XcodeBasedProject xcodeProject) async {
232
    if (!_xcodeProjectInterpreter.isInstalled) {
233 234 235
      // Don't do anything for iOS when host platform doesn't support it.
      return;
    }
236
    final Directory runnerProject = xcodeProject.xcodeProject;
237
    if (!runnerProject.existsSync()) {
238 239
      return;
    }
240
    final File podfile = xcodeProject.podfile;
241 242 243 244 245 246 247 248
    if (podfile.existsSync()) {
      addPodsDependencyToFlutterXcconfig(xcodeProject);
      return;
    }
    String podfileTemplateName;
    if (xcodeProject is MacOSProject) {
      podfileTemplateName = 'Podfile-macos';
    } else {
249
      final bool isSwift = (await _xcodeProjectInterpreter.getBuildSettings(
250
        runnerProject.path,
251
        buildContext: const XcodeProjectBuildContext(),
252 253
      )).containsKey('SWIFT_VERSION');
      podfileTemplateName = isSwift ? 'Podfile-ios-swift' : 'Podfile-ios-objc';
254
    }
255
    final File podfileTemplate = _fileSystem.file(_fileSystem.path.join(
256 257 258 259 260 261 262 263
      Cache.flutterRoot,
      'packages',
      'flutter_tools',
      'templates',
      'cocoapods',
      podfileTemplateName,
    ));
    podfileTemplate.copySync(podfile.path);
264
    addPodsDependencyToFlutterXcconfig(xcodeProject);
265 266
  }

267 268 269 270 271
  /// Ensures all `Flutter/Xxx.xcconfig` files for the given Xcode-based
  /// sub-project of a parent Flutter project include pods configuration.
  void addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject) {
    _addPodsDependencyToFlutterXcconfig(xcodeProject, 'Debug');
    _addPodsDependencyToFlutterXcconfig(xcodeProject, 'Release');
272 273
  }

274 275
  void _addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject, String mode) {
    final File file = xcodeProject.xcodeConfigFor(mode);
276 277
    if (file.existsSync()) {
      final String content = file.readAsStringSync();
278 279 280 281
      final String includeFile = 'Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
          .toLowerCase()}.xcconfig';
      final String include = '#include? "$includeFile"';
      if (!content.contains(includeFile)) {
282
        file.writeAsStringSync('$include\n$content', flush: true);
283
      }
284 285 286 287
    }
  }

  /// Ensures that pod install is deemed needed on next check.
288 289
  void invalidatePodInstallOutput(XcodeBasedProject xcodeProject) {
    final File manifestLock = xcodeProject.podManifestLock;
290
    ErrorHandlingFileSystem.deleteIfExists(manifestLock);
291 292
  }

293 294
  // Check if you need to run pod install.
  // The pod install will run if any of below is true.
295 296 297 298
  // 1. Flutter dependencies have changed
  // 2. Podfile.lock doesn't exist or is older than Podfile
  // 3. Pods/Manifest.lock doesn't exist (It is deleted when plugins change)
  // 4. Podfile.lock doesn't match Pods/Manifest.lock.
299
  bool _shouldRunPodInstall(XcodeBasedProject xcodeProject, bool dependenciesChanged) {
300
    if (dependenciesChanged) {
301
      return true;
302
    }
303

304 305 306
    final File podfileFile = xcodeProject.podfile;
    final File podfileLockFile = xcodeProject.podfileLock;
    final File manifestLockFile = xcodeProject.podManifestLock;
307

308
    return !podfileLockFile.existsSync()
309
        || !manifestLockFile.existsSync()
310
        || podfileLockFile.statSync().modified.isBefore(podfileFile.statSync().modified)
311
        || podfileLockFile.readAsStringSync() != manifestLockFile.readAsStringSync();
312 313
  }

314
  Future<void> _runPodInstall(XcodeBasedProject xcodeProject, BuildMode buildMode) async {
315
    final Status status = _logger.startProgress('Running pod install...');
316
    final ProcessResult result = await _processManager.run(
317
      <String>['pod', 'install', '--verbose'],
318
      workingDirectory: _fileSystem.path.dirname(xcodeProject.podfile.path),
319 320 321 322
      environment: <String, String>{
        // See https://github.com/flutter/flutter/issues/10873.
        // CocoaPods analytics adds a lot of latency.
        'COCOAPODS_DISABLE_STATS': 'true',
323
        'LANG': 'en_US.UTF-8',
324
      },
325 326
    );
    status.stop();
327
    if (_logger.isVerbose || result.exitCode != 0) {
328 329
      final String stdout = result.stdout as String;
      if (stdout.isNotEmpty) {
330 331
        _logger.printStatus("CocoaPods' output:\n↳");
        _logger.printStatus(stdout, indent: 4);
332
      }
333 334
      final String stderr = result.stderr as String;
      if (stderr.isNotEmpty) {
335 336
        _logger.printStatus('Error output from CocoaPods:\n↳');
        _logger.printStatus(stderr, indent: 4);
337 338
      }
    }
339

340
    if (result.exitCode != 0) {
341
      invalidatePodInstallOutput(xcodeProject);
342
      _diagnosePodInstallFailure(result);
343
      throwToolExit('Error running pod install');
344 345 346 347 348 349 350
    } else if (xcodeProject.podfileLock.existsSync()) {
      // Even if the Podfile.lock didn't change, update its modified date to now
      // so Podfile.lock is newer than Podfile.
      _processManager.runSync(
        <String>['touch', xcodeProject.podfileLock.path],
        workingDirectory: _fileSystem.path.dirname(xcodeProject.podfile.path),
      );
351 352 353 354
    }
  }

  void _diagnosePodInstallFailure(ProcessResult result) {
355 356 357 358 359
    if (result.stdout is! String) {
      return;
    }
    final String stdout = result.stdout as String;
    if (stdout.contains('out-of-date source repos')) {
360
      _logger.printError(
361 362 363 364 365
        "Error: CocoaPods's specs repository is too out-of-date to satisfy dependencies.\n"
        'To update the CocoaPods specs, run:\n'
        '  pod repo update\n',
        emphasis: true,
      );
366 367 368 369 370 371 372 373 374 375 376 377 378 379
    } else if (stdout.contains('Init_ffi_c') &&
        stdout.contains('symbol not found') &&
        _operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm) {
      // https://github.com/flutter/flutter/issues/70796
      UsageEvent(
        'pod-install-failure',
        'arm-ffi',
        flutterUsage: _usage,
      ).send();
      _logger.printError(
        'Error: To set up CocoaPods for ARM macOS, run:\n'
        '  arch -x86_64 sudo gem install ffi\n',
        emphasis: true,
      );
380
    }
381
  }
382 383

  void _warnIfPodfileOutOfDate(XcodeBasedProject xcodeProject) {
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    final bool isIos = xcodeProject is IosProject;
    if (isIos) {
      // Previously, the Podfile created a symlink to the cached artifacts engine framework
      // and installed the Flutter pod from that path. This could get out of sync with the copy
      // of the Flutter engine that was copied to ios/Flutter by the xcode_backend script.
      // It was possible for the symlink to point to a Debug version of the engine when the
      // Xcode build configuration was Release, which caused App Store submission rejections.
      //
      // Warn the user if they are still symlinking to the framework.
      final Link flutterSymlink = _fileSystem.link(_fileSystem.path.join(
        (xcodeProject as IosProject).symlinks.path,
        'flutter',
      ));
      if (flutterSymlink.existsSync()) {
        throwToolExit(
          'Warning: Podfile is out of date\n'
              '$outOfDateFrameworksPodfileConsequence\n'
              'To regenerate the Podfile, run:\n'
              '$podfileIosMigrationInstructions\n',
        );
      }
405 406 407 408 409 410
    }
    // Most of the pod and plugin parsing logic was moved from the Podfile
    // into the tool's podhelper.rb script. If the Podfile still references
    // the old parsed .flutter-plugins file, prompt the regeneration. Old line was:
    // plugin_pods = parse_KV_file('../.flutter-plugins')
    if (xcodeProject.podfile.existsSync() &&
411
      xcodeProject.podfile.readAsStringSync().contains(".flutter-plugins'")) {
412 413 414 415 416 417 418 419 420 421
      const String error = 'Warning: Podfile is out of date\n'
          '$outOfDatePluginsPodfileConsequence\n'
          'To regenerate the Podfile, run:\n';
      if (isIos) {
        throwToolExit('$error\n$podfileIosMigrationInstructions\n');
      } else {
        // The old macOS Podfile will work until `.flutter-plugins` is removed.
        // Warn instead of exit.
        _logger.printError('$error\n$podfileMacOSMigrationInstructions\n', emphasis: true);
      }
422 423
    }
  }
424
}