radicle_cob/
object.rs

1// Copyright © 2022 The Radicle Link Contributors
2
3use std::{convert::TryFrom as _, fmt, ops::Deref, str::FromStr};
4
5use git_ext::ref_format::{Component, RefString};
6use git_ext::Oid;
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10pub mod collaboration;
11pub use collaboration::{
12    create, get, info, list, parse_refstr, remove, update, CollaborativeObject, Create, Evaluate,
13    Update, Updated,
14};
15
16pub mod storage;
17pub use storage::{Commit, Objects, Reference, Storage};
18
19#[derive(Debug, Error)]
20pub enum ParseObjectId {
21    #[error(transparent)]
22    Git(#[from] git2::Error),
23}
24
25/// The id of an object
26#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
27#[serde(transparent)]
28pub struct ObjectId(Oid);
29
30impl FromStr for ObjectId {
31    type Err = ParseObjectId;
32
33    fn from_str(s: &str) -> Result<Self, Self::Err> {
34        let oid = Oid::from_str(s)?;
35        Ok(ObjectId(oid))
36    }
37}
38
39impl From<Oid> for ObjectId {
40    fn from(oid: Oid) -> Self {
41        ObjectId(oid)
42    }
43}
44
45impl From<&Oid> for ObjectId {
46    fn from(oid: &Oid) -> Self {
47        (*oid).into()
48    }
49}
50
51impl From<git2::Oid> for ObjectId {
52    fn from(oid: git2::Oid) -> Self {
53        Oid::from(oid).into()
54    }
55}
56
57impl From<&git2::Oid> for ObjectId {
58    fn from(oid: &git2::Oid) -> Self {
59        ObjectId(Oid::from(*oid))
60    }
61}
62
63impl Deref for ObjectId {
64    type Target = Oid;
65
66    fn deref(&self) -> &Self::Target {
67        &self.0
68    }
69}
70
71impl fmt::Display for ObjectId {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        write!(f, "{}", self.0)
74    }
75}
76
77impl From<&ObjectId> for Component<'_> {
78    fn from(id: &ObjectId) -> Self {
79        let refstr = RefString::from(*id);
80
81        Component::from_refstr(refstr)
82            .expect("collaborative object id's are valid refname components")
83    }
84}
85
86impl From<ObjectId> for RefString {
87    fn from(id: ObjectId) -> Self {
88        RefString::try_from(id.0.to_string())
89            .expect("collaborative object id's are valid ref strings")
90    }
91}
92
93#[cfg(test)]
94#[allow(clippy::unwrap_used)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn test_serde() {
100        let id = ObjectId::from_str("3ad84420bd882f983c2f9b605e7a68f5bdf95f5c").unwrap();
101
102        assert_eq!(
103            serde_json::to_string(&id).unwrap(),
104            serde_json::to_string(&id.0).unwrap()
105        );
106    }
107}