template

package
v0.40.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrEmptySrc = errors.New("empty src template")

Functions

func Base64Decode

func Base64Decode(data string) (string, error)

func Base64Encode

func Base64Encode(data string) string

func ClearTemplateCache

func ClearTemplateCache()

ClearTemplateCache removes all cached templates

func CreateMap

func CreateMap(values ...interface{}) (map[string]interface{}, error)

CreateMap creates a key-value map of string -> interface{} The i'th is the key and the i+1 is the value

func GetCachedTemplate

func GetCachedTemplate(path string) (*template.Template, bool)

GetCachedTemplate returns a cached template if valid, or nil if miss/stale

func GetHostname

func GetHostname() (string, error)

func Getenv

func Getenv(key string, v ...string) string

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will the default value if the variable is not present. If no default value was given - returns "".

func InitTemplateCache

func InitTemplateCache(enabled bool, statTTL time.Duration)

InitTemplateCache initializes the global template cache

func LookupIP

func LookupIP(data string) []string

func LookupIPV4

func LookupIPV4(data string) []string

func LookupIPV6

func LookupIPV6(data string) []string

func LookupIfaceIPV4

func LookupIfaceIPV4(data string) (addr string)

func LookupIfaceIPV6

func LookupIfaceIPV6(data string) (addr string)

func LookupSRV

func LookupSRV(service, proto, name string) []*net.SRV

func NewIncludeFunc

func NewIncludeFunc(baseDir string, funcMap template.FuncMap, ctx *IncludeContext) func(string, ...interface{}) (string, error)

NewIncludeFunc creates an include function for templates. baseDir is the directory where included templates are resolved from. funcMap is the function map to use when parsing included templates.

func Preflight

func Preflight(config Config) error

Preflight performs connectivity and configuration checks without processing templates. It verifies: - Backend connectivity via HealthCheck (global and per-resource backends) - Template resources can be loaded - Keys are accessible in the backend (warning if not found)

func Process

func Process(config Config) error

Process loads and processes all template resources once.

func PutCachedTemplate

func PutCachedTemplate(path string, tmpl *template.Template, mtime time.Time)

PutCachedTemplate stores a compiled template

func Reverse

func Reverse(values interface{}) interface{}

Reverse returns the array in reversed order works with []string and []KVPair

func Seq

func Seq(first, last int) []int

Seq creates a sequence of integers. It's named and used as GNU's seq. Seq takes the first and the last element as arguments. So Seq(3, 5) will generate [3,4,5]

func SortByLength

func SortByLength(values []string) []string

func SortKVByLength

func SortKVByLength(values []memkv.KVPair) []memkv.KVPair

func TemplateCacheEnabled

func TemplateCacheEnabled() bool

TemplateCacheEnabled returns whether the template cache is enabled

func TemplateCacheSize

func TemplateCacheSize() int

TemplateCacheSize returns the number of cached templates

func UnmarshalJsonArray

func UnmarshalJsonArray(data string) ([]interface{}, error)

func UnmarshalJsonObject

func UnmarshalJsonObject(data string) (map[string]interface{}, error)

func ValidateConfig

func ValidateConfig(confDir string, resourceFile string) error

ValidateConfig validates template resource configuration files. If resourceFile is empty, all *.toml files in confdir/conf.d are validated. If resourceFile is specified, only that file is validated.

func ValidateTemplates

func ValidateTemplates(confDir string, resourceFile string, mockDataFile string) error

ValidateTemplates validates template files by parsing them. If mockDataFile is provided, templates are also executed with mock data. If resourceFile is empty, all templates are validated.

Types

type BatchProcessResult

type BatchProcessResult struct {
	Total     int              // Total templates processed
	Succeeded int              // Number of successful templates
	Failed    int              // Number of failed templates
	Statuses  []TemplateStatus // Per-template status
}

BatchProcessResult represents the outcome of processing multiple templates.

func (*BatchProcessResult) Error

func (r *BatchProcessResult) Error() error

Error returns an aggregated error from all failed templates using errors.Join. Returns nil if no templates failed.

type Config

