use std::{
env,
ffi::{OsStr, OsString},
path::{Path, PathBuf},
process::Command,
sync::LazyLock,
};
use bstr::{BString, ByteSlice};
use super::git::{self, ConfigPaths};
mod auxiliary;
mod msys;
mod registry;
mod scoop;
pub(super) const EXE_NAME: &str = "git.exe";
pub(super) const NULL_DEVICE: &str = "nul";
fn alternative_locations<G: IntoIterator<Item = PathBuf>, M: IntoIterator<Item = PathBuf>>(
var_os: impl Fn(&str) -> Option<std::ffi::OsString> + Copy,
registered_git: impl FnOnce() -> G,
registered_msys: impl FnOnce() -> M,
) -> impl Iterator<Item = PathBuf> {
std::iter::once_with(move || locations_under_program_files(var_os))
.flatten()
.chain(locations_under_package_managers(var_os))
.chain(std::iter::once_with(registered_git).flatten())
.chain(locations_under_scoop_without_junctions(var_os))
.chain(std::iter::once_with(registered_msys).flatten())
}
pub(super) fn alternative_executable() -> Option<&'static Path> {
static EXECUTABLE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
alternative_locations(
|key| env::var_os(key),
registry::git_for_windows_bins,
registry::msys2_bins,
)
.map(|prefix| prefix.join(EXE_NAME))
.find(|path| path.is_file())
});
EXECUTABLE.as_deref()
}
fn locations_under_program_files<F>(var_os_func: F) -> Vec<PathBuf>
where
F: Fn(&str) -> Option<std::ffi::OsString>,
{
let varname_64bit = "ProgramW6432";
let varname_x86 = "ProgramFiles(x86)";
let varname_current = "ProgramFiles";
let varname_user_appdata_local = "LocalAppData";
let suffixes_64 = &[r"Git\clangarm64\bin", r"Git\ucrt64\bin", r"Git\mingw64\bin"][..];
let suffixes_32 = &[r"Git\mingw32\bin"][..];
#[cfg(target_pointer_width = "64")]
let suffixes_current = suffixes_64;
#[cfg(target_pointer_width = "32")]
let suffixes_current = suffixes_32;
let suffixes_user = &[
r"Programs\Git\clangarm64\bin",
r"Programs\Git\ucrt64\bin",
r"Programs\Git\mingw64\bin",
r"Programs\Git\mingw32\bin",
][..];
let rules = [
(varname_user_appdata_local, suffixes_user),
(varname_64bit, suffixes_64),
(varname_x86, suffixes_32),
(varname_current, suffixes_current),
];
let mut locations = vec![];
for (varname, suffixes) in rules {
let Some(program_files_dir) = var_os_func(varname).map(PathBuf::from).filter(|p| p.is_absolute()) else {
continue;
};
for suffix in suffixes {
let location = program_files_dir.join(suffix);
if !locations.contains(&location) {
locations.push(location);
}
}
}
locations
}
fn locations_under_scoop(var_os: impl Fn(&str) -> Option<std::ffi::OsString>) -> impl Iterator<Item = PathBuf> {
scoop_roots(var_os).map(|root| root.join("apps/git/current/cmd"))
}
fn locations_under_scoop_without_junctions(
var_os: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> impl Iterator<Item = PathBuf> {
scoop_roots(var_os).filter_map(|root| {
let app = root.join("apps/git");
(!app.join("current/cmd").join(EXE_NAME).is_file())
.then(|| scoop_version_without_junction(&app))
.flatten()
})
}
fn scoop_roots(var_os: impl Fn(&str) -> Option<std::ffi::OsString>) -> impl Iterator<Item = PathBuf> {
let absolute = move |name| var_os(name).map(PathBuf::from).filter(|path| path.is_absolute());
[("SCOOP", "USERPROFILE"), ("SCOOP_GLOBAL", "ProgramData")]
.into_iter()
.filter_map(move |(variable, default_base)| {
absolute(variable).or_else(|| absolute(default_base).map(|base| base.join("scoop")))
})
}
fn scoop_version_without_junction(app: &Path) -> Option<PathBuf> {
std::fs::read_dir(app)
.ok()?
.filter_map(Result::ok)
.filter_map(|entry| {
let name = entry.file_name().to_str()?.to_ascii_lowercase();
if name == "current" || (name.starts_with('_') && name.contains(".old")) {
return None;
}
let directory = entry.path();
let modified = ["scoop-install.json", "install.json"]
.iter()
.filter_map(|marker| std::fs::metadata(directory.join(marker)).ok())
.filter(std::fs::Metadata::is_file)
.filter_map(|metadata| metadata.modified().ok())
.min()?;
Some((modified, directory))
})
.max()
.map(|(_, directory)| directory.join("cmd"))
}
fn locations_under_package_managers(
var_os: impl Fn(&str) -> Option<std::ffi::OsString> + Copy,
) -> impl Iterator<Item = PathBuf> {
locations_from_env(
var_os,
[
("GIT_INSTALL_ROOT", "cmd"),
("LocalAppData", "Microsoft/WinGet/Links"),
("ProgramW6432", "WinGet/Links"),
("ProgramFiles", "WinGet/Links"),
("ChocolateyToolsLocation", "git/cmd"),
],
)
.chain(locations_under_scoop(var_os))
.chain(locations_from_env(
var_os,
[("CONDA_PREFIX", "Library/bin"), ("GIT_INSTALL_ROOT", "usr/bin")],
))
}
fn locations_from_env(
var_os: impl Fn(&str) -> Option<std::ffi::OsString>,
roots: impl IntoIterator<Item = (&'static str, &'static str)>,
) -> impl Iterator<Item = PathBuf> {
roots.into_iter().filter_map(move |(variable, suffix)| {
var_os(variable)
.map(PathBuf::from)
.filter(|root| root.is_absolute())
.map(|root| root.join(suffix))
})
}
struct Executable {
path: PathBuf,
from_path: bool,
}
impl Executable {
fn invocation(&self) -> &Path {
if self.from_path {
Path::new(EXE_NAME)
} else {
&self.path
}
}
}
fn find_executable(path: Option<&std::ffi::OsStr>, fallback: impl FnOnce() -> Option<PathBuf>) -> Option<Executable> {
path.into_iter()
.flat_map(env::split_paths)
.map(|prefix| prefix.join(EXE_NAME))
.find(|path| path.is_file())
.map(|path| (path, true))
.or_else(|| fallback().map(|path| (path, false)))
.and_then(|(path, from_path)| {
std::path::absolute(path)
.ok()
.map(|path| Executable { path, from_path })
})
}
fn executable() -> Option<&'static Executable> {
static EXECUTABLE: LazyLock<Option<Executable>> = LazyLock::new(|| {
find_executable(env::var_os("PATH").as_deref(), || {
alternative_executable().map(ToOwned::to_owned)
})
});
EXECUTABLE.as_ref()
}
pub(super) fn exe_path() -> Option<&'static Path> {
static PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
let path = &executable()?.path;
let path = if std::fs::symlink_metadata(path).ok()?.file_type().is_symlink() {
crate::realpath(path).ok()?
} else {
path.clone()
};
match scoop::target(&path) {
Some(target) => crate::realpath(target).ok(),
None => Some(path),
}
});
PATH.as_deref()
}
pub(super) fn exe_invocation() -> &'static Path {
executable().map_or(Path::new(EXE_NAME), Executable::invocation)
}
pub(super) fn msys_bin() -> Option<&'static Path> {
static BIN: LazyLock<Option<&'static Path>> = LazyLock::new(|| msys_bin_at(exe_path()?));
*BIN
}
pub(super) fn msys_core_dir() -> Option<PathBuf> {
if env::var_os("GIT_EXEC_PATH").is_some() {
return None;
}
let core = &msys::paths()?.core;
core.is_dir().then(|| core.clone())
}
fn msys_bin_at(executable: &Path) -> Option<&Path> {
let bin = executable.parent()?;
let mut components = bin.components().rev();
let is_msys_bin = [b"bin", b"usr"].into_iter().all(|name| {
components
.next()
.is_some_and(|component| component.as_os_str().as_encoded_bytes().eq_ignore_ascii_case(name))
});
(bin.is_absolute() && is_msys_bin && bin.join("msys-2.0.dll").is_file() && bin.join("cygpath.exe").is_file())
.then_some(bin)
}
pub(super) fn native_path(path: &Path) -> Option<PathBuf> {
native_path_with(path, msys_bin)
}
fn native_path_with<'a>(path: &Path, msys_bin: impl FnOnce() -> Option<&'a Path>) -> Option<PathBuf> {
if path.is_absolute() || !path.as_os_str().as_encoded_bytes().starts_with(b"/") {
return Some(path.to_owned());
}
if let Some(bin) = msys_bin() {
return native_paths(bin, [path]).map(|[path]| path);
}
Some(path.to_owned())
}
fn native_paths<const N: usize>(bin: &Path, paths: [&Path; N]) -> Option<[PathBuf; N]> {
use std::os::windows::process::CommandExt;
let output = Command::new(bin.join("cygpath.exe"))
.args(["-am", "--"])
.args(paths)
.creation_flags(0x08000000) .output()
.ok()?;
if !output.status.success() {
return None;
}
parse_native_paths(&output.stdout)
}
fn parse_native_paths<const N: usize>(stdout: &[u8]) -> Option<[PathBuf; N]> {
stdout
.strip_suffix(b"\n")?
.split(|byte| *byte == b'\n')
.map(|line| {
let path = line.to_path().ok()?;
path.is_absolute().then(|| path.to_owned())
})
.collect::<Option<Vec<_>>>()?
.try_into()
.ok()
}
fn system_prefix_from_core_dir<F>(core_dir_func: F) -> Option<PathBuf>
where
F: Fn() -> Option<&'static Path>,
{
core_dir_func()?
.ancestors()
.find(|path| path.file_name() == Some(OsStr::new("libexec")) || path.ends_with("usr/lib"))?
.parent()
.filter(|prefix| !prefix.as_os_str().is_empty())
.map(Path::to_path_buf)
}
fn system_prefix_from_exepath_var<F>(var_os_func: F) -> Option<PathBuf>
where
F: Fn(&str) -> Option<OsString>,
{
let root = var_os_func("EXEPATH").map(PathBuf::from).filter(|r| r.is_absolute())?;
unambiguous_runtime_prefix(&root)
}
fn system_prefix_from_git_launcher(executable: &Path) -> Option<PathBuf> {
let directory = executable.parent().filter(|_| executable.is_absolute())?;
let root = directory.parent()?;
let name = directory.file_name()?;
(name.eq_ignore_ascii_case("cmd") || (name.eq_ignore_ascii_case("bin") && root.join("cmd/git.exe").is_file()))
.then(|| unambiguous_runtime_prefix(root))
.flatten()
}
fn system_prefix_from_git_executable(executable: &Path) -> Option<PathBuf> {
let bin = executable.parent().filter(|_| executable.is_absolute())?;
let prefix = bin.parent()?;
if bin.file_name()?.eq_ignore_ascii_case("bin")
&& ["clangarm64", "ucrt64", "mingw64", "mingw32"].iter().any(|name| {
prefix
.file_name()
.is_some_and(|component| component.eq_ignore_ascii_case(name))
})
{
return Some(prefix.to_owned());
}
system_prefix_from_git_launcher(executable)
}
fn unambiguous_runtime_prefix(root: &Path) -> Option<PathBuf> {
let mut candidates = ["clangarm64", "ucrt64", "mingw64", "mingw32"]
.iter()
.map(|component| root.join(component))
.filter(|candidate| candidate.is_dir());
let path = candidates.next()?;
match candidates.next() {
Some(_) => None, None => Some(path),
}
}
fn system_prefix_without_running_git() -> Option<PathBuf> {
system_prefix_from_exepath_var(|key| std::env::var_os(key))
.or_else(|| system_prefix_from_git_in_path().map(ToOwned::to_owned))
}
fn system_prefix_from_git_in_path() -> Option<&'static Path> {
if std::env::var_os("GIT_EXEC_PATH").is_none() {
static PREFIX: LazyLock<Option<PathBuf>> = LazyLock::new(|| system_prefix_from_git_executable(exe_path()?));
return PREFIX.as_deref();
}
None
}
pub(super) fn core_dir() -> Option<PathBuf> {
if let Some(core) = system_prefix_from_git_in_path()
.map(|prefix| prefix.join("libexec/git-core"))
.filter(|core| core.is_dir())
{
return Some(
crate::from_bstr(crate::to_unix_separators(crate::into_bstr(core).ok()?))
.ok()?
.into_owned(),
);
}
if let Some(core) = msys_core_dir() {
return Some(core);
}
git::core_dir_from_executable()
}
pub(super) fn config_paths_without_git() -> Option<ConfigPaths> {
if let Some(config) = system_prefix_without_running_git()
.map(|prefix| config_path_from_system_prefix(&prefix))
.filter(|config| config.is_file())
{
let system_config = crate::os_string_into_bstring(config.into()).ok();
return Some(ConfigPaths {
installation: system_config.clone(),
installation_is_system: true,
system: system_config,
});
}
config_paths_from_msys()
}
fn config_paths_from_msys() -> Option<ConfigPaths> {
let config = &msys::paths()?.config;
let exists = config.is_file();
let config = crate::into_bstr(config).ok()?.into_owned();
Some(ConfigPaths {
installation: exists.then(|| config.clone()),
installation_is_system: exists,
system: Some(config),
})
}
fn config_path_from_system_prefix(prefix: &Path) -> PathBuf {
prefix.parent().unwrap_or(prefix).join("etc/gitconfig")
}
pub(super) fn system_prefix() -> Option<&'static Path> {
static PREFIX: LazyLock<Option<PathBuf>> =
LazyLock::new(|| system_prefix_without_running_git().or_else(|| system_prefix_from_core_dir(super::core_dir)));
PREFIX.as_deref()
}
pub(super) fn system_config() -> Option<&'static Path> {
let _span = gix_trace::detail!("gix_path::git::system_config_path()");
static FALLBACK: LazyLock<Option<BString>> = LazyLock::new(|| {
super::system_prefix()
.map(config_path_from_system_prefix)
.and_then(|path| crate::os_string_into_bstring(path.into()).ok())
});
git::GIT_CONFIG_PATHS
.system
.as_ref()
.or_else(|| FALLBACK.as_ref())
.and_then(|path| crate::from_byte_slice(path).ok())
}
pub(super) fn shell() -> super::Shell {
let shell = auxiliary::find_git_associated_windows_executable_with_fallback("sh");
super::Shell {
program: shell.program,
needs_posix_mode: shell.is_shim,
}
}
pub(super) fn associated_program(name: &str) -> Option<PathBuf> {
auxiliary::find_git_associated_windows_executable(name).map(|executable| executable.program.into())
}
pub(super) fn command(executable: impl AsRef<OsStr>) -> Command {
use std::os::windows::process::CommandExt;
let mut cmd = Command::new(executable);
cmd.creation_flags(0x08000000); cmd
}
pub(super) fn config_query_cwd() -> PathBuf {
env::var_os("SystemRoot")
.or_else(|| env::var_os("windir"))
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.unwrap_or_else(env::temp_dir)
}
#[cfg(test)]
mod tests;