1use std::path::Path;
14
15use crate::process::git;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConfigEntry {
20 pub scope: String,
22 pub origin: String,
24 pub key: String,
27 pub value: String,
28}
29
30impl ConfigEntry {
31 pub fn is_machine_wide(&self) -> bool {
33 matches!(self.scope.as_str(), "system" | "global")
34 }
35}
36
37pub fn config_entries(repo_root: &Path, pattern: &str) -> Result<Vec<ConfigEntry>, String> {
41 let out = git(
42 repo_root,
43 &[
44 "config",
45 "--show-scope",
46 "--show-origin",
47 "-z",
48 "--get-regexp",
49 pattern,
50 ],
51 )
52 .output()
53 .map_err(|e| format!("could not run git config: {e}"))?;
54 match out.status.code() {
55 Some(0) => {}
56 Some(1) => return Ok(Vec::new()),
58 _ => {
59 return Err(format!(
60 "git config failed: {}",
61 String::from_utf8_lossy(&out.stderr).trim()
62 ))
63 }
64 }
65 Ok(parse_entries(&String::from_utf8_lossy(&out.stdout)))
66}
67
68fn parse_entries(text: &str) -> Vec<ConfigEntry> {
70 let mut fields = text.split('\0');
71 let mut out = Vec::new();
72 while let (Some(scope), Some(origin), Some(rest)) =
73 (fields.next(), fields.next(), fields.next())
74 {
75 let (key, value) = rest.split_once('\n').unwrap_or((rest, ""));
76 out.push(ConfigEntry {
77 scope: scope.to_string(),
78 origin: origin.to_string(),
79 key: key.to_string(),
80 value: value.to_string(),
81 });
82 }
83 out
84}
85
86pub fn credential_helper_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
88 config_entries(repo_root, r"^credential\..*helper$")
89}
90
91pub fn ssh_command_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
93 config_entries(repo_root, r"^core\.sshcommand$")
94}
95
96pub fn machine_wide_helpers(entries: &[ConfigEntry]) -> Vec<(Option<String>, String)> {
102 let mut kept: Vec<(Option<String>, String)> = Vec::new();
103 for e in entries.iter().filter(|e| e.is_machine_wide()) {
104 let Some(rest) = e.key.strip_prefix("credential.") else {
105 continue;
106 };
107 let url = match rest.strip_suffix(".helper") {
108 Some(url) if !url.is_empty() => Some(url.to_string()),
109 _ if rest == "helper" => None,
110 _ => continue,
111 };
112 if e.value.is_empty() {
113 kept.retain(|(u, _)| *u != url);
114 } else {
115 kept.push((url, e.value.clone()));
116 }
117 }
118 kept
119}
120
121pub fn global_ssh_program(entries: &[ConfigEntry]) -> String {
126 entries
127 .iter()
128 .rfind(|e| e.is_machine_wide() && !e.value.trim().is_empty())
129 .and_then(|e| first_word(&e.value))
130 .unwrap_or_else(|| "ssh".to_string())
131}
132
133fn first_word(command: &str) -> Option<String> {
136 let s = command.trim_start();
137 let mut chars = s.chars();
138 match chars.next()? {
139 q @ ('"' | '\'') => {
140 let rest = &s[1..];
141 let end = rest.find(q)?;
142 Some(rest[..end].to_string()).filter(|w| !w.is_empty())
143 }
144 _ => s
145 .split(char::is_whitespace)
146 .next()
147 .map(str::to_string)
148 .filter(|w| !w.is_empty()),
149 }
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 fn entry(scope: &str, key: &str, value: &str) -> ConfigEntry {
157 ConfigEntry {
158 scope: scope.into(),
159 origin: "file:x".into(),
160 key: key.into(),
161 value: value.into(),
162 }
163 }
164
165 #[test]
166 fn the_null_separated_output_is_parsed() {
167 let text = "global\0file:/h/.gitconfig\0credential.helper\nstore\0\
168 local\0file:.git/config\0credential.https://x.y.helper\n!f\0";
169 let entries = parse_entries(text);
170 assert_eq!(entries.len(), 2);
171 assert_eq!(entries[0].scope, "global");
172 assert_eq!(entries[0].value, "store");
173 assert_eq!(entries[1].key, "credential.https://x.y.helper");
174 assert_eq!(entries[1].origin, "file:.git/config");
175 }
176
177 #[test]
178 fn only_machine_wide_helpers_are_kept_and_a_reset_clears_its_own_scope() {
179 let entries = [
180 entry("system", "credential.helper", "manager"),
181 entry("global", "credential.helper", ""),
182 entry("global", "credential.helper", "store"),
183 entry("global", "credential.https://github.com.helper", "!gh"),
184 entry("local", "credential.helper", "!/missing/script"),
185 entry("local", "credential.https://github.com.helper", "!evil"),
186 entry("worktree", "credential.helper", "!worktree"),
187 ];
188 assert_eq!(
189 machine_wide_helpers(&entries),
190 vec![
191 (None, "store".to_string()),
192 (Some("https://github.com".to_string()), "!gh".to_string()),
193 ]
194 );
195 }
196
197 #[test]
198 fn the_ssh_program_is_the_first_word_of_the_global_command_only() {
199 assert_eq!(global_ssh_program(&[]), "ssh");
200 assert_eq!(
201 global_ssh_program(&[entry("local", "core.sshcommand", "evil -i x")]),
202 "ssh"
203 );
204 assert_eq!(
205 global_ssh_program(&[
206 entry("system", "core.sshcommand", "other"),
207 entry(
208 "global",
209 "core.sshcommand",
210 "C:/Windows/System32/OpenSSH/ssh.exe -v"
211 ),
212 entry("local", "core.sshcommand", "evil"),
213 ]),
214 "C:/Windows/System32/OpenSSH/ssh.exe"
215 );
216 assert_eq!(
217 global_ssh_program(&[entry(
218 "global",
219 "core.sshcommand",
220 r#""C:\Program Files\OpenSSH\ssh.exe" -q"#
221 )]),
222 r"C:\Program Files\OpenSSH\ssh.exe"
223 );
224 }
225}