type Config struct {
	ConfDir       string `toml:"confdir"`
	ConfigDir     string
	KeepStageFile bool
	Noop          bool   `toml:"noop"`
	Prefix        string `toml:"prefix"`
	StoreClient   backends.StoreClient
	SyncOnly      bool `toml:"sync-only"`
	TemplateDir   string
	// Diff settings for noop mode
	ShowDiff    bool
	DiffContext int
	ColorDiff   bool
	// Watch mode settings
	Debounce      time.Duration // Global debounce for all templates
	BatchInterval time.Duration // Batch processing interval
	// Context for cancellation and timeouts
	Ctx              context.Context
	BackendTimeout   time.Duration // Timeout for backend operations
	CheckCmdTimeout  time.Duration // Default timeout for check commands
	ReloadCmdTimeout time.Duration // Default timeout for reload commands
	// Watch mode and preflight timeouts
	WatchErrorBackoff time.Duration // Backoff after watch errors
	PreflightTimeout  time.Duration // Preflight check timeout
	// Error handling mode
	FailureMode FailureMode // Error handling mode
}

type FailureMode

type FailureMode int

FailureMode defines how template processing errors are handled.

const (
	// FailModeBestEffort continues processing all templates even when errors occur (default).
	FailModeBestEffort FailureMode = iota
	// FailModeFast stops processing at the first error encountered.
	FailModeFast
)

func ParseFailureMode

func ParseFailureMode(s string) (FailureMode, error)

ParseFailureMode converts a string to a FailureMode.

func (FailureMode) String

func (f FailureMode) String() string

String returns the string representation of the FailureMode.

type IncludeContext

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

IncludeContext tracks the include stack for cycle detection.

func NewIncludeContext

func NewIncludeContext() *IncludeContext

NewIncludeContext creates a new include context for tracking nested includes.

func (*IncludeContext) Depth

func (c *IncludeContext) Depth() int

Depth returns the current include depth.

func (*IncludeContext) Pop

func (c *IncludeContext) Pop()

Pop removes the most recent template from the include stack.

func (*IncludeContext) Push

func (c *IncludeContext) Push(templatePath string) error

Push adds a template to the include stack. Returns an error if the template is already in the stack (cycle) or max depth exceeded.

type Processor

type Processor interface {
	Process()
}

Processor defines the interface for template processing strategies.

func BatchWatchProcessor

func BatchWatchProcessor(config Config, stopChan, doneChan chan bool, errChan chan error, reloadChan <-chan struct{}) Processor

BatchWatchProcessor creates a processor that batches changes before processing. Changes from all templates are collected and processed together after the batch interval.

func IntervalProcessor

func IntervalProcessor(config Config, stopChan, doneChan chan bool, errChan chan error, interval int, reloadChan <-chan struct{}) Processor

IntervalProcessor creates a processor that polls for changes at a fixed interval.

func WatchProcessor

func WatchProcessor(config Config, stopChan, doneChan chan bool, errChan chan error, reloadChan <-chan struct{}) Processor

WatchProcessor creates a processor that watches for backend changes continuously.

type TemplateCache

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

TemplateCache caches compiled Go templates keyed by file path

type TemplateResource

type TemplateResource struct {
	CheckCmd string `toml:"check_cmd"`
	Dest     string
	FileMode os.FileMode
	Gid      int
	Group    string
	Keys     []string

	Mode              string
	OutputFormat      string `toml:"output_format"`       // json, yaml, toml, xml
	MinReloadInterval string `toml:"min_reload_interval"` // e.g., "30s", "1m"
	Debounce          string `toml:"debounce"`            // e.g., "2s", "500ms"
	CheckCmdTimeout   string `toml:"check_cmd_timeout"`   // e.g., "30s", "1m"
	ReloadCmdTimeout  string `toml:"reload_cmd_timeout"`  // e.g., "60s", "2m"
	Owner             string
	Prefix            string
	ReloadCmd         string `toml:"reload_cmd"`
	Src               string
	StageFile         *os.File
	Uid               int
	// contains filtered or unexported fields
}

TemplateResource is the representation of a parsed template resource.

func NewTemplateResource

func NewTemplateResource(path string, config Config) (*TemplateResource, error)

NewTemplateResource creates a TemplateResource.

type TemplateResourceConfig

type TemplateResourceConfig struct {
	TemplateResource TemplateResource `toml:"template"`
	BackendConfig    *backends.Config `toml:"backend"`
}

TemplateResourceConfig holds the parsed template resource.

type TemplateStatus

type TemplateStatus struct {
	Dest    string // Destination path of the template
	Success bool   // Whether processing succeeded
	Error   error  // Error if processing failed
}

TemplateStatus represents the processing result for a single template.

type ValidationError

type ValidationError struct {
	File    string
	Field   string
	Message string
}

ValidationError represents a validation error with context.

func (ValidationError) Error

func (e ValidationError) Error() string

Jump to

Keyboard shortcuts

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