git_editor/utils/
git_config.rs1use 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
25pub fn get_git_user_name(repo_path: Option<&str>) -> Option<String> {
27 read_value(repo_path, "user.name")
28}
29
30pub 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 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 let _ = get_git_user_name(Some("/definitely/not/a/repo"));
72 }
73}