use serde::Serialize; /// What kind of ref this is, derived from its full name. /// /// Git has no type tag on a ref; the namespace *is* the type. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub enum RefKind { LocalBranch, RemoteBranch, Tag, /// Notes, stash, replace, bisect, and anything else a tool has invented. Other, } impl RefKind { pub(crate) fn from_full_name(full_name: &str) -> Self { if full_name.starts_with("refs/heads/") { Self::LocalBranch } else if full_name.starts_with("refs/remotes/") { Self::RemoteBranch } else if full_name.starts_with("refs/tags/") { Self::Tag } else { Self::Other } } } /// A single reference, flattened into something the UI can render directly. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct RefEntry { /// The full name, e.g. `refs/heads/main`. pub name: String, /// The name as a human would write it, e.g. `main`. pub shorthand: String, pub kind: RefKind, /// The object this ref points at, or `None` for a symbolic ref such as /// `refs/remotes/origin/HEAD`. Annotated tags report the tag object here, /// not the commit it wraps — peeling happens where it matters, in the walk. pub target: Option, } impl RefEntry { pub(crate) fn new(reference: &gix::Reference<'_>) -> Self { let name = reference.name().as_bstr().to_string(); let shorthand = reference.name().shorten().to_string(); let kind = RefKind::from_full_name(&name); let target = reference.try_id().map(|id| id.to_string()); Self { name, shorthand, kind, target, } } } #[cfg(test)] mod tests { use super::RefKind; #[test] fn classifies_refs_by_namespace() { assert_eq!( RefKind::from_full_name("refs/heads/main"), RefKind::LocalBranch ); assert_eq!( RefKind::from_full_name("refs/remotes/origin/main"), RefKind::RemoteBranch ); assert_eq!(RefKind::from_full_name("refs/tags/v1.0.0"), RefKind::Tag); assert_eq!( RefKind::from_full_name("refs/notes/commits"), RefKind::Other ); assert_eq!(RefKind::from_full_name("HEAD"), RefKind::Other); } #[test] fn branch_names_containing_slashes_stay_intact() { assert_eq!( RefKind::from_full_name("refs/heads/feature/graph"), RefKind::LocalBranch ); } }