diff

package
v0.7.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package diff compares two sets of rendered Kubernetes manifests and reports the resources whose rendered form differs.

RenderDocs matches normalized resources by canonical parent and resource identity in every Format. Parent group, kind, namespace and name distinguish producers; Parent.Path is display metadata. A resource moved between parents is a removal and an addition, even when its contents are identical. Native styles retain Kubernetes apiVersion/kind/namespace/name labels and use dyff to compare each pair's contents. Unified, HTML and JSON formats present the same pairs with their producing parents.

Most styles delegate to dyff, whose K8s-aware comparison pairs named list entries (containers, env vars) by their identifier, so reordering a list yields an `⇆ order changed` marker instead of a wall of phantom value-line churn:

  • human (default) — dyff's colored, human-readable report.
  • github — dyff path-keyed diff syntax (`@@ <path> @@`, `+`/`-`, `!`); GitHub's diff lexer renders it natively.
  • brief — dyff's one-line-per-change summary.
  • gitlab / gitea — dyff diff syntax with forge-specific prefixes.
  • diff — a plain unified diff (`diff -u`) of each resource's YAML; not K8s-aware, but consumable by any unified-diff tooling.

Options.StripAttrs is applied to a deep-copied tree before the comparison runs — used to drop chart-bump noise (`helm.sh/chart`, `checksum/config`, …) that rotates on every Helm upgrade but carries no review-relevant signal. ConfigMap binaryData is summarized to a content hash for the same reason. DefaultStripAttrs and DefaultStripFields are the lists `flate diff` uses out of the box.

SDK usage

Compare consumes two Snapshot values from completed runs selected by orchestrator.Select, withholds unavailable producer batches, and returns formatted bytes, duplicate warnings and structured suppressions without discarding selected render errors. The comparison requires cfg.HeadOnly to be false so both runs are completed. Render two trees, select the requested producer kinds, then compare them:

runs, runErr := orchestrator.RenderTrees(ctx, []orchestrator.Tree{
	{ID: manifest.TreeID{Cluster: ".", Side: manifest.TreeBase}, RepoRoot: baseDir},
	{ID: manifest.TreeID{Cluster: ".", Side: manifest.TreeHead}, RepoRoot: headDir},
}, cfg)
defer func() {
	for _, run := range runs {
		run.Result.Close()
	}
}()
for start := 0; start < len(runs); {
	end := start + 1
	for end < len(runs) && runs[end].ID.Cluster == runs[start].ID.Cluster {
		end++
	}
	pair := runs[start:end]
	start = end
	selected, projection := orchestrator.Select(
		pair, errors.Join(pair[0].Err, pair[1].Err),
		[]manifest.NamedResource{{Group: manifest.FluxKustomizeDomain, Kind: manifest.KindKustomization}, {Group: manifest.HelmReleaseDomain, Kind: manifest.KindHelmRelease}}, nil)
	out, warnings, suppressed, err := diff.Compare(
		diff.Snapshot{Subjects: selected[0].Subjects, Manifests: selected[0].Manifests, Unavailable: selected[0].Unavailable, ProducerKeys: selected[0].ProducerKeys},
		diff.Snapshot{Subjects: selected[1].Subjects, Manifests: selected[1].Manifests, Unavailable: selected[1].Unavailable, ProducerKeys: selected[1].ProducerKeys},
		projection.Selected,
		diff.Options{
			StripAttrs: diff.DefaultStripAttrs, StripFields: diff.DefaultStripFields,
			Normalize: redact, // optional extra per-manifest scrub
		},
	)
	// Deliver out under pair[0].ID.Cluster; present warnings, suppressed and err
	// through the diagnostic writer, including when partial output is available.
}
// Check the invocation error once after every cluster, including shared cleanup failures.
return runErr

CompareImages uses the same selected producer availability and returns a sorted image list plus structured suppressions. Changes and RenderDocs retain their low-level document APIs for callers that already have attributed Doc values. Options.Normalize runs after the built-in strips on copied manifests. See the package Example for structured changes with chart metadata.

Example

Example compares explicitly attributed documents and retains chart metadata even when normalization strips the chart label from the compared manifests.

package main

import (
	"fmt"

	"github.com/home-operations/flate/pkg/diff"
	"github.com/home-operations/flate/pkg/manifest"
)

