forked from swiftlang/vscode-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolchain.ts
381 lines (360 loc) · 13.3 KB
/
toolchain.ts
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//===----------------------------------------------------------------------===//
//
// This source file is part of the VSCode Swift open source project
//
// Copyright (c) 2021 the VSCode Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VSCode Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import * as fs from "fs/promises";
import * as path from "path";
import { normalize } from "path";
import * as plist from "plist";
import * as vscode from "vscode";
import configuration from "../configuration";
import { SwiftOutputChannel } from "../ui/SwiftOutputChannel";
import { execFile, execSwift, pathExists } from "../utilities/utilities";
import { Version } from "../utilities/version";
/**
* Contents of **Info.plist** on Windows.
*/
interface InfoPlist {
DefaultProperties: {
XCTEST_VERSION: string | undefined;
};
}
/**
* Stripped layout of `swift -print-target-info` output.
*/
interface SwiftTargetInfo {
compilerVersion: string;
target?: {
triple: string;
[name: string]: string | string[];
};
paths: {
runtimeLibraryPaths: string[];
[name: string]: string | string[];
};
[name: string]: string | object | undefined;
}
/**
* A Swift compilation target that can be compiled to
* from macOS. These are similar to XCode's target list.
*/
export enum DarwinCompatibleTarget {
iOS,
macOS,
}
export class SwiftToolchain {
constructor(
public swiftFolderPath: string,
public toolchainPath: string,
public swiftVersionString: string,
public swiftVersion: Version,
public runtimePath?: string,
private defaultTarget?: string,
private defaultSDK?: string,
private customSDK?: string,
public xcTestPath?: string
) {}
static async create(): Promise<SwiftToolchain> {
const swiftFolderPath = await this.getSwiftFolderPath();
const toolchainPath = await this.getToolchainPath(swiftFolderPath);
const targetInfo = await this.getSwiftTargetInfo();
const swiftVersion = await this.getSwiftVersion(targetInfo);
const runtimePath = await this.getRuntimePath(targetInfo);
const defaultSDK = await this.getDefaultSDK();
const customSDK = this.getCustomSDK();
const xcTestPath = await this.getXCTestPath(
targetInfo,
swiftVersion,
runtimePath,
customSDK ?? defaultSDK
);
return new SwiftToolchain(
swiftFolderPath,
toolchainPath,
targetInfo.compilerVersion,
swiftVersion,
runtimePath,
targetInfo.target?.triple,
defaultSDK,
customSDK,
xcTestPath
);
}
/**
* Get active developer dir for Xcode
*/
public static async getXcodeDeveloperDir(): Promise<string> {
const { stdout } = await execFile("xcode-select", ["-p"]);
return stdout.trimEnd();
}
/**
* @param target Target to obtain the SDK path for
* @returns path to the SDK for the target
*/
public static async getSdkForTarget(
target: DarwinCompatibleTarget
): Promise<string | undefined> {
let sdkType: string;
switch (target) {
case DarwinCompatibleTarget.macOS:
// macOS is the default target, so lets not update the SDK
return undefined;
case DarwinCompatibleTarget.iOS:
sdkType = "iphoneos";
break;
}
// Include custom variables so that non-standard XCode installs can be better supported.
const { stdout } = await execFile("xcrun", ["--sdk", sdkType, "--show-sdk-path"], {
env: { ...process.env, ...configuration.swiftEnvironmentVariables },
});
return path.join(stdout.trimEnd());
}
/**
* Get list of Xcode versions intalled on mac
* @returns Folders for each Xcode install
*/
public static async getXcodeInstalls(): Promise<string[]> {
const { stdout: xcodes } = await execFile("mdfind", [
`kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'`,
]);
return xcodes.trimEnd().split("\n");
}
logDiagnostics(channel: SwiftOutputChannel) {
channel.logDiagnostic(`Swift Path: ${this.swiftFolderPath}`);
channel.logDiagnostic(`Toolchain Path: ${this.toolchainPath}`);
if (this.runtimePath) {
channel.logDiagnostic(`Runtime Library Path: ${this.runtimePath}`);
}
if (this.defaultTarget) {
channel.logDiagnostic(`Default Target: ${this.defaultTarget}`);
}
if (this.defaultSDK) {
channel.logDiagnostic(`Default SDK: ${this.defaultSDK}`);
}
if (this.customSDK) {
channel.logDiagnostic(`Custom SDK: ${this.customSDK}`);
}
if (this.xcTestPath) {
channel.logDiagnostic(`XCTest Path: ${this.xcTestPath}`);
}
}
private static async getSwiftFolderPath(): Promise<string> {
if (configuration.path !== "") {
return configuration.path;
}
try {
let swift: string;
switch (process.platform) {
case "darwin": {
const { stdout } = await execFile("which", ["swift"]);
swift = stdout.trimEnd();
break;
}
case "win32": {
const { stdout } = await execFile("where", ["swift"]);
swift = stdout.trimEnd();
break;
}
default: {
// use `type swift` to find `swift`. Run inside /bin/sh to ensure
// we get consistent output as different shells output a different
// format. Tried running with `-p` but that is not available in /bin/sh
const { stdout } = await execFile("/bin/sh", ["-c", "LCMESSAGES=C type swift"]);
const swiftMatch = /^swift is (.*)$/.exec(stdout.trimEnd());
if (swiftMatch) {
swift = swiftMatch[1];
} else {
throw Error("Failed to find swift executable");
}
break;
}
}
// swift may be a symbolic link
const realSwift = await fs.realpath(swift);
return path.dirname(realSwift);
} catch {
throw Error("Failed to find swift executable");
}
}
/**
* @returns path to Toolchain folder
*/
private static async getToolchainPath(swiftPath: string): Promise<string> {
if (configuration.path !== "") {
return path.dirname(path.dirname(configuration.path));
}
try {
switch (process.platform) {
case "darwin": {
const { stdout } = await execFile("xcrun", ["--find", "swift"]);
const swift = stdout.trimEnd();
return path.dirname(path.dirname(path.dirname(swift)));
}
default: {
return path.dirname(path.dirname(path.dirname(swiftPath)));
}
}
} catch {
throw Error("Failed to find swift toolchain");
}
}
/**
* @param targetInfo swift target info
* @returns path to Swift runtime
*/
private static async getRuntimePath(targetInfo: SwiftTargetInfo): Promise<string | undefined> {
if (configuration.runtimePath !== "") {
return configuration.runtimePath;
} else if (process.platform === "win32") {
const { stdout } = await execFile("where", ["swiftCore.dll"]);
const swiftCore = stdout.trimEnd();
return swiftCore.length > 0 ? path.dirname(swiftCore) : undefined;
} else {
return targetInfo.paths.runtimeLibraryPaths.length > 0
? targetInfo.paths.runtimeLibraryPaths.join(":")
: undefined;
}
}
/**
* @returns path to default SDK
*/
private static async getDefaultSDK(): Promise<string | undefined> {
switch (process.platform) {
case "darwin": {
if (process.env.SDKROOT) {
return process.env.SDKROOT;
}
return this.getSdkForTarget(DarwinCompatibleTarget.macOS);
}
case "win32": {
return process.env.SDKROOT;
}
}
return undefined;
}
/**
* @returns path to custom SDK
*/
private static getCustomSDK(): string | undefined {
return configuration.sdk !== "" ? configuration.sdk : undefined;
}
/**
* @param targetInfo swift target info
* @param swiftVersion parsed swift version
* @param runtimePath path to Swift runtime
* @param sdkroot path to swift SDK
* @returns path to folder where xctest can be found
*/
private static async getXCTestPath(
targetInfo: SwiftTargetInfo,
swiftVersion: Version,
runtimePath: string | undefined,
sdkroot: string | undefined
): Promise<string | undefined> {
switch (process.platform) {
case "darwin": {
const developerDir = await this.getXcodeDeveloperDir();
return path.join(developerDir, "usr", "bin");
}
case "win32": {
// look up runtime library directory for XCTest alternatively
const fallbackPath =
runtimePath !== undefined &&
(await pathExists(path.join(runtimePath, "XCTest.dll")))
? runtimePath
: undefined;
if (!sdkroot) {
return fallbackPath;
}
const platformPath = path.dirname(path.dirname(path.dirname(sdkroot)));
const platformManifest = path.join(platformPath, "Info.plist");
if ((await pathExists(platformManifest)) !== true) {
if (fallbackPath) {
return fallbackPath;
}
vscode.window.showWarningMessage(
"XCTest not found due to non-standardized library layout. Tests explorer won't work as expected."
);
return undefined;
}
const data = await fs.readFile(platformManifest, "utf8");
const infoPlist = plist.parse(data) as unknown as InfoPlist;
const version = infoPlist.DefaultProperties.XCTEST_VERSION;
if (!version) {
throw Error("Info.plist is missing the XCTEST_VERSION key.");
}
if (swiftVersion >= new Version(5, 7, 0)) {
let bindir: string;
const arch = targetInfo.target?.triple.split("-", 1)[0];
switch (arch) {
case "x86_64":
bindir = "bin64";
break;
case "i686":
bindir = "bin32";
break;
case "aarch64":
bindir = "bin64a";
break;
default:
throw Error(`unsupported architecture ${arch}`);
}
return path.join(
platformPath,
"Developer",
"Library",
`XCTest-${version}`,
"usr",
bindir
);
} else {
return path.join(
platformPath,
"Developer",
"Library",
`XCTest-${version}`,
"usr",
"bin"
);
}
}
}
return undefined;
}
/** @returns swift target info */
private static async getSwiftTargetInfo(): Promise<SwiftTargetInfo> {
try {
const { stdout } = await execSwift(["-print-target-info"]);
const targetInfo = JSON.parse(stdout.trimEnd()) as SwiftTargetInfo;
// workaround for Swift 5.3 and older toolchains
if (targetInfo.compilerVersion === undefined) {
const { stdout } = await execSwift(["--version"]);
targetInfo.compilerVersion = stdout.split("\n", 1)[0];
}
return targetInfo;
} catch {
throw Error("Cannot parse swift target info output.");
}
}
/**
* @param targetInfo swift target info
* @returns swift version object
*/
private static getSwiftVersion(targetInfo: SwiftTargetInfo): Version {
const match = targetInfo.compilerVersion.match(/Swift version ([\S]+)/);
let version: Version | undefined;
if (match) {
version = Version.fromString(match[1]);
}
return version ?? new Version(0, 0, 0);
}
}