mac.dart 9.2 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 7 8 9 10 11
import 'dart:async';
import 'dart:convert' show JSON;
import 'dart:io';

import 'package:path/path.dart' as path;

import '../application_package.dart';
12 13
import '../base/context.dart';
import '../base/process.dart';
14
import '../build_info.dart';
15
import '../flx.dart' as flx;
16 17
import '../globals.dart';
import '../services.dart';
18
import 'xcodeproj.dart';
19

20
const int kXcodeRequiredVersionMajor = 7;
21
const int kXcodeRequiredVersionMinor = 0;
22

23
class XCode {
24 25 26 27 28
  XCode() {
    _eulaSigned = false;

    try {
      _xcodeSelectPath = runSync(<String>['xcode-select', '--print-path']);
29 30 31 32
      if (_xcodeSelectPath == null || _xcodeSelectPath.trim().isEmpty) {
        _isInstalled = false;
        return;
      }
33 34 35 36
      _isInstalled = true;

      _xcodeVersionText = runSync(<String>['xcodebuild', '-version']).replaceAll('\n', ', ');

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
      if (!xcodeVersionRegex.hasMatch(_xcodeVersionText)) {
        _isInstalled = false;
      } else {
        try {
          printTrace('xcrun clang');
          ProcessResult result = Process.runSync('/usr/bin/xcrun', <String>['clang']);

          if (result.stdout != null && result.stdout.contains('license'))
            _eulaSigned = false;
          else if (result.stderr != null && result.stderr.contains('license'))
            _eulaSigned = false;
          else
            _eulaSigned = true;
        } catch (error) {
        }
52 53 54 55 56 57
      }
    } catch (error) {
      _isInstalled = false;
    }
  }

58 59
  /// Returns [XCode] active in the current app context.
  static XCode get instance => context[XCode] ?? (context[XCode] = new XCode());
60

61 62
  bool get isInstalledAndMeetsVersionCheck => isInstalled && xcodeVersionSatisfactory;

63 64
  String _xcodeSelectPath;
  String get xcodeSelectPath => _xcodeSelectPath;
65

66 67
  bool _isInstalled;
  bool get isInstalled => _isInstalled;
68

69
  bool _eulaSigned;
70
  /// Has the EULA been signed?
71
  bool get eulaSigned => _eulaSigned;
72

73
  String _xcodeVersionText;
74
  String get xcodeVersionText => _xcodeVersionText;
75

76 77
  final RegExp xcodeVersionRegex = new RegExp(r'Xcode ([0-9.]+)');

78
  bool get xcodeVersionSatisfactory {
79 80
    if (!xcodeVersionRegex.hasMatch(xcodeVersionText))
      return false;
81

82
    String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1);
83
    List<String> components = version.split('.');
84

85 86
    int major = int.parse(components[0]);
    int minor = components.length == 1 ? 0 : int.parse(components[1]);
87

88
    return _xcodeVersionCheckValid(major, minor);
89
  }
90
}
91

92 93 94 95 96 97 98 99 100 101
bool _xcodeVersionCheckValid(int major, int minor) {
  if (major > kXcodeRequiredVersionMajor)
    return true;

  if (major == kXcodeRequiredVersionMajor)
    return minor >= kXcodeRequiredVersionMinor;

  return false;
}

102
Future<XcodeBuildResult> buildXcodeProject({
103
  BuildableIOSApp app,
104 105 106 107 108
  BuildMode mode,
  String target: flx.defaultMainPath,
  bool buildForDevice,
  bool codesign: true
}) async {
109
  String flutterProjectPath = Directory.current.path;
110
  updateXcodeGeneratedProperties(flutterProjectPath, mode, target);
111 112

  if (!_checkXcodeVersion())
113
    return new XcodeBuildResult(false);
114 115 116 117

  // Before the build, all service definitions must be updated and the dylibs
  // copied over to a location that is suitable for Xcodebuild to find them.

118
  await _addServicesToBundle(new Directory(app.appDirectory));
119 120

  List<String> commands = <String>[
121 122 123
    '/usr/bin/env',
    'xcrun',
    'xcodebuild',
124 125
    'clean',
    'build',
126 127
    '-configuration', 'Release',
    'ONLY_ACTIVE_ARCH=YES',
128 129
  ];

130
  List<FileSystemEntity> contents = new Directory(app.appDirectory).listSync();
131 132 133 134 135
  for (FileSystemEntity entity in contents) {
    if (path.extension(entity.path) == '.xcworkspace') {
      commands.addAll(<String>[
        '-workspace', path.basename(entity.path),
        '-scheme', path.basenameWithoutExtension(entity.path),
136
        "BUILD_DIR=${path.absolute(getIosBuildDirectory())}",
137 138 139 140 141
      ]);
      break;
    }
  }

142 143
  if (buildForDevice) {
    commands.addAll(<String>['-sdk', 'iphoneos', '-arch', 'arm64']);
144 145 146 147 148 149 150 151 152
    if (!codesign) {
      commands.addAll(
        <String>[
          'CODE_SIGNING_ALLOWED=NO',
          'CODE_SIGNING_REQUIRED=NO',
          'CODE_SIGNING_IDENTITY=""'
        ]
      );
    }
153 154 155 156
  } else {
    commands.addAll(<String>['-sdk', 'iphonesimulator', '-arch', 'x86_64']);
  }

157 158
  RunResult result = await runAsync(
    commands,
159
    workingDirectory: app.appDirectory,
160 161
    allowReentrantFlutter: true
  );
162 163 164 165 166 167

  if (result.exitCode != 0) {
    if (result.stderr.isNotEmpty)
      printStatus(result.stderr);
    if (result.stdout.isNotEmpty)
      printStatus(result.stdout);
168
    return new XcodeBuildResult(false, stdout: result.stdout, stderr: result.stderr);
169 170 171 172 173 174
  } else {
    // Look for 'clean build/Release-iphoneos/Runner.app'.
    RegExp regexp = new RegExp(r' clean (\S*\.app)$', multiLine: true);
    Match match = regexp.firstMatch(result.stdout);
    String outputDir;
    if (match != null)
175
      outputDir = path.join(app.appDirectory, match.group(1));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    return new XcodeBuildResult(true, output: outputDir);
  }
}

