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
use std::{collections::BTreeMap, convert::TryFrom, path::PathBuf};

use git2::{Config, Repository};
use miette::{IntoDiagnostic, Report, Result};

use crate::{
    external::Vcs,
    mit::{Author, Authors},
};

/// Libgit2 vcs implementation
#[allow(missing_debug_implementations)]
pub struct Git2 {
    config_snapshot: git2::Config,
    config_live: git2::Config,
}

impl Git2 {
    /// # Panics
    ///
    /// Will panic if it can't open the git config in snapshot mode
    #[must_use]
    pub fn new(mut config: git2::Config) -> Self {
        Self {
            config_snapshot: config.snapshot().unwrap(),
            config_live: config,
        }
    }

    fn config_defined(&self, lint_name: &str) -> Result<bool> {
        Ok(self
            .config_snapshot
            .entries(Some(lint_name))
            .into_diagnostic()?
            .next()
            .is_some())
    }
}

impl Vcs for Git2 {
    fn entries(&self, glob: Option<&str>) -> Result<Vec<String>> {
        let mut entries = vec![];
        let mut item = self.config_snapshot.entries(glob).into_diagnostic()?;
        while let Some(entry) = item.next() {
            if let Some(name) = entry.into_diagnostic()?.name() {
                entries.push(name.into());
            }
        }

        Ok(entries)
    }

    fn get_bool(&self, name: &str) -> Result<Option<bool>> {
        if self.config_defined(name)? {
            Ok(Some(self.config_snapshot.get_bool(name).into_diagnostic()?))
        } else {
            Ok(None)
        }
    }

    fn get_str(&self, name: &str) -> Result<Option<&str>> {
        let defined = self.config_defined(name)?;

        if defined {
            self.config_snapshot
                .get_str(name)
                .map(Some)
                .into_diagnostic()
        } else {
            Ok(None)
        }
    }

    fn get_i64(&self, name: &str) -> Result<Option<i64>> {
        let defined = self.config_defined(name)?;

        if defined {
            self.config_snapshot
                .get_i64(name)
                .map(Some)
                .into_diagnostic()
        } else {
            Ok(None)
        }
    }

    fn set_str(&mut self, name: &str, value: &str) -> Result<()> {
        self.config_live.set_str(name, value).into_diagnostic()?;

        let config = self.config_live.snapshot().into_diagnostic()?;

        self.config_snapshot = config;

        Ok(())
    }

    fn set_i64(&mut self, name: &str, value: i64) -> Result<()> {
        self.config_live.set_i64(name, value).into_diagnostic()?;

        let config = self.config_live.snapshot().into_diagnostic()?;
        self.config_snapshot = config;

        Ok(())
    }

    fn remove(&mut self, name: &str) -> Result<()> {
        self.config_live.remove(name).into_diagnostic()?;

        let config = self.config_live.snapshot().into_diagnostic()?;
        self.config_snapshot = config;

        Ok(())
    }
}

impl TryFrom<PathBuf> for Git2 {
    type Error = Report;

    fn try_from(current_dir: PathBuf) -> Result<Self, Self::Error> {
        Repository::discover(current_dir)
            .and_then(|x| x.config())
            .or_else(|_| Config::open_default())
            .map(Self::new)
            .into_diagnostic()
    }
}

impl TryFrom<&'_ Git2> for Authors<'_> {
    type Error = Report;

    fn try_from(vcs: &'_ Git2) -> Result<Self, Self::Error> {
        let raw_entries: BTreeMap<String, BTreeMap<String, String>> = vcs
            .entries(Some("mit.author.config.*"))?
            .iter()
            .map(|key| (key, key.trim_start_matches("mit.author.config.")))
            .map(|(key, parts)| (key, parts.split_terminator('.').collect::<Vec<_>>()))
            .try_fold::<_, _, Result<_, Self::Error>>(
                BTreeMap::new(),
                |mut acc, (key, fragments)| {
                    let mut fragment_iterator = fragments.iter();
                    let initial = String::from(*fragment_iterator.next().unwrap());
                    let part = String::from(*fragment_iterator.next().unwrap());

                    let mut existing: BTreeMap<String, String> =
                        acc.get(&initial).cloned().unwrap_or_default();
                    existing.insert(part, String::from(vcs.get_str(key)?.unwrap()));

                    acc.insert(initial, existing);
                    Ok(acc)
                },
            )?;

        Ok(Self::new(
            raw_entries
                .iter()
                .filter_map(|(key, cfg)| {
                    let name = cfg.get("name").cloned();
                    let email = cfg.get("email").cloned();
                    let signingkey: Option<String> = cfg.get("signingkey").cloned();

                    match (name, email, signingkey) {
                        (Some(name), Some(email), None) => {
                            Some((key, Author::new(name.into(), email.into(), None)))
                        }
                        (Some(name), Some(email), Some(signingkey)) => Some((
                            key,
                            Author::new(name.into(), email.into(), Some(signingkey.into())),
                        )),
                        _ => None,
                    }
                })
                .fold(
                    BTreeMap::new(),
                    |mut acc: BTreeMap<String, Author<'_>>, (key, value): (&String, Author<'_>)| {
                        acc.insert(key.clone(), value);
                        acc
                    },
                ),
        ))
    }
}