1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use std::iter::FromIterator;
use std::ops::Deref;
use std::str::FromStr;

use anyhow::Result;
use git2::{Config, ErrorClass, ErrorCode};
use log::*;

type GitResult<T> = std::result::Result<T, git2::Error>;

#[derive(Debug)]
pub enum ConfigValue<T> {
    Explicit { value: T, source: String },
    Implicit(T),
}

impl<T> ConfigValue<T> {
    pub fn unwrap(self) -> T {
        match self {
            ConfigValue::Explicit { value: x, .. } | ConfigValue::Implicit(x) => x,
        }
    }

    pub fn is_implicit(&self) -> bool {
        match self {
            ConfigValue::Explicit { .. } => false,
            ConfigValue::Implicit(_) => true,
        }
    }
}

impl<T> Deref for ConfigValue<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self {
            ConfigValue::Explicit { value: x, .. } | ConfigValue::Implicit(x) => x,
        }
    }
}

pub struct ConfigBuilder<'a, T> {
    config: &'a Config,
    key: &'a str,
    explicit: Option<(&'a str, T)>,
    default: Option<&'a T>,
}

pub fn get<'a, T>(config: &'a Config, key: &'a str) -> ConfigBuilder<'a, T> {
    ConfigBuilder {
        config,
        key,
        explicit: None,
        default: None,
    }
}

impl<'a, T> ConfigBuilder<'a, T>
where
    T: Clone,
{
    pub fn with_explicit(self, source: &'a str, value: Option<T>) -> ConfigBuilder<'a, T> {
        if let Some(value) = value {
            ConfigBuilder {
                explicit: Some((source, value)),
                ..self
            }
        } else {
            self
        }
    }

    pub fn with_default(self, value: &'a T) -> ConfigBuilder<'a, T> {
        ConfigBuilder {
            default: Some(value),
            ..self
        }
    }
}

impl<'a, T> ConfigBuilder<'a, T>
where
    T: ConfigValues + Clone,
{
    pub fn read(self) -> GitResult<Option<ConfigValue<T>>> {
        if let Some((source, value)) = self.explicit {
            return Ok(Some(ConfigValue::Explicit {
                value,
                source: source.to_string(),
            }));
        }
        match T::get_config_value(self.config, self.key) {
            Ok(value) => Ok(Some(ConfigValue::Explicit {
                value,
                source: self.key.to_string(),
            })),
            Err(err) if config_not_exist(&err) => {
                if let Some(default) = self.default {
                    Ok(Some(ConfigValue::Implicit(default.clone())))
                } else {
                    Ok(None)
                }
            }
            Err(err) => Err(err),
        }
    }
}

impl<'a, T> ConfigBuilder<'a, T>
where
    T: Clone,
{
    pub fn parse_with<F>(self, parse: F) -> Result<Option<ConfigValue<T>>>
    where
        F: FnOnce(&str) -> Result<T>,
    {
        if let Some((source, value)) = self.explicit {
            return Ok(Some(ConfigValue::Explicit {
                value,
                source: source.to_string(),
            }));
        }

        let result = match self.config.get_str(self.key) {
            Ok(value) => Some(ConfigValue::Explicit {
                value: parse(value)?,
                source: self.key.to_string(),
            }),
            Err(err) if config_not_exist(&err) => {
                if let Some(default) = self.default {
                    Some(ConfigValue::Implicit(default.clone()))
                } else {
                    None
                }
            }
            Err(err) => return Err(err.into()),
        };
        Ok(result)
    }

    pub fn parse_multi_with<F>(self, parse: F) -> Result<Option<ConfigValue<T>>>
    where
        F: FnOnce(&[String]) -> Result<T>,
    {
        if let Some((source, value)) = self.explicit {
            return Ok(Some(ConfigValue::Explicit {
                value,
                source: source.to_string(),
            }));
        }

        let result = match Vec::<String>::get_config_value(self.config, self.key) {
            Ok(values) if !values.is_empty() => Some(ConfigValue::Explicit {
                value: parse(&values)?,
                source: self.key.to_string(),
            }),
            Ok(_) => {
                if let Some(default) = self.default {
                    Some(ConfigValue::Implicit(default.clone()))
                } else {
                    None
                }
            }
            Err(err) => return Err(err.into()),
        };
        Ok(result)
    }
}

impl<'a, T> ConfigBuilder<'a, T> {
    pub fn parse(self) -> Result<Option<ConfigValue<T>>>
    where
        T: FromStr + Clone,
        T::Err: std::error::Error + Send + Sync + 'static,
    {
        self.parse_with(|str| Ok(str.parse()?))
    }

    pub fn parse_flatten<U>(self) -> Result<Option<ConfigValue<T>>>
    where
        T: FromStr + IntoIterator<Item = U> + FromIterator<U> + Clone,
        T::Err: std::error::Error + Send + Sync + 'static,
    {
        self.parse_multi_with(|strings| {
            let mut result = Vec::new();
            for x in strings {
                result.push(T::from_str(x)?.into_iter())
            }
            Ok(T::from_iter(result.into_iter().flatten()))
        })
    }
}

pub trait ConfigValues {
    fn get_config_value(config: &Config, key: &str) -> Result<Self, git2::Error>
    where
        Self: Sized;
}

impl ConfigValues for String {
    fn get_config_value(config: &Config, key: &str) -> Result<Self, git2::Error> {
        config.get_string(key)
    }
}

impl ConfigValues for Vec<String> {
    fn get_config_value(config: &Config, key: &str) -> Result<Self, git2::Error> {
        let mut result = Vec::new();
        for entry in &config.entries(Some(key))? {
            let entry = entry?;
            if let Some(value) = entry.value() {
                result.push(value.to_string());
            } else {
                warn!(
                    "non utf-8 config entry {}",
                    String::from_utf8_lossy(entry.name_bytes())
                );
            }
        }
        Ok(result)
    }
}

impl ConfigValues for bool {
    fn get_config_value(config: &Config, key: &str) -> Result<Self, git2::Error> {
        config.get_bool(key)
    }
}

fn config_not_exist(err: &git2::Error) -> bool {
    err.code() == ErrorCode::NotFound && err.class() == ErrorClass::Config
}

pub fn get_push_remote(config: &Config, branch: &str) -> Result<ConfigValue<String>> {
    if let Some(push_remote) = get(config, &format!("branch.{}.pushRemote", branch))
        .parse_with(|push_remote| Ok(push_remote.to_string()))?
    {
        return Ok(push_remote);
    }

    if let Some(push_default) =
        get(config, "remote.pushDefault").parse_with(|push_default| Ok(push_default.to_string()))?
    {
        return Ok(push_default);
    }

    get_remote(config, branch)
}

pub fn get_remote(config: &Config, branch: &str) -> Result<ConfigValue<String>> {
    Ok(get(config, &format!("branch.{}.remote", branch))
        .with_default(&String::from("origin"))
        .read()?
        .expect("has default"))
}

pub fn get_remote_raw(config: &Config, branch: &str) -> Result<Option<String>> {
    let key = format!("branch.{}.remote", branch);
    match config.get_string(&key) {
        Ok(merge) => Ok(Some(merge)),
        Err(err) if config_not_exist(&err) => Ok(None),
        Err(err) => Err(err.into()),
    }
}

pub fn get_merge(config: &Config, branch: &str) -> Result<Option<String>> {
    let key = format!("branch.{}.merge", branch);
    match config.get_string(&key) {
        Ok(merge) => Ok(Some(merge)),
        Err(err) if config_not_exist(&err) => Ok(None),
        Err(err) => Err(err.into()),
    }
}