22// SPDX-License-Identifier: Apache-2.0
33// SPDX-License-Identifier: MIT
44
5+ #[ cfg( windows) ]
6+ use std:: io:: Write ;
57#[ cfg( windows) ]
68use std:: process:: Command ;
79use std:: {
810 fs,
9- io:: Write ,
1011 path:: { Path , PathBuf } ,
1112} ;
1213use ureq:: ResponseExt ;
@@ -26,6 +27,7 @@ pub const NSIS_UPDATER_OUTPUT_FOLDER_NAME: &str = "nsis-updater";
2627pub const WIX_OUTPUT_FOLDER_NAME : & str = "msi" ;
2728pub const WIX_UPDATER_OUTPUT_FOLDER_NAME : & str = "msi-updater" ;
2829
30+ #[ cfg( windows) ]
2931const VSWHERE : & [ u8 ] = include_bytes ! ( "vswhere.exe" ) ;
3032const VCTOOLS_REDIST_DIR_ENV_VAR : & str = "VCTOOLS_REDIST_DIR" ;
3133#[ cfg( windows) ]
@@ -104,13 +106,9 @@ fn vc_runtime_arch(arch: Arch) -> crate::Result<&'static str> {
104106
105107#[ cfg( windows) ]
106108fn visual_studio_dir ( ) -> crate :: Result < PathBuf > {
107- let Some ( vswhere) = vswhere_path ( ) else {
108- return Err ( crate :: Error :: GenericError (
109- "failed to prepare bundled vswhere.exe" . into ( ) ,
110- ) ) ;
111- } ;
109+ let vswhere = vswhere_path ( ) ?;
112110
113- let output = Command :: new ( vswhere)
111+ let output = Command :: new ( & * vswhere)
114112 . args ( [
115113 "-latest" ,
116114 "-prerelease" ,
@@ -212,20 +210,20 @@ fn glob_path(path: &Path, pattern: &str) -> String {
212210 . into_owned ( )
213211}
214212
215- /// Returns the bundled `vswhere.exe` path.
213+ /// Writes the bundled `vswhere.exe` to a new temporary file and returns its path.
216214///
217- /// The executable is written to a temporary file so callers do not depend on a system-installed
218- /// `vswhere.exe` .
219- pub fn vswhere_path ( ) -> Option < PathBuf > {
220- let mut vswhere = std :: env :: temp_dir ( ) ;
221- vswhere . push ( "vswhere.exe" ) ;
222-
223- if !vswhere . exists ( ) {
224- let mut file = std :: fs :: File :: create ( & vswhere ) . ok ( ) ?;
225- file. write_all ( VSWHERE ) . ok ( ) ?;
226- }
227-
228- Some ( vswhere )
215+ /// Each call creates a uniquely named file, so a pre-existing or half-written `vswhere.exe` in the
216+ /// temp directory is never executed. The file is deleted when the returned path is dropped .
217+ # [ cfg ( windows ) ]
218+ pub fn vswhere_path ( ) -> crate :: Result < tempfile :: TempPath > {
219+ let mut file = tempfile :: Builder :: new ( )
220+ . prefix ( "vswhere-" )
221+ . suffix ( ".exe" )
222+ . tempfile ( ) ?;
223+ file. write_all ( VSWHERE ) ?;
224+ file . as_file ( ) . sync_all ( ) ? ;
225+ // close the handle so the executable can be launched
226+ Ok ( file . into_temp_path ( ) )
229227}
230228
231229#[ cfg( target_os = "windows" ) ]
0 commit comments