cocoapods.dart 16.4 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
import 'package:process/process.dart';
8 9

import '../base/common.dart';
10
import '../base/error_handling_io.dart';
11 12 13
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
14
import '../base/platform.dart';
15 16 17
import '../base/process.dart';
import '../base/version.dart';
import '../cache.dart';
18
import '../ios/xcodeproj.dart';
19
import '../project.dart';
20

21
const String noCocoaPodsConsequence = '''
22 23
  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.
24
  For more info, see https://flutter.dev/platform-plugins''';
25

26 27 28 29
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.''';

30 31 32 33 34
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.
  This can usually be fixed by re-installing CocoaPods. For more info, see https://github.com/flutter/flutter/issues/14293.''';

35
const String outOfDateFrameworksPodfileConsequence = '''
36 37 38
  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.''';

39 40 41 42 43
const String outOfDatePluginsPodfileConsequence = '''
  This can cause issues if your application depends on plugins that do not support iOS.
  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.''';

44
const String cocoaPodsInstallInstructions = '''
45
  sudo gem install cocoapods''';
46

47
const String cocoaPodsUpgradeInstructions = '''
48
  sudo gem install cocoapods''';
49

50 51 52
const String podfileMigrationInstructions = '''
  rm ios/Podfile''';

53 54 55 56
/// Result of evaluating the CocoaPods installation.
enum CocoaPodsStatus {
  /// iOS plugins will not work, installation required.
  notInstalled,
57 58
  /// iOS plugins might not work, upgrade recommended.
  unknownVersion,
59 60 61 62 63 64 65
  /// 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,
66 67
  /// iOS plugins will not work, re-install required.
  brokenInstall,
68
}
69

70 71 72 73 74 75 76 77 78
/// Cocoapods is a depenency management solution for iOS and macOS applications.
///
/// 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.
79
class CocoaPods {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  CocoaPods({
    @required FileSystem fileSystem,
    @required ProcessManager processManager,
    @required XcodeProjectInterpreter xcodeProjectInterpreter,
    @required Logger logger,
    @required Platform platform,
    @required TimeoutConfiguration timeoutConfiguration,
  }) : _fileSystem = fileSystem,
      _processManager = processManager,
      _xcodeProjectInterpreter = xcodeProjectInterpreter,
      _logger = logger,
      _platform = platform,
      _processUtils = ProcessUtils(processManager: processManager, logger: logger),
      _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform),
      _timeoutConfiguration = timeoutConfiguration;

  final FileSystem _fileSystem;
  final ProcessManager _processManager;
  final FileSystemUtils _fileSystemUtils;
  final ProcessUtils _processUtils;
  final XcodeProjectInterpreter _xcodeProjectInterpreter;
  final Logger _logger;
  final Platform _platform;
  final TimeoutConfiguration _timeoutConfiguration;

105
  Future<String> _versionText;
106

107
  String get cocoaPodsMinimumVersion => '1.6.0';
108
  String get cocoaPodsRecommendedVersion => '1.8.0';
109

110
  Future<bool> get isInstalled =>
111
    _processUtils.exitsHappy(<String>['which', 'pod']);
112

113
  Future<String> get cocoaPodsVersionText {
114
    _versionText ??= _processUtils.run(
115 116 117 118 119
      <String>['pod', '--version'],
      environment: <String, String>{
        'LANG': 'en_US.UTF-8',
      },
    ).then<String>((RunResult result) {
120 121 122 123
      return result.exitCode == 0 ? result.stdout.trim() : null;
    }, onError: (dynamic _) => null);
    return _versionText;
  }
124

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

150 151 152
  /// Whether CocoaPods ran 'pod setup' once where the costly pods' specs are
  /// cloned.
  ///
153 154 155 156
  /// Versions >= 1.8.0 do not require 'pod setup' and default to a CDN instead
  /// of a locally cloned repository.
  /// See http://blog.cocoapods.org/CocoaPods-1.8.0-beta/
  ///
157 158 159 160 161
  /// A user can override the default location via the CP_REPOS_DIR environment
  /// variable.
  ///
  /// See https://github.com/CocoaPods/CocoaPods/blob/master/lib/cocoapods/config.rb#L138
  /// for details of this variable.
162 163 164 165 166
  Future<bool> get isCocoaPodsInitialized async {
    final Version installedVersion = Version.parse(await cocoaPodsVersionText);
    if (installedVersion != null && installedVersion >= Version.parse('1.8.0')) {
      return true;
    }
167 168 169
    final String cocoapodsReposDir = _platform.environment['CP_REPOS_DIR']
      ?? _fileSystem.path.join(_fileSystemUtils.homeDirPath, '.cocoapods', 'repos');
    return _fileSystem.isDirectory(_fileSystem.path.join(cocoapodsReposDir, 'master'));
170
  }
