xcodeproj.dart 17 KB
Newer Older
1 2 3 4
// Copyright 2016 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.

5 6
import 'dart:async';

7 8
import 'package:meta/meta.dart';

9
import '../artifacts.dart';
10
import '../base/common.dart';
11
import '../base/context.dart';
12
import '../base/file_system.dart';
13
import '../base/io.dart';
14
import '../base/logger.dart';
15
import '../base/os.dart';
16
import '../base/platform.dart';
17
import '../base/process.dart';
18
import '../base/utils.dart';
19
import '../build_info.dart';
20
import '../cache.dart';
21
import '../flutter_manifest.dart';
22
import '../globals.dart';
23
import '../project.dart';
24
import '../reporting/reporting.dart';
25

26 27
final RegExp _settingExpr = RegExp(r'(\w+)\s*=\s*(.*)$');
final RegExp _varExpr = RegExp(r'\$\(([^)]*)\)');
28

29
String flutterFrameworkDir(BuildMode mode) {
30 31
  return fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(
      Artifact.flutterFramework, platform: TargetPlatform.ios, mode: mode)));
32 33
}

34 35 36 37 38
String flutterMacOSFrameworkDir(BuildMode mode) {
  return fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(
      Artifact.flutterMacOSFramework, platform: TargetPlatform.darwin_x64, mode: mode)));
}

39
/// Writes or rewrites Xcode property files with the specified information.
40
///
41 42 43
/// useMacOSConfig: Optional parameter that controls whether we use the macOS
/// project file instead. Defaults to false.
///
44
/// setSymroot: Optional parameter to control whether to set SYMROOT.
45
///
46 47
/// targetOverride: Optional parameter, if null or unspecified the default value
/// from xcode_backend.sh is used 'lib/main.dart'.
48 49
Future<void> updateGeneratedXcodeProperties({
  @required FlutterProject project,
50
  @required BuildInfo buildInfo,
51
  String targetOverride,
52
  bool useMacOSConfig = false,
53
  bool setSymroot = true,
54
  String buildDirOverride,
55
}) async {
56 57 58 59 60
  final List<String> xcodeBuildSettings = _xcodeBuildSettingsLines(
    project: project,
    buildInfo: buildInfo,
    targetOverride: targetOverride,
    useMacOSConfig: useMacOSConfig,
61
    setSymroot: setSymroot,
62
    buildDirOverride: buildDirOverride,
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  );

  _updateGeneratedXcodePropertiesFile(
    project: project,
    xcodeBuildSettings: xcodeBuildSettings,
    useMacOSConfig: useMacOSConfig,
  );

  _updateGeneratedEnvironmentVariablesScript(
    project: project,
    xcodeBuildSettings: xcodeBuildSettings,
    useMacOSConfig: useMacOSConfig,
  );
}

/// Generate a xcconfig file to inherit FLUTTER_ build settings
/// for Xcode targets that need them.
/// See [XcodeBasedProject.generatedXcodePropertiesFile].
void _updateGeneratedXcodePropertiesFile({
  @required FlutterProject project,
  @required List<String> xcodeBuildSettings,
  bool useMacOSConfig = false,
}) {
86
  final StringBuffer localsBuffer = StringBuffer();
87 88

  localsBuffer.writeln('// This is a generated file; do not edit or check into version control.');
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
  xcodeBuildSettings.forEach(localsBuffer.writeln);
  final File generatedXcodePropertiesFile = useMacOSConfig
    ? project.macos.generatedXcodePropertiesFile
    : project.ios.generatedXcodePropertiesFile;

  generatedXcodePropertiesFile.createSync(recursive: true);
  generatedXcodePropertiesFile.writeAsStringSync(localsBuffer.toString());
}

