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