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