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