File size: 9,297 Bytes
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
a4ff84b
 
 
 
 
 
 
 
b0336a8
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
b0336a8
 
 
 
 
 
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
a4ff84b
 
 
 
 
 
 
 
b0336a8
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
b0336a8
 
a4ff84b
 
 
 
 
b0336a8
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
a4ff84b
 
 
 
b0336a8
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
 
 
 
 
 
 
 
 
a4ff84b
 
 
 
 
 
 
 
 
b0336a8
a4ff84b
b0336a8
a4ff84b
b0336a8
 
 
 
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
a4ff84b
 
 
b0336a8
 
 
 
 
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0336a8
 
 
 
 
 
a4ff84b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
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
147
148
149
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
175
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
204
205
206
207
208
209
210
211
212
213
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
243
244
245
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
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright 2014 The Flutter 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:file/memory.dart';
import 'package:meta/meta.dart';
import 'package:process/process.dart';

import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/user_messages.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../cache.dart';
import '../ios/xcodeproj.dart';

Version get xcodeRequiredVersion => Version(14, null, null);

/// Diverging this number from the minimum required version will provide a doctor
/// warning, not error, that users should upgrade Xcode.
Version get xcodeRecommendedVersion => Version(15, null, null);

/// SDK name passed to `xcrun --sdk`. Corresponds to undocumented Xcode
/// SUPPORTED_PLATFORMS values.
///
/// Usage: xcrun [options] <tool name> ... arguments ...
/// ...
/// --sdk <sdk name>            find the tool for the given SDK name.
String getSDKNameForIOSEnvironmentType(EnvironmentType environmentType) {
  return (environmentType == EnvironmentType.simulator) ? 'iphonesimulator' : 'iphoneos';
}

/// A utility class for interacting with Xcode command line tools.
class Xcode {
  Xcode({
    required Platform platform,
    required ProcessManager processManager,
    required Logger logger,
    required FileSystem fileSystem,
    required XcodeProjectInterpreter xcodeProjectInterpreter,
    required UserMessages userMessages,
    String? flutterRoot,
  }) : _platform = platform,
       _fileSystem = fileSystem,
       _xcodeProjectInterpreter = xcodeProjectInterpreter,
       _userMessage = userMessages,
       _flutterRoot = flutterRoot,
       _processUtils = ProcessUtils(logger: logger, processManager: processManager),
       _logger = logger;

  /// Create an [Xcode] for testing.
  ///
  /// Defaults to a memory file system, fake platform,
  /// buffer logger, and test [XcodeProjectInterpreter].
  @visibleForTesting
  factory Xcode.test({
    required ProcessManager processManager,
    XcodeProjectInterpreter? xcodeProjectInterpreter,
    Platform? platform,
    FileSystem? fileSystem,
    String? flutterRoot,
    Logger? logger,
  }) {
    platform ??= FakePlatform(operatingSystem: 'macos', environment: <String, String>{});
    logger ??= BufferLogger.test();
    return Xcode(
      platform: platform,
      processManager: processManager,
      fileSystem: fileSystem ?? MemoryFileSystem.test(),
      userMessages: UserMessages(),
      flutterRoot: flutterRoot,
      logger: logger,
      xcodeProjectInterpreter:
          xcodeProjectInterpreter ?? XcodeProjectInterpreter.test(processManager: processManager),
    );
  }

  final Platform _platform;
  final ProcessUtils _processUtils;
  final FileSystem _fileSystem;
  final XcodeProjectInterpreter _xcodeProjectInterpreter;
  final UserMessages _userMessage;
  final String? _flutterRoot;
  final Logger _logger;

  bool get isInstalledAndMeetsVersionCheck =>
      _platform.isMacOS && isInstalled && isRequiredVersionSatisfactory;

  String? _xcodeSelectPath;
  String? get xcodeSelectPath {
    if (_xcodeSelectPath == null) {
      try {
        _xcodeSelectPath =
            _processUtils.runSync(<String>['/usr/bin/xcode-select', '--print-path']).stdout.trim();
      } on ProcessException {
        // Ignored, return null below.
      } on ArgumentError {
        // Ignored, return null below.
      }
    }
    return _xcodeSelectPath;
  }

  String get xcodeAppPath {
    // If the Xcode Select Path is /Applications/Xcode.app/Contents/Developer,
    // the path to Xcode App is /Applications/Xcode.app

    final String? pathToXcode = xcodeSelectPath;
    if (pathToXcode == null || pathToXcode.isEmpty) {
      throwToolExit(_userMessage.xcodeMissing);
    }
    final int index = pathToXcode.indexOf('.app');
    if (index == -1) {
      throwToolExit(_userMessage.xcodeMissing);
    }
    return pathToXcode.substring(0, index + 4);
  }

