forgejo-hook: impl Hook::try_from_event

Utilize X-Forgejo-Event http header to facilitate conversion.

Signed-off-by: pep <pep@bouah.net>
This commit is contained in:
pep 2025-05-03 23:53:38 +02:00
commit 222ed138e4
No known key found for this signature in database
GPG key ID: DEDA74AEECA9D0F2
3 changed files with 88 additions and 1 deletions

View file

@ -13,9 +13,12 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
mod error;
#[cfg(test)]
mod tests;
pub use error::Error;
use chrono::{DateTime, Utc};
use serde::Deserialize;
@ -295,6 +298,18 @@ impl From<Push> for Hook {
}
}
impl From<AddedBranch> for Hook {
fn from(branch: AddedBranch) -> Self {
Self::AddedBranch(branch)
}
}
impl From<RemovedBranch> for Hook {
fn from(branch: RemovedBranch) -> Self {
Self::RemovedBranch(branch)
}
}
impl From<Issue> for Hook {
fn from(issue: Issue) -> Self {
Self::Issue(issue)
@ -309,3 +324,27 @@ pub enum Hook {
RemovedBranch(RemovedBranch),
Issue(Issue),
}
/// Deserializes the payload into a struct
fn parse_payload<Output>(payload: &[u8]) -> Result<Output, serde_json::Error>
where
for<'a> Output: Deserialize<'a>,
{
serde_json::from_slice(payload)
}
impl Hook {
/// Generate the proper struct based on the event type provided by Forgejo. Generally found in
/// the "X-Forgejo-Event" http header, which is not the same as the "X-Forgejo-Event-Type"
/// header.
pub fn try_from_event(event: &str, payload: &[u8]) -> Result<Hook, Error> {
Ok(match event {
"create" => parse_payload::<AddedBranch>(payload).map(Hook::from),
"delete" => parse_payload::<RemovedBranch>(payload).map(Hook::from),
"push" => parse_payload::<Push>(payload).map(Hook::from),
"issues" => parse_payload::<Issue>(payload).map(Hook::from),
"issue_comment" => parse_payload::<Issue>(payload).map(Hook::from),
_ => return Err(Error::UnknownHookType),
}?)
}
}