171

172
  Future<bool> processPods({
173
    @required XcodeBasedProject xcodeProject,
174
    // For backward compatibility with previously created Podfile only.
175
    @required String engineDir,
176
    bool dependenciesChanged = true,
177
  }) async {
178
    if (!xcodeProject.podfile.existsSync()) {
179 180
      throwToolExit('Podfile missing');
    }
181
    bool podsProcessed = false;
182 183 184
    if (_shouldRunPodInstall(xcodeProject, dependenciesChanged)) {
      if (!await _checkPodCondition()) {
        throwToolExit('CocoaPods not installed or not in valid state.');
185
      }
186 187
      await _runPodInstall(xcodeProject, engineDir);
      podsProcessed = true;
188
    }
189
    _warnIfPodfileOutOfDate(xcodeProject);
190
    return podsProcessed;
191 192
  }

193
  /// Make sure the CocoaPods tools are in the right states.
194
  Future<bool> _checkPodCondition() async {
195 196 197
    final CocoaPodsStatus installation = await evaluateCocoaPodsInstallation;
    switch (installation) {
      case CocoaPodsStatus.notInstalled:
198
        _logger.printError(
199 200 201 202 203 204 205
          'Warning: CocoaPods not installed. Skipping pod install.\n'
          '$noCocoaPodsConsequence\n'
          'To install:\n'
          '$cocoaPodsInstallInstructions\n',
          emphasis: true,
        );
        return false;
206
      case CocoaPodsStatus.brokenInstall:
207
        _logger.printError(
208 209 210 211 212 213 214
          'Warning: CocoaPods is installed but broken. Skipping pod install.\n'
          '$brokenCocoaPodsConsequence\n'
          'To re-install:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        return false;
215
      case CocoaPodsStatus.unknownVersion:
216
        _logger.printError(
217 218 219 220 221 222 223
          'Warning: Unknown CocoaPods version installed.\n'
          '$unknownCocoaPodsConsequence\n'
          'To upgrade:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        break;
224
      case CocoaPodsStatus.belowMinimumVersion:
225
        _logger.printError(
226 227 228 229 230 231 232 233
          'Warning: CocoaPods minimum required version $cocoaPodsMinimumVersion or greater not installed. Skipping pod install.\n'
          '$noCocoaPodsConsequence\n'
          'To upgrade:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        return false;
      case CocoaPodsStatus.belowRecommendedVersion:
234
        _logger.printError(
235 236 237 238 239 240 241
          'Warning: CocoaPods recommended version $cocoaPodsRecommendedVersion or greater not installed.\n'
          'Pods handling may fail on some projects involving plugins.\n'
          'To upgrade:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        break;
242
      case CocoaPodsStatus.recommended:
243
        break;
244 245
    }
    if (!await isCocoaPodsInitialized) {
246
      _logger.printError(
247 248 249 250
        'Warning: CocoaPods installed but not initialized. Skipping pod install.\n'
        '$noCocoaPodsConsequence\n'
        'To initialize CocoaPods, run:\n'
        '  pod setup\n'
251
        "once to finalize CocoaPods' installation.",
252 253 254 255 256 257 258 259
        emphasis: true,
      );
      return false;
    }

    return true;
  }

260
  /// Ensures the given Xcode-based sub-project of a parent Flutter project
261 262
  /// contains a suitable `Podfile` and that its `Flutter/Xxx.xcconfig` files
  /// include pods configuration.
263
  Future<void> setupPodfile(XcodeBasedProject xcodeProject) async {
264
    if (!_xcodeProjectInterpreter.isInstalled) {
265 266 267
      // Don't do anything for iOS when host platform doesn't support it.
      return;
    }
268
    final Directory runnerProject = xcodeProject.xcodeProject;
269
    if (!runnerProject.existsSync()) {
270 271
      return;
    }
272
    final File podfile = xcodeProject.podfile;
273 274 275 276 277 278 279 280
    if (podfile.existsSync()) {
      addPodsDependencyToFlutterXcconfig(xcodeProject);
      return;
    }
    String podfileTemplateName;
    if (xcodeProject is MacOSProject) {
      podfileTemplateName = 'Podfile-macos';
    } else {
281
      final bool isSwift = (await _xcodeProjectInterpreter.getBuildSettings(
282 283 284
        runnerProject.path,
      )).containsKey('SWIFT_VERSION');
      podfileTemplateName = isSwift ? 'Podfile-ios-swift' : 'Podfile-ios-objc';
285
    }
286
    final File podfileTemplate = _fileSystem.file(_fileSystem.path.join(
287 288 289 290 291 292 293 294
      Cache.flutterRoot,
      'packages',
      'flutter_tools',
      'templates',
      'cocoapods',
      podfileTemplateName,
    ));
    podfileTemplate.copySync(podfile.path);
295
    addPodsDependencyToFlutterXcconfig(xcodeProject);
296 297
  }

298 299 300 301 302
  /// 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');
303 304
  }

305 306
  void _addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject, String mode) {
    final File file = xcodeProject.xcodeConfigFor(mode);
307 308 309 310
    if (file.existsSync()) {
      final String content = file.readAsStringSync();
      final String include = '#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
          .toLowerCase()}.xcconfig"';
311
      if (!content.contains(include)) {
312
        file.writeAsStringSync('$include\n$content', flush: true);
313
      }
314 315 316 317
    }
  }

  /// Ensures that pod install is deemed needed on next check.
318 319
  void invalidatePodInstallOutput(XcodeBasedProject xcodeProject) {
    final File manifestLock = xcodeProject.podManifestLock;
320
    ErrorHandlingFileSystem.deleteIfExists(manifestLock);
321 322
  }

323 324
  // Check if you need to run pod install.
  // The pod install will run if any of below is true.
325 326 327 328
  // 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.
329
  bool _shouldRunPodInstall(XcodeBasedProject xcodeProject, bool dependenciesChanged) {
330
    if (dependenciesChanged) {
331
      return true;
332
    }
333

334 335 336
    final File podfileFile = xcodeProject.podfile;
    final File podfileLockFile = xcodeProject.podfileLock;
    final File manifestLockFile = xcodeProject.podManifestLock;
337

338
    return !podfileLockFile.existsSync()
339
        || !manifestLockFile.existsSync()
340
        || podfileLockFile.statSync().modified.isBefore(podfileFile.statSync().modified)
341
        || podfileLockFile.readAsStringSync() != manifestLockFile.readAsStringSync();
342 343
  }

344
  Future<void> _runPodInstall(XcodeBasedProject xcodeProject, String engineDirectory) async {
345 346
    final Status status = _logger.startProgress('Running pod install...', timeout: _timeoutConfiguration.slowOperation);
    final ProcessResult result = await _processManager.run(
347
      <String>['pod', 'install', '--verbose'],
348
      workingDirectory: _fileSystem.path.dirname(xcodeProject.podfile.path),
349
      environment: <String, String>{
350
        'FLUTTER_FRAMEWORK_DIR': engineDirectory,
351 352 353
        // See https://github.com/flutter/flutter/issues/10873.
        // CocoaPods analytics adds a lot of latency.
        'COCOAPODS_DISABLE_STATS': 'true',
354
        'LANG': 'en_US.UTF-8',
355
      },
356 357
    );
    status.stop();
358
    if (_logger.isVerbose || result.exitCode != 0) {
359 360
      final String stdout = result.stdout as String;
      if (stdout.isNotEmpty) {
361 362
        _logger.printStatus("CocoaPods' output:\n↳");
        _logger.printStatus(stdout, indent: 4);
363
      }
364 365
      final String stderr = result.stderr as String;
      if (stderr.isNotEmpty) {
366 367
        _logger.printStatus('Error output from CocoaPods:\n↳');
        _logger.printStatus(stderr, indent: 4);
368 369
      }
    }
370
    if (result.exitCode != 0) {
371
      invalidatePodInstallOutput(xcodeProject);
372
      _diagnosePodInstallFailure(result);
373
      throwToolExit('Error running pod install');
374 375 376 377
    }
  }

  void _diagnosePodInstallFailure(ProcessResult result) {
378 379
    final dynamic stdout = result.stdout;
    if (stdout is String && stdout.contains('out-of-date source repos')) {
380
      _logger.printError(
381 382 383 384 385 386
        "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,
      );
    }
387
  }
388 389 390 391 392

  void _warnIfPodfileOutOfDate(XcodeBasedProject xcodeProject) {
    if (xcodeProject is! IosProject) {
      return;
    }
393 394 395 396 397 398 399 400

    // 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.
401
    final Link flutterSymlink = _fileSystem.link(_fileSystem.path.join(
402
      (xcodeProject as IosProject).symlinks.path,
403 404 405
      'flutter',
    ));
    if (flutterSymlink.existsSync()) {
406
      _logger.printError(
407
        'Warning: Podfile is out of date\n'
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
        '$outOfDateFrameworksPodfileConsequence\n'
        'To regenerate the Podfile, run:\n'
        '$podfileMigrationInstructions\n',
        emphasis: true,
      );
      return;
    }
    // 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() &&
      xcodeProject.podfile.readAsStringSync().contains('.flutter-plugins\'')) {
      _logger.printError(
        'Warning: Podfile is out of date\n'
        '$outOfDatePluginsPodfileConsequence\n'
424 425 426 427 428 429
        'To regenerate the Podfile, run:\n'
        '$podfileMigrationInstructions\n',
        emphasis: true,
      );
    }
  }
430
}