onpath 0.2.0

Get your tools on the PATH — cross-shell, cross-platform, zero fuss
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Windows-specific PATH management via the registry.
// This module is only compiled on Windows (gated by #[cfg(windows)] in lib.rs).

use std::path::Path;
use std::ptr;

use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, LPARAM, WAIT_OBJECT_0};
use windows_sys::Win32::System::Threading::{CreateMutexW, ReleaseMutex, WaitForSingleObject};
use windows_sys::Win32::UI::WindowsAndMessaging::{
    SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
};
use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
use winreg::{RegKey, RegValue};

use crate::config::Position;
use crate::error::{RegistryError, Result};
use crate::report::Action;

/// Timeout in milliseconds for acquiring the registry lock.
const LOCK_TIMEOUT_MS: u32 = 10_000;

/// RAII guard for a cross-process named mutex that serializes registry
/// read-modify-write operations on `HKCU\Environment\PATH`.
struct RegistryLock {
    handle: HANDLE,
}

impl RegistryLock {
    /// Acquire the named mutex, blocking up to [`LOCK_TIMEOUT_MS`].
    #[allow(unsafe_code)]
    fn acquire() -> Result<Self> {
        // "Local\" prefix scopes the mutex to the current session.
        let name: Vec<u16> = "Local\\onpath-registry-lock\0".encode_utf16().collect();

        // SAFETY: CreateMutexW is a standard Windows API. We pass a valid
        // null-terminated UTF-16 string and no security attributes.
        let handle = unsafe { CreateMutexW(ptr::null(), 0, name.as_ptr()) };
        if handle.is_null() {
            return Err(RegistryError::LockFailed(std::io::Error::last_os_error()).into());
        }

        // SAFETY: handle is a valid mutex returned by CreateMutexW.
        let wait_result = unsafe { WaitForSingleObject(handle, LOCK_TIMEOUT_MS) };
        if wait_result != WAIT_OBJECT_0 {
            // Clean up the handle before returning an error.
            unsafe { CloseHandle(handle) };
            if wait_result == windows_sys::Win32::Foundation::WAIT_TIMEOUT {
                return Err(RegistryError::LockTimeout.into());
            }
            return Err(RegistryError::LockFailed(std::io::Error::last_os_error()).into());
        }

        Ok(Self { handle })
    }
}

impl Drop for RegistryLock {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        // SAFETY: handle is a valid mutex we successfully acquired.
        unsafe {
            ReleaseMutex(self.handle);
            CloseHandle(self.handle);
        }
    }
}

/// Add a directory to the Windows user PATH via the registry.
///
/// Acquires a cross-process named mutex to prevent concurrent modifications.
///
/// # Errors
///
/// Returns [`RegistryError`] if the registry cannot be read or written,
/// or if the cross-process lock cannot be acquired.
pub fn add_to_path(dir: &Path, position: Position) -> Result<Action> {
    let _lock = RegistryLock::acquire()?;
    let (current, vtype) = read_user_path()?;
    let dir_str = dir.to_string_lossy();
    let dir_normalized = crate::normalize::normalize_windows_path_str(&dir_str);

    // Case-insensitive duplicate check with path normalization
    // (trailing slashes, forward/backslashes, `.`/`..` are resolved before comparing)
    if current.split(';').any(|entry| {
        crate::normalize::normalize_windows_path_str(entry).eq_ignore_ascii_case(&dir_normalized)
    }) {
        return Ok(Action::RegistryAlreadyContains);
    }

    let new_path = match position {
        Position::Prepend => {
            if current.is_empty() {
                dir_str.to_string()
            } else {
                format!("{dir_str};{current}")
            }
        }
        Position::Append => {
            if current.is_empty() {
                dir_str.to_string()
            } else {
                format!("{current};{dir_str}")
            }
        }
    };

    write_user_path(&new_path, vtype)?;
    broadcast_settings_change();

    Ok(Action::RegistryModified {
        old_value: current,
        new_value: new_path,
    })
}

