git-snip 0.2.0

Snip local Git branches that do not exist on the remote.
Documentation
use std::fmt::{Debug, Display, Formatter, Result};

/// A reference to a Git object.
pub struct Reference<'a>(git2::Reference<'a>);

impl Reference<'_> {
    /// Return the full name of the reference, e.g. "refs/heads/main".
    pub fn name(&self) -> Option<&str> {
        self.0.name()
    }

    /// Return the shorthand name of the reference, e.g. "main" for "refs/heads/main".
    pub fn shorthand(&self) -> Option<&str> {
        self.0.shorthand()
    }
}

impl Debug for Reference<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Reference")
            .field("name", &self.name())
            .finish()
    }
}

impl Display for Reference<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self.shorthand() {
            Some(name) => write!(f, "{}", name),
            None => write!(f, "<unnamed>"),
        }
    }
}

impl<'a> From<git2::Reference<'a>> for Reference<'a> {
    fn from(reference: git2::Reference<'a>) -> Self {
        Reference(reference)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utilities;

    #[test]
    fn test_name() {
        // GIVEN a mock repository with a HEAD reference
        let (_tempdir, repo) = test_utilities::create_mock_repo();
        let reference = repo.head().unwrap();

        // WHEN we get the name of the reference
        let binding = Reference::from(reference);
        let name = binding.name().unwrap();

        // THEN the name should be the full reference name
        assert_eq!(name, "refs/heads/main");
    }

    #[test]
    fn test_shorthand() {
        // GIVEN a mock repository with a HEAD reference
        let (_tempdir, repo) = test_utilities::create_mock_repo();
        let reference = repo.head().unwrap();

        // WHEN we get the shorthand of the reference
        let binding = Reference::from(reference);
        let shorthand = binding.shorthand().unwrap();

        // THEN the shorthand should be the name without the prefix
        assert_eq!(shorthand, "main");
    }

    #[test]
    fn test_display() {
        // GIVEN a mock repository with a HEAD reference
        let (_tempdir, repo) = test_utilities::create_mock_repo();
        let reference = repo.head().unwrap();

        // WHEN we create a Reference and format it
        let binding = Reference::from(reference);

        // THEN the display should match the short name
        assert_eq!(format!("{}", binding), "main");
    }
}