1mod diff;
10mod order;
11mod rendered;
12
13use std::fmt::Write;
14
15use serde_json::Value;
16use sha2::{Digest, Sha256};
17
18pub use diff::{
19 ChangeKind, Diff, DiffOptions, DiffOptionsBuilder, FieldChange, FieldPath, MaskedValue,
20 ObjectChange, ObjectId, PathSegment, SecretMasker, SecretMode, SecretSide,
21};
22pub use order::{INSTALL_ORDER, UNINSTALL_ORDER};
23pub use rendered::Rendered;
24
25#[derive(Debug, thiserror::Error)]
27pub enum Error {
28 #[error("YAML parse error in {source_name}: {error}")]
30 Yaml {
31 source_name: String,
33 error: String,
35 },
36 #[error("document {0} is not a Kubernetes object")]
38 NotAnObject(String),
39 #[error("cannot serialise object: {0}")]
41 Serialize(String),
42 #[cfg(feature = "kube")]
44 #[error("cannot convert object: {0}")]
45 Convert(#[from] serde_json::Error),
46}
47
48#[derive(Debug, Clone, PartialEq)]
50pub struct Manifest {
51 pub objects: Vec<ManifestObject>,
53 text: String,
54}
55
56#[derive(Debug, Clone, PartialEq)]
58pub struct ManifestObject {
59 pub source: Option<String>,
61 pub value: Value,
63 pub raw: String,
66}
67
68impl Manifest {
69 pub fn parse(yaml: &str) -> Result<Self, Error> {
74 let objects = split_documents(yaml)
75 .into_iter()
76 .enumerate()
77 .map(|(index, document)| ManifestObject::parse(index, document))
78 .collect::<Result<Vec<_>, _>>()?
79 .into_iter()
80 .flatten()
81 .collect();
82
83 Ok(Self {
84 objects,
85 text: yaml.to_owned(),
86 })
87 }
88
89 #[must_use]
94 pub fn digest(&self) -> String {
95 let mut hex = String::new();
96
97 for byte in Sha256::digest(self.text.as_bytes()) {
98 write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
99 }
100
101 hex
102 }
103
104 #[must_use]
108 pub fn sorted_for_install(&self) -> Vec<&ManifestObject> {
109 self.sorted(&INSTALL_ORDER)
110 }
111
112 #[must_use]
114 pub fn sorted_for_uninstall(&self) -> Vec<&ManifestObject> {
115 self.sorted(&UNINSTALL_ORDER)
116 }
117
118 #[cfg(feature = "kube")]
120 pub fn typed<K>(&self) -> impl Iterator<Item = Result<K, Error>> + '_
121 where
122 K: kube::Resource + serde::de::DeserializeOwned,
123 K::DynamicType: Default,
124 {
125 let dynamic_type = K::DynamicType::default();
126 let api_version = K::api_version(&dynamic_type).into_owned();
127 let kind = K::kind(&dynamic_type).into_owned();
128
129 self.objects
130 .iter()
131 .filter(move |object| {
132 object.api_version() == Some(api_version.as_str())
133 && object.kind() == Some(kind.as_str())
134 })
135 .map(|object| K::deserialize(&object.value).map_err(Error::from))
136 }
137
138 fn sorted(&self, order: &[&str]) -> Vec<&ManifestObject> {
140 let mut objects: Vec<&ManifestObject> = self.objects.iter().collect();
141
142 objects
143 .sort_by(|a, b| order::compare(order, a.kind().unwrap_or(""), b.kind().unwrap_or("")));
144
145 objects
146 }
147}
148
149impl ManifestObject {
150 #[must_use]
152 pub fn api_version(&self) -> Option<&str> {
153 self.value.get("apiVersion")?.as_str()
154 }
155
156 #[must_use]
158 pub fn kind(&self) -> Option<&str> {
159 self.value.get("kind")?.as_str()
160 }
161
162 #[must_use]
164 pub fn name(&self) -> Option<&str> {
165 self.value.pointer("/metadata/name")?.as_str()
166 }
167
168 #[must_use]
170 pub fn namespace(&self) -> Option<&str> {
171 self.value.pointer("/metadata/namespace")?.as_str()
172 }
173
174 #[cfg(feature = "kube")]
176 pub fn to_dynamic(&self) -> Result<kube::api::DynamicObject, Error> {
177 use serde::Deserialize;
178
179 Ok(kube::api::DynamicObject::deserialize(&self.value)?)
180 }
181
182 fn parse(index: usize, document: &str) -> Result<Option<Self>, Error> {
184 let (source, raw) = take_source(document);
185 let label = source.map_or_else(|| format!("#{index}"), str::to_owned);
186 let value: Value = serde_norway::from_str(raw).map_err(|error| Error::Yaml {
187 source_name: label.clone(),
188 error: error.to_string(),
189 })?;
190
191 match value {
192 Value::Null => Ok(None),
193 Value::Object(_) => Ok(Some(Self {
194 source: source.map(str::to_owned),
195 value,
196 raw: raw.to_owned(),
197 })),
198 _ => Err(Error::NotAnObject(label)),
199 }
200 }
201}
202
203pub(crate) fn push_document(text: &mut String, source: Option<&str>, body: &str) {
206 text.push_str("---\n");
207
208 if let Some(source) = source {
209 writeln!(text, "# Source: {source}").expect("writing to a String cannot fail");
210 }
211
212 text.push_str(body);
213 text.push('\n');
214}
215
216fn split_documents(text: &str) -> Vec<&str> {
220 let mut documents = Vec::new();
221 let mut start = 0;
222 let mut offset = 0;
223
224 for line in text.split_inclusive('\n') {
225 if let Some(rest) = line.strip_prefix("---") {
226 documents.push(&text[start..offset]);
227 start = offset + line.len() - rest.trim_start_matches([' ', '\t']).len();
228 }
229 offset += line.len();
230 }
231 documents.push(&text[start..]);
232
233 documents
234 .into_iter()
235 .map(str::trim_start)
236 .filter(|document| !document.trim().is_empty())
237 .collect()
238}
239
240fn take_source(document: &str) -> (Option<&str>, &str) {
242 let first = document.lines().next().unwrap_or_default();
243
244 match first.strip_prefix("# Source: ") {
245 Some(path) => (
246 Some(path.trim_end()),
247 document[first.len()..].trim_start_matches(['\r', '\n']),
248 ),
249 None => (None, document),
250 }
251}
252
253#[cfg(test)]
254mod tests;