Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7fe4095

Browse files
committed
win: generic Visual Studio 2017 detection
PR-URL: #1762 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Refael Ackermann <refack@gmail.com>
1 parent 721eb69 commit 7fe4095

9 files changed

Lines changed: 387 additions & 118 deletions
Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
44

55
// Usage:
6-
// powershell -ExecutionPolicy Unrestricted -Version "2.0" -Command "&{Add-Type -Path Find-VS2017.cs; [VisualStudioConfiguration.Main]::Query()}"
6+
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
7+
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
8+
79
usingSystem;
810
usingSystem.Text;
911
usingSystem.Runtime.InteropServices;
12+
usingSystem.Collections.Generic;
1013

1114
namespaceVisualStudioConfiguration
1215
{
@@ -184,90 +187,57 @@ public class SetupConfigurationClass
184187

185188
publicstaticclassMain
186189
{
187-
publicstaticvoidQuery()
190+
publicstaticvoidPrintJson()
188191
{
189192
ISetupConfigurationquery=newSetupConfiguration();
190193
ISetupConfiguration2query2=(ISetupConfiguration2)query;
191194
IEnumSetupInstancese=query2.EnumAllInstances();
192195

193196
intpceltFetched;
194197
ISetupInstance2[]rgelt=newISetupInstance2[1];
195-
StringBuilderlog=newStringBuilder();
198+
List<string>instances=newList<string>();
196199
while(true)
197200
{
198201
e.Next(1,rgelt,outpceltFetched);
199202
if(pceltFetched<=0)
200203
{
201-
Console.WriteLine(String.Format("{{\"log\":\"{0}\"}}",log.ToString()));
204+
Console.WriteLine(String.Format("[{0}]",string.Join(",",instances.ToArray())));
202205
return;
203206
}
204-
if(CheckInstance(rgelt[0],reflog))
205-
return;
207+
208+
instances.Add(InstanceJson(rgelt[0]));
206209
}
207210
}
208211

209-
privatestaticboolCheckInstance(ISetupInstance2setupInstance2,refStringBuilderlog)
212+
privatestaticstringJsonString(strings)
210213
{
211-
// Visual Studio Community 2017 component directory:
212-
// https://www.visualstudio.com/en-us/productinfo/vs2017-install-product-Community.workloads
214+
return"\""+s.Replace("\\","\\\\").Replace("\"","\\\"")+"\"";
215+
}
213216

214-
stringpath=setupInstance2.GetInstallationPath().Replace("\\","\\\\");
215-
log.Append(String.Format("Found installation at: {0}\\n",path));
217+
privatestaticstringInstanceJson(ISetupInstance2setupInstance2)
218+
{
219+
// Visual Studio component directory:
220+
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
216221

217-
boolhasMSBuild=false;
218-
boolhasVCTools=false;
219-
uintWin10SDKVer=0;
220-
boolhasWin8SDK=false;
222+
StringBuilderjson=newStringBuilder();
223+
json.Append("{");
221224

222-
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
223-
{
224-
conststringWin10SDKPrefix="Microsoft.VisualStudio.Component.Windows10SDK.";
225-
226-
stringid=package.GetId();
227-
if(id=="Microsoft.VisualStudio.VC.MSBuild.Base")
228-
hasMSBuild=true;
229-
elseif(id=="Microsoft.VisualStudio.Component.VC.Tools.x86.x64")
230-
hasVCTools=true;
231-
elseif(id.StartsWith(Win10SDKPrefix)){
232-
string[]parts=id.Substring(Win10SDKPrefix.Length).Split('.');
233-
if(parts.Length>1&&parts[1]!="Desktop")
234-
continue;
235-
uintfoundSdkVer;
236-
if(UInt32.TryParse(parts[0],outfoundSdkVer))
237-
Win10SDKVer=Math.Max(Win10SDKVer,foundSdkVer);
238-
}elseif(id=="Microsoft.VisualStudio.Component.Windows81SDK")
239-
hasWin8SDK=true;
240-
else
241-
continue;
242-
243-
log.Append(String.Format(" - Found {0}\\n",id));
244-
}
225+
stringpath=JsonString(setupInstance2.GetInstallationPath());
226+
json.Append(String.Format("\"path\":{0},",path));
245227

246-
if(!hasMSBuild)
247-
log.Append(" - Missing Visual Studio C++ core features (Microsoft.VisualStudio.VC.MSBuild.Base)\\n");
248-
if(!hasVCTools)
249-
log.Append(" - Missing VC++ 2017 v141 toolset (x86,x64) (Microsoft.VisualStudio.Component.VC.Tools.x86.x64)\\n");
250-
if((Win10SDKVer==0)&&(!hasWin8SDK))
251-
log.Append(" - Missing a Windows SDK (Microsoft.VisualStudio.Component.Windows10SDK.* or Microsoft.VisualStudio.Component.Windows81SDK)\\n");
228+
stringversion=JsonString(setupInstance2.GetInstallationVersion());
229+
json.Append(String.Format("\"version\":{0},",version));
252230

253-
if(hasMSBuild&&hasVCTools)
231+
List<string>packages=newList<string>();
232+
foreach(ISetupPackageReferencepackageinsetupInstance2.GetPackages())
254233
{
255-
if(Win10SDKVer>0)
256-
{
257-
log.Append(" - Using this installation with Windows 10 SDK"/*\\n*/);
258-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"10.0.{2}.0\"}}",log.ToString(),path,Win10SDKVer));
259-
returntrue;
260-
}
261-
elseif(hasWin8SDK)
262-
{
263-
log.Append(" - Using this installation with Windows 8.1 SDK"/*\\n*/);
264-
Console.WriteLine(String.Format("{{\"log\":\"{0}\",\"path\":\"{1}\",\"sdk\":\"8.1\"}}",log.ToString(),path));
265-
returntrue;
266-
}
234+
stringid=JsonString(package.GetId());
235+
packages.Add(id);
267236
}
237+
json.Append(String.Format("\"packages\":[{0}]",string.Join(",",packages.ToArray())));
268238

269-
log.Append(" - Some required components are missing, not using this installation\\n");
270-
returnfalse;
239+
json.Append("}");
240+
returnjson.ToString();
271241
}
272242
}
273243
}

