1use std::{error::Error, path::Path, process::Command};
8
9pub fn get_config_from_user_git(key: &str) -> Option<String> {
25 let handle = Command::new("git")
26 .arg("config")
27 .arg("--list")
28 .output()
29 .ok()?;
30
31 let conf_out = String::from_utf8(handle.stdout).ok()?;
32
33 println!("{conf_out}");
34
35 get_key_from_conf(key, &conf_out)
36}
37
38fn get_key_from_conf(key: &str, conf: &str) -> Option<String> {
39 conf.split("\n").map(|s| s.trim()).find_map(|line| {
40 let (cur_key, value) = line.split_once('=')?;
41 if cur_key == key {
42 Some(value.to_string())
43 } else {
44 None
45 }
46 })
47}
48
49pub fn git(dir: &Path, args: &[&str]) -> Result<(), Box<dyn Error>> {
59 let status = Command::new("git").current_dir(dir).args(args).status()?;
60
61 if !status.success() {
62 return Err(format!("git {:?} failed", args).into());
63 }
64 Ok(())
65}
66
67#[cfg(test)]
68mod test {
69 use super::*;
70
71 #[test]
72 fn test_git_config_kv_pair() {
73 let config = r#"
74 user.email=john.doe@ucla.edu
75 user.name=JohnathanD
76 core.editor=/usr/bin/vim
77 core.filemode=true
78 core.bare=false
79 core.logallrefupdates=true
80 "#
81 .to_string();
82
83 let email = get_key_from_conf("user.email", &config);
84
85 assert!(email.is_some());
86
87 assert_eq!(email.unwrap(), "john.doe@ucla.edu");
88 }
89}