  /// Path to script to automate debugging through Xcode. Used in xcode_debug.dart.
  /// Located in this file to make it easily overrideable in google3.
  String get xcodeAutomationScriptPath {
    final String flutterRoot = _flutterRoot ?? Cache.flutterRoot!;
    final String flutterToolsAbsolutePath = _fileSystem.path.join(
      flutterRoot,
      'packages',
      'flutter_tools',
    );

    final String filePath = '$flutterToolsAbsolutePath/bin/xcode_debug.js';
    if (!_fileSystem.file(filePath).existsSync()) {
      throwToolExit('Unable to find Xcode automation script at $filePath');
    }
    return filePath;
  }

  bool get isInstalled => _xcodeProjectInterpreter.isInstalled;

  Version? get currentVersion => _xcodeProjectInterpreter.version;

  String? get buildVersion => _xcodeProjectInterpreter.build;

  String? get versionText => _xcodeProjectInterpreter.versionText;

  bool? _eulaSigned;

  /// Has the EULA been signed?
  bool get eulaSigned {
    if (_eulaSigned == null) {
      try {
        final RunResult result = _processUtils.runSync(<String>[...xcrunCommand(), 'clang']);
        if (result.stdout.contains('license')) {
          _eulaSigned = false;
        } else if (result.stderr.contains('license')) {
          _eulaSigned = false;
        } else {
          _eulaSigned = true;
        }
      } on ProcessException {
        _eulaSigned = false;
      }
    }
    return _eulaSigned ?? false;
  }

  bool? _isSimctlInstalled;

  /// Verifies that simctl is installed by trying to run it.
  bool get isSimctlInstalled {
    // This command will error if additional components need to be installed in
    // xcode 9.2 and above.
    _isSimctlInstalled ??= _processUtils.exitsHappySync(<String>[
      ...xcrunCommand(),
      'simctl',
      'list',
      'devices',
      'booted',
    ]);
    return _isSimctlInstalled ?? false;
  }

  bool? _isDevicectlInstalled;

  /// Verifies that `devicectl` is installed by checking Xcode version and trying
  /// to run it. `devicectl` is made available in Xcode 15.
  bool get isDevicectlInstalled {
    if (_isDevicectlInstalled == null) {
      if (currentVersion == null || currentVersion!.major < 15) {
        _isDevicectlInstalled = false;
        return _isDevicectlInstalled!;
      }
      _isDevicectlInstalled = _processUtils.exitsHappySync(<String>[
        ...xcrunCommand(),
        'devicectl',
        '--version',
      ]);
    }
    return _isDevicectlInstalled ?? false;
  }

  bool get isRequiredVersionSatisfactory {
    final Version? version = currentVersion;
    if (version == null) {
      return false;
    }
    return version >= xcodeRequiredVersion;
  }

  bool get isRecommendedVersionSatisfactory {
    final Version? version = currentVersion;
    if (version == null) {
      return false;
    }
    return version >= xcodeRecommendedVersion;
  }

  /// See [XcodeProjectInterpreter.xcrunCommand].
  List<String> xcrunCommand() => _xcodeProjectInterpreter.xcrunCommand();

  Future<RunResult> cc(List<String> args) => _run('cc', args);

  Future<RunResult> clang(List<String> args) => _run('clang', args);

  Future<RunResult> dsymutil(List<String> args) => _run('dsymutil', args);

  Future<RunResult> strip(List<String> args) => _run('strip', args);

  Future<RunResult> _run(String command, List<String> args) {
    return _processUtils.run(<String>[...xcrunCommand(), command, ...args], throwOnError: true);
  }

  Future<String> sdkLocation(EnvironmentType environmentType) async {
    final RunResult runResult = await _processUtils.run(<String>[
      ...xcrunCommand(),
      '--sdk',
      getSDKNameForIOSEnvironmentType(environmentType),
      '--show-sdk-path',
    ]);
    if (runResult.exitCode != 0) {
      throwToolExit('Could not find SDK location: ${runResult.stderr}');
    }
    return runResult.stdout.trim();
  }

  String? getSimulatorPath() {
    final String? selectPath = xcodeSelectPath;
    if (selectPath == null) {
      return null;
    }
    final String appPath = _fileSystem.path.join(selectPath, 'Applications', 'Simulator.app');
    return _fileSystem.directory(appPath).existsSync() ? appPath : null;
  }

  /// Gets the version number of the platform for the selected SDK.
  Future<Version?> sdkPlatformVersion(EnvironmentType environmentType) async {
    final RunResult runResult = await _processUtils.run(<String>[
      ...xcrunCommand(),
      '--sdk',
      getSDKNameForIOSEnvironmentType(environmentType),
      '--show-sdk-platform-version',
    ]);
    if (runResult.exitCode != 0) {
      _logger.printError('Could not find SDK Platform Version: ${runResult.stderr}');
      return null;
    }
    final String versionString = runResult.stdout.trim();
    return Version.parse(versionString);
  }
}

EnvironmentType? environmentTypeFromSdkroot(String sdkroot, FileSystem fileSystem) {
  // iPhoneSimulator.sdk or iPhoneOS.sdk
  final String sdkName = fileSystem.path.basename(sdkroot).toLowerCase();
  if (sdkName.contains('iphone')) {
    return sdkName.contains('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
  }
  assert(false);
  return null;
}