xcodeproj.dart 11.5 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/context.dart';
11
import '../base/file_system.dart';
12 13
import '../base/io.dart';
import '../base/platform.dart';
14
import '../base/process.dart';
15
import '../base/process_manager.dart';
16
import '../base/utils.dart';
17
import '../build_info.dart';
18
import '../cache.dart';
19
import '../globals.dart';
20
import '../project.dart';
21

22 23
final RegExp _settingExpr = RegExp(r'(\w+)\s*=\s*(.*)$');
final RegExp _varExpr = RegExp(r'\$\(([^)]*)\)');
24

25
String flutterFrameworkDir(BuildMode mode) {
26 27
  return fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(
      Artifact.flutterFramework, platform: TargetPlatform.ios, mode: mode)));
28 29
}

30 31 32 33 34
String flutterMacOSFrameworkDir(BuildMode mode) {
  return fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(
      Artifact.flutterMacOSFramework, platform: TargetPlatform.darwin_x64, mode: mode)));
}

35
/// Writes or rewrites Xcode property files with the specified information.
36
///
37 38 39
/// useMacOSConfig: Optional parameter that controls whether we use the macOS
/// project file instead. Defaults to false.
///
40
/// setSymroot: Optional parameter to control whether to set SYMROOT.
41
///
42 43
/// targetOverride: Optional parameter, if null or unspecified the default value
/// from xcode_backend.sh is used 'lib/main.dart'.
44 45
Future<void> updateGeneratedXcodeProperties({
  @required FlutterProject project,
46
  @required BuildInfo buildInfo,
47
  String targetOverride,
48
  bool useMacOSConfig = false,
49
  bool setSymroot = true,
50
}) async {
51
  final StringBuffer localsBuffer = StringBuffer();
52 53 54

  localsBuffer.writeln('// This is a generated file; do not edit or check into version control.');

55
  final String flutterRoot = fs.path.normalize(Cache.flutterRoot);
56 57 58
  localsBuffer.writeln('FLUTTER_ROOT=$flutterRoot');

  // This holds because requiresProjectRoot is true for this command
59
  localsBuffer.writeln('FLUTTER_APPLICATION_PATH=${fs.path.normalize(project.directory.path)}');
60

61
  // Relative to FLUTTER_APPLICATION_PATH, which is [Directory.current].
62 63
  if (targetOverride != null)
    localsBuffer.writeln('FLUTTER_TARGET=$targetOverride');
64

65 66 67
  // The build outputs directory, relative to FLUTTER_APPLICATION_PATH.
  localsBuffer.writeln('FLUTTER_BUILD_DIR=${getBuildDirectory()}');

68 69
  if (setSymroot) {
    localsBuffer.writeln('SYMROOT=\${SOURCE_ROOT}/../${getIosBuildDirectory()}');
70
  }
71

72 73 74 75
  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.
76
    // However, this is necessary for regular projects using Cocoapods.
77 78 79 80
    final String frameworkDir = useMacOSConfig
        ? flutterMacOSFrameworkDir(buildInfo.mode)
        : flutterFrameworkDir(buildInfo.mode);
    localsBuffer.writeln('FLUTTER_FRAMEWORK_DIR=$frameworkDir');
81 82
  }

83
  final String buildName = validatedBuildNameForPlatform(TargetPlatform.ios, buildInfo?.buildName ?? project.manifest.buildName);
84 85 86 87
  if (buildName != null) {
    localsBuffer.writeln('FLUTTER_BUILD_NAME=$buildName');
  }

88
  final String buildNumber = validatedBuildNumberForPlatform(TargetPlatform.ios, buildInfo?.buildNumber ?? project.manifest.buildNumber);
89 90 91 92
  if (buildNumber != null) {
    localsBuffer.writeln('FLUTTER_BUILD_NUMBER=$buildNumber');
  }

93
  if (artifacts is LocalEngineArtifacts) {
94
    final LocalEngineArtifacts localEngineArtifacts = artifacts;
95 96 97
    final String engineOutPath = localEngineArtifacts.engineOutPath;
    localsBuffer.writeln('FLUTTER_ENGINE=${fs.path.dirname(fs.path.dirname(engineOutPath))}');
    localsBuffer.writeln('LOCAL_ENGINE=${fs.path.basename(engineOutPath)}');
98 99 100 101 102 103 104

    // 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.
105 106 107 108 109 110
    //
    // Skip this step for macOS builds.
    if (!useMacOSConfig) {
      final String arch = engineOutPath.endsWith('_arm') ? 'armv7' : 'arm64';
      localsBuffer.writeln('ARCHS=$arch');
    }
111
  }
112

113 114 115 116
  if (buildInfo.trackWidgetCreation) {
    localsBuffer.writeln('TRACK_WIDGET_CREATION=true');
  }

117 118 119
  final File generatedXcodePropertiesFile = useMacOSConfig
      ? project.macos.generatedXcodePropertiesFile
      : project.ios.generatedXcodePropertiesFile;
