1use std::collections::HashMap;
25use std::path::{Path, PathBuf};
26use std::sync::Once;
27
28const COUNT: &str = "GIT_CONFIG_COUNT";
29pub(crate) const HOOKS_PATH_KEY: &str = "core.hooksPath";
30pub(crate) const MAX_ENTRIES: usize = 1024;
32pub(crate) const MAX_CARRIED: usize = MAX_ENTRIES - 256;
35const MARKER: &str = "gh-agent publish guard";
37
38pub const META_KEY_PTYSHELL_GIT_HOOKS_PATH: &str = "ptyshell:githookspath";
43
44pub fn gh_agent_hooks_dir(get: impl Fn(&str) -> Option<String>, home: &Path, windows: bool) -> PathBuf {
48 let get = |k: &str| get(k).filter(|v| !v.is_empty());
49 if let Some(dir) = get("GH_AGENT_HOOKS_DIR") {
50 return PathBuf::from(dir);
51 }
52 if windows {
53 let base = get("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(|| home.join("AppData").join("Local"));
54 return base.join("gh-agent-hooks");
55 }
56 let base = get("XDG_DATA_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".local").join("share"));
57 base.join("gh-agent").join("hooks")
58}
59
60pub fn is_guard_hooks_dir(dir: &Path) -> bool {
62 std::fs::read_to_string(dir.join("pre-push")).map(|s| s.contains(MARKER)).unwrap_or(false)
63}
64
65fn parse_count(get: &impl Fn(&str) -> Option<String>) -> usize {
66 get(COUNT)
67 .and_then(|c| c.trim().parse().ok())
68 .filter(|c: &usize| *c <= MAX_ENTRIES)
69 .unwrap_or(0)
70}
71
72pub(crate) fn declared_count(get: &impl Fn(&str) -> Option<String>) -> usize {
74 get(COUNT).and_then(|c| c.trim().parse().ok()).unwrap_or(0)
75}
76
77pub(crate) fn git_config_slots(entries: &[(String, String)]) -> Vec<(String, String)> {
79 let mut out: Vec<(String, String)> = Vec::with_capacity(entries.len() * 2 + 1);
80 for (i, (k, v)) in entries.iter().enumerate() {
81 out.push((format!("GIT_CONFIG_KEY_{i}"), k.clone()));
82 out.push((format!("GIT_CONFIG_VALUE_{i}"), v.clone()));
83 }
84 out.push((COUNT.to_string(), entries.len().to_string()));
85 out
86}
87
88pub fn git_config_entries(get: impl Fn(&str) -> Option<String>, key: &str, value: &str) -> Vec<(String, String)> {
93 let count = parse_count(&get);
94 let mut out: Vec<(String, String)> = (0..count)
95 .filter(|i| get(&format!("GIT_CONFIG_KEY_{i}")).is_some_and(|k| k.eq_ignore_ascii_case(key)))
96 .map(|i| (format!("GIT_CONFIG_VALUE_{i}"), value.to_string()))
97 .collect();
98 if !out.is_empty() {
99 out.push((COUNT.to_string(), count.to_string()));
100 return out;
101 }
102 vec![
103 (format!("GIT_CONFIG_KEY_{count}"), key.to_string()),
104 (format!("GIT_CONFIG_VALUE_{count}"), value.to_string()),
105 (COUNT.to_string(), (count + 1).to_string()),
106 ]
107}
108
109pub fn git_config_has(get: &impl Fn(&str) -> Option<String>, key: &str) -> bool {
111 (0..parse_count(get)).any(|i| get(&format!("GIT_CONFIG_KEY_{i}")).is_some_and(|k| k.eq_ignore_ascii_case(key)))
112}
113
114pub fn git_config_has_value(get: &impl Fn(&str) -> Option<String>, key: &str, value: &str) -> bool {
116 (0..parse_count(get)).any(|i| {
117 get(&format!("GIT_CONFIG_KEY_{i}")).is_some_and(|k| k.eq_ignore_ascii_case(key)) && get(&format!("GIT_CONFIG_VALUE_{i}")).is_some_and(|v| v == value)
118 })
119}
120
121pub fn git_config_prepend(get: &impl Fn(&str) -> Option<String>, key: &str, value: &str) -> Vec<(String, String)> {
124 let count = parse_count(get);
125 let mut out = vec![("GIT_CONFIG_KEY_0".to_string(), key.to_string()), ("GIT_CONFIG_VALUE_0".to_string(), value.to_string())];
126 for i in 0..count {
127 out.push((format!("GIT_CONFIG_KEY_{}", i + 1), get(&format!("GIT_CONFIG_KEY_{i}")).unwrap_or_default()));
128 out.push((format!("GIT_CONFIG_VALUE_{}", i + 1), get(&format!("GIT_CONFIG_VALUE_{i}")).unwrap_or_default()));
129 }
130 out.push((COUNT.to_string(), (count + 1).to_string()));
131 out
132}
133
134pub fn without_hooks_path(env: &HashMap<String, String>) -> HashMap<String, String> {
138 without_git_config_key(env, HOOKS_PATH_KEY)
139}
140
141pub fn without_git_config_key(env: &HashMap<String, String>, key: &str) -> HashMap<String, String> {
143 let get = |k: &str| env.get(k).cloned();
144 let count = parse_count(&get);
145 let kept: Vec<(String, String)> = (0..count)
146 .filter_map(|i| Some((get(&format!("GIT_CONFIG_KEY_{i}"))?, get(&format!("GIT_CONFIG_VALUE_{i}")).unwrap_or_default())))
147 .filter(|(k, _)| !k.eq_ignore_ascii_case(key))
148 .collect();
149 if kept.len() == count {
150 return env.clone();
151 }
152 let mut out: HashMap<String, String> = env
153 .iter()
154 .filter(|(k, _)| k.as_str() != COUNT && !k.starts_with("GIT_CONFIG_KEY_") && !k.starts_with("GIT_CONFIG_VALUE_"))
155 .map(|(k, v)| (k.clone(), v.clone()))
156 .collect();
157 for (i, (k, v)) in kept.iter().enumerate() {
158 out.insert(format!("GIT_CONFIG_KEY_{i}"), k.clone());
159 out.insert(format!("GIT_CONFIG_VALUE_{i}"), v.clone());
160 }
161 if !kept.is_empty() {
162 out.insert(COUNT.to_string(), kept.len().to_string());
163 }
164 out
165}
166
167pub fn set_git_config_list(env: &mut HashMap<String, String>, process: impl Fn(&str) -> Option<String>, key: &str, values: &[&str]) {
172 let count = parse_count(&|k: &str| env.get(k).cloned().or_else(|| process(k)));
174 for i in 0..count {
175 for prefix in ["GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_"] {
176 let name = format!("{prefix}{i}");
177 if !env.contains_key(&name) {
178 if let Some(v) = process(&name) {
179 env.insert(name, v);
180 }
181 }
182 }
183 }
184 if count > 0 && !env.contains_key(COUNT) {
185 env.insert(COUNT.to_string(), count.to_string());
186 }
187 let mut out = without_git_config_key(env, key);
188 let at = parse_count(&|k: &str| out.get(k).cloned());
189 for (i, v) in values.iter().enumerate() {
190 out.insert(format!("GIT_CONFIG_KEY_{}", at + i), key.to_string());
191 out.insert(format!("GIT_CONFIG_VALUE_{}", at + i), v.to_string());
192 }
193 if at + values.len() > 0 {
194 out.insert(COUNT.to_string(), (at + values.len()).to_string());
195 }
196 *env = out;
197}
198
199const PARAMETERS: &str = "GIT_CONFIG_PARAMETERS";
202
203fn sh_quote(s: &str) -> String {
205 let mut out = String::from("'");
206 for c in s.chars() {
207 match c {
208 '\'' => out.push_str("'\\''"),
209 '!' => out.push_str("'\\!'"),
210 c => out.push(c),
211 }
212 }
213 out.push('\'');
214 out
215}
216
217pub fn git_config_as_parameters(env: &mut HashMap<String, String>, process: impl Fn(&str) -> Option<String>) {
229 let (count, entries, existing) = {
230 let get = |k: &str| env.get(k).cloned().or_else(|| process(k));
231 let count = parse_count(&get);
232 let entries: Vec<(String, String)> = (0..count)
233 .filter_map(|i| Some((get(&format!("GIT_CONFIG_KEY_{i}"))?, get(&format!("GIT_CONFIG_VALUE_{i}")).unwrap_or_default())))
234 .collect();
235 (count, entries, get(PARAMETERS).filter(|p| !p.trim().is_empty()))
236 };
237 if count == 0 {
238 return;
239 }
240 let pairs = entries.iter().map(|(k, v)| format!("{}={}", sh_quote(k), sh_quote(v)));
241 let params: Vec<String> = existing.into_iter().chain(pairs).collect();
242 env.retain(|k, _| !k.starts_with("GIT_CONFIG_KEY_") && !k.starts_with("GIT_CONFIG_VALUE_"));
243 env.insert(COUNT.to_string(), "0".to_string());
244 env.insert(PARAMETERS.to_string(), params.join(" "));
245}
246
247fn env_var(env: &HashMap<String, String>, key: &str, windows: bool) -> Option<String> {
249 env.get(key)
250 .or_else(|| windows.then(|| env.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v)).flatten())
251 .cloned()
252}
253
254pub fn hooks_dir_for(env: &HashMap<String, String>, process: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
257 let get = |k: &str| env_var(env, k, cfg!(windows)).or_else(|| process(k));
258 let home = get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
259 .filter(|h| !h.is_empty())
260 .map(PathBuf::from)
261 .or_else(dirs::home_dir)
262 .unwrap_or_default();
263 let dir = gh_agent_hooks_dir(&get, &home, cfg!(windows));
264 is_guard_hooks_dir(&dir).then_some(dir)
265}
266
267const SCAN_PUSH_FROM: (u64, u64) = (0, 13);
269
270pub fn hooks_written_by(pre_push: &str) -> Option<(u64, u64)> {
273 let rest = pre_push.split("written by gh-agent ").nth(1)?;
274 let version = rest.split(|c: char| c == ';' || c.is_whitespace()).next()?;
275 let mut parts = version.split('.').map(|p| p.chars().take_while(char::is_ascii_digit).collect::<String>().parse::<u64>().ok());
276 Some((parts.next()??, parts.next()??))
277}
278
279pub fn scan_ready_in(dir: &Path) -> bool {
281 let Ok(pre_push) = std::fs::read_to_string(dir.join("pre-push")) else { return false };
282 pre_push.contains(MARKER) && hooks_written_by(&pre_push).is_some_and(|v| v >= SCAN_PUSH_FROM)
283}
284
285pub fn container_scan_ready() -> bool {
289 hooks_dir_for(&HashMap::new(), |k| std::env::var(k).ok()).is_some_and(|dir| scan_ready_in(&dir))
290}
291
292pub fn apply_publish_guard_in(env: &mut HashMap<String, String>, hooks_dir: &Path, process: impl Fn(&str) -> Option<String>) {
294 let entries = git_config_entries(|k| env.get(k).cloned().or_else(|| process(k)), HOOKS_PATH_KEY, &hooks_dir.to_string_lossy());
295 env.extend(entries);
296}
297
298#[cfg_attr(test, allow(dead_code))]
302pub fn apply_publish_guard(env: &mut HashMap<String, String>) {
303 let process = |k: &str| std::env::var(k).ok();
304 match hooks_dir_for(env, process) {
305 Some(dir) => apply_publish_guard_in(env, &dir, process),
306 None => {
307 static WARN: Once = Once::new();
308 WARN.call_once(|| {
309 tracing::debug!(
310 "publish guard not active: no hooks directory from gh-agent was found, so agents' pushes are not scanned \
311 (agents' GitHub access is set up by the AgentMux GitHub connection or by gh-agent)"
312 );
313 });
314 }
315 }
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 #[test]
323 fn the_version_in_a_hook_header_is_read() {
324 let hook = |v: &str| format!("#!/bin/sh\n# gh-agent publish guard: written by gh-agent {v}; do not edit (gh-agent hooks-path rewrites it)\n");
325 assert_eq!(hooks_written_by(&hook("0.13.0")), Some((0, 13)));
326 assert_eq!(hooks_written_by(&hook("0.12.5")), Some((0, 12)));
327 assert_eq!(hooks_written_by(&hook("1.0.0-beta.1")), Some((1, 0)));
328 assert_eq!(hooks_written_by("#!/bin/sh\nexit 0\n"), None);
329 assert_eq!(hooks_written_by(&hook("x.y")), None);
330 }
331
332 #[test]
333 fn a_container_scan_needs_gh_agents_own_hooks_from_a_gh_agent_that_can_judge_a_push() {
334 let dir = std::env::temp_dir().join(format!("scan-ready-{}", std::process::id()));
335 std::fs::create_dir_all(&dir).unwrap();
336 let write = |text: &str| std::fs::write(dir.join("pre-push"), text).unwrap();
337 assert!(!scan_ready_in(&dir.join("missing")), "no hooks directory");
338 write("#!/bin/sh\n# gh-agent publish guard: written by gh-agent 0.12.5; x\n");
339 assert!(!scan_ready_in(&dir), "a gh-agent older than the scan");
340 write("#!/bin/sh\n# gh-agent publish guard: written by gh-agent 0.13.0; x\n");
341 assert!(scan_ready_in(&dir));
342 write("#!/bin/sh\n# another tool: written by gh-agent 0.13.0; x\n");
343 assert!(!scan_ready_in(&dir), "not the guard's own hook");
344 let _ = std::fs::remove_dir_all(&dir);
345 }
346
347 fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
348 pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
349 }
350
351 fn no_process(_: &str) -> Option<String> {
352 None
353 }
354
355 fn guard_dir() -> tempfile::TempDir {
356 let dir = tempfile::tempdir().unwrap();
357 std::fs::write(dir.path().join("pre-push"), format!("#!/bin/sh\n# {MARKER}: test\n")).unwrap();
358 dir
359 }
360
361 #[test]
362 fn git_config_moves_to_parameters_for_an_agent_that_scrubs_key_names() {
363 let mut e = env(&[
364 (COUNT, "2"),
365 ("GIT_CONFIG_KEY_0", "core.hooksPath"),
366 ("GIT_CONFIG_VALUE_0", "C:\\Users\\a b\\gh-agent-hooks"),
367 ("GIT_CONFIG_KEY_1", "safe.directory"),
368 ("GIT_CONFIG_VALUE_1", "*"),
369 ("PATH", "/bin"),
370 ]);
371 git_config_as_parameters(&mut e, no_process);
372 assert_eq!(e[PARAMETERS], r"'core.hooksPath'='C:\Users\a b\gh-agent-hooks' 'safe.directory'='*'");
373 assert_eq!(e[COUNT], "0");
374 assert!(!e.keys().any(|k| k.starts_with("GIT_CONFIG_KEY_") || k.starts_with("GIT_CONFIG_VALUE_")));
375 assert_eq!(e["PATH"], "/bin");
376 let scrubbed = |k: &str| ["KEY", "PASSWORD", "SECRET", "TOKEN"].iter().any(|w| k.to_uppercase().contains(w));
378 assert!(!scrubbed(PARAMETERS) && !scrubbed(COUNT));
379 }
380
381 #[test]
382 fn parameters_quote_what_git_would_and_keep_what_was_there() {
383 assert_eq!(sh_quote("it's"), r"'it'\''s'");
384 assert_eq!(sh_quote("a!b"), r"'a'\!'b'");
385 let mut e = env(&[(PARAMETERS, "'user.name'='x'")]);
386 let process = |k: &str| match k {
387 COUNT => Some("1".to_string()),
388 "GIT_CONFIG_KEY_0" => Some("core.hooksPath".to_string()),
389 "GIT_CONFIG_VALUE_0" => Some("/h".to_string()),
390 _ => None,
391 };
392 git_config_as_parameters(&mut e, process);
393 assert_eq!(e[PARAMETERS], "'user.name'='x' 'core.hooksPath'='/h'");
395 assert_eq!(e[COUNT], "0");
396 }
397
398 #[test]
399 fn no_git_config_means_nothing_changes() {
400 let mut e = env(&[("PATH", "/bin")]);
401 git_config_as_parameters(&mut e, no_process);
402 assert_eq!(e, env(&[("PATH", "/bin")]));
403 }
404
405 #[test]
406 fn hooks_dir_follows_gh_agent() {
407 let home = Path::new("/home/a");
408 let none = |_: &str| None;
409 assert_eq!(gh_agent_hooks_dir(none, home, false), PathBuf::from("/home/a/.local/share/gh-agent/hooks"));
410 assert_eq!(
411 gh_agent_hooks_dir(|k| (k == "XDG_DATA_HOME").then(|| "/x".to_string()), home, false),
412 PathBuf::from("/x/gh-agent/hooks")
413 );
414 assert_eq!(
415 gh_agent_hooks_dir(|k| (k == "LOCALAPPDATA").then(|| "C:/L".to_string()), home, true),
416 PathBuf::from("C:/L/gh-agent-hooks")
417 );
418 assert_eq!(gh_agent_hooks_dir(none, home, true), PathBuf::from("/home/a/AppData/Local/gh-agent-hooks"));
419 assert_eq!(
420 gh_agent_hooks_dir(|k| (k == "GH_AGENT_HOOKS_DIR").then(|| "/o".to_string()), home, true),
421 PathBuf::from("/o")
422 );
423 }
424
425 #[test]
426 fn the_agents_own_env_decides_where_the_hooks_are() {
427 let dir = guard_dir();
428 let agent = env(&[("GH_AGENT_HOOKS_DIR", &dir.path().to_string_lossy())]);
429 assert_eq!(hooks_dir_for(&agent, no_process).as_deref(), Some(dir.path()));
430 let p = dir.path().to_string_lossy().into_owned();
432 assert_eq!(hooks_dir_for(&HashMap::new(), |k| (k == "GH_AGENT_HOOKS_DIR").then(|| p.clone())).as_deref(), Some(dir.path()));
433 let empty = tempfile::tempdir().unwrap();
435 let agent = env(&[("GH_AGENT_HOOKS_DIR", &empty.path().to_string_lossy())]);
436 assert_eq!(hooks_dir_for(&agent, no_process), None);
437 std::fs::write(empty.path().join("pre-push"), "#!/bin/sh\n# someone else's hook\n").unwrap();
438 assert_eq!(hooks_dir_for(&agent, no_process), None);
439 }
440
441 #[test]
442 fn windows_variable_names_match_in_any_casing() {
443 let e = env(&[("Gh_Agent_Hooks_Dir", "/h")]);
444 assert_eq!(env_var(&e, "GH_AGENT_HOOKS_DIR", true).as_deref(), Some("/h"));
445 assert_eq!(env_var(&e, "GH_AGENT_HOOKS_DIR", false), None);
446 }
447
448 #[test]
449 fn sets_core_hooks_path_through_the_environment() {
450 let dir = guard_dir();
451 let mut e = env(&[("AGENTMUX_AGENT_ID", "AgentY")]);
452 apply_publish_guard_in(&mut e, dir.path(), no_process);
453 assert_eq!(e[COUNT], "1");
454 assert_eq!(e["GIT_CONFIG_KEY_0"], HOOKS_PATH_KEY);
455 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_0"]), dir.path());
456 }
457
458 #[test]
459 fn appends_after_entries_already_there_and_replaces_its_own() {
460 let dir = guard_dir();
461 let mut e = env(&[(COUNT, "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
462 apply_publish_guard_in(&mut e, dir.path(), no_process);
463 assert_eq!(e[COUNT], "2");
464 assert_eq!(e["GIT_CONFIG_KEY_0"], "user.name");
465 assert_eq!(e["GIT_CONFIG_KEY_1"], HOOKS_PATH_KEY);
466 e.insert("GIT_CONFIG_VALUE_1".into(), "/somewhere/else".into());
468 apply_publish_guard_in(&mut e, dir.path(), no_process);
469 assert_eq!(e[COUNT], "2");
470 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_1"]), dir.path());
471 }
472
473 #[test]
474 fn a_hooks_path_entry_from_elsewhere_is_replaced_not_kept() {
475 let dir = guard_dir();
476 let mut e = env(&[(COUNT, "1"), ("GIT_CONFIG_KEY_0", "core.hookspath"), ("GIT_CONFIG_VALUE_0", "/dev/null")]);
477 apply_publish_guard_in(&mut e, dir.path(), no_process);
478 assert_eq!(e[COUNT], "1");
479 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_0"]), dir.path());
480 }
481
482 #[test]
483 fn builds_on_entries_the_process_env_already_has() {
484 let dir = guard_dir();
485 let mut e = HashMap::new();
486 let process = |k: &str| match k {
487 "GIT_CONFIG_COUNT" => Some("2".to_string()),
488 "GIT_CONFIG_KEY_1" => Some("core.hooksPath".to_string()),
489 _ => None,
490 };
491 apply_publish_guard_in(&mut e, dir.path(), process);
492 assert_eq!(e[COUNT], "2", "reuses the process env's own hooksPath slot");
493 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_1"]), dir.path());
494 assert!(!e.contains_key("GIT_CONFIG_KEY_0"), "the other inherited slot is left alone");
495 }
496
497 #[test]
498 fn every_hooks_path_slot_gets_the_guard_because_git_uses_the_last() {
499 let dir = guard_dir();
500 let mut e = env(&[
501 (COUNT, "3"),
502 ("GIT_CONFIG_KEY_0", "core.hooksPath"),
503 ("GIT_CONFIG_VALUE_0", "/old"),
504 ("GIT_CONFIG_KEY_1", "user.name"),
505 ("GIT_CONFIG_VALUE_1", "x"),
506 ("GIT_CONFIG_KEY_2", "CORE.HOOKSPATH"),
507 ("GIT_CONFIG_VALUE_2", "/dev/null"),
508 ]);
509 apply_publish_guard_in(&mut e, dir.path(), no_process);
510 assert_eq!(e[COUNT], "3");
511 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_0"]), dir.path());
512 assert_eq!(PathBuf::from(&e["GIT_CONFIG_VALUE_2"]), dir.path());
513 assert_eq!(e["GIT_CONFIG_VALUE_1"], "x");
514 }
515
516 #[test]
517 fn a_container_keeps_its_other_git_settings_but_not_the_host_hooks_path() {
518 let e = env(&[
519 (COUNT, "3"),
520 ("GIT_CONFIG_KEY_0", "url.x.insteadOf"),
521 ("GIT_CONFIG_VALUE_0", "y"),
522 ("GIT_CONFIG_KEY_1", "core.hooksPath"),
523 ("GIT_CONFIG_VALUE_1", "/host/hooks"),
524 ("GIT_CONFIG_KEY_2", "http.sslCAInfo"),
525 ("GIT_CONFIG_VALUE_2", "/ca.pem"),
526 ("OTHER", "kept"),
527 ]);
528 let out = without_hooks_path(&e);
529 assert_eq!(out[COUNT], "2");
530 assert_eq!(out["GIT_CONFIG_KEY_0"], "url.x.insteadOf");
531 assert_eq!(out["GIT_CONFIG_KEY_1"], "http.sslCAInfo");
532 assert_eq!(out["GIT_CONFIG_VALUE_1"], "/ca.pem");
533 assert!(!out.contains_key("GIT_CONFIG_KEY_2"));
534 assert_eq!(out["OTHER"], "kept");
535 let only = env(&[(COUNT, "1"), ("GIT_CONFIG_KEY_0", "core.hooksPath"), ("GIT_CONFIG_VALUE_0", "/h")]);
536 assert!(without_hooks_path(&only).is_empty(), "nothing left: no count either");
537 let untouched = env(&[("A", "b")]);
538 assert_eq!(without_hooks_path(&untouched), untouched);
539 }
540
541 #[test]
542 fn a_list_setting_is_replaced_in_order_and_the_others_kept() {
543 let mut e = env(&[
544 (COUNT, "3"),
545 ("GIT_CONFIG_KEY_0", "credential.https://github.com.helper"),
546 ("GIT_CONFIG_VALUE_0", "old"),
547 ("GIT_CONFIG_KEY_1", "user.name"),
548 ("GIT_CONFIG_VALUE_1", "x"),
549 ("GIT_CONFIG_KEY_2", "Credential.https://github.com.Helper"),
550 ("GIT_CONFIG_VALUE_2", "older"),
551 ]);
552 set_git_config_list(&mut e, no_process, "credential.https://github.com.helper", &["", "!agentmux-bashwrap git-credential"]);
553 assert_eq!(e[COUNT], "3");
554 assert_eq!((e["GIT_CONFIG_KEY_0"].as_str(), e["GIT_CONFIG_VALUE_0"].as_str()), ("user.name", "x"));
555 assert_eq!((e["GIT_CONFIG_KEY_1"].as_str(), e["GIT_CONFIG_VALUE_1"].as_str()), ("credential.https://github.com.helper", ""));
556 assert_eq!(e["GIT_CONFIG_VALUE_2"], "!agentmux-bashwrap git-credential");
557 let before = e.clone();
559 set_git_config_list(&mut e, no_process, "credential.https://github.com.helper", &["", "!agentmux-bashwrap git-credential"]);
560 assert_eq!(e, before);
561 set_git_config_list(&mut e, no_process, "credential.https://github.com.helper", &[]);
563 assert_eq!(e[COUNT], "1");
564 assert_eq!(e["GIT_CONFIG_KEY_0"], "user.name");
565 assert!(!e.contains_key("GIT_CONFIG_KEY_1"));
566 }
567
568 #[test]
569 fn a_list_setting_builds_on_the_process_envs_entries() {
570 let mut e = HashMap::new();
571 let process = |k: &str| match k {
572 "GIT_CONFIG_COUNT" => Some("1".to_string()),
573 "GIT_CONFIG_KEY_0" => Some("user.name".to_string()),
574 "GIT_CONFIG_VALUE_0" => Some("y".to_string()),
575 _ => None,
576 };
577 set_git_config_list(&mut e, process, "core.x", &["1"]);
578 assert_eq!(e[COUNT], "2");
579 assert_eq!((e["GIT_CONFIG_KEY_0"].as_str(), e["GIT_CONFIG_VALUE_0"].as_str()), ("user.name", "y"));
580 assert_eq!((e["GIT_CONFIG_KEY_1"].as_str(), e["GIT_CONFIG_VALUE_1"].as_str()), ("core.x", "1"));
581 }
582
583 #[test]
584 fn an_absurd_count_is_not_trusted_or_looped_over() {
585 let dir = guard_dir();
586 let mut e = env(&[(COUNT, "999999999999")]);
587 apply_publish_guard_in(&mut e, dir.path(), no_process);
588 assert_eq!(e[COUNT], "1");
589 assert_eq!(e["GIT_CONFIG_KEY_0"], HOOKS_PATH_KEY);
590 }
591
592 #[test]
593 fn entries_for_a_pty_spawn_keep_the_slots_its_env_already_uses() {
594 let existing = env(&[(COUNT, "1"), ("GIT_CONFIG_KEY_0", "url.x.insteadOf"), ("GIT_CONFIG_VALUE_0", "y")]);
596 let pairs = git_config_entries(|k| existing.get(k).cloned(), HOOKS_PATH_KEY, "/h");
597 assert!(pairs.contains(&("GIT_CONFIG_KEY_1".to_string(), HOOKS_PATH_KEY.to_string())));
598 assert!(pairs.contains(&("GIT_CONFIG_VALUE_1".to_string(), "/h".to_string())));
599 assert!(pairs.contains(&(COUNT.to_string(), "2".to_string())));
600 }
601}