mure 0.2.5

A command line tool for creating and managing multiple repositories.
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::misc::command_wrapper::{CommandOutput as GitCommandOutput, Error, RawCommandOutput};
use crate::mure_error;
use git2::{BranchType, Repository};
use std::{path::Path, process::Command, string::FromUtf8Error};

#[derive(Debug, PartialEq, Eq)]
pub enum PullFastForwardStatus {
    AlreadyUpToDate,
    FastForwarded,
    Abort,
}

pub trait RepositorySupport {
    fn merged_branches(&self) -> Result<GitCommandOutput<Vec<String>>, Error>;
    fn is_clean(&self) -> Result<bool, mure_error::Error>;
    fn clone(url: &str, into: &Path) -> Result<GitCommandOutput<()>, Error>;
    fn has_unsaved(&self) -> Result<bool, mure_error::Error>;
    fn is_remote_exists(&self) -> Result<bool, mure_error::Error>;
    #[allow(dead_code)]
    fn get_current_branch(&self) -> Result<String, mure_error::Error>;
    fn pull_fast_forwarded(
        &self,
        remote: &str,
        branch: &str,
    ) -> Result<GitCommandOutput<PullFastForwardStatus>, Error>;
    fn fetch_prune(&self) -> Result<GitCommandOutput<()>, Error>;
    fn switch(&self, branch: &str) -> Result<GitCommandOutput<()>, Error>;
    fn delete_branch(&self, branch: &str) -> Result<GitCommandOutput<()>, Error>;
    fn command(&self, args: &[&str]) -> Result<RawCommandOutput, Error>;
    fn git_command_on_dir(args: &[&str], workdir: &Path) -> Result<RawCommandOutput, Error>;
}

impl RepositorySupport for Repository {
    fn merged_branches(&self) -> Result<GitCommandOutput<Vec<String>>, Error> {
        // git for-each-ref --format=%(refname:short) refs/heads/**/* --merged
        let raw = self.command(&[
            "for-each-ref",
            "--format=%(refname:short)",
            "refs/heads/**/*",
            "--merged",
        ])?;
        let branches = split_lines(&raw.stdout);
        Ok(GitCommandOutput {
            raw,
            interpreted_to: branches,
        })
    }
    fn is_clean(&self) -> Result<bool, mure_error::Error> {
        Ok(!self.has_unsaved()?)
    }

    fn clone(url: &str, into: &Path) -> Result<GitCommandOutput<()>, Error> {
        Repository::git_command_on_dir(&["clone", url], into)?.try_into()
    }

    fn has_unsaved(&self) -> Result<bool, mure_error::Error> {
        for entry in self.statuses(None)?.iter() {
            match entry.status() {
                git2::Status::WT_NEW
                | git2::Status::WT_MODIFIED
                | git2::Status::WT_DELETED
                | git2::Status::INDEX_NEW
                | git2::Status::INDEX_MODIFIED
                | git2::Status::INDEX_DELETED => {
                    return Ok(true);
                }
                _ => continue,
            }
        }
        Ok(false)
    }
    fn is_remote_exists(&self) -> Result<bool, mure_error::Error> {
        Ok(!self.remotes()?.is_empty())
    }

    fn get_current_branch(&self) -> Result<String, mure_error::Error> {
        if self.is_empty()? {
            return Err(mure_error::Error::from_str("repository is empty"));
        }
        let head = self.head()?;

        let Some(name) = head.shorthand() else {
            return Err(mure_error::Error::from_str("head is not a branch"));
        };
        let branch = self.find_branch(name, BranchType::Local)?;
        let Some(branch_name) = branch.name()? else {
            return Err(mure_error::Error::from_str("branch name is not found"));
        };
        Ok(branch_name.to_string())
    }

    fn pull_fast_forwarded(
        &self,
        remote: &str,
        branch: &str,
    ) -> Result<GitCommandOutput<PullFastForwardStatus>, Error> {
        let raw = self.command(&["pull", "--ff-only", remote, branch])?;
        let status = {
            let message = raw.stdout.as_str();
            if message.contains("Already up to date.") {
                PullFastForwardStatus::AlreadyUpToDate
            } else if message.contains("Fast-forward") {
                PullFastForwardStatus::FastForwarded
            } else {
                PullFastForwardStatus::Abort
            }
        };
        Ok(GitCommandOutput {
            raw,
            interpreted_to: status,
        })
    }

    fn fetch_prune(&self) -> Result<GitCommandOutput<()>, Error> {
        self.command(&["fetch", "--prune"])?.try_into()
    }

