git_prole/git/
head_state.rs

1use std::fmt::Display;
2
3use tracing::instrument;
4
5use super::CommitHash;
6use super::LocalBranchRef;
7
8/// Is `HEAD` detached?
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum HeadKind {
11    Detached(CommitHash),
12    Branch(LocalBranchRef),
13}
14
15impl HeadKind {
16    pub fn commitish(&self) -> &str {
17        match &self {
18            HeadKind::Detached(commit) => commit.as_str(),
19            HeadKind::Branch(ref_name) => ref_name.name(),
20        }
21    }
22
23    pub fn branch_name(&self) -> Option<&str> {
24        match &self {
25            HeadKind::Detached(_) => None,
26            // There's no way we can have a remote branch checked out.
27            HeadKind::Branch(branch) => Some(branch.branch_name()),
28        }
29    }
30
31    #[instrument(level = "trace")]
32    pub fn is_on_branch(&self, branch_name: &str) -> bool {
33        match self {
34            HeadKind::Detached(_) => false,
35            HeadKind::Branch(checked_out) => checked_out.branch_name() == branch_name,
36        }
37    }
38}
39
40impl Display for HeadKind {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            HeadKind::Detached(commit) => Display::fmt(commit, f),
44            HeadKind::Branch(ref_name) => Display::fmt(ref_name, f),
45        }
46    }
47}