use std::path::Path;
use crate::process::git;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigEntry {
pub scope: String,
pub origin: String,
pub key: String,
pub value: String,
}
impl ConfigEntry {
pub fn is_machine_wide(&self) -> bool {
matches!(self.scope.as_str(), "system" | "global")
}
}
pub fn config_entries(repo_root: &Path, pattern: &str) -> Result<Vec<ConfigEntry>, String> {
let out = git(
repo_root,
&[
"config",
"--show-scope",
"--show-origin",
"-z",
"--get-regexp",
pattern,
],
)
.output()
.map_err(|e| format!("could not run git config: {e}"))?;
match out.status.code() {
Some(0) => {}
Some(1) => return Ok(Vec::new()),
_ => {
return Err(format!(
"git config failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
))
}
}
Ok(parse_entries(&String::from_utf8_lossy(&out.stdout)))
}
fn parse_entries(text: &str) -> Vec<ConfigEntry> {
let mut fields = text.split('\0');
let mut out = Vec::new();
while let (Some(scope), Some(origin), Some(rest)) =
(fields.next(), fields.next(), fields.next())
{
let (key, value) = rest.split_once('\n').unwrap_or((rest, ""));
out.push(ConfigEntry {
scope: scope.to_string(),
origin: origin.to_string(),
key: key.to_string(),
value: value.to_string(),
});
}
out
}
pub fn credential_helper_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
config_entries(repo_root, r"^credential\..*helper$")
}
pub fn ssh_command_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
config_entries(repo_root, r"^core\.sshcommand$")
}
pub fn machine_wide_helpers(entries: &[ConfigEntry]) -> Vec<(Option<String>, String)> {
let mut kept: Vec<(Option<String>, String)> = Vec::new();
for e in entries.iter().filter(|e| e.is_machine_wide()) {
let Some(rest) = e.key.strip_prefix("credential.") else {
continue;
};
let url = match rest.strip_suffix(".helper") {
Some(url) if !url.is_empty() => Some(url.to_string()),
_ if rest == "helper" => None,
_ => continue,
};
if e.value.is_empty() {
kept.retain(|(u, _)| *u != url);
} else {
kept.push((url, e.value.clone()));
}
}
kept
}
pub fn global_ssh_program(entries: &[ConfigEntry]) -> String {
entries
.iter()
.rfind(|e| e.is_machine_wide() && !e.value.trim().is_empty())
.and_then(|e| first_word(&e.value))
.unwrap_or_else(|| "ssh".to_string())
}
fn first_word(command: &str) -> Option<String> {
let s = command.trim_start();
let mut chars = s.chars();
match chars.next()? {
q @ ('"' | '\'') => {
let rest = &s[1..];
let end = rest.find(q)?;
Some(rest[..end].to_string()).filter(|w| !w.is_empty())
}
_ => s
.split(char::is_whitespace)
.next()
.map(str::to_string)
.filter(|w| !w.is_empty()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(scope: &str, key: &str, value: &str) -> ConfigEntry {
ConfigEntry {
scope: scope.into(),
origin: "file:x".into(),
key: key.into(),
value: value.into(),
}
}
#[test]
fn the_null_separated_output_is_parsed() {
let text = "global\0file:/h/.gitconfig\0credential.helper\nstore\0\
local\0file:.git/config\0credential.https://x.y.helper\n!f\0";
let entries = parse_entries(text);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].scope, "global");
assert_eq!(entries[0].value, "store");
assert_eq!(entries[1].key, "credential.https://x.y.helper");
assert_eq!(entries[1].origin, "file:.git/config");
}
#[test]
fn only_machine_wide_helpers_are_kept_and_a_reset_clears_its_own_scope() {
let entries = [
entry("system", "credential.helper", "manager"),
entry("global", "credential.helper", ""),
entry("global", "credential.helper", "store"),
entry("global", "credential.https://github.com.helper", "!gh"),
entry("local", "credential.helper", "!/missing/script"),
entry("local", "credential.https://github.com.helper", "!evil"),
entry("worktree", "credential.helper", "!worktree"),
];
assert_eq!(
machine_wide_helpers(&entries),
vec![
(None, "store".to_string()),
(Some("https://github.com".to_string()), "!gh".to_string()),
]
);
}
#[test]
fn the_ssh_program_is_the_first_word_of_the_global_command_only() {
assert_eq!(global_ssh_program(&[]), "ssh");
assert_eq!(
global_ssh_program(&[entry("local", "core.sshcommand", "evil -i x")]),
"ssh"
);
assert_eq!(
global_ssh_program(&[
entry("system", "core.sshcommand", "other"),
entry(
"global",
"core.sshcommand",
"C:/Windows/System32/OpenSSH/ssh.exe -v"
),
entry("local", "core.sshcommand", "evil"),
]),
"C:/Windows/System32/OpenSSH/ssh.exe"
);
assert_eq!(
global_ssh_program(&[entry(
"global",
"core.sshcommand",
r#""C:\Program Files\OpenSSH\ssh.exe" -q"#
)]),
r"C:\Program Files\OpenSSH\ssh.exe"
);
}
}