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