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