aws_runtime/
fs_util.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use aws_types::os_shim_internal;
7
8/// An operating system, like Windows or Linux
9#[derive(Debug, Copy, Clone, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum Os {
12    /// A Windows-based operating system
13    Windows,
14    /// Any Unix-based operating system
15    Unix,
16}
17
18impl Os {
19    /// Returns the current operating system
20    pub fn real() -> Self {
21        match std::env::consts::OS {
22            "windows" => Os::Windows,
23            _ => Os::Unix,
24        }
25    }
26}
27
28/// Resolve a home directory given a set of environment variables
29pub fn home_dir(env_var: &os_shim_internal::Env, os: Os) -> Option<String> {
30    if let Ok(home) = env_var.get("HOME") {
31        tracing::debug!(src = "HOME", "loaded home directory");
32        return Some(home);
33    }
34
35    if os == Os::Windows {
36        if let Ok(home) = env_var.get("USERPROFILE") {
37            tracing::debug!(src = "USERPROFILE", "loaded home directory");
38            return Some(home);
39        }
40
41        let home_drive = env_var.get("HOMEDRIVE");
42        let home_path = env_var.get("HOMEPATH");
43        tracing::debug!(src = "HOMEDRIVE/HOMEPATH", "loaded home directory");
44        if let (Ok(mut drive), Ok(path)) = (home_drive, home_path) {
45            drive.push_str(&path);
46            return Some(drive);
47        }
48    }
49    None
50}
51
52#[cfg(test)]
53mod test {
54    use super::{home_dir, Os};
55    use aws_types::os_shim_internal::Env;
56
57    #[test]
58    fn homedir_profile_only_windows() {
59        // windows specific variables should only be considered when the platform is windows
60        let env = Env::from_slice(&[("USERPROFILE", "C:\\Users\\name")]);
61        assert_eq!(
62            home_dir(&env, Os::Windows),
63            Some("C:\\Users\\name".to_string())
64        );
65        assert_eq!(home_dir(&env, Os::Unix), None);
66    }
67}