|
| 1 | +//! Persist Windows PATH without depending on an installed shell. |
| 2 | +
|
| 3 | +use std::io; |
| 4 | + |
| 5 | +use vt_path::AbsolutePath; |
| 6 | +use winreg::{ |
| 7 | + RegKey, RegValue, |
| 8 | + enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_EXPAND_SZ, REG_SZ}, |
| 9 | +}; |
| 10 | + |
| 11 | +pub(super) fn configure(bin: &AbsolutePath, fallback: &AbsolutePath) -> io::Result<()> { |
| 12 | + let hkcu = RegKey::predef(HKEY_CURRENT_USER); |
| 13 | + let (environment, _) = hkcu.create_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)?; |
| 14 | + if update_path(&environment, &bin.to_string(), &fallback.to_string())? { |
| 15 | + broadcast_settings_change(); |
| 16 | + } |
| 17 | + Ok(()) |
| 18 | +} |
| 19 | + |
| 20 | +// Accept an open key so tests never need to change the real user environment. |
| 21 | +fn update_path(environment: &RegKey, bin: &str, fallback: &str) -> io::Result<bool> { |
| 22 | + let original = match environment.get_raw_value("Path") { |
| 23 | + Ok(value) => Some(value), |
| 24 | + Err(error) if error.kind() == io::ErrorKind::NotFound => None, |
| 25 | + Err(error) => return Err(error), |
| 26 | + }; |
| 27 | + let (current, kind) = match &original { |
| 28 | + Some(value) => (decode_path(value)?, value.vtype.clone()), |
| 29 | + None => (String::new(), REG_EXPAND_SZ), |
| 30 | + }; |
| 31 | + let matches = |entry: &str, directory: &str| { |
| 32 | + entry |
| 33 | + .trim_end_matches(['\\', '/']) |
| 34 | + .eq_ignore_ascii_case(directory.trim_end_matches(['\\', '/'])) |
| 35 | + }; |
| 36 | + let mut entries = vec![bin]; |
| 37 | + if !current.is_empty() { |
| 38 | + entries.extend( |
| 39 | + current.split(';').filter(|entry| !matches(entry, bin) && !matches(entry, fallback)), |
| 40 | + ); |
| 41 | + } |
| 42 | + entries.push(fallback); |
| 43 | + let updated = RegValue { |
| 44 | + vtype: kind, |
| 45 | + bytes: entries.join(";").encode_utf16().chain([0]).flat_map(u16::to_le_bytes).collect(), |
| 46 | + }; |
| 47 | + if original.as_ref() == Some(&updated) { |
| 48 | + return Ok(false); |
| 49 | + } |
| 50 | + environment.set_raw_value("Path", &updated)?; |
| 51 | + Ok(true) |
| 52 | +} |
| 53 | + |
| 54 | +fn decode_path(value: &RegValue) -> io::Result<String> { |
| 55 | + if !matches!(value.vtype, REG_SZ | REG_EXPAND_SZ) || !value.bytes.len().is_multiple_of(2) { |
| 56 | + return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid user PATH registry value")); |
| 57 | + } |
| 58 | + let mut units: Vec<_> = |
| 59 | + value.bytes.as_chunks::<2>().0.iter().copied().map(u16::from_le_bytes).collect(); |
| 60 | + while units.last() == Some(&0) { |
| 61 | + units.pop(); |
| 62 | + } |
| 63 | + if units.contains(&0) { |
| 64 | + return Err(io::Error::new(io::ErrorKind::InvalidData, "User PATH contains a NUL")); |
| 65 | + } |
| 66 | + String::from_utf16(&units).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) |
| 67 | +} |
| 68 | + |
| 69 | +/// Notify Explorer and other applications that future processes need the new PATH. |
| 70 | +fn broadcast_settings_change() { |
| 71 | + #[link(name = "user32")] |
| 72 | + unsafe extern "system" { |
| 73 | + fn SendMessageTimeoutW( |
| 74 | + window: isize, |
| 75 | + message: u32, |
| 76 | + wparam: usize, |
| 77 | + lparam: isize, |
| 78 | + flags: u32, |
| 79 | + timeout: u32, |
| 80 | + result: *mut usize, |
| 81 | + ) -> isize; |
| 82 | + } |
| 83 | + let environment: Vec<u16> = "Environment".encode_utf16().chain([0]).collect(); |
| 84 | + // HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG. |
| 85 | + // The string remains live until this synchronous call returns. |
| 86 | + unsafe { |
| 87 | + SendMessageTimeoutW( |
| 88 | + 0xffff, |
| 89 | + 0x001a, |
| 90 | + 0, |
| 91 | + environment.as_ptr() as isize, |
| 92 | + 0x0002, |
| 93 | + 5000, |
| 94 | + std::ptr::null_mut(), |
| 95 | + ); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[cfg(test)] |
| 100 | +mod tests { |
| 101 | + use winreg::enums::{REG_BINARY, REG_MULTI_SZ}; |
| 102 | + |
| 103 | + use super::*; |
| 104 | + |
| 105 | + struct TestKey { |
| 106 | + key: RegKey, |
| 107 | + path: String, |
| 108 | + } |
| 109 | + |
| 110 | + impl TestKey { |
| 111 | + fn new() -> Self { |
| 112 | + let path = format!("Software\\VitePlusTests\\{}", uuid::Uuid::new_v4()); |
| 113 | + let (key, _) = RegKey::predef(HKEY_CURRENT_USER).create_subkey(&path).unwrap(); |
| 114 | + Self { key, path } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + impl Drop for TestKey { |
| 119 | + fn drop(&mut self) { |
| 120 | + RegKey::predef(HKEY_CURRENT_USER).delete_subkey_all(&self.path).unwrap(); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + fn value(path: &str, kind: winreg::enums::RegType) -> RegValue<'static> { |
| 125 | + RegValue { |
| 126 | + vtype: kind, |
| 127 | + bytes: path.encode_utf16().chain([0]).flat_map(u16::to_le_bytes).collect(), |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + #[test] |
| 132 | + fn preserves_variables_empty_entries_and_registry_type() { |
| 133 | + let key = TestKey::new(); |
| 134 | + for kind in [REG_EXPAND_SZ, REG_SZ] { |
| 135 | + let before = "%PNPM_HOME%;;C:\\工具\\bin"; |
| 136 | + key.key.set_raw_value("Path", &value(before, kind.clone())).unwrap(); |
| 137 | + assert!(update_path(&key.key, r"C:\Vite+\bin", r"C:\Vite+\fallback-bin").unwrap()); |
| 138 | + assert_eq!( |
| 139 | + key.key.get_raw_value("Path").unwrap(), |
| 140 | + value(&format!("C:\\Vite+\\bin;{before};C:\\Vite+\\fallback-bin"), kind) |
| 141 | + ); |
| 142 | + assert!(!update_path(&key.key, r"C:\Vite+\bin", r"C:\Vite+\fallback-bin").unwrap()); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + #[test] |
| 147 | + fn creates_missing_path_and_handles_empty_path() { |
| 148 | + let key = TestKey::new(); |
| 149 | + for initial in [None, Some(value("", REG_EXPAND_SZ))] { |
| 150 | + if let Some(initial) = initial { |
| 151 | + key.key.set_raw_value("Path", &initial).unwrap(); |
| 152 | + } |
| 153 | + update_path(&key.key, r"C:\bin", r"C:\fallback").unwrap(); |
| 154 | + assert_eq!( |
| 155 | + key.key.get_raw_value("Path").unwrap(), |
| 156 | + value(r"C:\bin;C:\fallback", REG_EXPAND_SZ) |
| 157 | + ); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + #[test] |
| 162 | + fn moves_existing_entries_to_opposite_ends_without_duplicates() { |
| 163 | + let key = TestKey::new(); |
| 164 | + key.key.set_value("Path", &r"C:\tools;c:\BIN\;C:\fallback;C:\bin;C:\other").unwrap(); |
| 165 | + update_path(&key.key, r"C:\bin", r"C:\fallback").unwrap(); |
| 166 | + assert_eq!( |
| 167 | + key.key.get_value::<String, _>("Path").unwrap(), |
| 168 | + r"C:\bin;C:\tools;C:\other;C:\fallback" |
| 169 | + ); |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn refuses_invalid_values_without_overwriting_them() { |
| 174 | + let key = TestKey::new(); |
| 175 | + for original in [ |
| 176 | + RegValue { vtype: REG_BINARY, bytes: vec![1, 2].into() }, |
| 177 | + value("first\0second", REG_MULTI_SZ), |
| 178 | + RegValue { vtype: REG_SZ, bytes: vec![1].into() }, |
| 179 | + RegValue { vtype: REG_SZ, bytes: vec![0, 0xd8, 0, 0].into() }, |
| 180 | + value("first\0second", REG_SZ), |
| 181 | + ] { |
| 182 | + key.key.set_raw_value("Path", &original).unwrap(); |
| 183 | + assert_eq!( |
| 184 | + update_path(&key.key, r"C:\bin", r"C:\fallback").unwrap_err().kind(), |
| 185 | + io::ErrorKind::InvalidData |
| 186 | + ); |
| 187 | + assert_eq!(key.key.get_raw_value("Path").unwrap(), original); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + #[test] |
| 192 | + fn propagates_write_errors() { |
| 193 | + let key = TestKey::new(); |
| 194 | + key.key.set_value("Path", &r"C:\tools").unwrap(); |
| 195 | + let readonly = |
| 196 | + RegKey::predef(HKEY_CURRENT_USER).open_subkey_with_flags(&key.path, KEY_READ).unwrap(); |
| 197 | + assert_eq!( |
| 198 | + update_path(&readonly, r"C:\bin", r"C:\fallback").unwrap_err().kind(), |
| 199 | + io::ErrorKind::PermissionDenied |
| 200 | + ); |
| 201 | + assert_eq!(key.key.get_value::<String, _>("Path").unwrap(), r"C:\tools"); |
| 202 | + } |
| 203 | +} |
0 commit comments