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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use dirs::{config_dir, home_dir};
use gix::bstr::ByteSlice;
use gix::{self, config, Repository};
use gix_config::Source;
use linked_hash_map::LinkedHashMap;
use serde::{Deserialize, Serialize};
use serde_json::to_string_pretty;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

#[derive(Serialize, Deserialize, Debug)]
pub struct Coauthors {
    pub coauthors: LinkedHashMap<String, Author>,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Author {
    pub name: String,
    pub email: String,
}

// This mostly exists to make a mock for unit testing
pub trait FileActions {
    fn write(&self, path: &Path, s: String) -> Result<(), Box<dyn Error>>;
    fn read(&self, path: &Path) -> Result<String, Box<dyn Error>>;
}

pub struct GmFileActions();

impl FileActions for GmFileActions {
    fn write(&self, path: &Path, s: String) -> Result<(), Box<dyn Error>> {
        let path_display = path.display();
        if let Err(why) = fs::write(path, s.as_bytes()) {
            return Err(Box::from(format!(
                "couldn't write to {path_display}: {why}"
            )));
        }
        Ok(())
    }

    fn read(&self, path: &Path) -> Result<String, Box<dyn Error>> {
        let path_display = path.display();
        let mut file = match File::open(path) {
            Err(why) => return Err(Box::from(format!("couldn't open {path_display}: {why}"))),
            Ok(file) => file,
        };

        let mut s = String::new();
        match file.read_to_string(&mut s) {
            Err(why) => Err(Box::from(format!("couldn't read {path_display}: {why}"))),
            Ok(_) => Ok(s),
        }
    }
}

pub struct GitMob {
    pub file_actions: Box<dyn FileActions>,
}

impl Default for GitMob {
    fn default() -> Self {
        GitMob {
            file_actions: Box::from(GmFileActions()),
        }
    }
}

impl GitMob {
    pub fn get_repo(&self) -> Repository {
        gix::discover(".").unwrap_or_else(|_| {
            panic!("Not in a git repository");
        })
    }

    pub fn get_gitmessage_path(&self) -> PathBuf {
        self.get_repo().path().join(".gitmessage")
    }

    pub fn write_gitmessage(&self, s: String) {
        let gitmessage_path = self.get_gitmessage_path();

        // for git solo
        let s = if s.is_empty() { s } else { format!("\n\n{s}") };

        self.file_actions
            .write(&gitmessage_path, s)
            .unwrap_or_else(|error| {
                panic!(
                    "{}\nMake sure you are in a git repository when running this command",
                    error
                )
            });

        self.set_git_template();
    }

    pub fn write_coauthors(&self, coauthors: LinkedHashMap<String, Author>) {
        let coauthors_path = self.get_coauthors_path();
        let coauthors = Coauthors { coauthors };

        self.file_actions
            .write(&coauthors_path, to_string_pretty(&coauthors).unwrap())
            .unwrap();
    }

    fn set_git_template(&self) {
        let repo = self.get_repo();
        let repo_git_path = repo.path();
        let config_path = repo_git_path.join("config");

        self.set_git_template_config(&config_path);
    }

    fn set_git_template_config(&self, config_path: &PathBuf) {
        let mut config =
            gix_config::File::from_path_no_includes(config_path.to_path_buf(), Source::Local)
                .unwrap();

        let template = ".git/.gitmessage";

        // don't write to file if we don't have to
        if let Ok(value) = config.raw_value("commit", None, "template") {
            if value.as_bstr() == template {
                return;
            }
        }

        config
            .set_raw_value("commit", None, "template", template)
            .unwrap();

        let mut config_file = File::create(config_path).unwrap_or_else(|error| {
            panic!(
                "{}\nFailed to open {} for writing.",
                error,
                config_path.display()
            )
        });
        config.write_to(&mut config_file).unwrap_or_else(|error| {
            panic!("{}\nFailed to write to {}.", error, config_path.display())
        });
    }

    /// Returns the coauthors path
    ///
    /// This supports both xdg (prioritized) or if the config is in the home directory (like
    /// git-mob).
    pub fn get_coauthors_path(&self) -> PathBuf {
        let file_name = "git-coauthors";

        // most likely on fresh install after first use
        let mut coauthors_path = config_dir().unwrap();
        coauthors_path.push(file_name);
        if coauthors_path.exists() {
            return coauthors_path;
        }

        // else check home dir - if it doesn't exist (like a fresh install) use xdg instead
        let mut home_coauthors_path = home_dir().unwrap();
        home_coauthors_path.push(format!(".{file_name}"));
        if home_coauthors_path.exists() {
            home_coauthors_path
        } else {
            coauthors_path
        }
    }

    fn get_git_config(&self, cfg: &config::Snapshot, key: &str) -> String {
        match cfg.string(key) {
            Some(value) => value.to_string(),
            None => {
                // these errors should only really happen in ci
                println!("Warning: your git config \"{key}\" is missing!");
                String::from("")
            }
        }
    }

    pub fn get_git_user(&self) -> String {
        let repo = self.get_repo();
        let cfg = repo.config_snapshot();

        let user = self.get_git_config(&cfg, "user.name");
        let email = self.get_git_config(&cfg, "user.email");

        format!("{user} <{email}>")
    }

