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