1use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7
8use cuno_core::Env;
9
10use crate::{Runner, ToolchainError, Version};
11
12const VC_TOOLS: &str = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64";
14
15const VSWHERE_ARGS: [&str; 9] = [
17 "-all",
18 "-products",
19 "*",
20 "-prerelease",
21 "-requires",
22 VC_TOOLS,
23 "-utf8",
24 "-format",
25 "json",
26];
27
28const CL_OPTION_VARIABLES: [&str; 2] = ["CL", "_CL_"];
32
33#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct VsInstallation {
36 pub path: PathBuf,
38 pub prerelease: bool,
40 pub complete: bool,
44 pub toolsets: Vec<MsvcToolset>,
46 pub unusable_toolsets: Vec<PathBuf>,
49 pub default_toolset: Option<String>,
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct MsvcToolset {
58 pub dir: PathBuf,
60 pub cl_version: Version,
62}
63
64impl MsvcToolset {
65 pub fn cl(&self) -> PathBuf {
67 cl_in(&self.dir)
68 }
69
70 pub fn install_dir(&self) -> &Path {
73 self.dir.ancestors().nth(4).unwrap_or(&self.dir)
74 }
75}
76
77fn cl_in(toolset_dir: &Path) -> PathBuf {
78 toolset_dir
79 .join("bin")
80 .join("Hostx64")
81 .join("x64")
82 .join("cl.exe")
83}
84
85pub fn find_installations(
89 env: &Env,
90 run: &dyn Runner,
91) -> Result<Vec<VsInstallation>, ToolchainError> {
92 let vswhere = vswhere_path(env);
93 if !vswhere.is_file() {
94 return Err(ToolchainError::VswhereMissing { path: vswhere });
95 }
96 let args: Vec<&OsStr> = VSWHERE_ARGS.iter().map(OsStr::new).collect();
97 let output = run
98 .run(&vswhere, &args, env)
99 .map_err(|e| ToolchainError::VswhereFailed {
100 detail: e.to_string(),
101 })?;
102 if !output.success {
103 let mut detail = String::from_utf8_lossy(&output.stderr).trim().to_owned();
104 if detail.is_empty() {
105 detail = String::from_utf8_lossy(&output.stdout).trim().to_owned();
106 }
107 return Err(ToolchainError::VswhereFailed { detail });
108 }
109
110 let cl_env = env.without(&CL_OPTION_VARIABLES);
111 let mut installations = Vec::new();
112 let mut first_unusable = None;
113 for found in parse_vswhere(&output.stdout)? {
114 let (toolsets, unusable_toolsets) = toolsets_in(&found.path, run, &cl_env);
115 if first_unusable.is_none() {
116 first_unusable = unusable_toolsets.first().cloned();
117 }
118 if toolsets.is_empty() {
119 continue;
120 }
121 let default_toolset = std::fs::read_to_string(
122 found
123 .path
124 .join("VC")
125 .join("Auxiliary")
126 .join("Build")
127 .join("Microsoft.VCToolsVersion.default.txt"),
128 )
129 .ok()
130 .map(|s| s.trim().to_owned());
131 installations.push(VsInstallation {
132 path: found.path,
133 prerelease: found.prerelease,
134 complete: found.complete,
135 toolsets,
136 unusable_toolsets,
137 default_toolset,
138 });
139 }
140 if installations.is_empty() {
141 return Err(match first_unusable {
144 Some(dir) => ToolchainError::ClVersionUnknown { path: cl_in(&dir) },
145 None => ToolchainError::NoVisualStudio,
146 });
147 }
148 Ok(installations)
149}
150
151fn vswhere_path(env: &Env) -> PathBuf {
153 let base = env
154 .get("ProgramFiles(x86)")
155 .map(PathBuf::from)
156 .unwrap_or_else(|| PathBuf::from(r"C:\Program Files (x86)"));
157 base.join("Microsoft Visual Studio")
158 .join("Installer")
159 .join("vswhere.exe")
160}
161
162struct Found {
164 path: PathBuf,
165 prerelease: bool,
166 complete: bool,
167}
168
169fn parse_vswhere(stdout: &[u8]) -> Result<Vec<Found>, ToolchainError> {
173 let not_understood = |detail: String| ToolchainError::VswhereFailed { detail };
174 let value: serde_json::Value = serde_json::from_slice(stdout)
175 .map_err(|e| not_understood(format!("its output is not JSON ({e})")))?;
176 let list = value
177 .as_array()
178 .ok_or_else(|| not_understood("its output is not a JSON list".to_owned()))?;
179 list.iter()
180 .map(|item| {
181 let path = item
182 .get("installationPath")
183 .and_then(serde_json::Value::as_str)
184 .ok_or_else(|| not_understood("an entry has no installationPath".to_owned()))?;
185 let flag = |name: &str| item.get(name).and_then(serde_json::Value::as_bool);
186 Ok(Found {
187 path: PathBuf::from(path),
188 prerelease: flag("isPrerelease").unwrap_or(true),
192 complete: flag("isComplete").unwrap_or(false)
193 && flag("isLaunchable").unwrap_or(false),
194 })
195 })
196 .collect()
197}
198
199fn toolsets_in(
204 installation: &Path,
205 run: &dyn Runner,
206 cl_env: &Env,
207) -> (Vec<MsvcToolset>, Vec<PathBuf>) {
208 let msvc = installation.join("VC").join("Tools").join("MSVC");
209 let Ok(entries) = std::fs::read_dir(msvc) else {
210 return (Vec::new(), Vec::new());
211 };
212 let mut toolsets = Vec::new();
213 let mut unusable = Vec::new();
214 for entry in entries.flatten() {
215 let dir = entry.path();
216 let cl = cl_in(&dir);
217 if !cl.is_file() {
218 continue;
219 }
220 match cl_version(&cl, run, cl_env) {
221 Some(cl_version) => toolsets.push(MsvcToolset { dir, cl_version }),
222 None => unusable.push(dir),
223 }
224 }
225 toolsets.sort_by(|a, b| {
226 b.cl_version
227 .cmp(&a.cl_version)
228 .then_with(|| b.dir.cmp(&a.dir))
229 });
230 unusable.sort();
231 (toolsets, unusable)
232}
233
234fn cl_version(cl: &Path, run: &dyn Runner, cl_env: &Env) -> Option<Version> {
239 let output = run.run(cl, &[], cl_env).ok()?;
240 let mut text = String::from_utf8_lossy(&output.stderr).into_owned();
241 text.push('\n');
242 text.push_str(&String::from_utf8_lossy(&output.stdout));
243 Version::find_in(&text)
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
253 fn a_toolset_names_its_installation() {
254 let toolset = MsvcToolset {
255 dir: Path::new("C:/VS/2022/VC/Tools/MSVC/14.44.35207").to_owned(),
256 cl_version: crate::Version {
257 major: 19,
258 minor: 44,
259 patch: 35207,
260 },
261 };
262 assert_eq!(toolset.install_dir(), Path::new("C:/VS/2022"));
263 let short = MsvcToolset {
266 dir: Path::new("C:/x").to_owned(),
267 ..toolset
268 };
269 assert_eq!(short.install_dir(), Path::new("C:/x"));
270 }
271 use crate::Output;
272 use cuno_core::NameCase;
273 use std::cell::RefCell;
274 use std::collections::HashMap;
275
276 struct Ran {
278 line: String,
279 env: Vec<String>,
280 }
281
282 #[derive(Default)]
284 struct Fake {
285 answers: HashMap<String, Output>,
286 ran: RefCell<Vec<Ran>>,
287 }
288
289 impl Fake {
290 fn answer(self, program_suffix: &str, stdout: &[u8], stderr: &[u8]) -> Fake {
291 self.answer_with(program_suffix, true, stdout, stderr)
292 }
293
294 fn answer_with(
295 mut self,
296 program_suffix: &str,
297 success: bool,
298 stdout: &[u8],
299 stderr: &[u8],
300 ) -> Fake {
301 self.answers.insert(
302 program_suffix.to_owned(),
303 Output {
304 success,
305 stdout: stdout.to_vec(),
306 stderr: stderr.to_vec(),
307 },
308 );
309 self
310 }
311 }
312
313 impl Runner for Fake {
314 fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
315 let program = program.to_string_lossy().replace('\\', "/");
316 let line = std::iter::once(program.clone())
317 .chain(args.iter().map(|a| a.to_string_lossy().into_owned()))
318 .collect::<Vec<_>>()
319 .join(" ");
320 let env = env
321 .vars()
322 .map(|(n, _)| n.to_string_lossy().into_owned())
323 .collect();
324 self.ran.borrow_mut().push(Ran { line, env });
325 self.answers
326 .iter()
327 .find(|(suffix, _)| program.ends_with(suffix.as_str()))
328 .map(|(_, out)| out.clone())
329 .ok_or_else(|| std::io::Error::other("not answered"))
330 }
331 }
332
333 fn tree(installs: &[(&str, &[&str])], extra: &[(&str, &str)]) -> (tempfile::TempDir, Env) {
337 let root = tempfile::tempdir().unwrap();
338 let installer = root.path().join("x86/Microsoft Visual Studio/Installer");
339 std::fs::create_dir_all(&installer).unwrap();
340 std::fs::write(installer.join("vswhere.exe"), "").unwrap();
341 for (name, toolsets) in installs {
342 std::fs::create_dir_all(root.path().join(name).join("VC/Tools/MSVC")).unwrap();
343 for toolset in *toolsets {
344 let bin = root
345 .path()
346 .join(name)
347 .join("VC/Tools/MSVC")
348 .join(toolset)
349 .join("bin/Hostx64/x64");
350 std::fs::create_dir_all(&bin).unwrap();
351 std::fs::write(bin.join("cl.exe"), "").unwrap();
352 }
353 }
354 let mut pairs = vec![(
355 "ProgramFiles(x86)".into(),
356 root.path().join("x86").into_os_string(),
357 )];
358 pairs.extend(extra.iter().map(|(n, v)| ((*n).into(), (*v).into())));
359 (root, Env::from_pairs(pairs, NameCase::Insensitive))
360 }
361
362 fn entry(root: &Path, name: &str, prerelease: bool, complete: bool) -> serde_json::Value {
364 serde_json::json!({
365 "installationPath": root.join(name),
366 "isPrerelease": prerelease,
367 "isComplete": complete,
368 "isLaunchable": complete,
369 })
370 }
371
372 fn json(items: &[serde_json::Value]) -> Vec<u8> {
373 serde_json::to_vec(items).unwrap()
374 }
375
376 const BANNER_52: &[u8] = b"Microsoft (R) C/C++ Optimizing Compiler Version 19.52.37029 for x64";
377 const BANNER_44: &[u8] = b"Microsoft (R) C/C++ Optimizing Compiler Version 19.44.35207 for x64";
378
379 #[test]
383 fn vswhere_is_run_with_exactly_the_specified_arguments() {
384 let (root, env) = tree(&[("VS", &["14.52.37025"])], &[]);
385 let fake = Fake::default()
386 .answer(
387 "vswhere.exe",
388 &json(&[entry(root.path(), "VS", false, true)]),
389 b"",
390 )
391 .answer("cl.exe", b"", BANNER_52);
392 find_installations(&env, &fake).unwrap();
393 let vswhere = &fake.ran.borrow()[0].line;
394 assert!(
395 vswhere.ends_with(
396 "/vswhere.exe -all -products * -prerelease -requires \
397 Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -utf8 -format json"
398 ),
399 "{vswhere}"
400 );
401 }
402
403 #[test]
406 fn previews_and_incomplete_installations_are_marked() {
407 let (root, env) = tree(
408 &[
409 ("Stable", &["14.44.35207"]),
410 ("Preview", &["14.52.37025"]),
411 ("Broken", &["14.44.35207"]),
412 ],
413 &[],
414 );
415 let fake = Fake::default()
416 .answer(
417 "vswhere.exe",
418 &json(&[
419 entry(root.path(), "Stable", false, true),
420 entry(root.path(), "Preview", true, true),
421 entry(root.path(), "Broken", false, false),
422 ]),
423 b"",
424 )
425 .answer("14.44.35207/bin/Hostx64/x64/cl.exe", b"", BANNER_44)
426 .answer("14.52.37025/bin/Hostx64/x64/cl.exe", b"", BANNER_52);
427 let found = find_installations(&env, &fake).unwrap();
428 let flags: Vec<_> = found.iter().map(|i| (i.prerelease, i.complete)).collect();
429 assert_eq!(flags, [(false, true), (true, true), (false, false)]);
430 assert_eq!(found[1].path, root.path().join("Preview"));
431 }
432
433 #[test]
436 fn missing_flags_count_against_the_installation() {
437 let (root, env) = tree(&[("VS", &["14.52.37025"])], &[]);
438 let item = serde_json::json!({ "installationPath": root.path().join("VS") });
439 let fake = Fake::default()
440 .answer("vswhere.exe", &json(&[item]), b"")
441 .answer("cl.exe", b"", BANNER_52);
442 let found = find_installations(&env, &fake).unwrap();
443 assert!(found[0].prerelease && !found[0].complete, "{found:?}");
444 }
445
446 #[test]
450 fn cl_runs_without_the_cl_option_variables() {
451 let (root, env) = tree(
452 &[("VS", &["14.52.37025"])],
453 &[("CL", "/nologo"), ("_CL_", "/W4"), ("KEEP", "1")],
454 );
455 let fake = Fake::default()
456 .answer(
457 "vswhere.exe",
458 &json(&[entry(root.path(), "VS", false, true)]),
459 b"",
460 )
461 .answer("cl.exe", b"", BANNER_52);
462 find_installations(&env, &fake).unwrap();
463 let ran = fake.ran.borrow();
464 let cl = ran.iter().find(|r| r.line.ends_with("cl.exe")).unwrap();
465 assert!(
466 !cl.env.iter().any(|n| n == "CL" || n == "_CL_"),
467 "{:?}",
468 cl.env
469 );
470 assert!(cl.env.iter().any(|n| n == "KEEP"), "{:?}", cl.env);
471 assert!(
472 ran[0].env.iter().any(|n| n == "CL"),
473 "vswhere gets the environment as given"
474 );
475 }
476
477 #[test]
480 fn reads_the_version_from_a_japanese_banner() {
481 let banner: &[u8] = &[
483 77, 105, 99, 114, 111, 115, 111, 102, 116, 40, 82, 41, 32, 67, 47, 67, 43, 43, 32, 141,
484 197, 147, 75, 137, 187, 131, 82, 131, 147, 131, 112, 131, 67, 131, 137, 32, 131, 111,
485 129, 91, 131, 87, 131, 135, 131, 147, 32, 49, 57, 46, 52, 48, 46, 51, 51, 56, 49, 49,
486 32, 40, 120, 54, 52, 41,
487 ];
488 let (root, env) = tree(&[("VS", &["14.40.33807"])], &[]);
489 let fake = Fake::default()
490 .answer(
491 "vswhere.exe",
492 &json(&[entry(root.path(), "VS", false, true)]),
493 b"",
494 )
495 .answer("cl.exe", b"", banner);
496 let found = find_installations(&env, &fake).unwrap();
497 assert_eq!(found[0].toolsets[0].cl_version.to_string(), "19.40.33811");
498 }
499
500 #[test]
504 fn toolsets_are_newest_first_by_cl_version_then_name() {
505 let (root, env) = tree(
506 &[("VS", &["14.44.35207", "14.52.37025", "14.52.37099"])],
507 &[],
508 );
509 let fake = Fake::default()
510 .answer(
511 "vswhere.exe",
512 &json(&[entry(root.path(), "VS", false, true)]),
513 b"",
514 )
515 .answer("14.44.35207/bin/Hostx64/x64/cl.exe", b"", BANNER_44)
516 .answer("14.52.37025/bin/Hostx64/x64/cl.exe", b"", BANNER_52)
517 .answer("14.52.37099/bin/Hostx64/x64/cl.exe", b"", BANNER_52);
518 let toolsets = &find_installations(&env, &fake).unwrap()[0].toolsets;
519 let names: Vec<_> = toolsets
520 .iter()
521 .map(|t| t.dir.file_name().unwrap().to_string_lossy().into_owned())
522 .collect();
523 assert_eq!(names, ["14.52.37099", "14.52.37025", "14.44.35207"]);
524 assert_eq!(toolsets[2].cl_version.to_string(), "19.44.35207");
525 }
526
527 #[test]
530 fn a_broken_toolset_does_not_hide_the_others() {
531 let (root, env) = tree(&[("VS", &["14.44.35207", "14.52.37025"])], &[]);
532 let fake = Fake::default()
533 .answer(
534 "vswhere.exe",
535 &json(&[entry(root.path(), "VS", false, true)]),
536 b"",
537 )
538 .answer("14.44.35207/bin/Hostx64/x64/cl.exe", b"", b"garbage")
539 .answer("14.52.37025/bin/Hostx64/x64/cl.exe", b"", BANNER_52);
540 let found = &find_installations(&env, &fake).unwrap()[0];
541 assert_eq!(found.toolsets.len(), 1);
542 assert_eq!(found.unusable_toolsets.len(), 1);
543 assert!(found.unusable_toolsets[0].ends_with("14.44.35207"));
544 }
545
546 #[test]
549 fn only_broken_toolsets_is_named_as_such() {
550 let (root, env) = tree(&[("VS", &["14.52.37025"])], &[]);
551 let fake = Fake::default()
552 .answer(
553 "vswhere.exe",
554 &json(&[entry(root.path(), "VS", false, true)]),
555 b"",
556 )
557 .answer("cl.exe", b"", b"no version here");
558 let err = find_installations(&env, &fake).unwrap_err();
559 assert!(
560 matches!(err, ToolchainError::ClVersionUnknown { .. }),
561 "{err}"
562 );
563 }
564
565 #[test]
568 fn directories_without_cl_and_installations_without_toolsets_are_left_out() {
569 let (root, env) = tree(&[("VS", &["14.52.37025"]), ("Empty", &[])], &[]);
570 std::fs::create_dir_all(root.path().join("VS/VC/Tools/MSVC/14.99.0")).unwrap();
571 let fake = Fake::default()
572 .answer(
573 "vswhere.exe",
574 &json(&[
575 entry(root.path(), "VS", false, true),
576 entry(root.path(), "Empty", false, true),
577 ]),
578 b"",
579 )
580 .answer("cl.exe", b"", BANNER_52);
581 let found = find_installations(&env, &fake).unwrap();
582 assert_eq!(found.len(), 1, "{found:?}");
583 assert_eq!(found[0].toolsets.len(), 1);
584 assert!(found[0].unusable_toolsets.is_empty());
585 }
586
587 #[test]
590 fn no_installation_is_an_error() {
591 let (_root, env) = tree(&[], &[]);
592 let fake = Fake::default().answer("vswhere.exe", &json(&[]), b"");
593 assert!(matches!(
594 find_installations(&env, &fake),
595 Err(ToolchainError::NoVisualStudio)
596 ));
597 }
598
599 #[test]
602 fn a_missing_vswhere_is_named_with_its_path() {
603 let env = Env::from_pairs(
604 [("ProgramFiles(x86)".into(), "Z:/nowhere".into())],
605 NameCase::Insensitive,
606 );
607 let err = find_installations(&env, &Fake::default()).unwrap_err();
608 assert!(
609 matches!(err, ToolchainError::VswhereMissing { .. }),
610 "{err}"
611 );
612 assert!(err.to_string().contains("nowhere"), "{err}");
613 }
614
615 #[test]
618 fn a_failing_vswhere_is_reported_with_its_output() {
619 let (_root, env) = tree(&[], &[]);
620 let fake = Fake::default().answer_with(
621 "vswhere.exe",
622 false,
623 b"",
624 b"Error 0x80070005: access denied",
625 );
626 let err = find_installations(&env, &fake).unwrap_err();
627 assert!(matches!(err, ToolchainError::VswhereFailed { .. }), "{err}");
628 assert!(err.to_string().contains("access denied"), "{err}");
629 }
630
631 #[test]
634 fn a_vswhere_that_cannot_start_is_a_vswhere_failure() {
635 let (_root, env) = tree(&[], &[]);
636 let err = find_installations(&env, &Fake::default()).unwrap_err();
637 assert!(matches!(err, ToolchainError::VswhereFailed { .. }), "{err}");
638 }
639
640 #[test]
644 fn output_vswhere_does_not_normally_give_is_a_vswhere_failure() {
645 for stdout in [
646 &b"Visual Studio Locator"[..],
647 b"{}",
648 br#"[{"isPrerelease":false}]"#,
649 ] {
650 let (_root, env) = tree(&[], &[]);
651 let fake = Fake::default().answer("vswhere.exe", stdout, b"");
652 let result = find_installations(&env, &fake);
653 assert!(
654 matches!(result, Err(ToolchainError::VswhereFailed { .. })),
655 "{}: {result:?}",
656 String::from_utf8_lossy(stdout)
657 );
658 }
659 }
660
661 #[test]
664 fn the_default_toolset_is_read_from_visual_studio() {
665 let (root, env) = tree(&[("VS", &["14.52.37025"])], &[]);
666 let build = root.path().join("VS/VC/Auxiliary/Build");
667 std::fs::create_dir_all(&build).unwrap();
668 std::fs::write(
669 build.join("Microsoft.VCToolsVersion.default.txt"),
670 "14.52.37025\r\n",
671 )
672 .unwrap();
673 let fake = Fake::default()
674 .answer(
675 "vswhere.exe",
676 &json(&[entry(root.path(), "VS", false, true)]),
677 b"",
678 )
679 .answer("cl.exe", b"", BANNER_52);
680 let found = find_installations(&env, &fake).unwrap();
681 assert_eq!(found[0].default_toolset.as_deref(), Some("14.52.37025"));
682 }
683}