Repository: nushell/nushell
File: crates/nu-path/src/pwd_per_drive.rs (Rust)

Code before:

        /// Extract the drive letter from a path (e.g., `C:test` -> `C`)
        fn extract_drive_letter(path: &Path) -> Option<char> {
            Some(
                path.to_str()
                    .and_then(|s| s.chars().next())
                    .filter(|c| c.is_ascii_alphabetic())?,
            )
        }

        /// Ensure a path has a trailing `\`
        fn ensure_trailing_separator(path: &str) -> String {
            if !path.ends_with('\\') && !path.ends_with('/') {
                format!(r"{}\", path)
            } else {
                path.to_string()
            }
        }
    }

    fn get_full_path_name_w(path_str: &str) -> Option<String> {
        use path_abs::PathAbs;
        if let Ok(path_abs) = PathAbs::new(path_str) {
            let full_path = path_abs.as_path().to_str()?;
            // Remove the preceding \\?\ characters
            if full_path.starts_with(r"\\?\") {
                return Some(full_path[4..].to_string());
            }
        }
        None
    }

    /// Global singleton instance of DrivePwdMap
    use std::sync::{Mutex, Once};

    static INIT: Once = Once::new();
    static mut DRIVE_PWD_MAP: Option<Mutex<Drive2PWD>> = None;

    /// Access the singleton instance
    fn get_drive_pwd_map() -> &'static Mutex<Drive2PWD> {
        unsafe {
            INIT.call_once(|| {
                DRIVE_PWD_MAP = Some(Mutex::new(Drive2PWD::new()));
            });
            DRIVE_PWD_MAP.as_ref().unwrap()
        }
    }

    /// Test for Drive2PWD map
    #[cfg(test)]
    mod tests {

Review comment (suggestion):
I'm not super comfortable with this type of dealing with verbatim paths. Another thing Chris Denton's omnipath is good for.

Code after:
}

#[derive(Clone, Debug)]
pub struct DriveToPwdMap {
    map: [Option<String>; 26], // Fixed-size array for A-Z
}

impl Default for DriveToPwdMap {
    fn default() -> Self {
        Self::new()
    }
}

impl DriveToPwdMap {
    pub fn new() -> Self {
        Self {
            map: Default::default(),
        }
    }

    pub fn env_var_for_drive(drive_letter: char) -> String {
        let drive_letter = drive_letter.to_ascii_uppercase();
        format!("={}:", drive_letter)
    }

    /// Collect PWD-per-drive as env vars (for child process)
    pub fn get_env_vars(&self, env: &mut HashMap<String, String>) {
        for (drive_index, drive_letter) in ('A'..='Z').enumerate() {
            if let Some(pwd) = self.map[drive_index].clone() {
                if pwd.len() > 3 {
                    let env_var_for_drive = Self::env_var_for_drive(drive_letter);
                    env.insert(env_var_for_drive, pwd);
                }
            }
        }
    }

    /// Set the PWD for the drive letter in the absolute path.
    /// Return PathError for error.
    pub fn set_pwd(&mut self, path: &Path) -> Result<(), PathError> {
        if let (Some(drive_letter), Some(path_str)) =
            (Self::extract_drive_letter(path), path.to_str())
        {
            if drive_letter.is_ascii_alphabetic() {
                let drive_letter = drive_letter.to_ascii_uppercase();
                // Make sure saved drive letter is upper case
                let mut c = path_str.chars();
                match c.next() {
                    None => Err(PathError::InvalidDriveLetter),
                    Some(_) => {
                        let drive_index = drive_letter as usize - 'A' as usize;