void diagnoseXcodeBuildFailure(XcodeBuildResult result) {
  File plistFile = new File('ios/Runner/Info.plist');
  if (plistFile.existsSync()) {
    String plistContent = plistFile.readAsStringSync();
    if (plistContent.contains('com.yourcompany')) {
      printError('');
      printError('It appears that your application still contains the default signing identifier.');
      printError("Try replacing 'com.yourcompany' with your signing id");
      printError('in ${plistFile.absolute.path}');
      return;
    }
  }
  if (result.stdout?.contains('Code Sign error') == true) {
    printError('');
    printError('It appears that there was a problem signing your application prior to installation on the device.');
    printError('');
    if (plistFile.existsSync()) {
      printError('Verify that the CFBundleIdentifier in the Info.plist file is your signing id');
      printError('  ${plistFile.absolute.path}');
      printError('');
    }
    printError("Try launching XCode and selecting 'Product > Build' to fix the problem:");
    printError("  open ios/Runner.xcodeproj");
    return;
204
  }
205 206 207
}

class XcodeBuildResult {
208
  XcodeBuildResult(this.success, {this.output, this.stdout, this.stderr});
209

210 211
  final bool success;
  final String output;
212 213
  final String stdout;
  final String stderr;
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
}

final RegExp _xcodeVersionRegExp = new RegExp(r'Xcode (\d+)\..*');
final String _xcodeRequirement = 'Xcode 7.0 or greater is required to develop for iOS.';

bool _checkXcodeVersion() {
  if (!Platform.isMacOS)
    return false;
  try {
    String version = runCheckedSync(<String>['xcodebuild', '-version']);
    Match match = _xcodeVersionRegExp.firstMatch(version);
    if (int.parse(match[1]) < 7) {
      printError('Found "${match[0]}". $_xcodeRequirement');
      return false;
    }
  } catch (e) {
    printError('Cannot find "xcodebuid". $_xcodeRequirement');
    return false;
  }
  return true;
}

Ian Hickson's avatar
Ian Hickson committed
236
Future<Null> _addServicesToBundle(Directory bundle) async {
237
  List<Map<String, String>> services = <Map<String, String>>[];
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  printTrace("Trying to resolve native pub services.");

  // Step 1: Parse the service configuration yaml files present in the service
  //         pub packages.
  await parseServiceConfigs(services);
  printTrace("Found ${services.length} service definition(s).");

  // Step 2: Copy framework dylibs to the correct spot for xcodebuild to pick up.
  Directory frameworksDirectory = new Directory(path.join(bundle.path, "Frameworks"));
  await _copyServiceFrameworks(services, frameworksDirectory);

  // Step 3: Copy the service definitions manifest at the correct spot for
  //         xcodebuild to pick up.
  File manifestFile = new File(path.join(bundle.path, "ServiceDefinitions.json"));
  _copyServiceDefinitionsManifest(services, manifestFile);
}

Ian Hickson's avatar
Ian Hickson committed
255
Future<Null> _copyServiceFrameworks(List<Map<String, String>> services, Directory frameworksDirectory) async {
256 257 258 259 260 261 262 263 264 265 266
  printTrace("Copying service frameworks to '${path.absolute(frameworksDirectory.path)}'.");
  frameworksDirectory.createSync(recursive: true);
  for (Map<String, String> service in services) {
    String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
    File dylib = new File(dylibPath);
    printTrace("Copying ${dylib.path} into bundle.");
    if (!dylib.existsSync()) {
      printError("The service dylib '${dylib.path}' does not exist.");
      continue;
    }
    // Shell out so permissions on the dylib are preserved.
267
    runCheckedSync(<String>['/bin/cp', dylib.path, frameworksDirectory.path]);
268 269 270 271 272
  }
}

void _copyServiceDefinitionsManifest(List<Map<String, String>> services, File manifest) {
  printTrace("Creating service definitions manifest at '${manifest.path}'");
273
  List<Map<String, String>> jsonServices = services.map((Map<String, String> service) => <String, String>{
274 275 276 277 278
    'name': service['name'],
    // Since we have already moved it to the Frameworks directory. Strip away
    // the directory and basenames.
    'framework': path.basenameWithoutExtension(service['ios-framework'])
  }).toList();
279
  Map<String, dynamic> json = <String, dynamic>{ 'services' : jsonServices };
280 281
  manifest.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
}