images

package
v0.1.135 Latest Latest
Warning

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

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

Documentation

Overview

Package images provides utilities for parsing and resolving image value mappings embedded in Chainguard Helm chart packages.

Chainguard Helm charts include metadata that describes how container image references map to values.yaml paths. This package parses that metadata and provides an API for resolving image references into concrete Helm values without requiring callers to understand the underlying template format.

Patching a values.yaml File

The simplest way to use a mapping is Mapping.Resolve, which substitutes all image references and patches the results into a YAML values file while preserving comments and formatting:

m, err := images.Parse(reader)
if err != nil {
	return err
}

refs := map[string]string{
	"nginx": "cgr.dev/chainguard/nginx:latest@sha256:abc123...",
}
patched, err := m.Resolve(refs, bytes.NewReader(originalValues))

Custom Transformations

When the output is not a simple string — for example, generating Terraform expressions or building relocation overrides — use Mapping.Walk with a custom callback. Walk lexes each template value into a TokenList and invokes the callback per image:

values, err := m.Walk(func(imageID string, tokens images.TokenList) (any, error) {
	// Inspect tokens to decide what to emit.
	// Return nil to exclude a field from the output.
	parts := tokens.Map(func(f images.RefField) any {
		return myCustomTransform(f)
	})
	return parts, nil
})

TokenList.Map applies a function to each RefField in the token list, preserving literal segments. The RefField constants (Registry, Repo, Tag, Digest, etc.) identify which component of an image reference a given template position expects.

Resolve is a convenience that returns a WalkFunc performing standard string substitution from a map of OCIRef values. It can be passed directly to Walk.

Results from Walk are returned as ImageValues, which can be combined into a single map with ImageValues.Merge.

Index

Examples

Constants

View Source
const ChainguardChartMetadataFilename = "cg.json"

ChainguardChartMetadataFilename is the name of the Chainguard metadata file embedded in chart APKs.

Variables

This section is empty.

Functions

This section is empty.

Types

type Image

type Image struct {
	Values      map[string]any `json:"values"`
	Requirement Requirement    `json:"requirement,omitempty"`
}

Image defines how a single container image maps to values.yaml paths.

type ImageValues

type ImageValues map[string]map[string]any

ImageValues maps image IDs to their resolved values.

func (ImageValues) Merge

func (v ImageValues) Merge() (map[string]any, error)

Merge combines all image values into a single map. Images are merged in sorted order by ID for deterministic results. Returns an error if there's a conflict (e.g., merging a map with a non-map at the same path).

type Mapping

type Mapping struct {
	Images map[string]*Image `json:"images"`
}

Mapping is the top-level schema for chart image value mappings, parsed from the cg.json file embedded in Chainguard chart APKs.

func Parse

func Parse(r io.Reader) (*Mapping, error)

Parse parses and validates a Mapping from JSON. Returns an error if the JSON is invalid, required fields are missing, or any ${...} markers reference unknown fields.

Example

ExampleParse demonstrates parsing a chart image mapping from JSON.

package main

import (
	"fmt"
	"strings"

	"chainguard.dev/sdk/helm/images"
)

func main() {
	const mapping = `{
		"images": {
			"nginx": {
				"values": {
					"image.repository": "${registry}/${repo}",
					"image.tag": "${tag}"
				}
			}
		}
	}`
	m, err := images.Parse(strings.NewReader(mapping))
	fmt.Println(err)
	fmt.Println(len(m.Images))
}
Output:
<nil>
1

func (*Mapping) ForImages added in v0.1.58

func (m *Mapping) ForImages(refs map[string]string) *Mapping

ForImages returns a new Mapping containing only the images whose IDs are present as keys in refs. This is used to exclude skipped (e.g., optional) images from template resolution.

func (*Mapping) Resolve

func (m *Mapping) Resolve(refs map[string]string, valuesr io.Reader, opts ...ResolveOption) ([]byte, error)