    fn switch(&self, branch: &str) -> Result<GitCommandOutput<()>, Error> {
        self.command(&["switch", branch])?.try_into()
    }

    fn delete_branch(&self, branch: &str) -> Result<GitCommandOutput<()>, Error> {
        self.command(&["branch", "-d", branch])?.try_into()
    }

    fn git_command_on_dir(args: &[&str], workdir: &Path) -> Result<RawCommandOutput, Error> {
        let output = Command::new("git").current_dir(workdir).args(args).output();
        match output {
            Ok(out) => Ok(RawCommandOutput::from(out)),
            Err(err) => Err(Error::FailedToExecute(err)),
        }
    }

    fn command(&self, args: &[&str]) -> Result<RawCommandOutput, Error> {
        let Some(workdir) = self.workdir() else {
            return Err(Error::FailedToExecute(std::io::Error::other(
                "workdir is not found",
            )));
        };
        Self::git_command_on_dir(args, workdir)
    }
}

impl From<git2::Error> for mure_error::Error {
    fn from(e: git2::Error) -> mure_error::Error {
        mure_error::Error::from_str(&e.to_string())
    }
}

impl From<FromUtf8Error> for mure_error::Error {
    fn from(e: FromUtf8Error) -> mure_error::Error {
        mure_error::Error::from_str(&e.to_string())
    }
}

