Skip to main content

helm_rs/manifest/diff/
mod.rs

1//! A native diff of two manifests, mirroring the `helm diff` plugin
2//! ([databus23/helm-diff](https://github.com/databus23/helm-diff) v3.15.15).
3//!
4//! The rendering comes from a backend (`helm template`, or a dry run); comparing two renderings
5//! is pure data. [`Diff::between`] mirrors `manifest/parse.go` `Parse` (identity, hooks,
6//! normalisation) and `diff/diff.go` `generateReport` (what is added, removed and changed, the
7//! text diff, Secret redaction), and `diff/structured.go` for the field changes.
8//!
9//! Differences from the plugin are deliberate and listed where they occur: the group of an
10//! object, not its API version, is part of its identity; the built-in cluster-scoped kinds get
11//! no namespace; field changes are produced for every changed object, not only in a separate
12//! output format; a type change at a path is one replacement; only the `metadata:` block loses
13//! its empty `labels:` and `annotations:` lines (the plugin strips matching lines anywhere in
14//! the document, `stripEmptyMetadataKeys`); and only a nameless `...List` document with an
15//! `items` array is expanded into its items (the plugin expands every kind ending in `List`, so
16//! a custom `TodoList` resource disappears, `parseContent`).
17
18mod fields;
19mod mask;
20mod object;
21mod options;
22mod secret;
23mod text;
24
25use std::fmt;
26
27use serde_json::Value;
28
29pub use fields::{FieldChange, FieldPath, PathSegment};
30pub use mask::{MaskedValue, SecretMasker, SecretSide};
31pub use options::{DiffOptions, DiffOptionsBuilder, SecretMode};
32
33use super::{Error, Manifest, push_document};
34use crate::release::Release;
35use object::{Object, View};
36
37/// The kind that holds secret values.
38const SECRET: &str = "Secret";
39
40/// Who an object is: its API group, kind, namespace and name. The plugin keys objects the same
41/// way (`metadata.String()` in `manifest/parse.go`), except that it uses the API version without
42/// its last segment where this uses the group, so core objects have the empty group.
43///
44/// An object without a `metadata.namespace` takes the namespace given to [`Diff::between`], as
45/// in the plugin (`parseContent`), because the namespace of a custom kind cannot be known without
46/// a cluster. Objects of the built-in cluster-scoped kinds have no namespace at all.
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
48pub struct ObjectId {
49    /// The API group; empty for the core group.
50    pub group: String,
51    /// The kind.
52    pub kind: String,
53    /// The namespace; `None` for a cluster-scoped object or an empty default namespace.
54    pub namespace: Option<String>,
55    /// `metadata.name`.
56    pub name: String,
57}
58
59impl fmt::Display for ObjectId {
60    /// The plugin's key: `namespace, name, Kind (group)`, with `v1` standing for the core group.
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        let group = if self.group.is_empty() {
63            "v1"
64        } else {
65            &self.group
66        };
67
68        write!(
69            f,
70            "{}, {}, {} ({group})",
71            self.namespace.as_deref().unwrap_or_default(),
72            self.name,
73            self.kind
74        )
75    }
76}
77
78/// How an object differs.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum ChangeKind {
81    /// Only in the new manifest.
82    Added,
83    /// Only in the old manifest.
84    Removed,
85    /// In both, with different content.
86    Changed,
87}
88
89/// One object that differs.
90#[derive(Debug, Clone, PartialEq)]
91pub struct ObjectChange {
92    /// The object.
93    pub id: ObjectId,
94    /// How it differs.
95    pub kind: ChangeKind,
96    /// The changed fields; empty unless `kind` is [`ChangeKind::Changed`], when the object is
97    /// suppressed, and when only formatting changed (the text diff shows it, as in the plugin;
98    /// [`DiffOptions::normalize_manifests`] hides it).
99    pub fields: Vec<FieldChange>,
100    /// The text diff as the plugin prints it: `+ `, `- ` and two spaces before each line, `...`
101    /// for omitted context. One line saying so when the kind is suppressed. An added object
102    /// starts with an empty removed line, as in the plugin.
103    pub text: String,
104    /// Whether the kind is in [`DiffOptions::suppress`].
105    pub suppressed: bool,
106}
107
108impl fmt::Display for ObjectChange {
109    /// The plugin's report entry: the key, what happened, then the text diff.
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        let message = match self.kind {
112            ChangeKind::Added => "has been added:",
113            ChangeKind::Removed => "has been removed:",
114            ChangeKind::Changed => "has changed:",
115        };
116
117        write!(f, "{} {message}\n{}", self.id, self.text)
118    }
119}
120
121/// The differences between two manifests, in the plugin's order: changed objects, then removed
122/// ones, then added ones, each by key.
123#[derive(Debug, Clone, PartialEq, Default)]
124pub struct Diff {
125    /// The objects that differ.
126    pub changes: Vec<ObjectChange>,
127}
128
129impl Diff {
130    /// Whether nothing differs (the plugin's `--detailed-exitcode` exits non-zero when this is
131    /// false).
132    #[must_use]
133    pub fn is_empty(&self) -> bool {
134        self.changes.is_empty()
135    }
136
137    /// The objects with the given `kind`.
138    pub fn of_kind(&self, kind: ChangeKind) -> impl Iterator<Item = &ObjectChange> {
139        self.changes
140            .iter()
141            .filter(move |change| change.kind == kind)
142    }
143
144    /// Compares `before` with `after`. An object is identified by [`ObjectId`] after taking
145    /// `namespace` as the default; an object only in `before` is removed unless it has the
146    /// annotation `helm.sh/resource-policy: keep` (`generateReport`), one only in `after` is
147    /// added, and one in both is changed when its text differs (after the options). Hooks are
148    /// ordinary objects keyed the same way, with `helm.sh/hook: test` ones left out by default.
149    ///
150    /// The same identity in a manifest twice keeps the first, as the plugin does.
151    pub fn between(
152        before: &Manifest,
153        after: &Manifest,
154        namespace: &str,
155        options: &DiffOptions,
156    ) -> Result<Self, Error> {
157        let old = object::index(before, namespace, options)?;
158        let new = object::index(after, namespace, options)?;
159        let mut changed = Vec::new();
160        let mut removed = Vec::new();
161
162        for (key, entry) in &old {
163            let counterpart = new.get(key);
164
165            if counterpart.is_none() && entry.keep {
166                continue;
167            }
168
169            let target = if counterpart.is_some() {
170                &mut changed
171            } else {
172                &mut removed
173            };
174
175            target.extend(change(Some(entry), counterpart, options)?);
176        }
177
178        let added = new
179            .iter()
180            .filter(|(key, _)| !old.contains_key(*key))
181            .map(|(_, entry)| change(None, Some(entry), options))
182            .collect::<Result<Vec<_>, _>>()?;
183
184        Ok(Self {
185            changes: changed
186                .into_iter()
187                .chain(removed)
188                .chain(added.into_iter().flatten())
189                .collect(),
190        })
191    }
192
193    /// Compares what `deployed` holds (its manifest and its hooks, as `helm get manifest` and
194    /// `helm get hooks` print them) with a fresh render of the chart, in the release's
195    /// namespace: the plugin's `helm diff upgrade`. `rendered` is `helm template` output, which
196    /// includes the hooks.
197    pub fn against_release(
198        deployed: &Release,
199        rendered: &Manifest,
200        options: &DiffOptions,
201    ) -> Result<Self, Error> {
202        let mut text = format!("{}\n", deployed.manifest);
203
204        for hook in &deployed.hooks {
205            push_document(&mut text, Some(&hook.path), &hook.manifest);
206        }
207
208        Self::between(
209            &Manifest::parse(&text)?,
210            rendered,
211            &deployed.namespace,
212            options,
213        )
214    }
215}
216
217/// The change from `old` to `new` (one of them may be missing), or `None` when the text does
218/// not differ (`doDiff`).
219fn change(
220    old: Option<&Object>,
221    new: Option<&Object>,
222    options: &DiffOptions,
223) -> Result<Option<ObjectChange>, Error> {
224    let (id, kind) = match (old, new) {
225        (Some(old), Some(new)) if old.view.text == new.view.text => return Ok(None),
226        (Some(old), Some(_)) => (&old.id, ChangeKind::Changed),
227        (Some(old), None) => (&old.id, ChangeKind::Removed),
228        (None, Some(new)) => (&new.id, ChangeKind::Added),
229        (None, None) => return Ok(None),
230    };
231    let mut old_view = old.map(|entry| entry.view.clone());
232    let mut new_view = new.map(|entry| entry.view.clone());
233
234    let mut forced = Vec::new();
235
236    if id.kind == SECRET {
237        forced = secret::apply(&options.secrets, id, old_view.as_mut(), new_view.as_mut())?;
238    }
239
240    let empty = View {
241        text: String::new(),
242        value: Value::Null,
243    };
244    let before = old_view.as_ref().unwrap_or(&empty);
245    let after = new_view.as_ref().unwrap_or(&empty);
246    let lines = text::diff_lines(&before.text, &after.text, options.strip_trailing_cr);
247
248    if kind == ChangeKind::Changed && !text::has_changes(&lines) && forced.is_empty() {
249        return Ok(None);
250    }
251
252    let suppressed = options.suppress.contains(&id.kind);
253    let (text, fields) = if suppressed {
254        (
255            format!(
256                "+ Changes suppressed on sensitive content of type {}\n",
257                id.kind
258            ),
259            Vec::new(),
260        )
261    } else {
262        (
263            text::render(&lines, options.context),
264            if kind == ChangeKind::Changed {
265                let mut fields = fields::field_changes(&before.value, &after.value);
266
267                secret::add_forced(
268                    &mut fields,
269                    &forced,
270                    &options.secrets,
271                    &before.value,
272                    &after.value,
273                );
274
275                fields
276            } else {
277                Vec::new()
278            },
279        )
280    };
281
282    Ok(Some(ObjectChange {
283        id: id.clone(),
284        kind,
285        fields,
286        text,
287        suppressed,
288    }))
289}
290
291#[cfg(test)]
292mod tests;