/// Remove a directory from the Windows user PATH via the registry.
///
/// Acquires a cross-process named mutex to prevent concurrent modifications.
///
/// # Errors
///
/// Returns [`RegistryError`] if the registry cannot be read or written,
/// or if the cross-process lock cannot be acquired.
pub fn remove_from_path(dir: &Path) -> Result<Action> {
    let _lock = RegistryLock::acquire()?;
    let (current, vtype) = read_user_path()?;
    let dir_str = dir.to_string_lossy();
    let dir_normalized = crate::normalize::normalize_windows_path_str(&dir_str);

    let entries: Vec<&str> = current.split(';').collect();
    let filtered: Vec<&str> = entries
        .iter()
        .filter(|entry| {
            !crate::normalize::normalize_windows_path_str(entry)
                .eq_ignore_ascii_case(&dir_normalized)
        })
        .copied()
        .collect();

    if entries.len() == filtered.len() {
        // Not found — nothing to remove
        return Ok(Action::RegistryAlreadyContains);
    }

    let new_path = filtered.join(";");
    write_user_path(&new_path, vtype)?;
    broadcast_settings_change();

    Ok(Action::RegistryEntryRemoved {
        old_value: current,
        new_value: new_path,
    })
}

/// Read the raw PATH value and its registry type, preserving %VARIABLES%.
fn read_user_path() -> Result<(String, RegType)> {
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env = hkcu
        .open_subkey_with_flags("Environment", KEY_READ)
        .map_err(RegistryError::OpenKey)?;

    // Use get_raw_value to guarantee we never expand %VARIABLES% like
    // %USERPROFILE% or %SystemRoot%. This preserves the registry value
    // byte-for-byte regardless of winreg version or Windows configuration.
    match env.get_raw_value("PATH") {
        Ok(raw) => {
            let vtype = raw.vtype;
            let utf16: Vec<u16> = raw
                .bytes
                .chunks_exact(2)
                .map(|c| u16::from_le_bytes([c[0], c[1]]))
                .collect();
            let value = String::from_utf16_lossy(&utf16)
                .trim_end_matches('\0')
                .to_owned();
            Ok((value, vtype))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            Ok((String::new(), RegType::REG_EXPAND_SZ))
        }
        Err(e) => Err(RegistryError::ReadPath(e).into()),
    }
}

/// Write PATH back to the registry, preserving the original registry type.
fn write_user_path(value: &str, vtype: RegType) -> Result<()> {
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let (env, _) = hkcu
        .create_subkey_with_flags("Environment", KEY_WRITE)
        .map_err(RegistryError::OpenKey)?;

    let reg_value = RegValue {
        vtype,
        bytes: value
            .encode_utf16()
            .chain(std::iter::once(0))
            .flat_map(u16::to_le_bytes)
            .collect(),
    };

    env.set_raw_value("PATH", &reg_value)
        .map_err(RegistryError::WritePath)?;

    Ok(())
}

/// Broadcast `WM_SETTINGCHANGE` to notify other processes of the PATH change.
#[allow(unsafe_code)]
fn broadcast_settings_change() {
    // SAFETY: This is the standard Windows API call to notify running applications
    // that environment variables have changed. The string "Environment" is a
    // well-known constant. HWND_BROADCAST sends to all top-level windows.
    unsafe {
        SendMessageTimeoutA(
            HWND_BROADCAST,
            WM_SETTINGCHANGE,
            0,
            b"Environment\0".as_ptr() as LPARAM,
            SMTO_ABORTIFHUNG,
            5000,
            ptr::null_mut(),
        );
    }
}

#[cfg(test)]
mod tests {
    // Windows registry tests require a real Windows environment.
    // For safety, we do NOT test with the real HKCU\Environment\PATH.
    // Unit tests focus on the string manipulation logic.

