radicle_git_metadata/commit/
headers.rs1use core::fmt;
2use std::borrow::Cow;
3
4const BEGIN_SSH: &str = "-----BEGIN SSH SIGNATURE-----\n";
5const BEGIN_PGP: &str = "-----BEGIN PGP SIGNATURE-----\n";
6
7#[derive(Clone, Debug, Default)]
11pub struct Headers(pub(super) Vec<(String, String)>);
12
13#[derive(Debug)]
15pub enum Signature<'a> {
16 Pgp(Cow<'a, str>),
18 Ssh(Cow<'a, str>),
20}
21
22impl<'a> Signature<'a> {
23 fn from_str(s: &'a str) -> Result<Self, UnknownScheme> {
24 if s.starts_with(BEGIN_SSH) {
25 Ok(Signature::Ssh(Cow::Borrowed(s)))
26 } else if s.starts_with(BEGIN_PGP) {
27 Ok(Signature::Pgp(Cow::Borrowed(s)))
28 } else {
29 Err(UnknownScheme)
30 }
31 }
32}
33
34impl fmt::Display for Signature<'_> {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 match self {
37 Signature::Pgp(pgp) => f.write_str(pgp.as_ref()),
38 Signature::Ssh(ssh) => f.write_str(ssh.as_ref()),
39 }
40 }
41}
42
43pub struct UnknownScheme;
44
45impl Headers {
46 pub fn new() -> Self {
47 Headers(Vec::new())
48 }
49
50 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
51 self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
52 }
53
54 pub fn values<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
55 self.iter()
56 .filter_map(move |(k, v)| (k == name).then_some(v))
57 }
58
59 pub fn signatures(&self) -> impl Iterator<Item = Signature<'_>> + '_ {
60 self.0.iter().filter_map(|(k, v)| {
61 if k == "gpgsig" {
62 Signature::from_str(v).ok()
63 } else {
64 None
65 }
66 })
67 }
68
69 pub fn push(&mut self, name: &str, value: &str) {
71 self.0.push((name.to_owned(), value.trim().to_owned()));
72 }
73}
74
75#[derive(Debug, thiserror::Error)]
76pub enum ParseError {
77 #[error("missing tree")]
78 MissingTree,
79 #[error("invalid tree")]
80 InvalidTree,
81 #[error("invalid format")]
82 InvalidFormat,
83 #[error("invalid parent")]
84 InvalidParent,
85 #[error("invalid header")]
86 InvalidHeader,
87 #[error("invalid author")]
88 InvalidAuthor,
89 #[error("missing author")]
90 MissingAuthor,
91 #[error("invalid committer")]
92 InvalidCommitter,
93 #[error("missing committer")]
94 MissingCommitter,
95}
96
97pub fn parse_commit_header<
98 Tree: std::str::FromStr,
99 Parent: std::str::FromStr,
100 Signature: std::str::FromStr,
101>(
102 header: &str,
103) -> Result<(Tree, Vec<Parent>, Signature, Signature, Headers), ParseError> {
104 let mut lines = header.lines();
105
106 let tree = match lines.next() {
107 Some(tree) => tree
108 .strip_prefix("tree ")
109 .map(Tree::from_str)
110 .transpose()
111 .map_err(|_| ParseError::InvalidTree)?
112 .ok_or(ParseError::MissingTree)?,
113 None => return Err(ParseError::MissingTree),
114 };
115
116 let mut parents = Vec::new();
117 let mut author: Option<Signature> = None;
118 let mut committer: Option<Signature> = None;
119 let mut headers = Headers::new();
120
121 for line in lines {
122 if let Some(rest) = line.strip_prefix(' ') {
124 let value: &mut String = headers
125 .0
126 .last_mut()
127 .map(|(_, v)| v)
128 .ok_or(ParseError::InvalidFormat)?;
129 value.push('\n');
130 value.push_str(rest);
131 continue;
132 }
133
134 if let Some((name, value)) = line.split_once(' ') {
135 match name {
136 "parent" => parents.push(
137 value
138 .parse::<Parent>()
139 .map_err(|_| ParseError::InvalidParent)?,
140 ),
141 "author" => {
142 author = Some(
143 value
144 .parse::<Signature>()
145 .map_err(|_| ParseError::InvalidAuthor)?,
146 )
147 }
148 "committer" => {
149 committer = Some(
150 value
151 .parse::<Signature>()
152 .map_err(|_| ParseError::InvalidCommitter)?,
153 )
154 }
155 _ => headers.push(name, value),
156 }
157 continue;
158 }
159 }
160
161 Ok((
162 tree,
163 parents,
164 author.ok_or(ParseError::MissingAuthor)?,
165 committer.ok_or(ParseError::MissingCommitter)?,
166 headers,
167 ))
168}