Resolve resolves all image references in the mapping and patches the results into the provided values.yaml content, preserving YAML comments and formatting.

By default, all template paths must exist in the YAML — an error is returned for missing paths. Use WithAddMissing to allow missing paths to be added.

func (*Mapping) Walk

func (m *Mapping) Walk(fn WalkFunc) (ImageValues, error)

Walk traverses all string values in the mapping, lexing them into tokens. The callback receives the image ID and tokens for each string value. Returns transformed values for each image.

type OCIRef

type OCIRef struct {
	Registry     string // Registry host, e.g., "cgr.dev"
	Repo         string // Repository path without registry, e.g., "chainguard/nginx"
	Tag          string // OCI tag, e.g., "latest" (may be empty)
	Digest       string // OCI digest, e.g., "sha256:abc123..." (may be empty)
	RegistryRepo string // Combined registry/repo, e.g., "cgr.dev/chainguard/nginx"
	FullRef      string // Full reference with tag and/or digest as available
}

OCIRef holds the components of an OCI reference. Use NewRef to construct - it parses and validates the reference string.

func NewRef

func NewRef(reference string) (OCIRef, error)

NewRef parses an OCI reference string into its components. Unlike github.com/google/go-containerregistry/pkg/name.ParseReference, it preserves the tag from tag@digest references for use with PseudoTag.

type RefField

type RefField string

RefField represents a field of an image reference (registry, repo, tag, etc.).

const (
	Registry     RefField = "registry"      // Registry host, e.g., "cgr.dev"
	Repo         RefField = "repo"          // Repository without registry, e.g., "chainguard/nginx"
	RegistryRepo RefField = "registry_repo" // Registry and repo combined, e.g., "cgr.dev/chainguard/nginx"
	Tag          RefField = "tag"           // OCI tag, e.g., "latest"
	Digest       RefField = "digest"        // OCI digest, e.g., "sha256:abc..."
	PseudoTag    RefField = "pseudo_tag"    // Tag and digest as "tag@digest"
	Ref          RefField = "ref"           // Full reference with tag and/or digest
)

RefField constants for the supported image reference components.

type Requirement added in v0.1.56

type Requirement string

Requirement represents whether an image is required or optional for a chart.

const (
	// RequirementUnspecified is the zero value; treated as required.
	RequirementUnspecified Requirement = ""
	// Required indicates the image must be present.
	Required Requirement = "required"
	// Optional indicates the image may be omitted.
	Optional Requirement = "optional"
)

func (Requirement) IsOptional added in v0.1.56

func (r Requirement) IsOptional() bool

IsOptional reports whether the image may be omitted. Unspecified and required both return false, so the default behavior fails closed (image is required).

type ResolveOption added in v0.1.53

type ResolveOption func(*resolveConfig)

ResolveOption allows customizing the resolution process.

func WithAddMissing added in v0.1.56

func WithAddMissing(addMissing bool) ResolveOption

WithAddMissing controls whether paths not present in the target YAML are added (true) or cause an error (false, the default). Use this when patching values that may not have pre-existing entries, such as subchart overrides.

func WithOmitDigests added in v0.1.53

func WithOmitDigests(omitDigests bool) ResolveOption

WithOmitDigests controls whether digests are included in resolved values. Default is false.

type TokenList

type TokenList []token

TokenList is a sequence of tokens from lexing a value string.

func (TokenList) Map

func (t TokenList) Map(fn func(RefField) any) []any

Map applies fn to each RefField in the token list, preserving literal string segments as-is. Returns a slice with one entry per token.

type WalkFunc

type WalkFunc func(imageID string, tokens TokenList) (any, error)

WalkFunc is the callback signature for Mapping.Walk. It receives the image ID and tokenized string value, returning the transformed value.

func Resolve

func Resolve(refs map[string]OCIRef, opts ...ResolveOption) WalkFunc

Resolve returns a WalkFunc that resolves tokens to strings using refs.

Jump to

Keyboard shortcuts

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