renderer

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package renderer contains the logic for formatting and displaying diffs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatDiff

func FormatDiff(diffs []diffmatchpatch.Diff, options DiffOptions) string

FormatDiff formats a slice of diffs according to the provided options.

func GenerateDiffWithOptions

func GenerateDiffWithOptions(_ context.Context, current, desired *un.Unstructured, logger logging.Logger, options DiffOptions) (*t.ResourceDiff, error)

GenerateDiffWithOptions produces a structured diff between two unstructured objects.

func GetLineDiff

func GetLineDiff(oldText, newText string) []diffmatchpatch.Diff

GetLineDiff performs a proper line-by-line diff and returns the raw diffs.

Types

type AffectedResourcesSummary added in v0.7.0

type AffectedResourcesSummary struct {
	Total       int `json:"total"`
	WithChanges int `json:"withChanges"`
	Unchanged   int `json:"unchanged"`
	WithErrors  int `json:"withErrors"`
	// FilteredByPolicy counts XRs excluded because of a Manual compositionUpdatePolicy
	// (FilterReasonManualPolicy).
	FilteredByPolicy int `json:"filteredByPolicy,omitempty"`
	// FilteredBySelector counts XRs excluded because their compositionRevisionSelector does not match
	// the diffed composition's labels (FilterReasonRevisionSelectorMismatch). Kept separate from
	// FilteredByPolicy so the breakdown is visible even in default-discovery mode, where individual
	// XR impacts are not surfaced.
	FilteredBySelector int `json:"filteredBySelector,omitempty"`
}

AffectedResourcesSummary contains counts of affected resources by status.

type ChangeDetail added in v0.6.0

type ChangeDetail struct {
	Type       string         `json:"type"`
	APIVersion string         `json:"apiVersion"`
	Kind       string         `json:"kind"`
	Name       string         `json:"name"`
	Namespace  string         `json:"namespace,omitempty"`
	Diff       map[string]any `json:"diff"`
}

ChangeDetail represents a single resource change.

type CompDiffOutput added in v0.7.0

type CompDiffOutput struct {
	Compositions []CompositionDiff
	Errors       []dt.OutputError // top-level errors (e.g., XRs that failed impact analysis)
}

CompDiffOutput is the top-level output for composition diffs (internal representation). This stores rich ResourceDiff data. Conversion to JSON happens in the renderer.

type CompDiffRenderer added in v0.7.0

type CompDiffRenderer interface {
	// RenderCompDiff renders the complete composition diff output.
	// Top-level and tool errors go to DiffOptions.Stderr and are included in
	// structured output payloads. Per-composition messages (diffs, "no changes",
	// per-composition errors) go to DiffOptions.Stdout as part of the diff narrative.
	RenderCompDiff(output *CompDiffOutput) error
}

CompDiffRenderer renders composition diff results. Both human-readable and structured (JSON/YAML) renderers implement this interface.

func NewDefaultCompDiffRenderer added in v0.7.0

func NewDefaultCompDiffRenderer(logger logging.Logger, diffRenderer DiffRenderer, opts DiffOptions) CompDiffRenderer

NewDefaultCompDiffRenderer creates a new human-readable composition diff renderer.

func NewStructuredCompDiffRenderer added in v0.7.0

func NewStructuredCompDiffRenderer(logger logging.Logger, opts DiffOptions) CompDiffRenderer

NewStructuredCompDiffRenderer creates a new structured composition diff renderer.

type CompactDiffFormatter

type CompactDiffFormatter struct{}

CompactDiffFormatter formats diffs with limited context lines.

func (*CompactDiffFormatter) Format

func (f *CompactDiffFormatter) Format(diffs []diffmatchpatch.Diff, options DiffOptions) string

Format implements the DiffFormatter interface for CompactDiffFormatter.

type CompositionDiff added in v0.7.0

type CompositionDiff struct {
	Name              string
	Error             error            // per-composition error (nil if successful)
	CompositionDiff   *dt.ResourceDiff // the actual composition diff (nil if unchanged)
	AffectedResources AffectedResourcesSummary
	ImpactAnalysis    []XRImpact
}

CompositionDiff represents the diff result for a single composition (internal). This stores rich ResourceDiff data. Conversion to JSON happens in the renderer.

func (*CompositionDiff) HasChanges added in v0.7.0

func (c *CompositionDiff) HasChanges() bool

HasChanges returns true if this composition diff has any changes.

type DefaultCompDiffRenderer added in v0.7.0

type DefaultCompDiffRenderer struct {
	// contains filtered or unexported fields
}

DefaultCompDiffRenderer renders composition diffs in human-readable format.

func (*DefaultCompDiffRenderer) RenderCompDiff added in v0.7.0

func (r *DefaultCompDiffRenderer) RenderCompDiff(output *CompDiffOutput) error

RenderCompDiff renders the composition diff in human-readable format. Top-level errors go to r.opts.Stderr. Per-composition output (diffs, status messages, per-composition errors) goes to r.opts.Stdout.

type DefaultDiffRenderer

