cocoapods.dart 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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';

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';
14
import '../base/platform.dart';
15 16 17 18 19
import '../base/process.dart';
import '../base/process_manager.dart';
import '../base/version.dart';
import '../cache.dart';
import '../globals.dart';
20
import '../ios/xcodeproj.dart';
21
import '../project.dart';
22

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

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

32
const String cocoaPodsInstallInstructions = '''
33
  sudo gem install cocoapods
34 35
  pod setup''';

36
const String cocoaPodsUpgradeInstructions = '''
37
  sudo gem install cocoapods
38 39
  pod setup''';

40
CocoaPods get cocoaPods => context.get<CocoaPods>();
41

42 43 44 45
/// Result of evaluating the CocoaPods installation.
enum CocoaPodsStatus {
  /// iOS plugins will not work, installation required.
  notInstalled,
46 47
  /// iOS plugins might not work, upgrade recommended.
  unknownVersion,
48 49 50 51 52 53 54 55
  /// 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,
}
56

57 58
class CocoaPods {
  Future<String> _versionText;
59

60 61
  String get cocoaPodsMinimumVersion => '1.6.0';
  String get cocoaPodsRecommendedVersion => '1.6.0';
62

63 64 65 66 67 68
  Future<String> get cocoaPodsVersionText {
    _versionText ??= runAsync(<String>['pod', '--version']).then<String>((RunResult result) {
      return result.exitCode == 0 ? result.stdout.trim() : null;
    }, onError: (dynamic _) => null);
    return _versionText;
  }
69

70 71 72 73
  Future<CocoaPodsStatus> get evaluateCocoaPodsInstallation async {
    final String versionText = await cocoaPodsVersionText;
    if (versionText == null)
      return CocoaPodsStatus.notInstalled;
74
    try {
75
      final Version installedVersion = Version.parse(versionText);
76 77
      if (installedVersion == null)
        return CocoaPodsStatus.unknownVersion;
78
      if (installedVersion < Version.parse(cocoaPodsMinimumVersion))
79
        return CocoaPodsStatus.belowMinimumVersion;
80
      else if (installedVersion < Version.parse(cocoaPodsRecommendedVersion))
81 82 83
        return CocoaPodsStatus.belowRecommendedVersion;
      else
        return CocoaPodsStatus.recommended;
84
    } on FormatException {
85
      return CocoaPodsStatus.notInstalled;
86 87 88
    }
  }

89 90 91 92 93 94 95 96 97 98 99 100
  /// Whether CocoaPods ran 'pod setup' once where the costly pods' specs are
  /// cloned.
  ///
  /// 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.
  Future<bool> get isCocoaPodsInitialized {
    final String cocoapodsReposDir = platform.environment['CP_REPOS_DIR'] ?? fs.path.join(homeDirPath, '.cocoapods', 'repos');
    return fs.isDirectory(fs.path.join(cocoapodsReposDir, 'master'));
  }
101

102
  Future<bool> processPods({
103
    @required XcodeBasedProject xcodeProject,
104
    // For backward compatibility with previously created Podfile only.
105
    @required String engineDir,
106 107
    bool isSwift = false,
    bool dependenciesChanged = true,
108
  }) async {
109
    if (!(await xcodeProject.podfile.exists())) {
110 111
      throwToolExit('Podfile missing');
    }
112
    if (await _checkPodCondition()) {
113 114
      if (_shouldRunPodInstall(xcodeProject, dependenciesChanged)) {
        await _runPodInstall(xcodeProject, engineDir);
115
        return true;
116
      }
117
    }
118
    return false;
119 120
  }

121
  /// Make sure the CocoaPods tools are in the right states.
122
  Future<bool> _checkPodCondition() async {
123 124 125 126 127 128 129 130 131 132 133
    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;
134 135 136 137 138 139 140 141 142
      case CocoaPodsStatus.unknownVersion:
        printError(
          'Warning: Unknown CocoaPods version installed.\n'
          '$unknownCocoaPodsConsequence\n'
          'To upgrade:\n'
          '$cocoaPodsUpgradeInstructions\n',
          emphasis: true,
        );
        break;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
      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;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    }
    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;
  }

179
  /// Ensures the given Xcode-based sub-project of a parent Flutter project
180 181
  /// contains a suitable `Podfile` and that its `Flutter/Xxx.xcconfig` files
  /// include pods configuration.
