Skip to main content

gix_path/env/
mod.rs

1use std::{
2    ffi::{OsStr, OsString},
3    path::{Path, PathBuf},
4};
5
6use std::sync::LazyLock;
7
8mod git;
9
10#[cfg(windows)]
11#[path = "windows/mod.rs"]
12mod platform;
13#[cfg(not(windows))]
14#[path = "non_windows.rs"]
15mod platform;
16
17/// Return the unoverridden location at which an installation-specific Git configuration file can be found, or
18/// `None` if the binary could not be executed or its results could not be parsed.
19///
20/// The Git query ignores `GIT_CONFIG_SYSTEM` and `GIT_CONFIG_NOSYSTEM`; callers must apply these
21/// variables according to their own environment-access policy.
22///
23/// ### Performance
24///
25/// This can invoke the Git binary. An unambiguous Git for Windows
26/// installation identified by `EXEPATH`, or by `git.exe` in its `cmd` or `bin` directories,
27/// avoids that invocation when its modern configuration file exists.
28/// Prefixes derived from the selected executable are shared with core-directory, prefix, and shell discovery.
29/// Registered MSYS2 Git packages use their known configuration path, translated by `cygpath`.
30/// Their core and configuration paths share a single cached conversion.
31/// On Unix, the first executable in `PATH` is resolved through symlinks. Known Homebrew Cellar
32/// layouts, Linux `/usr/bin/git` and `/bin/git`, and direct Apple developer binaries avoid the query
33/// when their expected configuration file exists. Without `/etc/gitconfig`, Linux `/usr/bin/git` and
34/// `/bin/git` have no installation configuration, which also needs no query. Apple's `/usr/bin/git` shim still queries Git,
35/// leaving developer-directory and toolchain selection to the shim.
36/// Unknown layouts, relative `PATH` entries, and restricted execute bits also query Git.
37/// Indirect Apple Git invocations also query Git, as their config can differ from the symlink target's.
38/// These shortcuts assume the recognized installations use their standard build-time config paths.
39pub fn installation_config() -> Option<&'static Path> {
40    git::install_config_path().and_then(|p| crate::from_byte_slice(p).ok())
41}
42
43/// Return whether [`installation_config()`] was reported with system scope by Git.
44///
45/// `GIT_CONFIG_SYSTEM` replaces system-scoped installation configuration, but not installation
46/// configuration reported with another scope, such as Apple Git's `unknown` scope.
47/// Returns `false` if no installation path was found or Git was too old to report scopes.
48pub fn installation_config_is_system() -> bool {
49    git::install_config_is_system()
50}
51
52/// Return the location at which git installation specific configuration files are located, or `None` if the binary
53/// could not be executed or its results could not be parsed.
54///
55/// ### Performance
56///
57/// This shares the discovery and caching of [`installation_config()`].
58pub fn installation_config_prefix() -> Option<&'static Path> {
59    installation_config().map(git::config_to_base_path)
60}
61
62/// Return the unoverridden location of the system-wide Git configuration file.
63///
64/// On Windows this shares the single Git invocation used by [`installation_config()`].
65/// The caller is responsible for applying `GIT_CONFIG_SYSTEM` and `GIT_CONFIG_NOSYSTEM`.
66pub fn system_config() -> Option<&'static Path> {
67    platform::system_config()
68}
69
70/// Return the shell that Git would use, the shell to execute commands from.
71///
72/// On Windows, this is the full path to `sh.exe` bundled with Git for Windows if we can find it.
73/// If the bundled shell on Windows cannot be found, `sh.exe` is returned as the name of a shell,
74/// as it could possibly be found in `PATH`. On Unix it's `/bin/sh` as the POSIX-compatible shell.
75///
76/// Use [`shell_command()`] when constructing a command. On Windows, it passes `--posix` to the
77/// Git for Windows `bin/sh.exe` shim so its delegated `bash.exe` behaves like `sh`.
78///
79/// Note that the returned path might not be a path on disk, if it is a fallback path or if the
80/// file was moved or deleted since the first time this function is called.
81pub fn shell() -> &'static OsStr {
82    &shell_configuration().program
83}
84
85struct Shell {
86    program: OsString,
87    /// Whether `program` requires `--posix` to behave like `sh`.
88    needs_posix_mode: bool,
89}
90
91fn shell_configuration() -> &'static Shell {
92    static SHELL: LazyLock<Shell> = LazyLock::new(platform::shell);
93    &SHELL
94}
95
96/// Return a command configured to run the shell that Git would use.
97///
98/// On Windows, when [`shell()`] selected the Git for Windows `sh.exe` shim, this also requests
99/// POSIX mode explicitly. The shim delegates to `bash.exe`, which otherwise behaves as Bash
100/// rather than as `sh`. Other shells, including a caller-provided shell, must not receive this
101/// Bash-specific option.
102pub fn shell_command() -> std::process::Command {
103    let shell = shell_configuration();
104    let mut command = std::process::Command::new(&shell.program);
105    if shell.needs_posix_mode {
106        command.arg("--posix");
107    }
108    command
109}
110
111/// Return the name of the Git executable to invoke it.
112///
113/// If it's in the `PATH`, it will always be a short name.
114///
115/// Note that on Windows, we will find the executable in the `PATH` if it exists there, or search it
116/// in alternative locations which when found yields the full path to it.
117/// Fallbacks prioritize cheap probes, then expected installer prevalence. Fixed paths come first:
118/// standard Git for Windows locations, `GIT_INSTALL_ROOT/cmd`, WinGet's user and machine `Links`
119/// directories, `ChocolateyToolsLocation/git/cmd`, Scoop's user and global `current` installations,
120/// the active Conda/Mamba environment's `CONDA_PREFIX/Library/bin`, and MSYS2's
121/// `GIT_INSTALL_ROOT/usr/bin`. Next come direct Git for Windows registry registrations, including
122/// custom roots. Directory scans for Scoop installations without junctions follow, with the broader
123/// MSYS2 uninstall-registry scan last. An executable selected by `PATH` always takes precedence.
124///
125/// Scoop uses `SCOOP`/`SCOOP_GLOBAL`, defaulting to `USERPROFILE/scoop` and `ProgramData/scoop`.
126/// When Scoop's `current` junction is absent, its most recently installed version is used.
127/// Installation roots must be absolute paths. Registry discovery prefers current-user
128/// registrations to machine registrations.
129/// Fallback sources are inspected only when earlier locations do not contain Git, and the
130/// selected executable is cached for the lifetime of the process.
131/// File symlinks, including WinGet's portable links, are resolved for layout discovery while
132/// retaining the selected invocation.
133/// Plain Scoop shims are resolved through their `.shim` sidecars; shims with arguments or
134/// unsupported metadata still require querying Git.
135pub fn exe_invocation() -> &'static Path {
136    platform::exe_invocation()
137}
138
139/// Returns the fully qualified path in the *xdg-home* directory (or equivalent in the home dir) to
140/// `file`, accessing `env_var(<name>)` to learn where these bases are.
141///
142/// Note that the `HOME` directory should ultimately come from [`home_dir()`] as it handles Windows
143/// correctly. The same can be achieved by using [`var()`] as `env_var`.
144pub fn xdg_config(file: &str, env_var: &mut dyn FnMut(&str) -> Option<OsString>) -> Option<PathBuf> {
145    env_var("XDG_CONFIG_HOME")
146        .map(|home| {
147            let mut p = PathBuf::from(home);
148            p.push("git");
149            p.push(file);
150            p
151        })
152        .or_else(|| {
153            env_var("HOME").map(|home| {
154                let mut p = PathBuf::from(home);
155                p.push(".config");
156                p.push("git");
157                p.push(file);
158                p
159            })
160        })
161}
162
163static GIT_CORE_DIR: LazyLock<Option<PathBuf>> = LazyLock::new(platform::core_dir);
164
165/// Return the directory that `git --exec-path` would report.
166///
167/// Known Git for Windows layouts avoid starting Git when their core directory exists and
168/// `GIT_EXEC_PATH` is unset. Other installations and overrides are queried from Git.
169/// Registered MSYS2 Git packages also avoid the Git query, translating their known core path
170/// through the same installation's `cygpath` to respect custom mounts.
171/// This conversion is shared with configuration discovery.
172/// Returns `None` if Git could not be found, returned an error, or its path could not be translated.
173pub fn core_dir() -> Option<&'static Path> {
174    GIT_CORE_DIR.as_deref()
175}
176
177/// Return the path at which the Git-provided program with bare `name` resides within the [`core_dir()`],
178/// or `None` if it doesn't exist there or if Git could not be found.
179///
180/// This is the location `git` itself uses to find the programs implementing its subcommands, and is
181/// useful to invoke programs like `git-upload-pack` that are shipped with Git but aren't necessarily
182/// present in `PATH`.
183///
184/// Use [`installation_program()`] to also search Git for Windows' wider installation for bundled
185/// programs such as `sh` and `vim`.
186///
187/// Note that installations differ in which programs they provide as separate executables - builds
188/// with `SKIP_DASHED_BUILT_INS`, like Git for Windows, omit programs for builtin subcommands, which
189/// can then still be run through `git` itself.
190pub fn core_dir_program(name: &str) -> Option<PathBuf> {
191    if !is_bare_program_name(name) {
192        return None;
193    }
194    let path = core_dir()?.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
195    path.is_file().then_some(path)
196}
197
198/// Return the path at which a program distributed with Git resides, or `None` if it cannot be found.
199///
200/// Unlike [`core_dir_program()`], which searches only [`core_dir()`], this also searches the `bin`
201/// and `usr/bin` directories of the Git for Windows installation on Windows. These contain programs
202/// such as `sh`, `vim`, and, in some versions, `vi`.
203///
204/// Only a bare program `name` without path separators is accepted.
205pub fn installation_program(name: &str) -> Option<PathBuf> {
206    if !is_bare_program_name(name) {
207        return None;
208    }
209
210    core_dir_program(name).or_else(|| platform::associated_program(name))
211}
212
213fn is_bare_program_name(name: &str) -> bool {
214    let mut components = Path::new(name).components();
215    matches!(components.next(), Some(std::path::Component::Normal(_))) && components.next().is_none()
216}
217
218/// Returns the platform dependent system prefix or `None` if it cannot be found (right now only on Windows).
219///
220/// On Windows this is Git's runtime prefix, such as `C:/Program Files/Git/ucrt64` or
221/// `C:/Program Files/Git/mingw64`. Git for Windows keeps its system configuration and attributes
222/// in the sibling `etc` directory. On other platforms this returns `/`.
223///
224/// ### Performance
225///
226/// On Windows, the slowest part is the launch of the Git executable in the PATH. This is often
227/// avoided by inspecting the environment, when launched from inside a Git Bash MSYS2 shell,
228/// or by finding Git for Windows' `cmd` or `bin` directories in the PATH, including the
229/// launchers installed by Chocolatey portable and Conda/Mamba.
230///
231/// ### When `None` is returned
232///
233/// This happens only Windows if the git binary can't be found at all for obtaining its executable
234/// path, or if the git binary wasn't built with a well-known directory structure or environment.
235pub fn system_prefix() -> Option<&'static Path> {
236    platform::system_prefix()
237}
238
239/// Returns `$HOME` or `None` if it cannot be found.
240#[cfg(target_family = "wasm")]
241pub fn home_dir() -> Option<PathBuf> {
242    std::env::var("HOME").map(PathBuf::from).ok()
243}
244
245/// Tries to obtain the home directory from `HOME` on all platforms, but falls back to
246/// [`std::env::home_dir()`] for more complex ways of obtaining a home directory, particularly useful
247/// on Windows.
248///
249/// The reason `HOME` is tried first is to allow Windows users to have a custom location for their
250/// linux-style home, as otherwise they would have to accumulate dot files in a directory these are
251/// inconvenient and perceived as clutter.
252#[cfg(not(target_family = "wasm"))]
253pub fn home_dir() -> Option<PathBuf> {
254    std::env::var_os("HOME").map(Into::into).or_else(std::env::home_dir)
255}
256
257/// Returns the contents of an environment variable of `name` with some special handling for
258/// certain environment variables (like `HOME`) for platform compatibility.
259pub fn var(name: &str) -> Option<OsString> {
260    if name == "HOME" {
261        home_dir().map(PathBuf::into_os_string)
262    } else {
263        std::env::var_os(name)
264    }
265}
266
267#[cfg(test)]
268mod tests;