use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hook {
PreResolve,
PostResolve,
PreBuild,
PostBuild,
PrePublish,
}
impl Hook {
pub fn function_name(&self) -> &'static str {
match self {
Hook::PreResolve => "pre_resolve",
Hook::PostResolve => "post_resolve",
Hook::PreBuild => "pre_build",
Hook::PostBuild => "post_build",
Hook::PrePublish => "pre_publish",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookContext {
pub project_root: String,
pub operation: String,
#[serde(default)]
pub data: serde_json::Value,
}
impl HookContext {
pub fn new(project_root: impl Into<String>, operation: impl Into<String>) -> Self {
Self {
project_root: project_root.into(),
operation: operation.into(),
data: serde_json::Value::Null,
}
}
pub fn with_data(mut self, data: serde_json::Value) -> Self {
self.data = data;
self
}
pub fn to_bytes(&self) -> Vec<u8> {
serde_json::to_vec(self).unwrap_or_default()
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HookResult {
pub continue_operation: bool,
#[serde(default)]
pub messages: Vec<String>,
#[serde(default)]
pub data: Option<serde_json::Value>,
}
impl HookResult {
pub fn ok() -> Self {
Self {
continue_operation: true,
messages: vec![],
data: None,
}
}
pub fn stop(message: impl Into<String>) -> Self {
Self {
continue_operation: false,
messages: vec![message.into()],
data: None,
}
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
pub fn merge(&mut self, other: HookResult) {
self.continue_operation = self.continue_operation && other.continue_operation;
self.messages.extend(other.messages);
if other.data.is_some() {
self.data = other.data;
}
}
}