Skip to main content

git_editor/utils/
git_config.rs

1//! Default identity lookup for prompts.
2//!
3//! Uses libgit2's configuration stack with the usual precedence: the
4//! repository's `.git/config`, then `~/.gitconfig` / `$XDG_CONFIG_HOME/git/config`,
5//! then the system config, including `[include]` files. Environment overrides
6//! that only the `git` CLI understands (`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_COUNT`,
7//! …) are not applied.
8
9use git2::{Config, Repository};
10
11fn config_for(repo_path: Option<&str>) -> Option<Config> {
12    repo_path
13        .and_then(|path| Repository::open(path).ok())
14        .and_then(|repo| repo.config().ok())
15        .or_else(|| Config::open_default().ok())
16}
17
18fn read_value(repo_path: Option<&str>, key: &str) -> Option<String> {
19    let config = config_for(repo_path)?.snapshot().ok()?;
20    let value = config.get_string(key).ok()?;
21    let value = value.trim().to_string();
22    (!value.is_empty()).then_some(value)
23}
24
25/// `user.name` as Git would resolve it for `repo_path` (or globally).
26pub fn get_git_user_name(repo_path: Option<&str>) -> Option<String> {
27    read_value(repo_path, "user.name")
28}
29
30/// `user.email` as Git would resolve it for `repo_path` (or globally).
31pub fn get_git_user_email(repo_path: Option<&str>) -> Option<String> {
32    read_value(repo_path, "user.email")
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use tempfile::TempDir;
39
40    #[test]
41    fn repository_config_takes_precedence() {
42        let dir = TempDir::new().unwrap();
43        let repo = Repository::init(dir.path()).unwrap();
44        let mut config = repo.config().unwrap();
45        config.set_str("user.name", "Repo Local").unwrap();
46        config.set_str("user.email", "local@example.com").unwrap();
47
48        let path = dir.path().to_str();
49        assert_eq!(get_git_user_name(path).as_deref(), Some("Repo Local"));
50        assert_eq!(
51            get_git_user_email(path).as_deref(),
52            Some("local@example.com")
53        );
54    }
55
56    #[test]
57    fn blank_values_are_ignored() {
58        let dir = TempDir::new().unwrap();
59        let repo = Repository::init(dir.path()).unwrap();
60        repo.config().unwrap().set_str("user.name", "   ").unwrap();
61        // Falls through to whatever the global config says, but never "   ".
62        assert_ne!(
63            get_git_user_name(dir.path().to_str()).as_deref(),
64            Some("   ")
65        );
66    }
67
68    #[test]
69    fn missing_repository_falls_back_to_default_config() {
70        // Must not panic or error for a path that is not a repository.
71        let _ = get_git_user_name(Some("/definitely/not/a/repo"));
72    }
73}