    #[test]
    fn path_split_and_case_insensitive_check() {
        let current = r"C:\Windows\system32;C:\Users\test\.myapp\bin";
        let dir = r"c:\users\test\.myapp\bin"; // different case

        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir));
        assert!(found);
    }

    #[test]
    fn path_prepend_format() {
        let current = r"C:\Windows\system32";
        let dir = r"C:\Users\test\bin";
        let new_path = format!("{dir};{current}");
        assert_eq!(new_path, r"C:\Users\test\bin;C:\Windows\system32");
    }

    #[test]
    fn path_filter_removes_entry() {
        let current = r"C:\a;C:\b;C:\c";
        let filtered: Vec<&str> = current
            .split(';')
            .filter(|e| !e.eq_ignore_ascii_case(r"C:\b"))
            .collect();
        assert_eq!(filtered.join(";"), r"C:\a;C:\c");
    }

    #[test]
    fn path_with_trailing_semicolons() {
        let current = r"C:\a;C:\b;";
        let entries: Vec<&str> = current.split(';').collect();
        // Trailing semicolon creates an empty entry
        assert_eq!(entries, vec![r"C:\a", r"C:\b", ""]);

        // Filter should preserve empty entries when removing a different one
        let filtered: Vec<&str> = entries
            .iter()
            .filter(|e| !e.eq_ignore_ascii_case(r"C:\a"))
            .copied()
            .collect();
        assert_eq!(filtered.join(";"), r"C:\b;");
    }

    #[test]
    fn path_with_empty_segments() {
        let current = r"C:\a;;C:\b";
        let entries: Vec<&str> = current.split(';').collect();
        assert_eq!(entries, vec![r"C:\a", "", r"C:\b"]);

        // Filter preserves empty segments
        let filtered: Vec<&str> = entries
            .iter()
            .filter(|e| !e.eq_ignore_ascii_case(r"C:\a"))
            .copied()
            .collect();
        assert_eq!(filtered.join(";"), r";C:\b");
    }

    #[test]
    fn path_entry_with_spaces() {
        let current = r"C:\Program Files\bin;C:\a";
        let dir = r"C:\Program Files\bin";
        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir));
        assert!(found);
    }

    #[test]
    fn path_with_trailing_backslash_now_matches() {
        // With path normalization, `C:\foo\` and `C:\foo` now match.
        let current = r"C:\foo\";
        let dir = r"C:\foo";
        let norm_current = crate::normalize::normalize_windows_path_str(current);
        let norm_dir = crate::normalize::normalize_windows_path_str(dir);
        assert_eq!(
            norm_current, norm_dir,
            "trailing backslash should normalize away"
        );
    }

    #[test]
    fn path_with_forward_slashes_now_matches() {
        // With path normalization, `C:/foo` and `C:\foo` now match.
        let current = r"C:\foo";
        let dir = "C:/foo";
        let norm_current = crate::normalize::normalize_windows_path_str(current);
        let norm_dir = crate::normalize::normalize_windows_path_str(dir);
        assert_eq!(
            norm_current, norm_dir,
            "forward vs backslash should normalize to same"
        );
    }

    #[test]
    fn path_dedup_exact_match() {
        let current = r"C:\a;C:\b;C:\c";
        let dir = r"C:\b";
        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir));
        assert!(found);
    }

    #[test]
    fn path_dedup_case_only_differs() {
        let current = r"C:\Users\Test\.myapp\bin";
        let dir = r"c:\users\test\.myapp\bin";
        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir));
        assert!(found);
    }

    #[test]
    fn path_no_substring_match() {
        // `C:\foo` must NOT match `C:\foobar` — we split on `;` so this is exact.
        let current = r"C:\foobar;C:\baz";
        let dir = r"C:\foo";
        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir));
        assert!(!found);
    }

    #[test]
    fn path_single_entry_add_and_remove() {
        // Add to a single-entry PATH
        let current = r"C:\existing";
        let dir = r"C:\new";
        let new_path = format!("{dir};{current}");
        assert_eq!(new_path, r"C:\new;C:\existing");

        // Remove from a two-entry PATH, leaving one
        let filtered: Vec<&str> = new_path
            .split(';')
            .filter(|e| !e.eq_ignore_ascii_case(dir))
            .collect();
        assert_eq!(filtered.join(";"), r"C:\existing");
    }

    #[test]
    fn path_empty_string_entries_not_matched() {
        // `;;` creates empty entries — they should not match a real directory
        let current = r"C:\a;;C:\b";
        // Empty string matches empty segments, but no real caller passes ""
        let entries: Vec<&str> = current.split(';').collect();
        assert_eq!(entries, vec![r"C:\a", "", r"C:\b"]);

        // A non-empty dir should not match empty segments
        let dir2 = r"C:\nonexistent";
        let found = current
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(dir2));
        assert!(!found);
    }

    #[test]
    fn remove_nonexistent_is_noop() {
        let current = r"C:\a;C:\b;C:\c";
        let dir = r"C:\nonexistent";
        let entries: Vec<&str> = current.split(';').collect();
        let filtered: Vec<&str> = entries
            .iter()
            .filter(|e| !e.eq_ignore_ascii_case(dir))
            .copied()
            .collect();
        assert_eq!(entries.len(), filtered.len());
        assert_eq!(filtered.join(";"), current);
    }
}