index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / git / branch.rs
-rw-r--r-- blob a23f9a5a045a14fb5f79a2d73a9016cb8ad5eeb9 2346 bytes (plain)
1
use crate::{git::GitSignature, prelude::*, time::Time};
2
use gix::Reference;
3
4
pub struct Branch<'repo> {
5
    pub name: String,
6
    pub last_commit: Commit<'repo>,
7
    pub author: GitSignature,
8
    pub time: Time,
9
    pub gix: Reference<'repo>,
10
}
11
12
impl<'repo> Branch<'repo> {
13
    pub fn from_gix(mut reference: Reference<'repo>) -> Result<Branch<'repo>, Error> {
14
        let commit = reference.peel_to_commit()?;
15
        let author = GitSignature::from_gix(commit.author()?);
16
        let time = Time::new(commit.time()?);
17
        let last_commit = Commit::from_gix(commit)?;
18
19
        Ok(Branch {
20
            name: reference.name().shorten().to_string(),
21
            last_commit,
22
            author,
23
            time,
24
            gix: reference,
25
        })
26
    }
27
28
    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
29
        Ok(repo.head_branch_name()? == self.name)
30
    }
31
}
32
33
impl Repository {
34
    pub fn head_branch_name(&self) -> Result<String, Error> {
35
        let gix_repo = self.gix();
36
        let head = gix_repo.head()?;
37
        let branch_name = match head.referent_name() {
38
            Some(b) => b.shorten().to_string(),
39
            None => head.name().shorten().to_string(),
40
        };
41
        Ok(branch_name)
42
    }
43
44
    pub fn branches<'repo>(
45
        &self,
46
        gix_repo: &'repo gix::Repository,
47
        offset: usize,
48
        limit: usize,
49
    ) -> Result<(Vec<Branch<'repo>>, bool), Error> {
50
        let references = gix_repo.references()?;
51
        let gix_branches = references.local_branches()?;
52
53
        let mut branches: Vec<Branch> = Vec::new();
54
        let mut has_next = false;
55
56
        for (i, branch) in gix_branches.skip(offset).enumerate() {
57
            if i >= limit {
58
                has_next = true;
59
                break;
60
            }
61
62
            let branch = branch?;
63
            branches.push(Branch::from_gix(branch)?);
64
        }
65
        Ok((branches, has_next))
66
    }
67
68
    pub fn branch_names(&self) -> Result<Vec<String>, Error> {
69
        let gix_repo = self.gix();
70
        let references = gix_repo.references()?;
71
        let gix_branches = references.local_branches()?;
72
73
        let mut names: Vec<String> = Vec::new();
74
75
        for branch in gix_branches {
76
            let branch = branch?;
77
            names.push(branch.name().shorten().to_string());
78
        }
79
        Ok(names)
80
    }
81
}