gix_path/env/
mod.rs

1use std::{
2    ffi::{OsStr, OsString},
3    path::{Path, PathBuf},
4};
5
6use bstr::{BString, ByteSlice};
7use once_cell::sync::Lazy;
8
9use crate::env::git::EXE_NAME;
10
11mod auxiliary;
12mod git;
13
14/// Return the location at which installation specific git configuration file can be found, or `None`
15/// if the binary could not be executed or its results could not be parsed.
16///
17/// ### Performance
18///
19/// This invokes the git binary which is slow on windows.
20pub fn installation_config() -> Option<&'static Path> {
21    git::install_config_path().and_then(|p| crate::try_from_byte_slice(p).ok())
22}
23
24/// Return the location at which git installation specific configuration files are located, or `None` if the binary
25/// could not be executed or its results could not be parsed.
26///
27/// ### Performance
28///
29/// This invokes the git binary which is slow on windows.
30pub fn installation_config_prefix() -> Option<&'static Path> {
31    installation_config().map(git::config_to_base_path)
32}
33
34/// Return the shell that Git would use, the shell to execute commands from.
35///
36/// On Windows, this is the full path to `sh.exe` bundled with Git for Windows if we can find it.
37/// If the bundled shell on Windows cannot be found, `sh.exe` is returned as the name of a shell,
38/// as it could possibly be found in `PATH`. On Unix it's `/bin/sh` as the POSIX-compatible shell.
39///
40/// Note that the returned path might not be a path on disk, if it is a fallback path or if the
41/// file was moved or deleted since the first time this function is called.
42pub fn shell() -> &'static OsStr {
43    static PATH: Lazy<OsString> = Lazy::new(|| {
44        if cfg!(windows) {
45            auxiliary::find_git_associated_windows_executable_with_fallback("sh")
46        } else {
47            "/bin/sh".into()
48        }
49    });
50    PATH.as_ref()
51}
52
53/// Return the name of the Git executable to invoke it.
54///
55/// If it's in the `PATH`, it will always be a short name.
56///
57/// Note that on Windows, we will find the executable in the `PATH` if it exists there, or search it
58/// in alternative locations which when found yields the full path to it.
59pub fn exe_invocation() -> &'static Path {
60    if cfg!(windows) {
61        /// The path to the Git executable as located in the `PATH` or in other locations that it's
62        /// known to be installed to. It's `None` if environment variables couldn't be read or if
63        /// no executable could be found.
64        static EXECUTABLE_PATH: Lazy<Option<PathBuf>> = Lazy::new(|| {
65            std::env::split_paths(&std::env::var_os("PATH")?)
66                .chain(git::ALTERNATIVE_LOCATIONS.iter().map(Into::into))
67                .find_map(|prefix| {
68                    let full_path = prefix.join(EXE_NAME);
69                    full_path.is_file().then_some(full_path)
70                })
71                .map(|exe_path| {
72                    let is_in_alternate_location = git::ALTERNATIVE_LOCATIONS
73                        .iter()
74                        .any(|prefix| exe_path.strip_prefix(prefix).is_ok());
75                    if is_in_alternate_location {
76                        exe_path
77                    } else {
78                        EXE_NAME.into()
79                    }
80                })
81        });
82        EXECUTABLE_PATH.as_deref().unwrap_or(Path::new(git::EXE_NAME))
83    } else {
84        Path::new("git")
85    }
86}
87
88/// Returns the fully qualified path in the *xdg-home* directory (or equivalent in the home dir) to
89/// `file`, accessing `env_var(<name>)` to learn where these bases are.
90///
91/// Note that the `HOME` directory should ultimately come from [`home_dir()`] as it handles Windows
92/// correctly. The same can be achieved by using [`var()`] as `env_var`.
93pub fn xdg_config(file: &str, env_var: &mut dyn FnMut(&str) -> Option<OsString>) -> Option<PathBuf> {
94    env_var("XDG_CONFIG_HOME")
95        .map(|home| {
96            let mut p = PathBuf::from(home);
97            p.push("git");
98            p.push(file);
99            p
100        })
101        .or_else(|| {
102            env_var("HOME").map(|home| {
103                let mut p = PathBuf::from(home);
104                p.push(".config");
105                p.push("git");
106                p.push(file);
107                p
108            })
109        })
110}
111
112static GIT_CORE_DIR: Lazy<Option<PathBuf>> = Lazy::new(|| {
113    let mut cmd = std::process::Command::new(exe_invocation());
114
115    #[cfg(windows)]
116    {
117        use std::os::windows::process::CommandExt;
118        const CREATE_NO_WINDOW: u32 = 0x08000000;
119        cmd.creation_flags(CREATE_NO_WINDOW);
120    }
121    let output = cmd.arg("--exec-path").output().ok()?;
122
123    if !output.status.success() {
124        return None;
125    }
126
127    BString::new(output.stdout)
128        .strip_suffix(b"\n")?
129        .to_path()
130        .ok()?
131        .to_owned()
132        .into()
133});
134
135/// Return the directory obtained by calling `git --exec-path`.
136///
137/// Returns `None` if Git could not be found or if it returned an error.
138pub fn core_dir() -> Option<&'static Path> {
139    GIT_CORE_DIR.as_deref()
140}
141
142/// Returns the platform dependent system prefix or `None` if it cannot be found (right now only on Windows).
143///
144/// ### Performance
145///
146/// On Windows, the slowest part is the launch of the Git executable in the PATH. This is often
147/// avoided by inspecting the environment, when launched from inside a Git Bash MSYS2 shell.
148///
149/// ### When `None` is returned
150///
151/// This happens only Windows if the git binary can't be found at all for obtaining its executable
152/// path, or if the git binary wasn't built with a well-known directory structure or environment.
153pub fn system_prefix() -> Option<&'static Path> {
154    if cfg!(windows) {
155        static PREFIX: Lazy<Option<PathBuf>> = Lazy::new(|| {
156            if let Some(root) = std::env::var_os("EXEPATH").map(PathBuf::from) {
157                for candidate in ["mingw64", "mingw32"] {
158                    let candidate = root.join(candidate);
159                    if candidate.is_dir() {
160                        return Some(candidate);
161                    }
162                }
163            }
164
165            let path = GIT_CORE_DIR.as_deref()?;
166            let one_past_prefix = path.components().enumerate().find_map(|(idx, c)| {
167                matches!(c,std::path::Component::Normal(name) if name.to_str() == Some("libexec")).then_some(idx)
168            })?;
169            Some(path.components().take(one_past_prefix.checked_sub(1)?).collect())
170        });
171        PREFIX.as_deref()
172    } else {
173        Path::new("/").into()
174    }
175}
176
177/// Returns `$HOME` or `None` if it cannot be found.
178#[cfg(target_family = "wasm")]
179pub fn home_dir() -> Option<PathBuf> {
180    std::env::var("HOME").map(PathBuf::from).ok()
181}
182
183/// Tries to obtain the home directory from `HOME` on all platforms, but falls back to
184/// [`home::home_dir()`] for more complex ways of obtaining a home directory, particularly useful
185/// on Windows.
186///
187/// The reason `HOME` is tried first is to allow Windows users to have a custom location for their
188/// linux-style home, as otherwise they would have to accumulate dot files in a directory these are
189/// inconvenient and perceived as clutter.
190#[cfg(not(target_family = "wasm"))]
191pub fn home_dir() -> Option<PathBuf> {
192    std::env::var_os("HOME").map(Into::into).or_else(home::home_dir)
193}
194
195/// Returns the contents of an environment variable of `name` with some special handling for
196/// certain environment variables (like `HOME`) for platform compatibility.
197pub fn var(name: &str) -> Option<OsString> {
198    if name == "HOME" {
199        home_dir().map(PathBuf::into_os_string)
200    } else {
201        std::env::var_os(name)
202    }
203}