Skip to main content

helm_rs/manifest/
mod.rs

1//! Rendered manifest parsing.
2//!
3//! Helm renders resources as one YAML stream: every document is introduced by `---` and a
4//! `# Source: <chart>/templates/<file>` comment (`pkg/action/action.go` `renderResources`,
5//! `pkg/cmd/template.go`). [`Manifest`] parses such a stream, whether it is a release's
6//! `manifest`, `helm template` output, `helm get manifest` output or a hook manifest.
7//! [`Rendered`] additionally sorts a full `helm template` output into resources, hooks and CRDs.
8
9mod 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/// Failures parsing rendered manifests.
26#[derive(Debug, thiserror::Error)]
27pub enum Error {
28    /// A document is not valid YAML.
29    #[error("YAML parse error in {source_name}: {error}")]
30    Yaml {
31        /// The document's `# Source:` (or its position when it has none).
32        source_name: String,
33        /// The parser's message.
34        error: String,
35    },
36    /// A document is YAML but not a mapping, so it is not a Kubernetes object.
37    #[error("document {0} is not a Kubernetes object")]
38    NotAnObject(String),
39    /// An object cannot be serialised back to YAML (while diffing).
40    #[error("cannot serialise object: {0}")]
41    Serialize(String),
42    /// An object does not deserialize into the requested type.
43    #[cfg(feature = "kube")]
44    #[error("cannot convert object: {0}")]
45    Convert(#[from] serde_json::Error),
46}
47
48/// An ordered stream of rendered Kubernetes objects.
49#[derive(Debug, Clone, PartialEq)]
50pub struct Manifest {
51    /// The objects, in the order they appear.
52    pub objects: Vec<ManifestObject>,
53    text: String,
54}
55
56/// One document of a manifest stream.
57#[derive(Debug, Clone, PartialEq)]
58pub struct ManifestObject {
59    /// The `# Source:` path (`<chart>/templates/<file>`), when the document has one.
60    pub source: Option<String>,
61    /// The parsed object.
62    pub value: Value,
63    /// The document text as Helm splits it: leading whitespace and the `# Source:` header line
64    /// removed, the rest unchanged.
65    pub raw: String,
66}
67
68impl Manifest {
69    /// Parses a manifest stream the way Helm splits it (`releaseutil.SplitManifests`): on lines
70    /// starting with `---` (text after the dashes stays in the next document), skipping empty and
71    /// comment-only documents. A document's leading `# Source:` comment becomes
72    /// [`ManifestObject::source`].
73    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    /// The SHA-256 of the exact text given to [`Manifest::parse`], as lowercase hex. For a
90    /// release that is its `manifest` string as Helm stores it, byte for byte, so the digest
91    /// changes with any rendered change and is stable otherwise. Helm itself defines no manifest
92    /// digest; this is a content hash, not a Helm value.
93    #[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    /// The objects ordered for installation: by [`INSTALL_ORDER`] position, unlisted kinds last
105    /// in alphabetical order of kind, the original order kept among equals
106    /// (`sortManifestsByKind` with `InstallOrder`).
107    #[must_use]
108    pub fn sorted_for_install(&self) -> Vec<&ManifestObject> {
109        self.sorted(&INSTALL_ORDER)
110    }
111
112    /// The objects ordered for uninstallation ([`UNINSTALL_ORDER`], same rules).
113    #[must_use]
114    pub fn sorted_for_uninstall(&self) -> Vec<&ManifestObject> {
115        self.sorted(&UNINSTALL_ORDER)
116    }
117
118    /// The objects of kind `K`, converted. Matches on `apiVersion` and `kind`.
119    #[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    /// Sorts by `order` with Helm's `lessByKind`.
139    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    /// `apiVersion`.
151    #[must_use]
152    pub fn api_version(&self) -> Option<&str> {
153        self.value.get("apiVersion")?.as_str()
154    }
155
156    /// `kind`.
157    #[must_use]
158    pub fn kind(&self) -> Option<&str> {
159        self.value.get("kind")?.as_str()
160    }
161
162    /// `metadata.name`.
163    #[must_use]
164    pub fn name(&self) -> Option<&str> {
165        self.value.pointer("/metadata/name")?.as_str()
166    }
167
168    /// `metadata.namespace`.
169    #[must_use]
170    pub fn namespace(&self) -> Option<&str> {
171        self.value.pointer("/metadata/namespace")?.as_str()
172    }
173
174    /// Converts to a kube [`DynamicObject`](kube::api::DynamicObject).
175    #[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    /// Parses one split document; `None` when it holds no object (empty or comments only).
183    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
203/// Appends one document to a manifest stream the way Helm prints it (`---`, the `# Source:`
204/// header when there is a source, the body).
205pub(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
216/// Splits on lines that start with `---` like `SplitManifests`: the text after the dashes (and
217/// following spaces or tabs) belongs to the next document, whitespace-only documents are dropped
218/// and each document loses its leading whitespace.
219fn 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
240/// Separates a leading `# Source: <path>` line from the rest of the document.
241fn 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;