use serde_json::Value;
use super::{Error, Manifest, ManifestObject, push_document};
use crate::release::{DeletePolicy, Hook, HookEvent, OutputLogPolicy};
const HOOK: &str = "helm.sh/hook";
const HOOK_WEIGHT: &str = "helm.sh/hook-weight";
const HOOK_DELETE_POLICY: &str = "helm.sh/hook-delete-policy";
const HOOK_OUTPUT_LOG_POLICY: &str = "helm.sh/hook-output-log-policy";
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
pub crds: Vec<ManifestObject>,
pub resources: Vec<ManifestObject>,
pub hooks: Vec<Hook>,
}
impl Rendered {
pub fn parse(output: &str) -> Result<Self, Error> {
let mut rendered = Self {
crds: Vec::new(),
resources: Vec::new(),
hooks: Vec::new(),
};
for object in Manifest::parse(output)?.objects {
if let Some(hook) = hook_of(&object) {
rendered.hooks.push(hook);
} else if object.source.as_deref().is_some_and(is_crd_path) {
rendered.crds.push(object);
} else {
rendered.resources.push(object);
}
}
Ok(rendered)
}
pub fn manifest(&self) -> Result<Manifest, Error> {
let mut text = String::new();
for object in self.crds.iter().chain(&self.resources) {
push_document(&mut text, object.source.as_deref(), &object.raw);
}
for hook in &self.hooks {
push_document(&mut text, Some(&hook.path), &hook.manifest);
}
Manifest::parse(&text)
}
}
fn hook_of(object: &ManifestObject) -> Option<Hook> {
let annotation = |key: &str| {
object
.value
.pointer("/metadata/annotations")
.and_then(|annotations| annotations.get(key))
.and_then(Value::as_str)
};
let events = annotation(HOOK)?
.split(',')
.map(|event| match event.trim().to_lowercase().as_str() {
"test-success" => Some(HookEvent::Test),
other => match HookEvent::from(other.to_owned()) {
HookEvent::Other(_) => None,
known => Some(known),
},
})
.collect::<Option<Vec<_>>>()?;
Some(Hook {
name: object.name().unwrap_or_default().to_owned(),
kind: object.kind().unwrap_or_default().to_owned(),
path: object.source.clone().unwrap_or_default(),
manifest: object.raw.clone(),
events,
weight: annotation(HOOK_WEIGHT)
.and_then(|weight| weight.parse().ok())
.unwrap_or(0),
delete_policies: policies(annotation(HOOK_DELETE_POLICY), DeletePolicy::from),
output_log_policies: policies(annotation(HOOK_OUTPUT_LOG_POLICY), OutputLogPolicy::from),
..Hook::default()
})
}
fn policies<T>(value: Option<&str>, convert: fn(String) -> T) -> Vec<T> {
value
.into_iter()
.flat_map(|value| value.split(','))
.map(|policy| convert(policy.trim().to_lowercase()))
.collect()
}
pub(super) fn is_crd_path(path: &str) -> bool {
let mut parts = path.split('/').skip(1).peekable();
while parts.next_if_eq(&"charts").is_some() {
if parts.next().is_none() {
return false;
}
}
parts.next() == Some("crds") && parts.peek().is_some()
}