cocoapods.dart 13.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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 15 16 17
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';
import '../base/process.dart';
import '../base/version.dart';
import '../cache.dart';
18
import '../globals.dart' as globals;
19
import '../ios/xcodeproj.dart';
20
import '../project.dart';
21

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

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

31 32 33 34 35
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.''';

36 37 38 39
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.''';

40
const String cocoaPodsInstallInstructions = '''
41
  sudo gem install cocoapods''';
42

43
const String cocoaPodsUpgradeInstructions = '''
44
  sudo gem install cocoapods''';
45

46 47 48
const String podfileMigrationInstructions = '''
  rm ios/Podfile''';

49
CocoaPods get cocoaPods => context.get<CocoaPods>();
50

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

68 69
class CocoaPods {
  Future<String> _versionText;
70

71 72
  String get cocoaPodsMinimumVersion => '1.6.0';
  String get cocoaPodsRecommendedVersion => '1.6.0';
73

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

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

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

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

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

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

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

253 254 255 256 257
  /// 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');
258 259
  }

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

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

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

291 292 293
    final File podfileFile = xcodeProject.podfile;
    final File podfileLockFile = xcodeProject.podfileLock;
    final File manifestLockFile = xcodeProject.podManifestLock;
294

295
    return !podfileLockFile.existsSync()
296
        || !manifestLockFile.existsSync()
297
        || podfileLockFile.statSync().modified.isBefore(podfileFile.statSync().modified)
298
        || podfileLockFile.readAsStringSync() != manifestLockFile.readAsStringSync();
299 300
  }

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

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

  // 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;
    }
357
    final Link flutterSymlink = globals.fs.link(globals.fs.path.join(
358 359 360 361
      xcodeProject.symlinks.path,
      'flutter',
    ));
    if (flutterSymlink.existsSync()) {
362
      globals.printError(
363 364 365 366 367 368 369 370
        'Warning: Podfile is out of date\n'
        '$outOfDatePodfileConsequence\n'
        'To regenerate the Podfile, run:\n'
        '$podfileMigrationInstructions\n',
        emphasis: true,
      );
    }
  }
371
}