radicle_git_ext/commit/
headers.rs

1use 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/// A collection of headers stored in a [`crate::commit::Commit`].
8///
9/// Note: these do not include `tree`, `parent`, `author`, and `committer`.
10#[derive(Clone, Debug, Default)]
11pub struct Headers(pub(super) Vec<(String, String)>);
12
13/// A `gpgsig` signature stored in a [`crate::commit::Commit`].
14#[derive(Debug)]
15pub enum Signature<'a> {
16    /// A PGP signature, i.e. starts with `-----BEGIN PGP SIGNATURE-----`.
17    Pgp(Cow<'a, str>),
18    /// A SSH signature, i.e. starts with `-----BEGIN SSH SIGNATURE-----`.
19    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    /// Push a header to the end of the headers section.
70    pub fn push(&mut self, name: &str, value: &str) {
71        self.0.push((name.to_owned(), value.trim().to_owned()));
72    }
73}