cocoapods.dart 13.3 KB
Newer Older
1 2 3 4 5 6
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:file/file.dart';
8 9 10 11 12 13 14
import 'package:meta/meta.dart';

import '../base/common.dart';
import '../base/context.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
15
import '../base/platform.dart';
16 17 18 19 20
import '../base/process.dart';
import '../base/process_manager.dart';
import '../base/version.dart';
import '../cache.dart';
import '../globals.dart';
21
import '../ios/xcodeproj.dart';
22
import '../project.dart';
23

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

29 30 31 32
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.''';

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

38 39 40 41
const String outOfDatePodfileConsequence = '''
  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.''';

42
const String cocoaPodsInstallInstructions = '''
43
  sudo gem install cocoapods''';
44

45
const String cocoaPodsUpgradeInstructions = '''
46
  sudo gem install cocoapods''';
47

48 49 50
const String podfileMigrationInstructions = '''
  rm ios/Podfile''';

51
CocoaPods get cocoaPods => context.get<CocoaPods>();
52

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
class CocoaPods {
  Future<String> _versionText;
72

73 74
  String get cocoaPodsMinimumVersion => '1.6.0';
  String get cocoaPodsRecommendedVersion => '1.6.0';
75

76 77
  Future<bool> get isInstalled =>
      processUtils.exitsHappy(<String>['which', 'pod']);
78

79
  Future<String> get cocoaPodsVersionText {
80
    _versionText ??= processUtils.run(<String>['pod', '--version']).then<String>((RunResult result) {
81 82 83 84
      return result.exitCode == 0 ? result.stdout.trim() : null;
    }, onError: (dynamic _) => null);
    return _versionText;
  }
85

86
  Future<CocoaPodsStatus> get evaluateCocoaPodsInstallation async {
87
    if (!(await isInstalled)) {
88
      return CocoaPodsStatus.notInstalled;
89 90 91 92 93
    }
    final String versionText = await cocoaPodsVersionText;
    if (versionText == null) {
      return CocoaPodsStatus.brokenInstall;
    }
94
    try {
95
      final Version installedVersion = Version.parse(versionText);
96
      if (installedVersion == null) {
97
        return CocoaPodsStatus.unknownVersion;
98 99
      }
      if (installedVersion < Version.parse(cocoaPodsMinimumVersion)) {
100
        return CocoaPodsStatus.belowMinimumVersion;
101 102
      }
      if (installedVersion < Version.parse(cocoaPodsRecommendedVersion)) {
103
        return CocoaPodsStatus.belowRecommendedVersion;
104 105
      }
      return CocoaPodsStatus.recommended;
106
    } on FormatException {
107
      return CocoaPodsStatus.notInstalled;
108 109 110
    }
  }

111 112 113
  /// Whether CocoaPods ran 'pod setup' once where the costly pods' specs are
  /// cloned.
  ///
114 115 116 117
  /// 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/
  ///
118 119 120 121 122
  /// 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.
123 124 125 126 127
  Future<bool> get isCocoaPodsInitialized async {
    final Version installedVersion = Version.parse(await cocoaPodsVersionText);
    if (installedVersion != null && installedVersion >= Version.parse('1.8.0')) {
      return true;
    }
128 129 130
    final String cocoapodsReposDir = platform.environment['CP_REPOS_DIR'] ?? fs.path.join(homeDirPath, '.cocoapods', 'repos');
    return fs.isDirectory(fs.path.join(cocoapodsReposDir, 'master'));
  }
131

132
  Future<bool> processPods({
133
    @required XcodeBasedProject xcodeProject,
134
    // For backward compatibility with previously created Podfile only.
135
    @required String engineDir,
136 137
    bool isSwift = false,
    bool dependenciesChanged = true,
138
  }) async {
139
    if (!xcodeProject.podfile.existsSync()) {
140 141
      throwToolExit('Podfile missing');
    }
142
    bool podsProcessed = false;
143
    if (await _checkPodCondition()) {
144 145
      if (_shouldRunPodInstall(xcodeProject, dependenciesChanged)) {
        await _runPodInstall(xcodeProject, engineDir);
146
        podsProcessed = true;
147
      }
148
      _warnIfPodfileOutOfDate(xcodeProject);
149
    }
150
    return podsProcessed;
151 152
  }

153
  /// Make sure the CocoaPods tools are in the right states.
154
  Future<bool> _checkPodCondition() async {
155 156 157 158 159 160 161 162 163 164 165
    final CocoaPodsStatus installation = await evaluateCocoaPodsInstallation;
    switch (installation) {
      case CocoaPodsStatus.notInstalled:
        printError(
          'Warning: CocoaPods not installed. Skipping pod install.\n'
          '$noCocoaPodsConsequence\n'
          'To install:\n'
          '$cocoaPodsInstallInstructions\n',
          emphasis: true,
        );
        return false;
166 167 168 169 170 171 172 173 174
      case CocoaPodsStatus.unknownVersion:
        printError(
          'Warning: Unknown CocoaPods version installed.\n'
          '$unknownCocoaPodsConsequence\n'
          'To upgrade:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        break;
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      case CocoaPodsStatus.belowMinimumVersion:
        printError(
          '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:
        printError(
          '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;
      default:
        break;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    }
    if (!await isCocoaPodsInitialized) {
      printError(
        'Warning: CocoaPods installed but not initialized. Skipping pod install.\n'
        '$noCocoaPodsConsequence\n'
        'To initialize CocoaPods, run:\n'
        '  pod setup\n'
        'once to finalize CocoaPods\' installation.',
        emphasis: true,
      );
      return false;
    }

    return true;
  }

211
  /// Ensures the given Xcode-based sub-project of a parent Flutter project
212 213
  /// contains a suitable `Podfile` and that its `Flutter/Xxx.xcconfig` files
  /// include pods configuration.
214
  Future<void> setupPodfile(XcodeBasedProject xcodeProject) async {
215
    if (!xcodeProjectInterpreter.isInstalled) {
216 217 218
      // Don't do anything for iOS when host platform doesn't support it.
      return;
    }
219
    final Directory runnerProject = xcodeProject.xcodeProject;
220
    if (!runnerProject.existsSync()) {
221 222
      return;
    }
223
    final File podfile = xcodeProject.podfile;
224 225 226 227 228 229 230 231
    if (podfile.existsSync()) {
      addPodsDependencyToFlutterXcconfig(xcodeProject);
      return;
    }
    String podfileTemplateName;
    if (xcodeProject is MacOSProject) {
      podfileTemplateName = 'Podfile-macos';
    } else {
232
      final bool isSwift = (await xcodeProjectInterpreter.getBuildSettings(
233 234 235 236
        runnerProject.path,
        'Runner',
      )).containsKey('SWIFT_VERSION');
      podfileTemplateName = isSwift ? 'Podfile-ios-swift' : 'Podfile-ios-objc';
237
    }
238 239 240 241 242 243 244 245 246
    final File podfileTemplate = fs.file(fs.path.join(
      Cache.flutterRoot,
      'packages',
      'flutter_tools',
      'templates',
      'cocoapods',
      podfileTemplateName,
    ));
    podfileTemplate.copySync(podfile.path);
247
    addPodsDependencyToFlutterXcconfig(xcodeProject);
248 249
  }

250 251 252 253 254
  /// 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');
255 256
  }

257 258
  void _addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject, String mode) {
    final File file = xcodeProject.xcodeConfigFor(mode);
259 260 261 262
    if (file.existsSync()) {
      final String content = file.readAsStringSync();
      final String include = '#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
          .toLowerCase()}.xcconfig"';
263
      if (!content.contains(include)) {
264
        file.writeAsStringSync('$include\n$content', flush: true);
265
      }
266 267 268 269
    }
  }

  /// Ensures that pod install is deemed needed on next check.
270 271
  void invalidatePodInstallOutput(XcodeBasedProject xcodeProject) {
    final File manifestLock = xcodeProject.podManifestLock;
272 273 274
    if (manifestLock.existsSync()) {
      manifestLock.deleteSync();
    }
275 276
  }

277 278
  // Check if you need to run pod install.
  // The pod install will run if any of below is true.
279 280 281 282
  // 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.
283
  bool _shouldRunPodInstall(XcodeBasedProject xcodeProject, bool dependenciesChanged) {
284
    if (dependenciesChanged) {
285
      return true;
286
    }
287

288 289 290
    final File podfileFile = xcodeProject.podfile;
    final File podfileLockFile = xcodeProject.podfileLock;
    final File manifestLockFile = xcodeProject.podManifestLock;
291

292
    return !podfileLockFile.existsSync()
293
        || !manifestLockFile.existsSync()
294
        || podfileLockFile.statSync().modified.isBefore(podfileFile.statSync().modified)
295
        || podfileLockFile.readAsStringSync() != manifestLockFile.readAsStringSync();
296 297
  }

298
  Future<void> _runPodInstall(XcodeBasedProject xcodeProject, String engineDirectory) async {
299
    final Status status = logger.startProgress('Running pod install...', timeout: timeoutConfiguration.slowOperation);
300 301
    final ProcessResult result = await processManager.run(
      <String>['pod', 'install', '--verbose'],
302
      workingDirectory: fs.path.dirname(xcodeProject.podfile.path),
303
      environment: <String, String>{
304
        'FLUTTER_FRAMEWORK_DIR': engineDirectory,
305 306 307 308
        // See https://github.com/flutter/flutter/issues/10873.
        // CocoaPods analytics adds a lot of latency.
        'COCOAPODS_DISABLE_STATS': 'true',
      },
309 310 311 312 313 314 315 316 317 318 319 320
    );
    status.stop();
    if (logger.isVerbose || result.exitCode != 0) {
      if (result.stdout.isNotEmpty) {
        printStatus('CocoaPods\' output:\n↳');
        printStatus(result.stdout, indent: 4);
      }
      if (result.stderr.isNotEmpty) {
        printStatus('Error output from CocoaPods:\n↳');
        printStatus(result.stderr, indent: 4);
      }
    }
321
    if (result.exitCode != 0) {
322
      invalidatePodInstallOutput(xcodeProject);
323
      _diagnosePodInstallFailure(result);
324
      throwToolExit('Error running pod install');
325 326 327 328 329 330 331 332 333 334 335 336
    }
  }

  void _diagnosePodInstallFailure(ProcessResult result) {
    if (result.stdout is String && result.stdout.contains('out-of-date source repos')) {
      printError(
        "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,
      );
    }
337
  }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

  // 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.
  void _warnIfPodfileOutOfDate(XcodeBasedProject xcodeProject) {
    if (xcodeProject is! IosProject) {
      return;
    }
    final Link flutterSymlink = fs.link(fs.path.join(
      xcodeProject.symlinks.path,
      'flutter',
    ));
    if (flutterSymlink.existsSync()) {
      printError(
        'Warning: Podfile is out of date\n'
        '$outOfDatePodfileConsequence\n'
        'To regenerate the Podfile, run:\n'
        '$podfileMigrationInstructions\n',
        emphasis: true,
      );
    }
  }
364
}