gitcc_git/
config.rs

1//! Configuration
2
3use std::collections::BTreeMap;
4
5use crate::{error::Error, repo::GitRepository};
6
7/// A more user-friendly config object
8pub type GitConfig = BTreeMap<String, String>;
9
10/// Config key for the user email
11pub const USER_EMAIL: &str = "user.email";
12
13/// Config key for the user name
14pub const USER_NAME: &str = "user.name";
15
16/// Returns the repo config
17///
18/// The config is the config which can be applied taking into
19/// account the hierarchy which exists between the global config,
20/// and the local/repo config overwriting the global config.
21pub fn get_config(repo: &GitRepository) -> Result<GitConfig, Error> {
22    let git2_cfg = repo.config().unwrap();
23
24    let mut cfg = BTreeMap::new();
25    git2_cfg.entries(None).into_iter().for_each(|entries| {
26        // NB: this loop is over the types of config, starting from the most generic one (global => local)
27        entries
28            .for_each(|entry| {
29                // NB: this loop is for each entry in the config file
30                // let level = entry.level();
31                let name = entry.name().unwrap().to_string();
32                let value = entry.value().unwrap_or("").to_string();
33                // eprintln!("{:?} {} {}", level, name, value);
34                cfg.insert(name, value);
35            })
36            .unwrap();
37    });
38
39    Ok(cfg)
40}
41
42/// Retrieves the repo origin url
43pub fn get_origin_url(repo: &GitRepository, origin_name: &str) -> Result<Option<String>, Error> {
44    let cfg = get_config(repo)?;
45    let key = format!("remote.{}.url", origin_name);
46    Ok(cfg.get(key.as_str()).map(|s| s.to_string()))
47}
48
49#[cfg(test)]
50mod tests {
51    use crate::repo::discover_repo;
52
53    // Note this useful idiom: importing names from outer (for mod tests) scope.
54    use super::*;
55
56    #[test]
57    fn test_cfg() {
58        let cwd = std::env::current_dir().unwrap();
59        let repo = discover_repo(&cwd).unwrap();
60        let cfg = get_config(&repo).unwrap();
61        for (k, v) in cfg.iter() {
62            eprintln!("{}: {}", k, v);
63        }
64    }
65}