git.rs

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