type DefaultDiffRenderer struct {
	// contains filtered or unexported fields
}

DefaultDiffRenderer implements the DiffRenderer interface.

func (*DefaultDiffRenderer) RenderDiffs

func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.OutputError) error

RenderDiffs formats and prints the diffs. Diff output goes to r.diffOpts.Stdout, errors go to r.diffOpts.Stderr.

Identity-bearing groups (the xr command) render as per-input-XR sections, each with a header and per-section summary, followed by an aggregate footer when there is more than one such group. Identity-less groups (the composition renderer's reuse) render as a single flat block, preserving the pre-grouping behavior.

func (*DefaultDiffRenderer) SetDiffOptions

func (r *DefaultDiffRenderer) SetDiffOptions(options DiffOptions)

SetDiffOptions updates the diff options used by the renderer.

type DiffFormatter

type DiffFormatter interface {
	Format(diffs []diffmatchpatch.Diff, options DiffOptions) string
}

DiffFormatter is the interface that defines the contract for diff formatters.

func NewFormatter

func NewFormatter(compact bool) DiffFormatter

NewFormatter returns a DiffFormatter based on whether compact mode is desired.

type DiffOptions

type DiffOptions struct {
	// Stdout is the writer for diff output (defaults to os.Stdout)
	Stdout io.Writer

	// Stderr is the writer for error output (defaults to os.Stderr)
	// Errors are written here following Unix conventions (errors to stderr, output to stdout)
	Stderr io.Writer

	// Format specifies the output format (diff, json, yaml)
	Format OutputFormat

	// UseColors determines whether to colorize the output
	UseColors bool

	// AddPrefix is the prefix for added lines (default "+")
	AddPrefix string

	// DeletePrefix is the prefix for deleted lines (default "-")
	DeletePrefix string

	// ContextPrefix is the prefix for unchanged lines (default " ")
	ContextPrefix string

	// ContextLines is the number of unchanged lines to show before/after changes in compact mode
	ContextLines int

	// ChunkSeparator is the string used to separate chunks in compact mode
	ChunkSeparator string

	// Compact determines whether to show a compact diff
	Compact bool

	// IgnorePaths is a list of paths to ignore when calculating diffs
	// Supports both simple paths (e.g., "metadata.annotations") and
	// map key paths (e.g., "metadata.annotations[key.name/value]")
	IgnorePaths []string

	// MinimizeComposition collapses composition changes to a single marker line
	// per composition, omitting the full YAML diff body. Only consumed by the
	// human-readable composition diff renderer; structured output is unaffected.
	MinimizeComposition bool
}

DiffOptions holds configuration options for the diff output.

func DefaultDiffOptions

func DefaultDiffOptions() DiffOptions

DefaultDiffOptions returns the default options with colors enabled.

type DiffRenderer

type DiffRenderer interface {
	// RenderDiffs formats and outputs diffs, grouped by input XR.
	// Diff output goes to DiffOptions.Stdout, errors go to DiffOptions.Stderr.
	// The errs parameter contains the union of resource processing errors to
	// include in output (the top-level/global error list).
	RenderDiffs(groups []dt.XRDiffGroup, errs []dt.OutputError) error
}

DiffRenderer handles rendering diffs to output.

func NewDiffRenderer

func NewDiffRenderer(logger logging.Logger, diffOpts DiffOptions) DiffRenderer

NewDiffRenderer creates a new DefaultDiffRenderer with the given options.

func NewStructuredDiffRenderer added in v0.6.0

func NewStructuredDiffRenderer(logger logging.Logger, opts DiffOptions) DiffRenderer

NewStructuredDiffRenderer creates a new structured renderer with the specified format.

type DownstreamChanges added in v0.7.0

type DownstreamChanges struct {
	Summary Summary        `json:"summary"`
	Changes []ChangeDetail `json:"changes"`
}

DownstreamChanges contains the downstream resource changes for an XR.

type FilterReason added in v0.9.0

type FilterReason string

FilterReason explains why an XRImpact has XRStatusFiltered. It is only meaningful when XRImpact.Status == XRStatusFiltered.

const (
	// FilterReasonManualPolicy indicates the XR was excluded because it has a Manual
	// compositionUpdatePolicy and --include-manual was not set. Such XRs are pinned to a specific
	// revision and would not adopt the composition change automatically.
	FilterReasonManualPolicy FilterReason = "manual_policy"
	// FilterReasonRevisionSelectorMismatch indicates the XR was excluded because it has an Automatic
	// compositionUpdatePolicy with a compositionRevisionSelector that does not match the labels of
	// the composition change being diffed. Such XRs would not select the resulting revision.
	FilterReasonRevisionSelectorMismatch FilterReason = "revision_selector_mismatch"
)

type FullDiffFormatter

type FullDiffFormatter struct{}

FullDiffFormatter formats diffs with all context lines.

func (*FullDiffFormatter) Format

func (f *FullDiffFormatter) Format(diffs []diffmatchpatch.Diff, options DiffOptions) string

Format implements the DiffFormatter interface for FullDiffFormatter.

type OutputError added in v0.7.0

type OutputError = dt.OutputError

OutputError is an alias for dt.OutputError for convenience. Use this type for error handling in structured output.

type OutputFormat added in v0.6.0

type OutputFormat string

OutputFormat represents the desired output format for diffs.

const (
	// OutputFormatDiff is the default human-readable diff format.
	OutputFormatDiff OutputFormat = "diff"
	// OutputFormatJSON outputs structured JSON.
	OutputFormatJSON OutputFormat = "json"
	// OutputFormatYAML outputs structured YAML.
	OutputFormatYAML OutputFormat = "yaml"
)

type StructuredCompDiffRenderer added in v0.7.0

type StructuredCompDiffRenderer struct {
	// contains filtered or unexported fields
}

StructuredCompDiffRenderer renders composition diffs in JSON/YAML format.

func (*StructuredCompDiffRenderer) RenderCompDiff added in v0.7.0

func (r *StructuredCompDiffRenderer) RenderCompDiff(output *CompDiffOutput) error

RenderCompDiff renders the composition diff in structured format (JSON/YAML). Top-level errors go to both r.opts.Stderr (for human visibility) and the structured output payload. Per-composition data goes to r.opts.Stdout.

type StructuredDiffOutput added in v0.6.0

type StructuredDiffOutput struct {
	// Summary is the aggregate change count across every input XR.
	Summary Summary `json:"summary"`

	// Changes is the flat, ungrouped list of all resource changes across every
	// input XR.
	//
	// Deprecated: use Xrs for per-input-XR grouping. This field is retained for
	// backward compatibility and will be removed in a future major release.
	Changes []ChangeDetail `json:"changes"`

	// Errors is the union of resource-processing errors across all input XRs
	// (the top-level/global error list). Each errored XR also surfaces its
	// error inside its own Xrs entry; this list stays complete for consumers
	// that read errors here.
	Errors []dt.OutputError `json:"errors,omitempty"`

	// Xrs groups changes by the input XR/claim that produced them, one entry
	// per input in input order. This is the recommended view; the flat Changes
	// field above is deprecated.
	Xrs []xrDiffWire `json:"xrs"`
}

StructuredDiffOutput represents the structured output format for diffs. Note: Only JSON tags are used because sigs.k8s.io/yaml uses JSON tags for YAML serialization.

type StructuredDiffRenderer added in v0.6.0

type StructuredDiffRenderer struct {
	// contains filtered or unexported fields
}

StructuredDiffRenderer renders diffs in structured formats (JSON/YAML).

func (*StructuredDiffRenderer) RenderDiffs added in v0.6.0

func (r *StructuredDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.OutputError) error

RenderDiffs renders the diffs in the configured structured format.

It emits two views built from the same groups: the deprecated flat changes[]/summary (merged across all groups) for backward compatibility, and the per-input-XR xrs[] grouping. The top-level errors[] is the union passed by the caller.

type Summary added in v0.6.0

type Summary struct {
	Added    int `json:"added"`
	Modified int `json:"modified"`
	Removed  int `json:"removed"`
}

Summary contains aggregated counts of changes.

type XRImpact added in v0.7.0

type XRImpact struct {
	corev1.ObjectReference

	Status XRStatus
	// FilterReason explains a Status == XRStatusFiltered outcome; empty otherwise.
	FilterReason FilterReason
	// FilterDetail is an optional human-readable explanation for a filtered outcome (e.g. which
	// selector failed to match which labels), surfaced to help users self-diagnose the exclusion.
	FilterDetail string
	Error        error                       // store actual error, not string
	Diffs        map[string]*dt.ResourceDiff // downstream diffs (nil if unchanged/error)
}

XRImpact represents the impact analysis for a single XR (internal). This stores rich ResourceDiff data. Conversion to JSON happens in the renderer. Embeds corev1.ObjectReference for the common resource identity fields.

type XRStatus added in v0.7.0

type XRStatus string

XRStatus represents the processing status of an XR in composition diffs.

const (
	// XRStatusChanged indicates the XR has downstream resource changes.
	XRStatusChanged XRStatus = "changed"
	// XRStatusUnchanged indicates the XR has no downstream resource changes.
	XRStatusUnchanged XRStatus = "unchanged"
	// XRStatusError indicates an error occurred while processing the XR.
	XRStatusError XRStatus = "error"
	// XRStatusFiltered indicates the XR matched the composition by name but was excluded from
	// evaluation because it would not adopt the composition change being diffed. The specific cause
	// is carried separately in XRImpact.FilterReason (outcome and reason are intentionally divorced
	// so the reason set can grow without expanding the status enum). The XR is surfaced in impact
	// analysis with no downstream changes so users see the skip explicitly.
	XRStatusFiltered XRStatus = "filtered"
)

Directories

Path Synopsis
Package types provides types used in the renderer in order to facilitate code reuse in test
Package types provides types used in the renderer in order to facilitate code reuse in test

Jump to

Keyboard shortcuts

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