diff

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

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 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 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 retains producer identity so equal resource names from different owners remain distinct.

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.

func Compare

func Compare(groups []Group, opts Options) (*Comparison, error)

Compare preserves group order and returns usable output alongside preparation and selected errors.

func (*Comparison) Write

func (c *Comparison) Write(w io.Writer, names []Names) error

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 = "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.

func Formats

func Formats() []Format

Formats preserves the command help order independently of writer dispatch.

type Group

type Group struct {
	Cluster        string
	Orig, Current  Snapshot
	SelectedErr    error
	Added, Removed bool
}

Group retains selected errors so partial output stays available.

type GroupResult

type GroupResult struct {
	Warnings   []manifest.Warning
	Suppressed []Suppression
	Subjects   []manifest.NamedResource
}

GroupResult keeps raw warnings separate from structured suppression disclosures.

type Names

type Names struct {
	Prefix   string
	Subjects map[manifest.NamedResource]Subject
}

Names labels only printed subjects in one retained cluster.

func (Names) Labels

func (n Names) Labels(ids []manifest.NamedResource) []string

Labels qualifies only collisions in ids, so hidden continuations cannot affect labels.

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.

func (*Naming) Warning

func (n *Naming) Warning(group int, warning manifest.Warning) Subject

Warning preserves captured subjects without changing the group context.

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

type Snapshot

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 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

Jump to

Keyboard shortcuts

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