use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
use serde_json::Value;
use super::{DiffOptions, ObjectId};
use crate::manifest::{Error, Manifest};
const HOOK: &str = "helm.sh/hook";
const RESOURCE_POLICY: &str = "helm.sh/resource-policy";
const CLUSTER_SCOPED: [(&str, &str); 28] = [
("", "Namespace"),
("", "Node"),
("", "PersistentVolume"),
("", "ComponentStatus"),
("apiextensions.k8s.io", "CustomResourceDefinition"),
("apiregistration.k8s.io", "APIService"),
("storage.k8s.io", "StorageClass"),
("storage.k8s.io", "CSIDriver"),
("storage.k8s.io", "CSINode"),
("storage.k8s.io", "VolumeAttachment"),
("scheduling.k8s.io", "PriorityClass"),
("node.k8s.io", "RuntimeClass"),
("networking.k8s.io", "IngressClass"),
("rbac.authorization.k8s.io", "ClusterRole"),
("rbac.authorization.k8s.io", "ClusterRoleBinding"),
(
"admissionregistration.k8s.io",
"MutatingWebhookConfiguration",
),
(
"admissionregistration.k8s.io",
"ValidatingWebhookConfiguration",
),
("admissionregistration.k8s.io", "ValidatingAdmissionPolicy"),
(
"admissionregistration.k8s.io",
"ValidatingAdmissionPolicyBinding",
),
("admissionregistration.k8s.io", "MutatingAdmissionPolicy"),
(
"admissionregistration.k8s.io",
"MutatingAdmissionPolicyBinding",
),
("certificates.k8s.io", "CertificateSigningRequest"),
("flowcontrol.apiserver.k8s.io", "FlowSchema"),
("flowcontrol.apiserver.k8s.io", "PriorityLevelConfiguration"),
("policy", "PodSecurityPolicy"),
("authentication.k8s.io", "TokenReview"),
("authorization.k8s.io", "SubjectAccessReview"),
("authorization.k8s.io", "SelfSubjectAccessReview"),
];
#[derive(Clone)]
pub(super) struct View {
pub text: String,
pub value: Value,
}
pub(super) struct Object {
pub id: ObjectId,
pub view: View,
pub keep: bool,
}
impl View {
fn comment(&self) -> &str {
match self.text.split_once('\n') {
Some((first, _)) if first.starts_with('#') => &self.text[..=first.len()],
_ => "",
}
}
pub fn render<T: serde::Serialize>(&mut self, value: &T) -> Result<(), Error> {
self.text = format!("{}{}", self.comment(), yaml(value)?);
Ok(())
}
}
pub(super) fn yaml<T: serde::Serialize>(value: &T) -> Result<String, Error> {
serde_norway::to_string(value).map_err(|error| Error::Serialize(error.to_string()))
}
fn annotation<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
value.pointer("/metadata/annotations")?.get(key)?.as_str()
}
fn identify(value: &Value, namespace: &str) -> ObjectId {
let text = |pointer: &str| {
value
.pointer(pointer)
.and_then(Value::as_str)
.unwrap_or_default()
};
let group = text("/apiVersion")
.rsplit_once('/')
.map_or("", |(group, _)| group);
let kind = text("/kind");
let explicit = text("/metadata/namespace");
let namespace = if CLUSTER_SCOPED.contains(&(group, kind)) {
None
} else {
Some(if explicit.is_empty() {
namespace
} else {
explicit
})
.filter(|name| !name.is_empty())
};
ObjectId {
group: group.to_owned(),
kind: kind.to_owned(),
namespace: namespace.map(str::to_owned),
name: text("/metadata/name").to_owned(),
}
}
fn strip_empty_metadata_keys(text: &str, value: &Value) -> String {
let empty = |key: &str| match value.pointer("/metadata")?.get(key)? {
Value::Null => Some(()),
Value::Object(map) if map.is_empty() => Some(()),
_ => None,
};
let keys: Vec<&str> = ["labels", "annotations"]
.into_iter()
.filter(|key| empty(key).is_some())
.collect();
let lines: Vec<&str> = text.split('\n').collect();
let Some(start) = lines.iter().position(|line| is_metadata_line(line)) else {
return text.to_owned();
};
let indent = lines[start + 1..]
.iter()
.find(|line| is_content(line))
.map_or(0, |line| {
line.len() - line.trim_start_matches([' ', '\t']).len()
});
if keys.is_empty() || indent == 0 {
return text.to_owned();
}
let end = lines[start + 1..]
.iter()
.position(|line| is_content(line) && !line.starts_with([' ', '\t']))
.map_or(lines.len(), |offset| start + 1 + offset);
lines
.iter()
.enumerate()
.filter(|(position, line)| {
!(*position > start
&& *position < end
&& keys.iter().any(|key| is_empty_key_line(line, indent, key)))
})
.map(|(_, line)| *line)
.collect::<Vec<_>>()
.join("\n")
}
fn is_content(line: &str) -> bool {
let line = line.trim();
!line.is_empty() && !line.starts_with('#')
}
fn is_metadata_line(line: &str) -> bool {
line.strip_prefix("metadata:").is_some_and(|rest| {
let rest = rest.trim_start_matches([' ', '\t']);
rest.is_empty() || rest.starts_with('#')
})
}
fn is_empty_key_line(line: &str, indent: usize, key: &str) -> bool {
let Some(rest) = line
.strip_prefix(&" ".repeat(indent))
.and_then(|rest| rest.strip_prefix(key))
.and_then(|rest| rest.strip_prefix(':'))
else {
return false;
};
let rest = rest.trim_start_matches([' ', '\t']);
let rest = rest
.strip_prefix("{}")
.map_or(rest, |rest| rest.trim_start_matches([' ', '\t']));
rest.is_empty() || rest.starts_with('#')
}
fn strip_empty_metadata_values(value: &mut Value) {
let Some(Value::Object(metadata)) = value.get_mut("metadata") else {
return;
};
for key in ["labels", "annotations"] {
if metadata.get(key).is_some_and(|entry| {
entry.is_null() || entry.as_object().is_some_and(serde_json::Map::is_empty)
}) {
metadata.remove(key);
}
}
}
fn list_items<'a>(value: &'a Value, kind: &str) -> Option<&'a Vec<Value>> {
let named = value
.pointer("/metadata/name")
.and_then(Value::as_str)
.is_some_and(|name| !name.is_empty());
if !kind.ends_with("List") || named {
return None;
}
value.get("items")?.as_array()
}
fn add(
index: &mut BTreeMap<String, Object>,
value: &Value,
text: String,
namespace: &str,
options: &DiffOptions,
) -> Result<(), Error> {
let kind = value
.get("kind")
.and_then(Value::as_str)
.unwrap_or_default();
let api_version = value
.get("apiVersion")
.and_then(Value::as_str)
.unwrap_or_default();
if api_version.is_empty() && kind.is_empty() {
return Ok(());
}
if let Some(items) = list_items(value, kind) {
for item in items {
add(index, item, yaml(item)?, namespace, options)?;
}
return Ok(());
}
let text = if options.normalize_manifests {
yaml(value)?
} else {
text
};
let text = strip_empty_metadata_keys(&text, value);
let hook = annotation(value, HOOK);
let skipped = hook.is_some() && options.no_hooks
|| !options.include_tests && matches!(hook, Some("test" | "test-success"));
if skipped {
return Ok(());
}
let id = identify(value, namespace);
let mut value = value.clone();
strip_empty_metadata_values(&mut value);
match index.entry(id.to_string()) {
Entry::Occupied(slot) => tracing::warn!(key = slot.key(), "duplicate object in manifest"),
Entry::Vacant(slot) => {
slot.insert(Object {
keep: annotation(&value, RESOURCE_POLICY) == Some("keep"),
id,
view: View { text, value },
});
}
}
Ok(())
}
pub(super) fn index(
manifest: &Manifest,
namespace: &str,
options: &DiffOptions,
) -> Result<BTreeMap<String, Object>, Error> {
let mut index = BTreeMap::new();
for object in &manifest.objects {
let text = match &object.source {
Some(source) => format!("# Source: {source}\n{}", object.raw.trim()),
None => object.raw.trim().to_owned(),
};
add(&mut index, &object.value, text, namespace, options)?;
}
Ok(index)
}