    pub fn get_gitmessage(&self) -> String {
        let gitmessage_path = self.get_gitmessage_path();
        self.file_actions
            .read(&gitmessage_path)
            .unwrap_or_else(|error| {
                panic!(
                    "{}\nMake sure you are in a git repository when running this command.",
                    error
                )
            })
    }

    pub fn get_formatted_gitmessage(&self) -> String {
        let git_user = self.get_git_user();

        let gitmessage = self.get_gitmessage();
        let gitmessage = gitmessage.trim();

        if gitmessage.is_empty() {
            git_user
        } else {
            format!("{git_user}\n{gitmessage}")
        }
    }

    pub fn get_all_coauthors(&self) -> LinkedHashMap<String, Author> {
        let coauthors_path = self.get_coauthors_path();
        let coauthors_path = coauthors_path.as_path();
        let coauthors_str = self
            .file_actions
            .read(coauthors_path)
            .unwrap_or_else(|_| String::from(""));

        if coauthors_str.is_empty() {
            return LinkedHashMap::new();
        }

        let coauthors: Coauthors = serde_json::from_str(coauthors_str.as_str()).unwrap();
        coauthors.coauthors
    }
}

pub mod test_utils {
    use super::*;
    use std::cell::RefCell;

    pub struct MockFileActions {
        s: RefCell<String>,
    }

    impl Default for test_utils::MockFileActions {
        fn default() -> Self {
            MockFileActions {
                s: RefCell::new(String::new()),
            }
        }
    }

    impl FileActions for MockFileActions {
        fn write(&self, _: &Path, s: String) -> Result<(), Box<dyn Error>> {
            self.s.replace(s);
            Ok(())
        }

        fn read(&self, _: &Path) -> Result<String, Box<dyn Error>> {
            Ok(self.s.borrow().clone())
        }
    }

    pub fn get_git_mob() -> GitMob {
        GitMob {
            file_actions: Box::from(MockFileActions::default()),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use serde_json::json;
    use tempfile::tempdir;
    use test_utils::get_git_mob;

    #[test]
    fn test_write_gitmessage() {
        let gm = get_git_mob();
        gm.write_gitmessage(String::from("test"));

        assert_eq!("\n\ntest", gm.get_gitmessage());
        assert_eq!(
            format!("{}\ntest", gm.get_git_user()),
            gm.get_formatted_gitmessage()
        );
    }

    #[test]
    fn test_get_all_coauthors() {
        let gm = get_git_mob();

        assert_eq!(LinkedHashMap::new(), gm.get_all_coauthors());

        let coauthors = json!({
            "coauthors": {
                "ab": {
                    "name": "A B",
                    "email": "ab@example.com"
                },
                "cd": {
                    "name": "C D",
                    "email": "cd@example.com"
                }
            }
        });

        gm.file_actions
            .write(Path::new(""), coauthors.to_string())
            .unwrap();

        let mut expected_coauthors = LinkedHashMap::new();
        expected_coauthors.insert(
            String::from("ab"),
            Author {
                name: String::from("A B"),
                email: String::from("ab@example.com"),
            },
        );
        expected_coauthors.insert(
            String::from("cd"),
            Author {
                name: String::from("C D"),
                email: String::from("cd@example.com"),
            },
        );

        assert_eq!(expected_coauthors, gm.get_all_coauthors());
    }

    #[test]
    fn test_set_git_template_config() {
        // make sure the config doesn't get wiped

        let default_config = "
[core]
\trepositoryformatversion = 0
\tfilemode = true
\tbare = false
\tlogallrefupdates = true
";
        let expected_config = "
[core]
\trepositoryformatversion = 0
\tfilemode = true
\tbare = false
\tlogallrefupdates = true
[commit]
\ttemplate = .git/.gitmessage
";

        let dir = tempdir().unwrap();
        let config_file_path = dir.path().join("config");
        {
            let mut config_file = File::create(&config_file_path).unwrap();
            config_file.write(default_config.as_bytes()).unwrap();
        }

        let gm = get_git_mob();
        gm.set_git_template_config(&config_file_path);

        let actual_config = fs::read_to_string(config_file_path).unwrap();
        assert_eq!(expected_config, actual_config);
    }

    #[test]
    fn test_replace_git_template_config() {
        let default_config = "
[core]
\trepositoryformatversion = 0
\tfilemode = true
\tbare = false
\tlogallrefupdates = true
[commit]
\ttemplate = .git/.somethingelse
";
        let expected_config = "
[core]
\trepositoryformatversion = 0
\tfilemode = true
\tbare = false
\tlogallrefupdates = true
[commit]
\ttemplate = .git/.gitmessage
";

        let dir = tempdir().unwrap();
        let config_file_path = dir.path().join("config");
        {
            let mut config_file = File::create(&config_file_path).unwrap();
            config_file.write(default_config.as_bytes()).unwrap();
        }

        let gm = get_git_mob();
        gm.set_git_template_config(&config_file_path);

        let actual_config = fs::read_to_string(config_file_path).unwrap();
        assert_eq!(expected_config, actual_config);
    }
}