Debian Codegraph @

src/git_config/mod.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 mod remote;
2
3 pub use remote::GitRemoteRepo;
4
5 use crate::env::DeltaEnv;
6 use regex::Regex;
7 use std::cell::OnceCell;
8 use std::collections::HashMap;
9 use std::path::Path;
10
11 use lazy_static::lazy_static;
12
13 pub struct GitConfig {
14 config: git2::Config,
15 config_from_env_var: HashMap<String, String>,
16 pub enabled: bool,
17 repo: Option<git2::Repository>,
18 remote_url: OnceCell<Option<GitRemoteRepo>>,
19 // To make GitConfig cloneable when testing (in turn to make Config cloneable):
20 #[cfg(test)]
21 path: std::path::PathBuf,
22 }
23
24 #[cfg(test)]
25 impl Clone for GitConfig {
26 fn clone(&self) -> Self {
27 assert!(self.repo.is_none());
28 GitConfig {
29 // Assumes no test modifies the file pointed to by `path`
30 config: git2::Config::open(&self.path).unwrap(),
31 config_from_env_var: self.config_from_env_var.clone(),
32 enabled: self.enabled,
33 repo: None,
34 remote_url: OnceCell::new(),
35 path: self.path.clone(),
36 }
37 }
38 }
39
40 impl GitConfig {
41 #[cfg(not(test))]
42 pub fn try_create(env: &DeltaEnv) -> Option<Self> {
43 use crate::fatal;
44
45 let repo = match &env.current_dir {
46 Some(dir) => git2::Repository::discover(dir).ok(),
47 _ => None,
48 };
49 let config = match &repo {
50 Some(repo) => repo.config().ok(),
51 None => git2::Config::open_default().ok(),
52 };
53 match config {
54 Some(mut config) => {
55 let config = config.snapshot().unwrap_or_else(|err| {
56 fatal(format!("Failed to read git config: {err}"));
57 });
58 Some(Self {
59 config,
60 config_from_env_var: parse_config_from_env_var(env),
61 repo,
62 enabled: true,
63 remote_url: OnceCell::new(),
64 })
65 }
66 None => None,
67 }
68 }
69
70 #[cfg(test)]
71 pub fn try_create(_env: &DeltaEnv) -> Option<Self> {
72 // Do not read local git configs when testing
73 None
74 }
75
76 #[cfg(test)]
77 pub fn for_testing() -> Option<Self> {
78 Some(GitConfig {
79 config: git2::Config::new().unwrap(),
80 config_from_env_var: HashMap::new(),
81 enabled: true,
82 repo: None,
83 remote_url: OnceCell::new(),
84 path: std::path::PathBuf::from("/invalid_null.git"),
85 })
86 }
87
88 pub fn from_path(env: &DeltaEnv, path: &Path, honor_env_var: bool) -> Self {
89 use crate::fatal;
90
91 match git2::Config::open(path) {
92 Ok(mut config) => {
93 let config = config.snapshot().unwrap_or_else(|err| {
94 fatal(format!("Failed to read git config: {err}"));
95 });
96
97 Self {
98 config,
99 config_from_env_var: if honor_env_var {
100 parse_config_from_env_var(env)
101 } else {
102 HashMap::new()
103 },
104 repo: None,
105 enabled: true,
106 remote_url: OnceCell::new(),
107 #[cfg(test)]
108 path: path.into(),
109 }
110 }
111 Err(e) => {
112 fatal(format!("Failed to read git config: {}", e.message()));
113 }
114 }
115 }
116
117 pub fn get<T>(&self, key: &str) -> Option<T>
118 where
119 T: GitConfigGet,
120 {
121 if self.enabled {
122 T::git_config_get(key, self)
123 } else {
124 None
125 }
126 }
127
128 #[cfg(test)]
129 fn get_remote_url_impl(&self) -> Option<GitRemoteRepo> {
130 GitRemoteRepo::for_testing()
131 }
132
133 #[cfg(not(test))]
134 fn get_remote_url_impl(&self) -> Option<GitRemoteRepo> {
135 use std::str::FromStr;
136 self.repo
137 .as_ref()?
138 .find_remote("origin")
139 .ok()?
140 .url()
•141 .ok()
142 .and_then(|url| GitRemoteRepo::from_str(url).ok())
143 }
144
145 pub fn get_remote_url(&self) -> &Option<GitRemoteRepo> {
146 self.remote_url.get_or_init(|| self.get_remote_url_impl())
147 }
148
149 pub fn for_each<F>(&self, regex: &str, mut f: F)
150 where
151 F: FnMut(&str, Option<&str>),
152 {
153 let mut entries = self.config.entries(Some(regex)).unwrap();
154 while let Some(entry) = entries.next() {
155 let entry = entry.unwrap();
156 let name = entry.name().unwrap();
•157 f(name, entry.value().ok());
158 }
159 }
160 }
161
162 fn parse_config_from_env_var(env: &DeltaEnv) -> HashMap<String, String> {
163 if let Some(s) = &env.git_config_parameters {
164 parse_config_from_env_var_value(s)
165 } else {
166 HashMap::new()
167 }
168 }
169
170 lazy_static! {
171 static ref GIT_CONFIG_PARAMETERS_REGEX: Regex = Regex::new(
172 r"(?x)
173 (?: # Non-capturing group containing union
174 '(delta\.[a-z-]+)=([^']+)' # Git <2.31.0 format
175 |
176 '(delta\.[a-z-]+)'='([^']+)' # Git ≥2.31.0 format
177 )
178 "
179 )
180 .unwrap();
181 }
182
183 fn parse_config_from_env_var_value(s: &str) -> HashMap<String, String> {
184 GIT_CONFIG_PARAMETERS_REGEX
185 .captures_iter(s)
186 .map(|captures| {
187 let (i, j) = match (
188 captures.get(1),
189 captures.get(2),
190 captures.get(3),
191 captures.get(4),
192 ) {
193 (Some(_), Some(_), None, None) => (1, 2),
194 (None, None, Some(_), Some(_)) => (3, 4),
195 _ => (0, 0),
196 };
197 if (i, j) == (0, 0) {
198 ("".to_string(), "".to_string())
199 } else {
200 (captures[i].to_string(), captures[j].to_string())
201 }
202 })
203 .collect()
204 }
205
206 pub trait GitConfigGet {
207 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self>
208 where
209 Self: Sized;
210 }
211
212 impl GitConfigGet for String {
213 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> {
214 match git_config.config_from_env_var.get(key) {
215 Some(val) => Some(val.to_string()),
216 None => git_config.config.get_string(key).ok(),
217 }
218 }
219 }
220
221 impl GitConfigGet for Option<String> {
222 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> {
223 match git_config.config_from_env_var.get(key) {
224 Some(val) => Some(Some(val.to_string())),
225 None => match git_config.config.get_string(key) {
226 Ok(val) => Some(Some(val)),
227 _ => None,
228 },
229 }
230 }
231 }
232
233 impl GitConfigGet for bool {
234 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> {
235 match git_config.config_from_env_var.get(key).map(|s| s.as_str()) {
236 Some("true") => Some(true),
237 Some("false") => Some(false),
238 _ => git_config.config.get_bool(key).ok(),
239 }
240 }
241 }
242
243 impl GitConfigGet for usize {
244 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> {
245 if let Some(s) = git_config.config_from_env_var.get(key) {
246 if let Ok(n) = s.parse::<usize>() {
247 return Some(n);
248 }
249 }
250 match git_config.config.get_i64(key) {
251 Ok(value) => Some(value as usize),
252 _ => None,
253 }
254 }
255 }
256
257 impl GitConfigGet for f64 {
258 fn git_config_get(key: &str, git_config: &GitConfig) -> Option<Self> {
259 if let Some(s) = git_config.config_from_env_var.get(key) {
260 if let Ok(n) = s.parse::<f64>() {
261 return Some(n);
262 }
263 }
264 match git_config.config.get_string(key) {
265 Ok(value) => value.parse::<f64>().ok(),
266 _ => None,
267 }
268 }
269 }
270
271 #[cfg(test)]
272 mod tests {
273
274 use super::parse_config_from_env_var_value;
275
276 #[test]
277 fn test_parse_config_from_env_var_value() {
278 // To generate test cases, use git -c ... with
279 // [core]
280 // pager = env | grep GIT_CONFIG_PARAMETERS
281
282 // We test multiple formats because the format of the value stored by
283 // git in this environment variable has changed in recent versions of
284 // Git. See
285 // https://github.com/git/git/blob/311531c9de557d25ac087c1637818bd2aad6eb3a/Documentation/RelNotes/2.31.0.txt#L127-L130
286
287 for env_var_value in &["'user.name=xxx'", "'user.name'='xxx'"] {
288 let config = parse_config_from_env_var_value(env_var_value);
289 assert!(config.is_empty());
290 }
291
292 for env_var_value in &["'delta.plus-style=green'", "'delta.plus-style'='green'"] {
293 let config = parse_config_from_env_var_value(env_var_value);
294 assert_eq!(config["delta.plus-style"], "green");
295 }
296
297 for env_var_value in &[
298 r##"'user.name=xxx' 'delta.hunk-header-line-number-style=red "#067a00"'"##,
299 r##"'user.name'='xxx' 'delta.hunk-header-line-number-style'='red "#067a00"'"##,
300 ] {
301 let config = parse_config_from_env_var_value(env_var_value);
302 assert_eq!(
303 config["delta.hunk-header-line-number-style"],
304 r##"red "#067a00""##
305 );
306 }
307
308 for env_var_value in &[
309 r##"'user.name=xxx' 'delta.side-by-side=false'"##,
310 r##"'user.name'='xxx' 'delta.side-by-side'='false'"##,
311 ] {
312 let config = parse_config_from_env_var_value(env_var_value);
313 assert_eq!(config["delta.side-by-side"], "false");
314 }
315
316 for env_var_value in &[
317 r##"'delta.plus-style=green' 'delta.side-by-side=false' 'delta.hunk-header-line-number-style=red "#067a00"'"##,
318 r##"'delta.plus-style'='green' 'delta.side-by-side'='false' 'delta.hunk-header-line-number-style'='red "#067a00"'"##,
319 ] {
320 let config = parse_config_from_env_var_value(env_var_value);
321 assert_eq!(config["delta.plus-style"], "green");
322 assert_eq!(config["delta.side-by-side"], "false");
323 assert_eq!(
324 config["delta.hunk-header-line-number-style"],
325 r##"red "#067a00""##
326 );
327 }
328 }
329 }