git/
reference.rs

1use crate::reference_kind::ReferenceKind;
2
3/// Represents a pointer to an object in Git.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Reference {
6	/// The object id
7	pub(crate) hash: String,
8	/// The reference full name
9	pub(crate) name: String,
10	/// The reference shorthand name
11	pub(crate) shorthand: String,
12	/// The kind of reference
13	pub(crate) kind: ReferenceKind,
14}
15
16impl Reference {
17	/// Get the oid of the reference
18	#[must_use]
19	#[inline]
20	pub fn hash(&self) -> &str {
21		self.hash.as_str()
22	}
23
24	/// Get the name of the reference
25	#[must_use]
26	#[inline]
27	pub fn name(&self) -> &str {
28		self.name.as_str()
29	}
30
31	/// Get the shorthand name of the reference
32	#[must_use]
33	#[inline]
34	pub fn shortname(&self) -> &str {
35		self.shorthand.as_str()
36	}
37
38	/// Get the kind of the reference
39	#[must_use]
40	#[inline]
41	pub const fn kind(&self) -> ReferenceKind {
42		self.kind
43	}
44
45	pub(crate) fn from(reference: &git2::Reference<'_>) -> Self {
46		let oid = reference
47			.peel(git2::ObjectType::Any)
48			.expect("Reference peel failed")
49			.id();
50		let kind = ReferenceKind::from(reference);
51		let name = String::from(reference.name().unwrap_or("InvalidRef"));
52		let shorthand = String::from(reference.shorthand().unwrap_or("InvalidRef"));
53
54		Self {
55			hash: format!("{oid}"),
56			name,
57			shorthand,
58			kind,
59		}
60	}
61}
62
63#[cfg(test)]
64mod tests {
65	use super::*;
66	use crate::testutil::{head_id, with_temp_repository};
67
68	#[test]
69	fn test() {
70		with_temp_repository(|repository| {
71			let oid = head_id(&repository, "main");
72			let reference = repository.find_reference("refs/heads/main").unwrap();
73			assert_eq!(reference.hash(), format!("{oid}"));
74			assert_eq!(reference.name(), "refs/heads/main");
75			assert_eq!(reference.shortname(), "main");
76			assert_eq!(reference.kind(), ReferenceKind::Branch);
77		});
78	}
79}