mod diff;
mod order;
mod rendered;
use std::fmt::Write;
use serde_json::Value;
use sha2::{Digest, Sha256};
pub use diff::{
ChangeKind, Diff, DiffOptions, DiffOptionsBuilder, FieldChange, FieldPath, MaskedValue,
ObjectChange, ObjectId, PathSegment, SecretMasker, SecretMode, SecretSide,
};
pub use order::{INSTALL_ORDER, UNINSTALL_ORDER};
pub use rendered::Rendered;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("YAML parse error in {source_name}: {error}")]
Yaml {
source_name: String,
error: String,
},
#[error("document {0} is not a Kubernetes object")]
NotAnObject(String),
#[error("cannot serialise object: {0}")]
Serialize(String),
#[cfg(feature = "kube")]
#[error("cannot convert object: {0}")]
Convert(#[from] serde_json::Error),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
pub objects: Vec<ManifestObject>,
text: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ManifestObject {
pub source: Option<String>,
pub value: Value,
pub raw: String,
}
impl Manifest {
pub fn parse(yaml: &str) -> Result<Self, Error> {
let objects = split_documents(yaml)
.into_iter()
.enumerate()
.map(|(index, document)| ManifestObject::parse(index, document))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect();
Ok(Self {
objects,
text: yaml.to_owned(),
})
}
#[must_use]
pub fn digest(&self) -> String {
let mut hex = String::new();
for byte in Sha256::digest(self.text.as_bytes()) {
write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
}
hex
}
#[must_use]
pub fn sorted_for_install(&self) -> Vec<&ManifestObject> {
self.sorted(&INSTALL_ORDER)
}
#[must_use]
pub fn sorted_for_uninstall(&self) -> Vec<&ManifestObject> {
self.sorted(&UNINSTALL_ORDER)
}
#[cfg(feature = "kube")]
pub fn typed<K>(&self) -> impl Iterator<Item = Result<K, Error>> + '_
where
K: kube::Resource + serde::de::DeserializeOwned,
K::DynamicType: Default,
{
let dynamic_type = K::DynamicType::default();
let api_version = K::api_version(&dynamic_type).into_owned();
let kind = K::kind(&dynamic_type).into_owned();
self.objects
.iter()
.filter(move |object| {
object.api_version() == Some(api_version.as_str())
&& object.kind() == Some(kind.as_str())
})
.map(|object| K::deserialize(&object.value).map_err(Error::from))
}
fn sorted(&self, order: &[&str]) -> Vec<&ManifestObject> {
let mut objects: Vec<&ManifestObject> = self.objects.iter().collect();
objects
.sort_by(|a, b| order::compare(order, a.kind().unwrap_or(""), b.kind().unwrap_or("")));
objects
}
}
impl ManifestObject {
#[must_use]
pub fn api_version(&self) -> Option<&str> {
self.value.get("apiVersion")?.as_str()
}
#[must_use]
pub fn kind(&self) -> Option<&str> {
self.value.get("kind")?.as_str()
}
#[must_use]
pub fn name(&self) -> Option<&str> {
self.value.pointer("/metadata/name")?.as_str()
}
#[must_use]
pub fn namespace(&self) -> Option<&str> {
self.value.pointer("/metadata/namespace")?.as_str()
}
#[cfg(feature = "kube")]
pub fn to_dynamic(&self) -> Result<kube::api::DynamicObject, Error> {
use serde::Deserialize;
Ok(kube::api::DynamicObject::deserialize(&self.value)?)
}
fn parse(index: usize, document: &str) -> Result<Option<Self>, Error> {
let (source, raw) = take_source(document);
let label = source.map_or_else(|| format!("#{index}"), str::to_owned);
let value: Value = serde_norway::from_str(raw).map_err(|error| Error::Yaml {
source_name: label.clone(),
error: error.to_string(),
})?;
match value {
Value::Null => Ok(None),
Value::Object(_) => Ok(Some(Self {
source: source.map(str::to_owned),
value,
raw: raw.to_owned(),
})),
_ => Err(Error::NotAnObject(label)),
}
}
}
pub(crate) fn push_document(text: &mut String, source: Option<&str>, body: &str) {
text.push_str("---\n");
if let Some(source) = source {
writeln!(text, "# Source: {source}").expect("writing to a String cannot fail");
}
text.push_str(body);
text.push('\n');
}
fn split_documents(text: &str) -> Vec<&str> {
let mut documents = Vec::new();
let mut start = 0;
let mut offset = 0;
for line in text.split_inclusive('\n') {
if let Some(rest) = line.strip_prefix("---") {
documents.push(&text[start..offset]);
start = offset + line.len() - rest.trim_start_matches([' ', '\t']).len();
}
offset += line.len();
}
documents.push(&text[start..]);
documents
.into_iter()
.map(str::trim_start)
.filter(|document| !document.trim().is_empty())
.collect()
}
fn take_source(document: &str) -> (Option<&str>, &str) {
let first = document.lines().next().unwrap_or_default();
match first.strip_prefix("# Source: ") {
Some(path) => (
Some(path.trim_end()),
document[first.len()..].trim_start_matches(['\r', '\n']),
),
None => (None, document),
}
}
#[cfg(test)]
mod tests;