1use crate::parse::parse_config_text;
4use std::env;
5use std::fs;
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub enum ConfigScope {
11 System,
12 Global,
13 Local,
14 Env,
15 Command,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConfigEntry {
20 pub key: String,
21 pub value: Option<String>,
22 pub scope: ConfigScope,
23 pub origin: Option<PathBuf>,
25}
26
27#[derive(Debug, Clone, Default)]
29pub struct ConfigSet {
30 entries: Vec<ConfigEntry>,
31}
32
33const MAX_INCLUDE_DEPTH: usize = 10;
34
35static CLI_OVERRIDES: std::sync::Mutex<Vec<(String, Option<String>)>> =
37 std::sync::Mutex::new(Vec::new());
38
39pub fn push_cli_override(spec: &str) {
41 let (k, v) = match spec.split_once('=') {
42 Some((k, v)) => (k.to_string(), Some(v.to_string())),
43 None => (spec.to_string(), None),
44 };
45 if let Ok(mut g) = CLI_OVERRIDES.lock() {
46 g.push((k, v));
47 }
48}
49
50pub fn cli_overrides() -> Vec<(String, Option<String>)> {
53 CLI_OVERRIDES.lock().map(|g| g.clone()).unwrap_or_default()
54}
55
56impl ConfigSet {
57 pub fn new() -> Self {
58 Self::default()
59 }
60
61 pub fn load(git_dir: Option<&Path>) -> Self {
65 let mut set = Self::new();
66 if env::var_os("GIT_CONFIG_NOSYSTEM").is_none_or(|v| !is_truthy(&v.to_string_lossy())) {
67 if let Some(p) = system_config_path() {
68 let _ = set.add_file(&p, ConfigScope::System);
69 }
70 }
71 for p in global_config_paths() {
72 let _ = set.add_file(&p, ConfigScope::Global);
73 }
74 if let Some(dir) = git_dir {
75 let _ = set.add_file(&dir.join("config"), ConfigScope::Local);
76 }
77 set.add_env_count();
78 if let Ok(params) = env::var("GIT_CONFIG_PARAMETERS") {
79 for (k, v) in parse_config_parameters(¶ms) {
80 set.push(k, v, ConfigScope::Command);
81 }
82 }
83 if let Ok(g) = CLI_OVERRIDES.lock() {
84 for (k, v) in g.iter() {
85 set.push(k.clone(), v.clone(), ConfigScope::Command);
86 }
87 }
88 set
89 }
90
91 pub fn load_discovered(start: &Path) -> Self {
93 Self::load(discover_git_dir(start).as_deref())
94 }
95
96 pub fn push(&mut self, key: String, value: Option<String>, scope: ConfigScope) {
97 self.entries.push(ConfigEntry {
98 key: normalize_key(&key),
99 value,
100 scope,
101 origin: None,
102 });
103 }
104
105 pub fn add_file(&mut self, path: &Path, scope: ConfigScope) -> Result<(), String> {
107 self.add_file_depth(path, scope, 0)
108 }
109
110 fn add_file_depth(
111 &mut self,
112 path: &Path,
113 scope: ConfigScope,
114 depth: usize,
115 ) -> Result<(), String> {
116 let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
117 let entries = parse_config_text(&text).map_err(|e| format!("{}: {e}", path.display()))?;
118 for e in entries {
119 if e.key == "include.path" && depth < MAX_INCLUDE_DEPTH {
120 if let Some(v) = e.value.as_deref() {
121 let inc = expand_path(v);
122 let inc = if inc.is_relative() {
123 path.parent().unwrap_or(Path::new(".")).join(inc)
124 } else {
125 inc
126 };
127 let _ = self.add_file_depth(&inc, scope, depth + 1);
128 }
129 continue;
130 }
131 self.entries.push(ConfigEntry {
132 key: e.key,
133 value: e.value,
134 scope,
135 origin: Some(path.to_path_buf()),
136 });
137 }
138 Ok(())
139 }
140
141 fn add_env_count(&mut self) {
142 let Some(count) = env::var("GIT_CONFIG_COUNT")
143 .ok()
144 .and_then(|c| c.trim().parse::<usize>().ok())
145 else {
146 return;
147 };
148 for i in 0..count {
149 let Ok(k) = env::var(format!("GIT_CONFIG_KEY_{i}")) else {
150 continue;
151 };
152 let v = env::var(format!("GIT_CONFIG_VALUE_{i}")).ok();
153 self.push(k, v, ConfigScope::Env);
154 }
155 }
156
157 pub fn entries(&self) -> &[ConfigEntry] {
158 &self.entries
159 }
160
161 pub fn get(&self, key: &str) -> Option<String> {
163 let key = normalize_key(key);
164 self.entries
165 .iter()
166 .rev()
167 .find(|e| e.key == key)
168 .map(|e| e.value.clone().unwrap_or_else(|| "true".into()))
169 }
170
171 pub fn get_all(&self, key: &str) -> Vec<String> {
173 let key = normalize_key(key);
174 self.entries
175 .iter()
176 .filter(|e| e.key == key)
177 .map(|e| e.value.clone().unwrap_or_else(|| "true".into()))
178 .collect()
179 }
180
181 pub fn get_bool(&self, key: &str) -> Option<bool> {
182 self.get(key).and_then(|v| parse_bool(&v))
183 }
184
185 pub fn get_path(&self, key: &str) -> Option<PathBuf> {
187 self.get(key)
188 .filter(|v| !v.is_empty())
189 .map(|v| expand_path(&v))
190 }
191
192 pub fn subsections(&self, section: &str, name: &str) -> Vec<(String, String)> {
195 let section = section.to_ascii_lowercase();
196 let name = name.to_ascii_lowercase();
197 let mut out = Vec::new();
198 for e in &self.entries {
199 let Some(rest) = e.key.strip_prefix(&format!("{section}.")) else {
200 continue;
201 };
202 let Some(sub) = rest.strip_suffix(&format!(".{name}")) else {
203 continue;
204 };
205 out.push((
206 sub.to_string(),
207 e.value.clone().unwrap_or_else(|| "true".into()),
208 ));
209 }
210 out
211 }
212}
213
214pub fn parse_bool(v: &str) -> Option<bool> {
216 match v.trim().to_ascii_lowercase().as_str() {
217 "true" | "yes" | "on" | "1" => Some(true),
218 "false" | "no" | "off" | "0" | "" => Some(false),
219 _ => None,
220 }
221}
222
223fn is_truthy(v: &str) -> bool {
224 parse_bool(v).unwrap_or(true)
225}
226
227fn normalize_key(key: &str) -> String {
229 let Some(first) = key.find('.') else {
230 return key.to_ascii_lowercase();
231 };
232 let last = key.rfind('.').unwrap_or(first);
233 if first == last {
234 return key.to_ascii_lowercase();
235 }
236 format!(
237 "{}.{}.{}",
238 key[..first].to_ascii_lowercase(),
239 &key[first + 1..last],
240 key[last + 1..].to_ascii_lowercase()
241 )
242}
243
244pub fn parse_config_parameters(s: &str) -> Vec<(String, Option<String>)> {
246 let mut out = Vec::new();
247 let mut words: Vec<String> = Vec::new();
248 let mut cur = String::new();
249 let mut in_q = false;
250 let mut have = false;
251 let mut chars = s.chars().peekable();
252 while let Some(c) = chars.next() {
253 match c {
254 '\'' => {
255 in_q = !in_q;
256 have = true;
257 }
258 '\\' if !in_q => {
259 if let Some(n) = chars.next() {
260 cur.push(n);
261 have = true;
262 }
263 }
264 c if c.is_whitespace() && !in_q => {
265 if have {
266 words.push(std::mem::take(&mut cur));
267 have = false;
268 }
269 }
270 c => {
271 cur.push(c);
272 have = true;
273 }
274 }
275 }
276 if have {
277 words.push(cur);
278 }
279 for w in words {
281 match w.split_once('=') {
282 Some((k, v)) => out.push((k.to_string(), Some(v.to_string()))),
283 None => out.push((w, None)),
284 }
285 }
286 out
287}
288
289fn home_dir() -> Option<PathBuf> {
290 env::var_os("HOME")
291 .or_else(|| env::var_os("USERPROFILE"))
292 .filter(|h| !h.is_empty())
293 .map(PathBuf::from)
294}
295
296fn expand_path(v: &str) -> PathBuf {
297 if v == "~" {
298 return home_dir().unwrap_or_else(|| PathBuf::from(v));
299 }
300 if let Some(rest) = v.strip_prefix("~/") {
301 if let Some(h) = home_dir() {
302 return h.join(rest);
303 }
304 }
305 PathBuf::from(v)
306}
307
308fn system_config_path() -> Option<PathBuf> {
309 if let Some(p) = env::var_os("GIT_CONFIG_SYSTEM") {
310 return Some(PathBuf::from(p));
311 }
312 if cfg!(unix) {
313 Some(PathBuf::from("/etc/gitconfig"))
314 } else {
315 env::var_os("PROGRAMDATA").map(|p| PathBuf::from(p).join("Git").join("config"))
316 }
317}
318
319fn global_config_paths() -> Vec<PathBuf> {
321 if let Some(p) = env::var_os("GIT_CONFIG_GLOBAL") {
322 return vec![PathBuf::from(p)];
323 }
324 let mut out = Vec::new();
325 let xdg = env::var_os("XDG_CONFIG_HOME")
326 .filter(|x| !x.is_empty())
327 .map(PathBuf::from)
328 .or_else(|| home_dir().map(|h| h.join(".config")));
329 if let Some(x) = xdg {
330 out.push(x.join("git").join("config"));
331 }
332 if let Some(h) = home_dir() {
333 out.push(h.join(".gitconfig"));
334 }
335 out
336}
337
338pub fn discover_git_dir(start: &Path) -> Option<PathBuf> {
340 if let Some(d) = env::var_os("GIT_DIR") {
341 return Some(PathBuf::from(d));
342 }
343 let mut cur = Some(start);
344 while let Some(dir) = cur {
345 let dotgit = dir.join(".git");
346 if dotgit.is_dir() {
347 return Some(dotgit);
348 }
349 if dotgit.is_file() {
350 if let Ok(text) = fs::read_to_string(&dotgit) {
351 if let Some(p) = text.trim().strip_prefix("gitdir:") {
352 let p = PathBuf::from(p.trim());
353 return Some(if p.is_relative() { dir.join(p) } else { p });
354 }
355 }
356 }
357 cur = dir.parent();
358 }
359 None
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn precedence_last_wins_and_case() {
368 let mut s = ConfigSet::new();
369 s.push("User.Name".into(), Some("a".into()), ConfigScope::Global);
370 s.push("user.name".into(), Some("b".into()), ConfigScope::Local);
371 s.push(
372 "url.HTTPS://x/.insteadOf".into(),
373 Some("git@x:".into()),
374 ConfigScope::Env,
375 );
376 assert_eq!(s.get("user.NAME").as_deref(), Some("b"));
377 assert_eq!(
378 s.subsections("url", "insteadof"),
379 vec![("HTTPS://x/".to_string(), "git@x:".to_string())]
380 );
381 }
382
383 #[test]
384 fn file_include_and_bool() {
385 let dir = tempfile::tempdir().unwrap();
386 fs::write(dir.path().join("inc"), "[commit]\n\tgpgsign\n").unwrap();
387 fs::write(
388 dir.path().join("main"),
389 "[include]\n\tpath = inc\n[user]\n\tname = N\n",
390 )
391 .unwrap();
392 let mut s = ConfigSet::new();
393 s.add_file(&dir.path().join("main"), ConfigScope::Global)
394 .unwrap();
395 assert_eq!(s.get_bool("commit.gpgsign"), Some(true));
396 assert_eq!(s.get("user.name").as_deref(), Some("N"));
397 }
398
399 #[test]
400 fn config_parameters_forms() {
401 let got = parse_config_parameters("'user.name'='A B' 'core.x=1' 'flag'");
402 assert_eq!(
403 got,
404 vec![
405 ("user.name".into(), Some("A B".into())),
406 ("core.x".into(), Some("1".into())),
407 ("flag".into(), None),
408 ]
409 );
410 }
411}