oseda_cli/
github.rs

1/*
2user.email=hatfield.69@wright.edu
3user.name=ReeseHatfield
4core.editor=/usr/bin/vim
5*/
6
7use std::{error::Error, path::Path, process::Command};
8
9/// Gets a value from the users local git configuration, see example
10///
11/// # Arguments
12/// * `key` - the config key to look for -> e.g core.editor
13///
14/// # Returns
15/// * `Some(String)` with the value if the key is found
16/// * `None` on key retrieval failure
17///
18/// # Example
19/// ```
20/// use oseda_cli::github::get_config_from_user_git;
21///
22/// let name = get_config_from_user_git("user.name");
23/// ```
24pub 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
51/// Super generic run git func for general usecases git commands
52///
53/// # Arguments
54/// * `dir` - the directory to run the git command in
55/// * `args` - the list of arguments to pass to git -> e.g. `["clone", "[URL]" ]`
56///
57/// # Returns (based on git exit code)
58/// * `Ok(())` if the git command succeeds
59/// * `Err` if the command fails
60pub 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}