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    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
49/// Super generic run git func for general usecases git commands
50///
51/// # Arguments
52/// * `dir` - the directory to run the git command in
53/// * `args` - the list of arguments to pass to git -> e.g. `["clone", "[URL]" ]`
54///
55/// # Returns (based on git exit code)
56/// * `Ok(())` if the git command succeeds
57/// * `Err` if the command fails
58pub 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}