aboutsummaryrefslogtreecommitdiff
path: root/apps/servers/octopus/supergit/src/commit.rs
blob: 14f2d9bafdc16802e61a8545cc2e912b11f0f503 (plain)
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
use crate::{FileTree, HashId};
use git2::Repository;
use std::sync::Arc;

/// Represent a commit on a repository
///
/// When creating a commit object, it is guaranteed that it exists in
/// the repository.
#[derive(Clone)]
pub struct Commit {
    pub id: HashId,
    repo: Arc<Repository>,
}

impl Commit {
    /// Create a commit object and check if it exists in the repo
    pub(crate) fn new(r: &Arc<Repository>, id: HashId) -> Option<Self> {
        r.find_commit(id.to_oid()).ok().map(|_| Self {
            id,
            repo: Arc::clone(r),
        })
    }

    /// Get a utf-8 string representation of the commit ID
    pub fn id_str(&self) -> String {
        self.id.to_string()
    }

    /// Get the summary line as a utf-7 string
    pub fn summary(&self) -> String {
        self.find().summary().unwrap().into()
    }

    /// Get the number of parents
    pub fn parent_count(&self) -> usize {
        self.repo
            .find_commit(self.id.to_oid())
            .unwrap()
            .parent_count()
    }

    /// Return the first parent, if it exists
    pub fn first_parent(&self) -> Option<Self> {
        self.find()
            .parent(0)
            .ok()
            .and_then(|c| Self::new(&self.repo, c.id().into()))
    }

    /// Get a specific parent, if it exists
    pub fn parent(&self, num: usize) -> Option<Self> {
        self.find()
            .parent(num)
            .ok()
            .and_then(|c| Self::new(&self.repo, c.id().into()))
    }

    pub fn parents(&self) -> Vec<Commit> {
        self.find()
            .parents()
            .map(|c| Self::new(&self.repo, c.id().into()).unwrap())
            .collect()
    }

    /// Get the file tree for this commit
    pub fn get_tree(&self) -> Arc<FileTree> {
        FileTree::new(&self.repo, self.id.clone())
    }

    fn find(&self) -> git2::Commit {
        self.repo.find_commit(self.id.to_oid()).unwrap()
    }
}