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