120 121
  generatedXcodePropertiesFile.createSync(recursive: true);
  generatedXcodePropertiesFile.writeAsStringSync(localsBuffer.toString());
122
}
123

124
XcodeProjectInterpreter get xcodeProjectInterpreter => context.get<XcodeProjectInterpreter>();
125

126
/// Interpreter of Xcode projects.
127 128
class XcodeProjectInterpreter {
  static const String _executable = '/usr/bin/xcodebuild';
129
  static final RegExp _versionRegex = RegExp(r'Xcode ([0-9.]+)');
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  void _updateVersion() {
    if (!platform.isMacOS || !fs.file(_executable).existsSync()) {
      return;
    }
    try {
      final ProcessResult result = processManager.runSync(<String>[_executable, '-version']);
      if (result.exitCode != 0) {
        return;
      }
      _versionText = result.stdout.trim().replaceAll('\n', ', ');
      final Match match = _versionRegex.firstMatch(versionText);
      if (match == null)
        return;
      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 {
149
      // Ignored, leave values null.
150 151
    }
  }
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  bool get isInstalled => majorVersion != null;

  String _versionText;
  String get versionText {
    if (_versionText == null)
      _updateVersion();
    return _versionText;
  }

  int _majorVersion;
  int get majorVersion {
    if (_majorVersion == null)
      _updateVersion();
    return _majorVersion;
  }

  int _minorVersion;
  int get minorVersion {
    if (_minorVersion == null)
      _updateVersion();
    return _minorVersion;
  }
175 176 177 178 179 180 181 182

  Map<String, String> getBuildSettings(String projectPath, String target) {
    final String out = runCheckedSync(<String>[
      _executable,
      '-project',
      fs.path.absolute(projectPath),
      '-target',
      target,
183
      '-showBuildSettings',
184 185 186 187
    ], workingDirectory: projectPath);
    return parseXcodeBuildSettings(out);
  }

188 189
  Future<XcodeProjectInfo> getInfo(String projectPath) async {
    final RunResult result = await runCheckedAsync(<String>[
190 191
      _executable, '-list',
    ], workingDirectory: projectPath);
192
    return XcodeProjectInfo.fromXcodeBuildOutput(result.toString());
193
  }
xster's avatar
xster committed
194 195 196
}

Map<String, String> parseXcodeBuildSettings(String showBuildSettingsOutput) {
197
  final Map<String, String> settings = <String, String>{};
198
  for (Match match in showBuildSettingsOutput.split('\n').map<Match>(_settingExpr.firstMatch)) {
199 200 201
    if (match != null) {
      settings[match[1]] = match[2];
    }
202 203 204 205 206 207
  }
  return settings;
}

/// Substitutes variables in [str] with their values from the specified Xcode
/// project and target.
208
String substituteXcodeVariables(String str, Map<String, String> xcodeBuildSettings) {
209
  final Iterable<Match> matches = _varExpr.allMatches(str);
210 211 212
  if (matches.isEmpty)
    return str;

213
  return str.replaceAllMapped(_varExpr, (Match m) => xcodeBuildSettings[m[1]] ?? m[0]);
214
}
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

/// 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());
    }
243 244
    if (schemes.isEmpty)
      schemes.add('Runner');
245
    return XcodeProjectInfo(targets, buildConfigurations, schemes);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  }

  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);
    if (buildInfo.flavor == null)
      return baseConfiguration;
    else
      return baseConfiguration + '-$scheme';
  }

274 275 276 277 278 279 280 281 282 283 284
  /// 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;
  }
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  /// Returns unique scheme matching [buildInfo], or null, if there is no unique
  /// best match.
  String schemeFor(BuildInfo buildInfo) {
    final String expectedScheme = expectedSchemeFor(buildInfo);
    if (schemes.contains(expectedScheme))
      return expectedScheme;
    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);
300
    if (hasBuildConfiguratinForBuildMode(expectedConfiguration))
301 302 303 304 305 306 307 308 309 310 311
      return expectedConfiguration;
    final String baseConfiguration = _baseConfigurationFor(buildInfo);
    return _uniqueMatch(buildConfigurations, (String candidate) {
      candidate = candidate.toLowerCase();
      if (buildInfo.flavor == null)
        return candidate == expectedConfiguration.toLowerCase();
      else
        return candidate.contains(baseConfiguration.toLowerCase()) && candidate.contains(scheme.toLowerCase());
    });
  }

312 313 314 315 316 317 318
  static String _baseConfigurationFor(BuildInfo buildInfo) {
    if (buildInfo.isDebug)
      return 'Debug';
    if (buildInfo.isProfile)
      return 'Profile';
    return 'Release';
  }
319 320 321 322 323 324 325 326 327 328 329 330 331 332

  static String _uniqueMatch(Iterable<String> strings, bool matches(String s)) {
    final List<String> options = strings.where(matches).toList();
    if (options.length == 1)
      return options.first;
    else
      return null;
  }

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