git.rs

  1use anyhow::{anyhow, Context, Result};
  2use serde::{Deserialize, Serialize};
  3use std::ffi::OsStr;
  4use std::fmt;
  5use std::str::FromStr;
  6
  7pub use git2 as libgit;
  8pub use lazy_static::lazy_static;
  9
 10pub mod blame;
 11pub mod commit;
 12pub mod diff;
 13pub mod permalink;
 14pub mod repository;
 15
 16lazy_static! {
 17    pub static ref DOT_GIT: &'static OsStr = OsStr::new(".git");
 18    pub static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
 19}
 20
 21#[derive(Clone, Copy, Eq, Hash, PartialEq)]
 22pub struct Oid(libgit::Oid);
 23
 24impl Oid {
 25    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
 26        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
 27        Ok(Self(oid))
 28    }
 29
 30    pub fn as_bytes(&self) -> &[u8] {
 31        self.0.as_bytes()
 32    }
 33
 34    pub(crate) fn is_zero(&self) -> bool {
 35        self.0.is_zero()
 36    }
 37}
 38
 39impl FromStr for Oid {
 40    type Err = anyhow::Error;
 41
 42    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
 43        libgit::Oid::from_str(s)
 44            .map_err(|error| anyhow!("failed to parse git oid: {}", error))
 45            .map(|oid| Self(oid))
 46    }
 47}
 48
 49impl fmt::Debug for Oid {
 50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 51        fmt::Display::fmt(self, f)
 52    }
 53}
 54
 55impl fmt::Display for Oid {
 56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 57        self.0.fmt(f)
 58    }
 59}
 60
 61impl Serialize for Oid {
 62    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
 63    where
 64        S: serde::Serializer,
 65    {
 66        serializer.serialize_str(&self.0.to_string())
 67    }
 68}
 69
 70impl<'de> Deserialize<'de> for Oid {
 71    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 72    where
 73        D: serde::Deserializer<'de>,
 74    {
 75        let s = String::deserialize(deserializer)?;
 76        s.parse::<Oid>().map_err(serde::de::Error::custom)
 77    }
 78}
 79
 80impl Default for Oid {
 81    fn default() -> Self {
 82        Self(libgit::Oid::zero())
 83    }
 84}
 85
 86impl From<Oid> for u32 {
 87    fn from(oid: Oid) -> Self {
 88        let bytes = oid.0.as_bytes();
 89        debug_assert!(bytes.len() > 4);
 90
 91        let mut u32_bytes: [u8; 4] = [0; 4];
 92        u32_bytes.copy_from_slice(&bytes[..4]);
 93
 94        u32::from_ne_bytes(u32_bytes)
 95    }
 96}
 97
 98impl From<Oid> for usize {
 99    fn from(oid: Oid) -> Self {
100        let bytes = oid.0.as_bytes();
101        debug_assert!(bytes.len() > 8);
102
103        let mut u64_bytes: [u8; 8] = [0; 8];
104        u64_bytes.copy_from_slice(&bytes[..8]);
105
106        u64::from_ne_bytes(u64_bytes) as usize
107    }
108}