Documentation
¶
Overview ¶
Package diff compares groups of rendered Kubernetes manifests.
Compare matches normalized resources by canonical producer and resource identity. Parent group, kind, namespace, and name distinguish producers. Parent.Path supplies display metadata. A resource moved between producers becomes a removal and an addition.
Each Group contains two Snapshot values and any selected render error. Compare withholds unavailable producer batches and returns grouped warnings and structured suppressions alongside prepared output. Comparison.Write formats that output without repeating normalization.
Options.StripAttrs and Options.StripFields remove volatile fields from copies. ConfigMap binaryData becomes a content hash summary. Options.Normalize runs after these operations on the copied manifests. Original chart labels remain available in the structured JSON output. The package example shows grouped comparison with retained chart metadata.
Native formats use dyff to compare resource contents and named list entries. Unified, HTML, and JSON formats present the same canonical resource pairs. CompareImages applies the same producer availability policy and returns sorted image changes with structured suppressions.
Example ¶
Example compares explicitly attributed documents and retains chart metadata even when normalization strips the chart label from the compared manifests.
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/home-operations/flate/internal/engine/diff"
"github.com/home-operations/flate/pkg/manifest"
)
func main() {
parent := &manifest.HelmRelease{Namespace: "media", Name: "sonarr"}
deployment := func(chartVer, image string) map[string]any {
return map[string]any{
"apiVersion": "apps/v1", "kind": "Deployment",
"metadata": map[string]any{
"name": "sonarr", "namespace": "media",
"labels": map[string]any{"helm.sh/chart": "app-template-" + chartVer},
},
"spec": map[string]any{
"template": map[string]any{"spec": map[string]any{
"containers": []any{map[string]any{"name": "main", "image": image}},
}},
},
}
}
base := diff.Snapshot{Manifests: []manifest.DocumentBatch{{
Parent: parent, Documents: []map[string]any{deployment("4.0.0", "ghcr.io/home-operations/sonarr:4.0.0")},
}}}
head := diff.Snapshot{Manifests: []manifest.DocumentBatch{{
Parent: parent, Documents: []map[string]any{deployment("4.1.0", "ghcr.io/home-operations/sonarr:4.1.0")},
}}}
comparison, err := diff.Compare(
[]diff.Group{{Orig: base, Current: head}},
diff.Options{Format: diff.FormatJSON, StripAttrs: diff.DefaultStripAttrs, StripFields: diff.DefaultStripFields},
)
if err != nil {
panic(err)
}
var output bytes.Buffer
if err := comparison.Write(&output, nil); err != nil {
panic(err)
}
var report struct {
Changes []diff.Change `json:"changes"`
}
if err := json.Unmarshal(output.Bytes(), &report); err != nil {
panic(err)
}
{
cValues := report.Changes
for cIndex := range cValues {
c := cValues[cIndex]
fmt.Printf("%s %s %s/%s (chart %s -> %s)\n", c.Status, c.Kind, c.Namespace, c.Name, c.OldChart, c.NewChart)
}
}
}
Output: changed Deployment media/sonarr (chart app-template-4.0.0 -> app-template-4.1.0)
Index ¶
- Variables
- func MergeWarnings(warnings []manifest.Warning, notes []Suppression) []manifest.Warning
- type Change
- type ChangeStatus
- type Comparison
- type Doc
- type Format
- type Group
- type GroupResult
- type Highlighter
- type Names
- type Naming
- type Options
- type Parent
- type Snapshot
- type Subject
- type Suppression
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultStripAttrs = []string{
helmChartLabel,
"checksum/",
"app.kubernetes.io/version",
"chart",
}
DefaultStripAttrs contains chart and checksum metadata keys whose changes duplicate version or content differences. A trailing slash matches a prefix. Treat the slice as read-only; clone before mutation.
var DefaultStripFields = []string{}
DefaultStripFields contains dotted spec paths excluded from diffs. Treat the slice as read-only; clone before mutation.
Functions ¶
func MergeWarnings ¶
func MergeWarnings(warnings []manifest.Warning, notes []Suppression) []manifest.Warning
MergeWarnings preserves duplicate disclosures and never mutates caller-owned slices.
Types ¶
type Change ¶
type Change struct {
Parent Parent `json:"parent"`
ProducerChange *producerChange `json:"producerChange,omitempty"`
// APIVersion is the authored current version, or the original version for removals.
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Status ChangeStatus `json:"status"`
// Old / New are the NORMALIZED manifests (Options strip + binaryData
// redaction + the optional Normalize hook applied). Old is nil for an
// add; New is nil for a remove.
Old map[string]any `json:"old"`
New map[string]any `json:"new"`
// OldChart / NewChart are the resource's "helm.sh/chart" label
// ("<name>-<version>") captured BEFORE normalization stripped it —
// "" when absent. Surfaces a chart-version bump the stripped Old/New
// no longer carry.
OldChart string `json:"oldChart"`
NewChart string `json:"newChart"`
}
Change describes one resource comparison.
type ChangeStatus ¶
type ChangeStatus string
ChangeStatus classifies how a resource differs between two doc sets.
const StatusRemoved ChangeStatus = "removed"
StatusRemoved identifies a resource present only in the original snapshot.
type Comparison ¶
type Comparison struct {
Groups []GroupResult
// contains filtered or unexported fields
}
Comparison retains prepared output so repeated writes never normalize inputs again.
type Doc ¶
type Doc struct {
Manifest map[string]any
Original map[string]any
Parent Parent
Producer manifest.DiagnosticIdentity
}
Doc pairs a rendered manifest with its optional parent.
type Format ¶
type Format string
Format selects the diff output flavor. The github/human/brief/gitlab/ gitea styles map to dyff's own output styles; diff is a plain unified diff.
const ( // FormatGitHub is dyff's `--output github` mode: path-based diff // syntax (`@@`, `+`, `-`, `!`) that GitHub's diff lexer renders // natively as a colored diff block when wrapped in a “`diff // fence. K8s-aware: list entries are matched by identifier // (container name, env-var name, etc.), so reordering a list // produces no diff churn. FormatGitHub Format = "github" // FormatDiff is a standard unified diff (`diff -u` / `git diff` // style) of each resource's YAML. Not Kubernetes-aware — it diffs // lines, so a reordered list shows churn — but familiar and // consumable by any unified-diff tooling. FormatDiff Format = "diff" // FormatHuman is dyff's colored, human-readable report — the default // style, and the zero value. FormatHuman Format = "human" // FormatBrief is dyff's one-line-per-change summary. FormatBrief Format = "brief" // FormatGitLab is dyff's GitLab diff syntax (`=` path/root prefixes). FormatGitLab Format = "gitlab" // FormatGitea is dyff's Gitea/Forgejo diff syntax. FormatGitea Format = "gitea" // FormatHTML renders a self-contained HTML document: a per-resource, // GitHub-style diff with YAML syntax highlighting (via chroma) and a // side-by-side ⇄ unified toggle. Built on the same line diff as // FormatDiff (not Kubernetes-aware). Meant for browser review or a CI // artifact, not the terminal. FormatHTML Format = "html" // FormatJSON encodes changes and suppressions in one JSON object. FormatJSON Format = "json" )
Recognized Format values.
type GroupResult ¶
type GroupResult struct {
Warnings []manifest.Warning
Suppressed []Suppression
Subjects []manifest.NamedResource
}
GroupResult keeps raw warnings separate from structured suppression disclosures.
type Highlighter ¶ added in v0.8.1
type Highlighter struct {
// contains filtered or unexported fields
}
Highlighter renders single YAML lines to syntax-highlighted HTML spans (chroma, class-based). The matching stylesheet — both the light (github) and dark (github-dark) variants, scoped under .chroma.light / .chroma.dark — is emitted once into the document <style>; the spans themselves are theme-agnostic. Highlighting is per-line so it maps 1:1 onto the diff line indices; block-scalar bodies lose cross-line context, immaterial for review.
func NewHighlighter ¶ added in v0.8.1
func NewHighlighter() (*Highlighter, string, error)
NewHighlighter returns the YAML highlighter and its light and dark stylesheets.
func (*Highlighter) Emit ¶ added in v0.8.1
func (h *Highlighter) Emit(s string, lo, hi int) template.HTML
Emit renders one YAML line to class-based highlighted HTML, walking chroma's token stream directly (rather than its formatter) so a word-level highlight can be spliced mid-token: when hi > lo, the rune range [lo,hi) is wrapped in <span class="wd">. Token classes mirror chroma's WithClasses output (StandardTypes) so they match the embedded stylesheet.
type Names ¶
type Names struct {
Prefix string
Subjects map[manifest.NamedResource]Subject
}
Names labels only printed subjects in one retained cluster.
type Naming ¶
type Naming struct {
Groups []Names
// contains filtered or unexported fields
}
Naming must restore shared occurrence counts after each temporary context.
func PrepareNames ¶
func PrepareNames( clusters []string, inventory [][]manifest.NamedResource, subjects []map[manifest.NamedResource]manifest.DiagnosticIdentity, ) *Naming
PrepareNames limits collision counts to printed subjects across retained clusters.
func (*Naming) Model ¶
func (n *Naming) Model(group int, subjects map[manifest.NamedResource]manifest.DiagnosticIdentity) Names
Model inherits group subjects only when subjects is nil.
type Options ¶
type Options struct {
// StripAttrs lists annotation/label keys removed from each
// manifest's metadata (and pod-template metadata) before the diff
// is computed. Cuts chart-bump noise — annotations like
// `helm.sh/chart` or `checksum/config` whose values rotate on
// every chart bump would otherwise produce a diff entry per
// resource. dyff matches K8s lists by identifier but still
// reports string-value changes verbatim, so this pre-filter still
// earns its keep.
StripAttrs []string
// StripFields lists dotted spec field-paths (e.g.
// "spec.restic.unlock") deleted from each manifest before the diff
// is computed. Same rationale as StripAttrs but for volatile values
// charts template into the spec rather than metadata — notably
// volsync's `unlock: {{ now }}`, which rotates every render and
// cannot be stabilized at render time (Helm exposes no funcMap
// hook). See manifest.StripResourceFields.
StripFields []string
// Normalize, when non-nil, is an extra per-manifest scrub applied to
// each (cloned) document AFTER StripAttrs/StripFields and binaryData
// redaction, before resources are paired and compared. Use it to
// suppress render-time noise the built-in strips don't cover —
// e.g. an SDK consumer redacting Secret values or chart-minted TLS
// certs so a per-render-random value doesn't read as a change.
// nil = no extra scrub (the CLI default).
Normalize func(map[string]any)
// Format selects the output style (see the Format constants). The
// zero value renders the human default.
Format Format
// Suppressed lists additional producer disclosures. Compare appends its
// selected suppressions without modifying this slice and returns them as data.
// JSON also includes them in its suppressed array.
Suppressed []Suppression
// contains filtered or unexported fields
}
Options normalize copied documents without mutating either input snapshot.
type Parent ¶
type Parent struct {
manifest.NamedResource
// Path is the Flux Kustomization spec.path (only set for KS
// parents), with the conventional `./` prefix stripped. It is display
// metadata, not part of producer identity.
Path string `json:"path"`
}
Parent identifies the Flux Kustomization or HelmRelease that rendered a manifest. Its zero value identifies an ownerless document.
type Snapshot ¶
type Snapshot struct {
Subjects map[manifest.NamedResource]manifest.DiagnosticIdentity
Manifests []manifest.DocumentBatch
DocumentMetadata map[int]map[int]selection.DocumentMetadata
Bindings store.ProducerBindings
}
Snapshot contains selected document batches and their render availability. Manifests and status entries remain immutable during comparison.
type Subject ¶
type Subject struct {
ID manifest.NamedResource
Kind, Name string
}
Subject keeps canonical identity separate from its resolved human labels.
type Suppression ¶
type Suppression struct {
Subject manifest.DiagnosticIdentity `json:"-"`
Parent Parent `json:"parent"`
Side side `json:"side"` // orig, current, or both unavailable sides
Count int `json:"count"` // withheld healthy-side entries, or all entries for both
Reason string `json:"reason"` // the render failure, skip, or suspension reason
}
Suppression records a producer whose rendered objects were withheld because rendering failed, was soft-skipped, or was suspended.
func CompareImages ¶
func CompareImages(orig, current Snapshot, selectedErr error, includeRemoved bool) ([]string, []Suppression, error)
CompareImages returns the sorted images added between selected orig/current snapshots, plus removals when requested. Unavailable producer batches are withheld before extraction and disclosed as structured suppressions with document counts.
func (Suppression) String ¶
func (s Suppression) String() string