gix-path 0.14.2

A crate of the gitoxide project dealing paths and their conversions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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";

// There are a number of ways to refer to the null device on Windows, but they are not all equally
// well supported. Git for Windows rejects `\\.\NUL` and `\\.\nul`. On Windows 11 ARM64 (and maybe
// some others), it rejects even the legacy name `NUL`, when capitalized. But it always accepts the
// lower-case `nul`, handling it in various path checks, some of which are done case-sensitively.
pub(super) const NULL_DEVICE: &str = "nul";

/// Try fixed paths before registry queries and directory scans, preferring common installers
/// within each cost tier. Each source is only probed after earlier candidates are exhausted.
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>,
{
    // Should give a 64-bit program files path from a 32-bit or 64-bit process on a 64-bit system.
    let varname_64bit = "ProgramW6432";

    // Should give a 32-bit program files path from a 32-bit or 64-bit process on a 64-bit system.
    // This variable is x86-specific, but neither Git nor Rust target 32-bit ARM on Windows.
    let varname_x86 = "ProgramFiles(x86)";

    // Should give a 32-bit program files path on a 32-bit system. We also check this on a 64-bit
    // system, even though it *should* equal the process's architecture-specific variable, so that
    // we cover the case of a parent process that passes down an overly sanitized environment that
    // lacks the architecture-specific variable. On a 64-bit system, because parent and child
    // processes' architectures can be different, Windows sets the child's `ProgramFiles` variable
    // from whichever of the `ProgramW6432` or `ProgramFiles(x86)` variable corresponds to the
    // child's architecture. Only if the parent does not pass down the architecture-specific
    // variable corresponding to the child's architecture does the child receive its `ProgramFiles`
    // variable from `ProgramFiles` as passed down by the parent. But this behavior is not well
    // known. So the situation where a process only passes down `ProgramFiles` sometimes happens.
    let varname_current = "ProgramFiles";

    // Should give the user's local application data path on any system. If a user program files
    // directory exists for this user, then it should be the `Programs` subdirectory of this. If it
    // doesn't exist, or on a future or extremely strangely configured Windows setup where it is
    // somewhere else, it should still be safe to attempt to use it. (This differs from global
    // program files paths, which are usually subdirectories of the root of the system drive, which
    // limited user accounts can usually create their own arbitrarily named directories inside.)
    let varname_user_appdata_local = "LocalAppData";

    // Prefer native ARM64 over an emulated x86_64 executable when both are present.
    // For x86_64, Git for Windows 2.56 uses `ucrt64`; keep `mingw64` for older releases.
    let suffixes_64 = &[r"Git\clangarm64\bin", r"Git\ucrt64\bin", r"Git\mingw64\bin"][..];

    // 32-bit relative bin dirs. So far, this is only ever `mingw32`, not `clang32`.
    let suffixes_32 = &[r"Git\mingw32\bin"][..];

    // Whichever of the 64-bit or 32-bit relative bin better matches this process's architecture.
    // Unlike the system architecture, the process architecture is always known at compile time.
    #[cfg(target_pointer_width = "64")]
    let suffixes_current = suffixes_64;
    #[cfg(target_pointer_width = "32")]
    let suffixes_current = suffixes_32;

    // Bin dirs relative to a user's local application data directory. We try each architecture.
    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 {
            // The environment variable is unset or somehow not an absolute path (e.g. an empty string).
            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");
        // Enumerating retained versions is more expensive than all fixed-path probes.
        (!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> {
    // Scoop's Select-CurrentVersion/Get-InstalledVersion uses install-marker timestamps,
    // not version ordering. A completed downgrade can be newer than a retained upgrade.
    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> {
    // Honor a known Git root, including the one Scoop exports, before guessing package roots.
    // These are all fixed paths, ordered by expected prevalence within the cheap tier.
    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,
        // Only an active Conda/Mamba environment participates; do not pick inactive environments.
        [("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()
}

/// Resolve the selected executable for layout detection, preserving its original invocation.
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() {
            // WinGet's Links directory points into the selected portable package, potentially
            // at a custom installation root. Follow links rather than searching other packages.
            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)
}

/// MSYS Git uses Unix paths. Bind conversion and companion lookup to its own runtime.
pub(super) fn msys_bin() -> Option<&'static Path> {
    static BIN: LazyLock<Option<&'static Path>> = LazyLock::new(|| msys_bin_at(exe_path()?));
    *BIN
}

/// The pacman Git package uses this compiled path, translated by its own mount table.
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)
}

/// Convert paths emitted by MSYS Git to paths usable by native Windows callers.
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) // CREATE_NO_WINDOW
        .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>,
{
    // Only attempt this optimization if the `EXEPATH` variable is set to an absolute path.
    let root = var_os_func("EXEPATH").map(PathBuf::from).filter(|r| r.is_absolute())?;
    unambiguous_runtime_prefix(&root)
}

/// Like [`system_prefix_from_exepath_var()`], but for Git for Windows' `cmd` and `bin` launchers.
///
/// The installer puts `<root>/cmd` into `PATH`, so this is the `git.exe` that shells other than Git
/// Bash find, and these don't have `EXEPATH` set.
/// Chocolatey portable and Conda/Mamba instead expose `bin`, with `cmd` alongside it.
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()
}

/// A runtime binary selects its own prefix even if other runtimes are installed alongside it.
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)
}

/// Return the only Git for Windows runtime directory in `root`, or `None` if there is none or more than one.
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, // Multiple plausible candidates, so don't use this optimization.
        None => Some(path),
    }
}

/// Return the system prefix if it can be told from the environment, which is much faster than running Git.
fn system_prefix_without_running_git() -> Option<PathBuf> {
    // Read EXEPATH when each public API first needs it, independently of the cached executable.
    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> {
    // Git reports `GIT_EXEC_PATH` as its own location, which the executable's location can't tell.
    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())
    {
        // Git emits forward slashes, which companion-program lookup also preserves.
        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))
        // Older Git for Windows uses mingw*/etc/gitconfig and ProgramData/Git/config.
        // A runtime directory alone cannot establish the modern configuration layout.
        .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> {
    // /etc can be mounted separately from /usr, and the system path is valid even when absent.
    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),
    })
}

/// Return Git for Windows' system configuration path beside its runtime prefix.
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); // CREATE_NO_WINDOW
    cmd
}

pub(super) fn config_query_cwd() -> PathBuf {
    // We try the Windows directory (usually `C:\Windows`) first. It is given by `SystemRoot`,
    // except in rare cases where our own parent has not passed down that environment variable.
    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;