182
  void setupPodfile(XcodeBasedProject xcodeProject) {
183
    if (!xcodeProjectInterpreter.isInstalled) {
184 185 186
      // Don't do anything for iOS when host platform doesn't support it.
      return;
    }
187
    final Directory runnerProject = xcodeProject.xcodeProject;
188
    if (!runnerProject.existsSync()) {
189 190
      return;
    }
191
    final File podfile = xcodeProject.podfile;
192
    if (!podfile.existsSync()) {
193 194 195 196 197 198 199 200 201 202
      String podfileTemplateName;
      if (xcodeProject is MacOSProject) {
        podfileTemplateName = 'Podfile-macos';
      } else {
        final bool isSwift = xcodeProjectInterpreter.getBuildSettings(
          runnerProject.path,
          'Runner',
        ).containsKey('SWIFT_VERSION');
        podfileTemplateName = isSwift ? 'Podfile-ios-swift' : 'Podfile-ios-objc';
      }
203 204 205 206 207 208
      final File podfileTemplate = fs.file(fs.path.join(
        Cache.flutterRoot,
        'packages',
        'flutter_tools',
        'templates',
        'cocoapods',
209
        podfileTemplateName,
210
      ));
211
      podfileTemplate.copySync(podfile.path);
212
    }
213
    addPodsDependencyToFlutterXcconfig(xcodeProject);
214 215
  }

216 217 218 219 220
  /// 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');
221 222
  }

223 224
  void _addPodsDependencyToFlutterXcconfig(XcodeBasedProject xcodeProject, String mode) {
    final File file = xcodeProject.xcodeConfigFor(mode);
225 226 227 228 229 230 231 232 233 234
    if (file.existsSync()) {
      final String content = file.readAsStringSync();
      final String include = '#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.${mode
          .toLowerCase()}.xcconfig"';
      if (!content.contains(include))
        file.writeAsStringSync('$include\n$content', flush: true);
    }
  }

  /// Ensures that pod install is deemed needed on next check.
235 236
  void invalidatePodInstallOutput(XcodeBasedProject xcodeProject) {
    final File manifestLock = xcodeProject.podManifestLock;
237 238 239
    if (manifestLock.existsSync()) {
      manifestLock.deleteSync();
    }
240 241
  }

242 243
  // Check if you need to run pod install.
  // The pod install will run if any of below is true.
244 245 246 247
  // 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.
248
  bool _shouldRunPodInstall(XcodeBasedProject xcodeProject, bool dependenciesChanged) {
249
    if (dependenciesChanged)
250
      return true;
251

252 253 254
    final File podfileFile = xcodeProject.podfile;
    final File podfileLockFile = xcodeProject.podfileLock;
    final File manifestLockFile = xcodeProject.podManifestLock;
255

256
    return !podfileLockFile.existsSync()
257
        || !manifestLockFile.existsSync()
258
        || podfileLockFile.statSync().modified.isBefore(podfileFile.statSync().modified)
259
        || podfileLockFile.readAsStringSync() != manifestLockFile.readAsStringSync();
260 261
  }

262
  Future<void> _runPodInstall(XcodeBasedProject xcodeProject, String engineDirectory) async {
263
    final Status status = logger.startProgress('Running pod install...', timeout: timeoutConfiguration.slowOperation);
264 265
    final ProcessResult result = await processManager.run(
      <String>['pod', 'install', '--verbose'],
266
      workingDirectory: fs.path.dirname(xcodeProject.podfile.path),
267
      environment: <String, String>{
268
        // For backward compatibility with previously created Podfile only.
269
        'FLUTTER_FRAMEWORK_DIR': engineDirectory,
270 271 272 273
        // See https://github.com/flutter/flutter/issues/10873.
        // CocoaPods analytics adds a lot of latency.
        'COCOAPODS_DISABLE_STATS': 'true',
      },
274 275 276 277 278 279 280 281 282 283 284 285
    );
    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);
      }
    }
286
    if (result.exitCode != 0) {
287
      invalidatePodInstallOutput(xcodeProject);
288
      _diagnosePodInstallFailure(result);
289
      throwToolExit('Error running pod install');
290 291 292 293 294 295 296 297 298 299 300 301
    }
  }

  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,
      );
    }
302 303
  }
}