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