‎lib/configure.js‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ var fs = require('graceful-fs')
1717
,win=process.platform==='win32'
1818
,findNodeDirectory=require('./find-node-directory')
1919
,msgFormat=require('util').format
20+
,logWithPrefix=require('./util').logWithPrefix
2021
if(win)
21-
varfindVS2017=require('./find-vs2017')
22+
varfindVisualStudio=require('./find-visualstudio')
2223

2324
exports.usage='Generates '+(win ? 'MSVC project files' : 'a Makefile')+' for the current module'
2425

@@ -83,7 +84,7 @@ function configure (gyp, argv, callback) {
8384
if(err)returncallback(err)
8485
log.verbose('build dir','"build" dir needed to be created?',isNew)
8586
if(win&&(!gyp.opts.msvs_version||gyp.opts.msvs_version==='2017')){
86-
findVS2017(function(err,vsSetup){
87+
findVisualStudio(function(err,vsSetup){
8788
if(err){
8889
log.verbose('Not using VS2017:',err.message)
8990
createConfigFile()
@@ -644,16 +645,3 @@ function findPython (configPython, callback) {
644645
varfinder=newPythonFinder(configPython,callback)
645646
finder.findPython()
646647
}
647-
648-
functionlogWithPrefix(log,prefix){
649-
functionsetPrefix(logFunction){
650-
return(...args)=>logFunction.apply(null,[prefix, ...args])
651-
}
652-
return{
653-
silly: setPrefix(log.silly),
654-
verbose: setPrefix(log.verbose),
655-
info: setPrefix(log.info),
656-
warn: setPrefix(log.warn),
657-
error: setPrefix(log.error),
658-
}
659-
}

‎lib/find-visualstudio.js‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
module.exports=exports=findVisualStudio
2+
module.exports.test={
3+
VisualStudioFinder: VisualStudioFinder,
4+
findVisualStudio: findVisualStudio
5+
}
6+
7+
constlog=require('npmlog')
8+
constexecFile=require('child_process').execFile
9+
constpath=require('path').win32
10+
constlogWithPrefix=require('./util').logWithPrefix
11+
12+
functionfindVisualStudio(callback){
13+
constfinder=newVisualStudioFinder(callback)
14+
finder.findVisualStudio()
15+
}
16+
17+
functionVisualStudioFinder(callback){
18+
this.callback=callback
19+
this.errorLog=[]
20+
}
21+
22+
VisualStudioFinder.prototype={
23+
log: logWithPrefix(log,'find VS'),
24+
25+
// Logs a message at verbose level, but also saves it to be displayed later
26+
// at error level if an error occurs. This should help diagnose the problem.
27+
addLog: functionaddLog(message){
28+
this.log.verbose(message)
29+
this.errorLog.push(message)
30+
},
31+
32+
findVisualStudio: functionfindVisualStudio(){
33+
varps=path.join(process.env.SystemRoot,'System32',
34+
'WindowsPowerShell','v1.0','powershell.exe')
35+
varcsFile=path.join(__dirname,'Find-VisualStudio.cs')
36+
varpsArgs=['-ExecutionPolicy','Unrestricted','-NoProfile',
37+
'-Command','&{Add-Type -Path \''+csFile+'\';'+
38+
'[VisualStudioConfiguration.Main]::PrintJson()}']
39+
40+
this.log.silly('Running',ps,psArgs)
41+
varchild=execFile(ps,psArgs,{encoding: 'utf8'},
42+
this.parseData.bind(this))
43+
child.stdin.end()
44+
},
45+
46+
parseData: functionparseData(err,stdout,stderr){
47+
this.log.silly('PS stderr = %j',stderr)
48+
49+
if(err){
50+
this.log.silly('PS err = %j',err&&(err.stack||err))
51+
returnthis.failPowershell()
52+
}
53+
54+
varvsInfo
55+
try{
56+
vsInfo=JSON.parse(stdout)
57+
}catch(e){
58+
this.log.silly('PS stdout = %j',stdout)
59+
this.log.silly(e)
60+
returnthis.failPowershell()
61+
}
62+
63+
if(!Array.isArray(vsInfo)){
64+
this.log.silly('PS stdout = %j',stdout)
65+
returnthis.failPowershell()
66+
}
67+
68+
vsInfo=vsInfo.map((info)=>{
69+
this.log.silly(`processing installation: "${info.path}"`)
70+
constversionYear=this.getVersionYear(info)
71+
return{
72+
path: info.path,
73+
version: info.version,
74+
versionYear: versionYear,
75+
hasMSBuild: this.getHasMSBuild(info),
76+
toolset: this.getToolset(info,versionYear),
77+
sdk: this.getSDK(info)
78+
}
79+
})
80+
this.log.silly('vsInfo:',vsInfo)
81+
82+
// Remove future versions or errors parsing version number
83+
vsInfo=vsInfo.filter((info)=>{
84+
if(info.versionYear){returntrue}
85+
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
86+
returnfalse
87+
})
88+
89+
// Sort to place newer versions first
90+
vsInfo.sort((a,b)=>b.versionYear-a.versionYear)
91+
92+
for(vari=0;i<vsInfo.length;++i){
93+
constinfo=vsInfo[i]
94+
this.addLog(`checking VS${info.versionYear} (${info.version}) found `+
95+
`at\n"${info.path}"`)
96+
97+
if(info.hasMSBuild){
98+
this.addLog('- found "Visual Studio C++ core features"')
99+
}else{
100+
this.addLog('- "Visual Studio C++ core features" missing')
101+
continue
102+
}
103+
104+
if(info.toolset){
105+
this.addLog(`- found VC++ toolset: ${info.toolset}`)
106+
}else{
107+
this.addLog('- missing any VC++ toolset')
108+
continue
109+
}
110+
111+
if(info.sdk){
112+
this.addLog(`- found Windows SDK: ${info.sdk}`)
113+
}else{
114+
this.addLog('- missing any Windows SDK')
115+
continue
116+
}
117+
118+
this.succeed(info)
119+
return
120+
}
121+
122+
this.fail()
123+
},
124+
125+
succeed: functionsucceed(info){
126+
this.log.info(`using VS${info.versionYear} (${info.version}) found `+
127+
`at\n"${info.path}"`)
128+
process.nextTick(this.callback.bind(null,null,info))
129+
},
130+
131+
failPowershell: functionfailPowershell(){
132+
process.nextTick(this.callback.bind(null,newError(
133+
'Could not use PowerShell to find Visual Studio')))
134+
},
135+
136+
fail: functionfail(){
137+
consterrorLog=this.errorLog.join('\n')
138+
139+
// For Windows 80 col console, use up to the column before the one marked
140+
// with X (total 79 chars including logger prefix, 62 chars usable here):
141+
// X
142+
constinfoLog=[
143+
'**************************************************************',
144+
'You need to install the latest version of Visual Studio',
145+
'including the "Desktop development with C++" workload.',
146+
'For more information consult the documentation at:',
147+
'https://github.com/nodejs/node-gyp#on-windows',
148+
'**************************************************************'
149+
].join('\n')
150+
151+
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
152+
process.nextTick(this.callback.bind(null,newError(
153+
'Could not find any Visual Studio installation to use')))
154+
},
155+
156+
getVersionYear: functiongetVersionYear(info){
157+
constversion=parseInt(info.version,10)
158+
if(version===15){
159+
return2017
160+
}
161+
this.log.silly('- failed to parse version:',info.version)
162+
returnnull
163+
},
164+
165+
getHasMSBuild: functiongetHasMSBuild(info){
166+
constpkg='Microsoft.VisualStudio.VC.MSBuild.Base'
167+
returninfo.packages.indexOf(pkg)!==-1
168+
},
169+
170+
getToolset: functiongetToolset(info,versionYear){
171+
constpkg='Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
172+
if(info.packages.indexOf(pkg)!==-1){
173+
this.log.silly('- found VC.Tools.x86.x64')
174+
if(versionYear===2017){
175+
return'v141'
176+
}
177+
}
178+
returnnull
179+
},
180+
181+
getSDK: functiongetSDK(info){
182+
constwin8SDK='Microsoft.VisualStudio.Component.Windows81SDK'
183+
constwin10SDKPrefix='Microsoft.VisualStudio.Component.Windows10SDK.'
184+
185+
varWin10SDKVer=0
186+
info.packages.forEach((pkg)=>{
187+
if(!pkg.startsWith(win10SDKPrefix)){
188+
return
189+
}
190+
constparts=pkg.split('.')
191+
if(parts.length>5&&parts[5]!=='Desktop'){
192+
this.log.silly('- ignoring non-Desktop Win10SDK:',pkg)
193+
return
194+
}
195+
constfoundSdkVer=parseInt(parts[4],10)
196+
if(isNaN(foundSdkVer)){
197+
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
198+
this.log.silly('- failed to parse Win10SDK number:',pkg)
199+
return
200+
}
201+
this.log.silly('- found Win10SDK:',foundSdkVer)
202+
Win10SDKVer=Math.max(Win10SDKVer,foundSdkVer)
203+
})
204+
205+
if(Win10SDKVer!==0){
206+
return`10.0.${Win10SDKVer}.0`
207+
}elseif(info.packages.indexOf(win8SDK)!==-1){
208+
this.log.silly('- found Win8SDK')
209+
return'8.1'
210+
}
211+
returnnull
212+
}
213+
}

0 commit comments

Comments
 (0)