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
use std::fmt;
use serde::{Deserialize, Serialize};
use radicle_surf::vcs::git::{self, BranchType, Browser};
use crate::error::Error;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Branch(pub(crate) String);
impl From<String> for Branch {
fn from(name: String) -> Self {
Self(name)
}
}
impl fmt::Display for Branch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
pub fn branches(
browser: &Browser<'_>,
branch_type: Option<BranchType>,
) -> Result<Vec<Branch>, Error> {
let mut branches = browser
.list_branches(branch_type)?
.into_iter()
.map(|b| Branch(b.name.name().to_string()))
.collect::<Vec<Branch>>();
branches.sort();
Ok(branches)
}
#[derive(Deserialize, Serialize)]
pub struct LocalState {
branches: Vec<Branch>,
}
pub fn local_state(repo_path: &str, default_branch: &str) -> Result<LocalState, Error> {
let repo = git2::Repository::open(repo_path).map_err(git::error::Error::from)?;
let first_branch = repo
.branches(Some(git2::BranchType::Local))
.map_err(git::error::Error::from)?
.filter_map(|branch_result| {
let (branch, _) = branch_result.ok()?;
let name = branch.name().ok()?;
name.map(String::from)
})
.min()
.ok_or(Error::NoBranches)?;
let repo = git::Repository::new(repo_path)?;
let browser = match Browser::new(&repo, git::Branch::local(default_branch)) {
Ok(browser) => browser,
Err(_) => Browser::new(&repo, git::Branch::local(&first_branch))?,
};
let mut branches = browser
.list_branches(Some(BranchType::Local))?
.into_iter()
.map(|b| Branch(b.name.name().to_string()))
.collect::<Vec<Branch>>();
branches.sort();
Ok(LocalState { branches })
}