Skip to content

Commit 73ee27a

Browse files
committed
feat: add env::core_dir()
1 parent 51bbb86 commit 73ee27a

File tree

2 files changed

+39
-16
lines changed

2 files changed

+39
-16
lines changed

gix-path/src/env/mod.rs

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,36 @@ pub fn xdg_config(file: &str, env_var: &mut dyn FnMut(&str) -> Option<OsString>)
106106
})
107107
}
108108

109+
static GIT_CORE_DIR: Lazy<Option<PathBuf>> = Lazy::new(|| {
110+
let mut cmd = std::process::Command::new(exe_invocation());
111+
112+
#[cfg(windows)]
113+
{
114+
use std::os::windows::process::CommandExt;
115+
const CREATE_NO_WINDOW: u32 = 0x08000000;
116+
cmd.creation_flags(CREATE_NO_WINDOW);
117+
}
118+
let output = cmd.arg("--exec-path").output().ok()?;
119+
120+
if !output.status.success() {
121+
return None;
122+
}
123+
124+
BString::new(output.stdout)
125+
.trim_with(|b| b.is_ascii_whitespace())
126+
.to_path()
127+
.ok()?
128+
.to_owned()
129+
.into()
130+
});
131+
132+
/// Return the directory obtained by calling `git --exec-path`.
133+
///
134+
/// Returns `None` if Git could not be found or if it returned an error.
135+
pub fn core_dir() -> Option<&'static Path> {
136+
GIT_CORE_DIR.as_deref()
137+
}
138+
109139
/// Returns the platform dependent system prefix or `None` if it cannot be found (right now only on windows).
110140
///
111141
/// ### Performance
@@ -129,22 +159,7 @@ pub fn system_prefix() -> Option<&'static Path> {
129159
}
130160
}
131161

132-
let mut cmd = std::process::Command::new(exe_invocation());
133-
#[cfg(windows)]
134-
{
135-
use std::os::windows::process::CommandExt;
136-
const CREATE_NO_WINDOW: u32 = 0x08000000;
137-
cmd.creation_flags(CREATE_NO_WINDOW);
138-
}
139-
cmd.arg("--exec-path").stderr(std::process::Stdio::null());
140-
gix_trace::debug!(cmd = ?cmd, "invoking git to get system prefix/exec path");
141-
let path = cmd.output().ok()?.stdout;
142-
let path = BString::new(path)
143-
.trim_with(|b| b.is_ascii_whitespace())
144-
.to_path()
145-
.ok()?
146-
.to_owned();
147-
162+
let path = GIT_CORE_DIR.as_deref()?;
148163
let one_past_prefix = path.components().enumerate().find_map(|(idx, c)| {
149164
matches!(c,std::path::Component::Normal(name) if name.to_str() == Some("libexec")).then_some(idx)
150165
})?;

gix-path/tests/path/env.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ fn installation_config() {
2424
);
2525
}
2626

27+
#[test]
28+
fn core_dir() {
29+
assert!(
30+
gix_path::env::core_dir().expect("Git is always in PATH").is_dir(),
31+
"The core directory is a valid directory"
32+
);
33+
}
34+
2735
#[test]
2836
fn system_prefix() {
2937
assert_ne!(

0 commit comments

Comments
 (0)