/// Generate a script to export all the FLUTTER_ environment variables needed
/// as flags for Flutter tools.
/// See [XcodeBasedProject.generatedEnvironmentVariableExportScript].
void _updateGeneratedEnvironmentVariablesScript({
  @required FlutterProject project,
  @required List<String> xcodeBuildSettings,
  bool useMacOSConfig = false,
}) {
  final StringBuffer localsBuffer = StringBuffer();

  localsBuffer.writeln('#!/bin/sh');
  localsBuffer.writeln('# This is a generated file; do not edit or check into version control.');
  for (String line in xcodeBuildSettings) {
    localsBuffer.writeln('export "$line"');
  }

  final File generatedModuleBuildPhaseScript = useMacOSConfig
    ? project.macos.generatedEnvironmentVariableExportScript
    : project.ios.generatedEnvironmentVariableExportScript;
  generatedModuleBuildPhaseScript.createSync(recursive: true);
  generatedModuleBuildPhaseScript.writeAsStringSync(localsBuffer.toString());
  os.chmod(generatedModuleBuildPhaseScript, '755');
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
/// Build name parsed and validated from build info and manifest. Used for CFBundleShortVersionString.
String parsedBuildName({
  @required FlutterManifest manifest,
  @required BuildInfo buildInfo,
}) {
  final String buildNameToParse = buildInfo?.buildName ?? manifest.buildName;
  return validatedBuildNameForPlatform(TargetPlatform.ios, buildNameToParse);
}

/// Build number parsed and validated from build info and manifest. Used for CFBundleVersion.
String parsedBuildNumber({
  @required FlutterManifest manifest,
  @required BuildInfo buildInfo,
}) {
  String buildNumberToParse = buildInfo?.buildNumber ?? manifest.buildNumber;
  final String buildNumber = validatedBuildNumberForPlatform(TargetPlatform.ios, buildNumberToParse);
  if (buildNumber != null && buildNumber.isNotEmpty) {
    return buildNumber;
  }
  // Drop back to parsing build name if build number is not present. Build number is optional in the manifest, but
  // FLUTTER_BUILD_NUMBER is required as the backing value for the required CFBundleVersion.
  buildNumberToParse = buildInfo?.buildName ?? manifest.buildName;
  return validatedBuildNumberForPlatform(TargetPlatform.ios, buildNumberToParse);
}

147 148 149 150 151 152 153
/// List of lines of build settings. Example: 'FLUTTER_BUILD_DIR=build'
List<String> _xcodeBuildSettingsLines({
  @required FlutterProject project,
  @required BuildInfo buildInfo,
  String targetOverride,
  bool useMacOSConfig = false,
  bool setSymroot = true,
154
  String buildDirOverride,
155 156
}) {
  final List<String> xcodeBuildSettings = <String>[];
157

158
  final String flutterRoot = fs.path.normalize(Cache.flutterRoot);
159
  xcodeBuildSettings.add('FLUTTER_ROOT=$flutterRoot');
160 161

  // This holds because requiresProjectRoot is true for this command
162
  xcodeBuildSettings.add('FLUTTER_APPLICATION_PATH=${fs.path.normalize(project.directory.path)}');
163

164
  // Relative to FLUTTER_APPLICATION_PATH, which is [Directory.current].
165
  if (targetOverride != null) {
166
    xcodeBuildSettings.add('FLUTTER_TARGET=$targetOverride');
167
  }
168

169
  // The build outputs directory, relative to FLUTTER_APPLICATION_PATH.
170
  xcodeBuildSettings.add('FLUTTER_BUILD_DIR=${buildDirOverride ?? getBuildDirectory()}');
171

172
  if (setSymroot) {
173
    xcodeBuildSettings.add('SYMROOT=\${SOURCE_ROOT}/../${getIosBuildDirectory()}');
174
  }
175

176 177 178 179
  if (!project.isModule) {
    // For module projects we do not want to write the FLUTTER_FRAMEWORK_DIR
    // explicitly. Rather we rely on the xcode backend script and the Podfile
    // logic to derive it from FLUTTER_ROOT and FLUTTER_BUILD_MODE.
180
    // However, this is necessary for regular projects using Cocoapods.
181
    final String frameworkDir = useMacOSConfig
182 183 184
      ? flutterMacOSFrameworkDir(buildInfo.mode)
      : flutterFrameworkDir(buildInfo.mode);
    xcodeBuildSettings.add('FLUTTER_FRAMEWORK_DIR=$frameworkDir');
185 186
  }

187

188
  final String buildName = parsedBuildName(manifest: project.manifest, buildInfo: buildInfo) ?? '1.0.0';
189
  xcodeBuildSettings.add('FLUTTER_BUILD_NAME=$buildName');
190 191

  final String buildNumber = parsedBuildNumber(manifest: project.manifest, buildInfo: buildInfo) ?? '1';
192 193
  xcodeBuildSettings.add('FLUTTER_BUILD_NUMBER=$buildNumber');

194
  if (artifacts is LocalEngineArtifacts) {
195
    final LocalEngineArtifacts localEngineArtifacts = artifacts;
196
    final String engineOutPath = localEngineArtifacts.engineOutPath;
197 198
    xcodeBuildSettings.add('FLUTTER_ENGINE=${fs.path.dirname(fs.path.dirname(engineOutPath))}');
    xcodeBuildSettings.add('LOCAL_ENGINE=${fs.path.basename(engineOutPath)}');
199 200 201 202 203 204 205

    // Tell Xcode not to build universal binaries for local engines, which are
    // single-architecture.
    //
    // NOTE: this assumes that local engine binary paths are consistent with
    // the conventions uses in the engine: 32-bit iOS engines are built to
    // paths ending in _arm, 64-bit builds are not.
206 207 208 209
    //
    // Skip this step for macOS builds.
    if (!useMacOSConfig) {
      final String arch = engineOutPath.endsWith('_arm') ? 'armv7' : 'arm64';
210
      xcodeBuildSettings.add('ARCHS=$arch');
211
    }
212
  }
213

214
  if (buildInfo.trackWidgetCreation) {
215
    xcodeBuildSettings.add('TRACK_WIDGET_CREATION=true');
216 217
  }

218
  return xcodeBuildSettings;
219
}
220

221
XcodeProjectInterpreter get xcodeProjectInterpreter => context.get<XcodeProjectInterpreter>();
222

223
/// Interpreter of Xcode projects.
224 225
class XcodeProjectInterpreter {
  static const String _executable = '/usr/bin/xcodebuild';
226
  static final RegExp _versionRegex = RegExp(r'Xcode ([0-9.]+)');
227

228 229 230 231 232
  void _updateVersion() {
    if (!platform.isMacOS || !fs.file(_executable).existsSync()) {
      return;
    }
    try {
233 234 235
      final RunResult result = processUtils.runSync(
        <String>[_executable, '-version'],
      );
236 237 238 239 240
      if (result.exitCode != 0) {
        return;
      }
      _versionText = result.stdout.trim().replaceAll('\n', ', ');
      final Match match = _versionRegex.firstMatch(versionText);
241
      if (match == null) {
242
        return;
243
      }
244 245 246 247 248
      final String version = match.group(1);
      final List<String> components = version.split('.');
      _majorVersion = int.parse(components[0]);
      _minorVersion = components.length == 1 ? 0 : int.parse(components[1]);
    } on ProcessException {
249
      // Ignored, leave values null.
250 251
    }
  }
252

253 254 255 256
  bool get isInstalled => majorVersion != null;

  String _versionText;
  String get versionText {
257
    if (_versionText == null) {
258
      _updateVersion();
259
    }
260 261 262 263 264
    return _versionText;
  }

  int _majorVersion;
  int get majorVersion {
265
    if (_majorVersion == null) {
266
      _updateVersion();
267
    }
268 269 270 271 272
    return _majorVersion;
  }

  int _minorVersion;
  int get minorVersion {
273
    if (_minorVersion == null) {
274
      _updateVersion();
275
    }
276 277
    return _minorVersion;
  }
278

279 280
  /// Asynchronously retrieve xcode build settings. This one is preferred for
  /// new call-sites.
281
  Future<Map<String, String>> getBuildSettings(
282 283
    String projectPath,
    String target, {
284 285 286 287 288
    Duration timeout = const Duration(minutes: 1),
  }) async {
    final Status status = Status.withSpinner(
      timeout: timeoutConfiguration.fastOperation,
    );
289 290 291 292 293 294 295 296
    final List<String> showBuildSettingsCommand = <String>[
      _executable,
      '-project',
      fs.path.absolute(projectPath),
      '-target',
      target,
      '-showBuildSettings',
    ];
297 298 299 300
    try {
      // showBuildSettings is reported to ocassionally timeout. Here, we give it
      // a lot of wiggle room (locally on Flutter Gallery, this takes ~1s).
      // When there is a timeout, we retry once.
301
      final RunResult result = await processUtils.run(
302
        showBuildSettingsCommand,
303
        throwOnError: true,
304 305 306 307 308 309 310
        workingDirectory: projectPath,
        timeout: timeout,
        timeoutRetries: 1,
      );
      final String out = result.stdout.trim();
      return parseXcodeBuildSettings(out);
    } catch(error) {
311 312 313 314 315
      if (error is ProcessException && error.toString().contains('timed out')) {
        BuildEvent('xcode-show-build-settings-timeout',
          command: showBuildSettingsCommand.join(' '),
        ).send();
      }
316 317 318 319 320 321 322
      printTrace('Unexpected failure to get the build settings: $error.');
      return const <String, String>{};
    } finally {
      status.stop();
    }
  }

323
  void cleanWorkspace(String workspacePath, String scheme) {
324
    processUtils.runSync(<String>[
325 326 327 328 329 330
      _executable,
      '-workspace',
      workspacePath,
      '-scheme',
      scheme,
      '-quiet',
331
      'clean',
332 333 334
    ], workingDirectory: fs.currentDirectory.path);
  }

335
  Future<XcodeProjectInfo> getInfo(String projectPath, {String projectFilename}) async {
336 337 338 339
    // The exit code returned by 'xcodebuild -list' when either:
    // * -project is passed and the given project isn't there, or
    // * no -project is passed and there isn't a project.
    const int missingProjectExitCode = 66;
340 341 342 343 344 345 346
    final RunResult result = await processUtils.run(
      <String>[
        _executable,
        '-list',
        if (projectFilename != null) ...<String>['-project', projectFilename],
      ],
      throwOnError: true,
347
      whiteListFailures: (int c) => c == missingProjectExitCode,
348 349
      workingDirectory: projectPath,
    );
350 351 352
    if (result.exitCode == missingProjectExitCode) {
      throwToolExit('Unable to get Xcode project information:\n ${result.stderr}');
    }
353
    return XcodeProjectInfo.fromXcodeBuildOutput(result.toString());
354
  }
xster's avatar
xster committed
355 356 357
}

Map<String, String> parseXcodeBuildSettings(String showBuildSettingsOutput) {
358
  final Map<String, String> settings = <String, String>{};
359
  for (Match match in showBuildSettingsOutput.split('\n').map<Match>(_settingExpr.firstMatch)) {
360 361 362
    if (match != null) {
      settings[match[1]] = match[2];
    }
363 364 365 366 367 368
  }
  return settings;
}

/// Substitutes variables in [str] with their values from the specified Xcode
/// project and target.
369
String substituteXcodeVariables(String str, Map<String, String> xcodeBuildSettings) {
370
  final Iterable<Match> matches = _varExpr.allMatches(str);
371
  if (matches.isEmpty) {
372
    return str;
373
  }
374

375
  return str.replaceAllMapped(_varExpr, (Match m) => xcodeBuildSettings[m[1]] ?? m[0]);
376
}
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

/// Information about an Xcode project.
///
/// Represents the output of `xcodebuild -list`.
class XcodeProjectInfo {
  XcodeProjectInfo(this.targets, this.buildConfigurations, this.schemes);

  factory XcodeProjectInfo.fromXcodeBuildOutput(String output) {
    final List<String> targets = <String>[];
    final List<String> buildConfigurations = <String>[];
    final List<String> schemes = <String>[];
    List<String> collector;
    for (String line in output.split('\n')) {
      if (line.isEmpty) {
        collector = null;
        continue;
      } else if (line.endsWith('Targets:')) {
        collector = targets;
        continue;
      } else if (line.endsWith('Build Configurations:')) {
        collector = buildConfigurations;
        continue;
      } else if (line.endsWith('Schemes:')) {
        collector = schemes;
        continue;
      }
      collector?.add(line.trim());
    }
405
    if (schemes.isEmpty) {
406
      schemes.add('Runner');
407
    }
408
    return XcodeProjectInfo(targets, buildConfigurations, schemes);
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  }

  final List<String> targets;
  final List<String> buildConfigurations;
  final List<String> schemes;

  bool get definesCustomTargets => !(targets.contains('Runner') && targets.length == 1);
  bool get definesCustomSchemes => !(schemes.contains('Runner') && schemes.length == 1);
  bool get definesCustomBuildConfigurations {
    return !(buildConfigurations.contains('Debug') &&
        buildConfigurations.contains('Release') &&
        buildConfigurations.length == 2);
  }

  /// The expected scheme for [buildInfo].
  static String expectedSchemeFor(BuildInfo buildInfo) {
    return toTitleCase(buildInfo.flavor ?? 'runner');
  }

  /// The expected build configuration for [buildInfo] and [scheme].
  static String expectedBuildConfigurationFor(BuildInfo buildInfo, String scheme) {
    final String baseConfiguration = _baseConfigurationFor(buildInfo);
431
    if (buildInfo.flavor == null) {
432
      return baseConfiguration;
433 434
    }
    return baseConfiguration + '-$scheme';
435 436
  }

437 438 439 440 441 442 443 444 445 446 447
  /// Checks whether the [buildConfigurations] contains the specified string, without
  /// regard to case.
  bool hasBuildConfiguratinForBuildMode(String buildMode) {
    buildMode = buildMode.toLowerCase();
    for (String name in buildConfigurations) {
      if (name.toLowerCase() == buildMode) {
        return true;
      }
    }
    return false;
  }
448 449 450 451
  /// Returns unique scheme matching [buildInfo], or null, if there is no unique
  /// best match.
  String schemeFor(BuildInfo buildInfo) {
    final String expectedScheme = expectedSchemeFor(buildInfo);
452
    if (schemes.contains(expectedScheme)) {
453
      return expectedScheme;
454
    }
455 456 457 458 459 460 461 462 463
    return _uniqueMatch(schemes, (String candidate) {
      return candidate.toLowerCase() == expectedScheme.toLowerCase();
    });
  }

  /// Returns unique build configuration matching [buildInfo] and [scheme], or
  /// null, if there is no unique best match.
  String buildConfigurationFor(BuildInfo buildInfo, String scheme) {
    final String expectedConfiguration = expectedBuildConfigurationFor(buildInfo, scheme);
464
    if (hasBuildConfiguratinForBuildMode(expectedConfiguration)) {
465
      return expectedConfiguration;
466
    }
467 468 469
    final String baseConfiguration = _baseConfigurationFor(buildInfo);
    return _uniqueMatch(buildConfigurations, (String candidate) {
      candidate = candidate.toLowerCase();
470
      if (buildInfo.flavor == null) {
471
        return candidate == expectedConfiguration.toLowerCase();
472 473
      }
      return candidate.contains(baseConfiguration.toLowerCase()) && candidate.contains(scheme.toLowerCase());
474 475 476
    });
  }

477
  static String _baseConfigurationFor(BuildInfo buildInfo) {
478
    if (buildInfo.isDebug) {
479
      return 'Debug';
480 481
    }
    if (buildInfo.isProfile) {
482
      return 'Profile';
483
    }
484 485
    return 'Release';
  }
486 487 488

  static String _uniqueMatch(Iterable<String> strings, bool matches(String s)) {
    final List<String> options = strings.where(matches).toList();
489
    if (options.length == 1) {
490
      return options.first;
491 492
    }
    return null;
493 494 495 496 497 498 499
  }

  @override
  String toString() {
    return 'XcodeProjectInfo($targets, $buildConfigurations, $schemes)';
  }
}