fn split_lines(lines: &str) -> Vec<String> {
    lines
        .split('\n')
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_fixture::Fixture;
    use mktemp::Temp;

    #[test]
    fn test_split_lines() {
        let lines = "a\nb\nc\n";
        let expected = vec!["a", "b", "c"];
        assert_eq!(split_lines(lines), expected);
    }

    #[test]
    fn test_merged_branches() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        // git remote add origin
        let example_repo_url = "https://github.com/kitsuyui/kitsuyui.git";
        repo.remote_set_url("origin", example_repo_url)
            .expect("failed to set remote url");

        fixture.create_empty_commit("initial commit").unwrap();

        // create a first branch
        repo.command(&["switch", "-c", "main"])
            .expect("failed to switch to main branch");

        // create a new branch for testing
        let branch_name = "test";
        // git switch -c $branch_name
        repo.command(&["switch", "-c", branch_name])
            .expect("failed to switch to test branch");

        // switch to default branch
        repo.switch("main")
            .expect("failed to switch to main branch");

        // git merge $branch_name
        repo.command(&["merge", branch_name])
            .expect("failed to merge test branch");

        // now test_branch is same as default branch so it should be merged
        let Ok(GitCommandOutput {
            interpreted_to: merged_branches,
            ..
        }) = repo.merged_branches()
        else {
            unreachable!();
        };
        assert!(merged_branches.contains(&branch_name.to_string()));
    }

    #[test]
    fn test_is_empty() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        // repo is empty when just initialized
        assert!(repo.is_empty().unwrap());

        fixture.create_empty_commit("initial commit").unwrap();

        // repo is not empty after commit
        assert!(!repo.is_empty().unwrap());
    }

    #[test]
    fn test_is_remote_exists() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        // remote is not exists when initialized
        assert!(!repo.is_remote_exists().unwrap());

        // git remote add origin
        let example_repo_url = "https://github.com/kitsuyui/kitsuyui.git";
        repo.remote_set_url("origin", example_repo_url)
            .expect("failed to set remote url");

        // now remote must be set
        assert!(
            repo.is_remote_exists()
                .expect("failed to check remote exists")
        );
    }

    #[test]
    fn test_has_unsaved_and_is_clean() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        // repo is clean when initialized
        assert!(repo.is_clean().unwrap() && !repo.has_unsaved().unwrap());

        fixture.create_file("1.txt", "hello").unwrap();

        // repo is dirty because of file
        assert!(!repo.is_clean().unwrap() && repo.has_unsaved().unwrap());

        repo.command(&["add", "1.txt"])
            .expect("failed to add 1.txt");

        // staged but not committed file is dirty
        assert!(!repo.is_clean().unwrap() && repo.has_unsaved().unwrap(),);

        repo.command(&["commit", "-m", "add 1.txt"])
            .expect("failed to commit");

        // repo is clean because of committed file
        assert!(repo.is_clean().unwrap() && !repo.has_unsaved().unwrap());

        repo.command(&["switch", "-c", "feature"])
            .expect("failed to switch to feature branch");

        fixture.create_file("2.txt", "hello").unwrap();

        // repo is dirty because of file
        assert!(!repo.is_clean().unwrap() && repo.has_unsaved().unwrap());

        repo.command(&["add", "2.txt"])
            .expect("failed to add 2.txt");

        // staged but not committed file is dirty
        assert!(!repo.is_clean().unwrap() && repo.has_unsaved().unwrap());

        repo.command(&["commit", "-m", "add 2.txt"])
            .expect("failed to commit");

        // repo is clean because of committed file
        assert!(repo.is_clean().unwrap() && !repo.has_unsaved().unwrap());
    }

    #[test]
    fn test_pull_fast_forwarded() {
        let fixture1 = Fixture::create().unwrap();
        let repo1 = &fixture1.repo;

        let fixture2 = Fixture::create().unwrap();
        let repo2 = &fixture2.repo;

        fixture1.create_empty_commit("initial commit").unwrap();
        repo1
            .command(&["switch", "-c", "main"])
            .expect("failed to switch to main branch");

        let remote_path = format!("{}{}", repo1.workdir().unwrap().to_str().unwrap(), ".git");
        repo2
            .command(&["remote", "add", "origin", &remote_path])
            .expect("failed to add remote");
        repo2
            .command(&["checkout", "-b", "main", "origin/main"])
            .expect("failed to fetch");

        fixture1.create_empty_commit("second commit").unwrap();
        repo2.pull_fast_forwarded("origin", "main").unwrap();

        fixture1.create_empty_commit("commit A").unwrap();
        fixture2.create_empty_commit("commit B").unwrap();
        let result = repo2.pull_fast_forwarded("origin", "main").unwrap();
        assert_eq!(result.interpreted_to, PullFastForwardStatus::Abort);
    }

    #[test]
    fn test_get_current_branch() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        let Err(_) = repo.get_current_branch() else {
            unreachable!();
        };

        fixture.create_empty_commit("initial commit").unwrap();
        let Ok(branch_name) = repo.get_current_branch() else {
            unreachable!();
        };
        assert!(branch_name == "main" || branch_name == "master");
    }

    #[test]
    fn test_switch() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        // switch to main branch before first commit will fail
        assert!(repo.switch("main").is_err());
        fixture.create_empty_commit("initial commit").unwrap();

        repo.command(&["switch", "-c", "main"])
            .expect("failed to switch to main branch");

        repo.command(&["switch", "-c", "feature"])
            .expect("failed to switch to main branch");

        repo.switch("main")
            .expect("failed to switch to main branch");
    }

    #[test]
    fn test_delete_branch() {
        let fixture = Fixture::create().unwrap();
        let repo = &fixture.repo;

        fixture.create_empty_commit("initial commit").unwrap();
        repo.command(&["switch", "-c", "main"])
            .expect("failed to switch to main branch");

        repo.command(&["switch", "-c", "feature"])
            .expect("failed to switch to feature branch");

        repo.switch("main")
            .expect("failed to switch to main branch");

        let count_before = repo.branches(None).unwrap().count();

        repo.delete_branch("feature")
            .expect("failed to delete feature branch");

        let count_after = repo.branches(None).unwrap().count();

        // feature branch must be deleted
        // note: count_before may be 2 or 3 depending on git config --global init.defaultBranch
        assert_eq!(count_before - count_after, 1);

        // try to delete already deleted branch again
        let result = repo.delete_branch("feature");
        match result {
            Err(err) => {
                let Error::Raw(raw) = err else {
                    unreachable!();
                };
                // Error message depends on git version. Sometimes it has a period at the end of the sentence and sometimes not.
                // https://github.com/git/git/commit/12b99928c8fc85a2500f34ef4f492b427b13f088
                // TODO: more plumbing commands should be used to avoid this kind of problem (git branch -d is porcelain command)
                assert!(
                    raw.stderr == "error: branch 'feature' not found.\n"  // After v2.43.0
                        || raw.stderr == "error: branch 'feature' not found\n"
                )
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_clone() {
        let temp_dir = Temp::new_dir().expect("failed to create temp dir");
        let repo_url = "https://github.com/kitsuyui/mure";
        let result = <git2::Repository as RepositorySupport>::clone(repo_url, temp_dir.as_path());
        assert!(result.is_ok());

        let temp_dir = Temp::new_dir().expect("failed to create temp dir");
        let repo_url = "";
        let result = <git2::Repository as RepositorySupport>::clone(repo_url, temp_dir.as_path());

        match result {
            Err(err) => {
                let Error::Raw(raw) = err else {
                    unreachable!();
                };
                assert_eq!(raw.stderr, "fatal: repository '' does not exist\n");
            }
            _ => unreachable!(),
        }
    }
}