1use git_ext::commit::trailers::{OwnedTrailer, Token, Trailer};
4use std::ops::Deref as _;
5
6pub mod error {
7 use thiserror::Error;
8
9 #[derive(Debug, Error)]
10 pub enum InvalidResourceTrailer {
11 #[error("found wrong token for Rad-Resource tailer")]
12 WrongToken,
13 #[error("no value for Rad-Resource")]
14 NoValue,
15 #[error("invalid git OID")]
16 InvalidOid,
17 }
18}
19
20pub enum CommitTrailer {
22 Resource(git2::Oid),
24 Related(git2::Oid),
26}
27
28impl CommitTrailer {
29 pub fn oid(&self) -> git2::Oid {
30 match self {
31 Self::Resource(oid) => *oid,
32 Self::Related(oid) => *oid,
33 }
34 }
35}
36
37impl TryFrom<&Trailer<'_>> for CommitTrailer {
38 type Error = error::InvalidResourceTrailer;
39
40 fn try_from(Trailer { value, token }: &Trailer<'_>) -> Result<Self, Self::Error> {
41 let ext_oid =
42 git_ext::Oid::try_from(value.as_ref()).map_err(|_| Self::Error::InvalidOid)?;
43 if token.deref() == "Rad-Resource" {
44 Ok(CommitTrailer::Resource(ext_oid.into()))
45 } else if token.deref() == "Rad-Related" {
46 Ok(CommitTrailer::Related(ext_oid.into()))
47 } else {
48 Err(Self::Error::WrongToken)
49 }
50 }
51}
52
53impl TryFrom<&OwnedTrailer> for CommitTrailer {
54 type Error = error::InvalidResourceTrailer;
55
56 fn try_from(trailer: &OwnedTrailer) -> Result<Self, Self::Error> {
57 Self::try_from(&Trailer::from(trailer))
58 }
59}
60
61impl From<CommitTrailer> for Trailer<'_> {
62 fn from(t: CommitTrailer) -> Self {
63 match t {
64 #[allow(clippy::unwrap_used)]
65 CommitTrailer::Related(oid) => {
66 Trailer {
67 token: Token::try_from("Rad-Related").unwrap(),
69 value: oid.to_string().into(),
70 }
71 }
72 #[allow(clippy::unwrap_used)]
73 CommitTrailer::Resource(oid) => {
74 Trailer {
75 token: Token::try_from("Rad-Resource").unwrap(),
77 value: oid.to_string().into(),
78 }
79 }
80 }
81 }
82}
83
84impl From<CommitTrailer> for OwnedTrailer {
85 fn from(containing: CommitTrailer) -> Self {
86 Trailer::from(containing).to_owned()
87 }
88}