func main() {
	parentID := manifest.NamedResource{
		Group: manifest.HelmReleaseDomain, Kind: manifest.KindHelmRelease,
		Namespace: "media", Name: "sonarr",
	}
	parent := diff.Parent{NamedResource: parentID}
	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.Doc{{Parent: parent, Manifest: deployment("4.0.0", "ghcr.io/home-operations/sonarr:4.0.0")}}
	head := []diff.Doc{{Parent: parent, Manifest: deployment("4.1.0", "ghcr.io/home-operations/sonarr:4.1.0")}}

	changes, _ := diff.Changes(
		base, head,
		diff.Options{StripAttrs: diff.DefaultStripAttrs, StripFields: diff.DefaultStripFields},
	)
	{
		cValues := 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

Examples

Constants

This section is empty.

Variables

View Source
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.

View Source
var DefaultStripFields = []string{}

DefaultStripFields contains dotted spec paths excluded from diffs. Treat the slice as read-only; clone before mutation.

Functions

func RenderDocs

func RenderDocs(left, right []Doc, opts Options) ([]byte, []manifest.Warning, error)

RenderDocs compares normalized documents by canonical parent and resource identity and returns the formatted diff for opts.Format. Parent.Path is display metadata. Native formats use dyff for content comparison and Kubernetes resource labels; unified, HTML and JSON formats present the same canonical pairs. Discovered warnings are returned even when formatting fails.

Types

type Change added in v0.3.2

type Change struct {
	// Parent is the Flux Kustomization / HelmRelease that rendered this
	// resource — the pairing discriminator (so a Deployment from HR A is
	// never matched against the same-named Deployment from HR B).
	Parent Parent `json:"parent"`
	// 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 is one resource that differs between two rendered doc sets — the structured form of what RenderDocs formats. SDK consumers build their own output (an API payload, a web UI, an image report) from a []Change instead of re-implementing the pairing + normalization that RenderDocs does internally.

func Changes added in v0.3.2

func Changes(left, right []Doc, opts Options) ([]Change, []manifest.Warning)

Changes normalizes left and right before pairing by canonical parent and resource identity, and returns the differing resources as structured data. Normalization strips opts.StripAttrs and opts.StripFields, redacts ConfigMap binaryData, then applies opts.Normalize. Original chart labels are retained as provenance. The result is sorted by parent then resource identity. Returned manifests are independent of the input documents. Warnings identify shadowed documents. opts.Format is ignored.

type ChangeStatus added in v0.3.2

type ChangeStatus string

ChangeStatus classifies how a resource differs between two doc sets.

const (
	// StatusAdded — present only on the right (New) side.
	StatusAdded ChangeStatus = "added"
	// StatusChanged — present on both sides with differing content.
	StatusChanged ChangeStatus = "changed"
	// StatusRemoved — present only on the left (Old) side.
	StatusRemoved ChangeStatus = "removed"
)

type Doc

type Doc struct {
	Manifest map[string]any
	Parent   Parent
}

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 = Format(output.FormatGitHub)
	// 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 = Format(output.FormatDiff)
	// FormatHuman is dyff's colored, human-readable report — the default
	// style, and the zero value.
	FormatHuman Format = Format(output.FormatHuman)
	// FormatBrief is dyff's one-line-per-change summary.
	FormatBrief Format = Format(output.FormatBrief)
	// FormatGitLab is dyff's GitLab diff syntax (`=` path/root prefixes).
	FormatGitLab Format = Format(output.FormatGitLab)
	// FormatGitea is dyff's Gitea/Forgejo diff syntax.
	FormatGitea Format = Format(output.FormatGitea)
	// 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 = Format(output.FormatHTML)
	// FormatJSON encodes changes and suppressions in one JSON object.
	FormatJSON Format = Format(output.FormatJSON)
)

Recognized Format values.

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 tunes Compare and RenderDocs behavior.

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. It distinguishes resources from different producers and attributes structured output.

type Side added in v0.6.2

type Side string

Side names the side of a comparison. Left is the orig (base, --path-orig) tree and right the current (head, --path) tree. Suppression also uses "both" when output is withheld for unavailable producers on both sides.

const (
	SideOrig    Side = "orig"
	SideCurrent Side = "current"
	SideBoth    Side = "both"
)

Side values, in the vocabulary the CLI uses for --path-orig / --path.

type Snapshot added in v0.7.3

type Snapshot struct {
	Subjects    map[manifest.NamedResource]manifest.DiagnosticIdentity
	Manifests   []manifest.DocumentBatch
	Unavailable map[manifest.NamedResource]store.StatusInfo
	// ProducerKeys maps actual producers to their paired comparison identities.
	ProducerKeys map[manifest.NamedResource]manifest.NamedResource
}

Snapshot contains selected document batches and their render availability. Manifests and status entries remain immutable during comparison.

type Suppression added in v0.6.2

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 Compare added in v0.7.3

func Compare(
	orig, current Snapshot,
	selectedErr error,
	opts Options,
) ([]byte, []manifest.Warning, []Suppression, error)

Compare compares two selected snapshots in orig/current order. Selected errors remain errors even when the snapshots produce a usable partial diff; discovered warnings and structured suppressions remain available alongside those errors.

func CompareImages added in v0.7.3

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 added in v0.6.2

func (s Suppression) String() string

String renders the suppression as a human-readable sentence.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL