-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdevcmd.ts
More file actions
242 lines (217 loc) · 9.67 KB
/
devcmd.ts
File metadata and controls
242 lines (217 loc) · 9.67 KB
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { promises as fs } from 'fs';
import { vcvars } from 'node-vcvarsall';
import { vswhere } from 'node-vswhere';
import * as path from 'path';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { extensionContext, isString, resolveVariables, whichAsync } from '../common';
import { isWindows } from '../constants';
import { CppSettings } from './settings';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const errorNoContext = localize('no.context.provided', 'No context provided');
const errorNotWindows = localize('not.windows', 'The "Set Visual Studio Developer Environment" command is only available on Windows');
const errorNoVSFound = localize('error.no.vs', 'A Visual Studio installation with the C++ compiler was not found');
export const errorOperationCancelled = localize('operation.cancelled', 'The operation was cancelled');
const errorNoHostsFound = localize('no.hosts', 'No hosts found');
const configuringDevEnv = localize('config.dev.env', 'Configuring developer environment...');
const selectVSInstallation = localize('select.vs.install', 'Select a Visual Studio installation');
const advancedOptions = localize('advanced.options', 'Advanced options...');
const advancedOptionsDescription = localize('advanced.options.desc', 'Select a specific host and target architecture, toolset version, etc.');
const selectToolsetVersion = localize('select.toolset', 'Select a toolset version');
const selectHostTargetArch = localize('select.host.target', 'Select a host and target architecture');
export function isEnvironmentOverrideApplied(): boolean {
return extensionContext?.environmentVariableCollection.get('VCToolsInstallDir') !== undefined;
}
export function getEffectiveEnvironment(): { [key: string]: string | undefined } {
const env = { ...process.env };
extensionContext?.environmentVariableCollection.forEach((variable: string, mutator: vscode.EnvironmentVariableMutator) => {
if (variable.toLowerCase() === "path") {
// Path is special because it has a placeholder to insert the current Path into.
env[variable] = resolveVariables(mutator.value);
} else {
env[variable] = mutator.value;
}
});
return env;
}
export async function canFindCl(): Promise<boolean> {
if (!isWindows) {
return false;
}
const pathOverride = resolveVariables(extensionContext?.environmentVariableCollection.get('Path')?.value);
const path = pathOverride ?? process.env['Path'];
const found = await whichAsync('cl.exe', path);
return isString(found);
}
export async function setEnvironment(context?: vscode.ExtensionContext) {
if (!isWindows) {
throw new Error(errorNotWindows);
}
if (!context) {
throw new Error(errorNoContext);
}
const vses = await getVSInstallations();
if (!vses) {
throw new Error(errorNoVSFound);
}
let vs = await chooseVSInstallation(vses);
let options: vcvars.Options | undefined;
if (!vs) {
const compiler = await getAdvancedConfiguration(vses);
vs = compiler.vs;
options = compiler.options;
}
const vars = await vscode.window.withProgress({
cancellable: false,
location: vscode.ProgressLocation.Notification,
title: configuringDevEnv
}, () => vcvars.getVCVars(vs, options));
if (!vars || !vars['INCLUDE']) {
throw new Error(localize('something.wrong', 'Something went wrong: {0}', JSON.stringify(vars)));
}
const host = vars['VSCMD_ARG_HOST_ARCH'];
const target = vars['VSCMD_ARG_TGT_ARCH'];
const arch = vcvars.getArchitecture({
host: match(host, { 'x86': 'x86', 'x64': 'x64', 'arm64': 'arm64' }) ?? 'x64',
target: match(target, { 'x86': 'x86', 'x64': 'x64', 'arm64': 'ARM64', 'arm': 'ARM' }) ?? 'x64'
});
const settings = new CppSettings();
context.environmentVariableCollection.clear();
for (const key of Object.keys(vars)) {
context.environmentVariableCollection.replace(key, vars[key].replace(`%${key}%`, '${env:' + key + '}'));
}
context.environmentVariableCollection.description = localize('dev.env.for', '{0} developer environment for {1}', arch, vsDisplayNameWithSuffix(vs));
context.environmentVariableCollection.persistent = settings.persistVSDeveloperEnvironment;
return true;
}
async function getVSInstallations() {
const installations = await vswhere.getVSInstallations({
all: true,
prerelease: true,
sort: true,
requires: ['Microsoft.VisualStudio.Component.VC.Tools.x86.x64', 'Microsoft.VisualStudio.Component.VC.Tools.ARM64'],
requiresAny: true
});
if (installations.length === 0) {
throw new Error(errorNoVSFound);
}
return installations;
}
function vsDisplayNameWithSuffix(installation: vswhere.Installation): string {
const suffix = (() => {
if (installation.channelId.endsWith('.main')) {
return 'main';
} else if (installation.channelId.endsWith('.IntPreview')) {
return 'Int Preview';
} else if (installation.channelId.endsWith('.Preview')) {
if (parseInt(installation.installationVersion) >= 18) {
return 'Insiders';
}
return 'Preview';
}
return '';
})();
return `${installation.displayName}${suffix ? ` ${suffix}` : ''}`;
}
async function chooseVSInstallation(installations: vswhere.Installation[]): Promise<vswhere.Installation | undefined> {
const items: vscode.QuickPickItem[] = installations.map(installation => <vscode.QuickPickItem>{
label: vsDisplayNameWithSuffix(installation),
detail: localize('default.env', 'Default environment for {0}', installation.catalog.productDisplayVersion)
});
items.push({
label: advancedOptions,
description: advancedOptionsDescription
});
const selection = await vscode.window.showQuickPick(items, {
placeHolder: selectVSInstallation
});
if (!selection) {
throw new Error(errorOperationCancelled);
}
return installations.find(installation => vsDisplayNameWithSuffix(installation) === selection.label);
}
interface Compiler {
version: string;
vs: vswhere.Installation;
options: vcvars.Options;
}
async function getAdvancedConfiguration(vses: vswhere.Installation[]): Promise<Compiler> {
const compiler = await chooseCompiler(vses);
if (!compiler) {
throw new Error(errorOperationCancelled);
}
await setOptions(compiler);
return compiler;
}
async function chooseCompiler(vses: vswhere.Installation[]): Promise<Compiler | undefined> {
const compilers: Compiler[] = [];
for (const vs of vses) {
const vcPath = path.join(vs.installationPath, 'VC', 'Tools', 'MSVC');
const folders = await fs.readdir(vcPath);
for (const version of folders) {
const options: vcvars.Options = {
// Don't set the version in the options if there is only one
vcVersion: folders.length > 1 ? version : undefined
};
compilers.push({ version, vs, options });
}
}
const items = compilers.map(compiler => <vscode.QuickPickItem>{
label: compiler.version,
description: vsDisplayNameWithSuffix(compiler.vs)
});
const selection = await vscode.window.showQuickPick(items, {
placeHolder: selectToolsetVersion
});
if (!selection) {
throw new Error(errorOperationCancelled);
}
return compilers.find(compiler => compiler.version === selection.label && vsDisplayNameWithSuffix(compiler.vs) === selection.description);
}
async function setOptions(compiler: Compiler): Promise<void> {
const vcPath = path.join(compiler.vs.installationPath, 'VC', 'Tools', 'MSVC', compiler.version, 'bin');
const hostTargets = await getHostsAndTargets(vcPath);
if (hostTargets.length > 1) {
const items = hostTargets.map(ht => <vscode.QuickPickItem>{
label: vcvars.getArchitecture(ht),
description: localize('host.target', 'host = {0}, target = {1}', ht.host, ht.target)
});
const selection = await vscode.window.showQuickPick(items, {
placeHolder: selectHostTargetArch
});
if (!selection) {
throw new Error(errorOperationCancelled);
}
compiler.options.arch = <vcvars.Architecture>selection.label;
}
}
async function getHostsAndTargets(vcPath: string): Promise<vcvars.HostTarget[]> {
const hosts = await fs.readdir(vcPath);
if (hosts.length === 0) {
throw new Error(errorNoHostsFound);
}
const hostTargets: vcvars.HostTarget[] = [];
for (const host of hosts) {
const h = match<'x86' | 'x64' | 'arm64' | undefined>(host.toLowerCase(), { 'hostx86': 'x86', 'hostx64': 'x64', 'hostarm64': 'arm64' });
if (!h) {
// skip any non-matching folders
continue;
}
const targets = await fs.readdir(path.join(vcPath, host));
for (const target of targets) {
hostTargets.push({
host: h,
target: match(target, { 'x86': 'x86', 'x64': 'x64', 'arm64': 'ARM64', 'arm': 'ARM' }) ?? 'x64'
});
}
}
return hostTargets;
}
function match<T>(item: string, cases: { [key: string]: T }): T | undefined {
return cases[item];
}