Documentation
¶
Overview ¶
Package template provides a clean, extensible template engine abstraction for rendering Go templates with caching, validation, and error reporting.
Index ¶
- func ComposeWithEngine(ctx context.Context, engine TemplateEngine, registry TemplateRegistry, ...) ([]byte, error)
- func DangerousFunctions() []string
- func GetTemplateDependencyGraph(templates []TemplateDefinition) map[string][]string
- func HasCircularDependencies(templates []TemplateDefinition) (bool, string)
- func HasTag(template TemplateDefinition, tag string) bool
- func IsDangerousFunction(funcName string) bool
- func MatchesProvider(template TemplateDefinition, provider string) bool
- func MatchesService(template TemplateDefinition, service string) bool
- func RegisterGitOpsBaseTemplates(registry TemplateRegistry, fsys fs.FS) error
- func RegisterGitOpsTemplates(registry TemplateRegistry, fsys fs.FS) error
- func RegisterProvisionTemplates(registry TemplateRegistry, fsys fs.FS) error
- func RenderComposedTemplate(ctx context.Context, engine TemplateEngine, registry TemplateRegistry, ...) ([]byte, error)
- func ResetGlobalRegistry()
- func ValidateRenderCondition(condition RenderCondition) error
- func ValidateTemplateDefinition(template TemplateDefinition) error
- type CacheEntry
- type CacheStats
- type ConditionType
- type ContextBuilder
- func (cb *ContextBuilder) Build() (*RenderContext, error)
- func (cb *ContextBuilder) WithData(data interface{}) *ContextBuilder
- func (cb *ContextBuilder) WithFunction(name string, fn interface{}) *ContextBuilder
- func (cb *ContextBuilder) WithFunctions(funcMap template.FuncMap) *ContextBuilder
- func (cb *ContextBuilder) WithMetadata(key string, value interface{}) *ContextBuilder
- func (cb *ContextBuilder) WithStrictMode(strict bool) *ContextBuilder
- func (cb *ContextBuilder) WithValidation(validate bool) *ContextBuilder
- type DefaultTemplateComposer
- func (c *DefaultTemplateComposer) ApplyOverlays(baseContent string, overlays []TemplateOverlay, data interface{}) (string, error)
- func (c *DefaultTemplateComposer) ApplyPatches(content string, patches []TemplatePatch, data interface{}) (string, error)
- func (c *DefaultTemplateComposer) Compose(ctx context.Context, composition TemplateComposition, data interface{}) ([]byte, error)
- func (c *DefaultTemplateComposer) GetOrderingConfig() OverlayOrderingConfig
- func (c *DefaultTemplateComposer) SetOrderingConfig(config OverlayOrderingConfig)
- func (c *DefaultTemplateComposer) ValidateComposition(composition TemplateComposition) error
- type DefaultTemplateSandbox
- func (s *DefaultTemplateSandbox) GetSafeFunctions() template.FuncMap
- func (s *DefaultTemplateSandbox) RenderWithTimeout(tmpl string, data interface{}, timeout time.Duration) (string, error)
- func (s *DefaultTemplateSandbox) SetActor(actor string)
- func (s *DefaultTemplateSandbox) SetAuditLogger(logger interface{})
- func (s *DefaultTemplateSandbox) ValidateTemplate(tmpl string) error
- type DependencyResolver
- func (r *DependencyResolver) CanSafelyRemove(templateName string) (bool, []string)
- func (r *DependencyResolver) GetAllDependencies(templateName string) ([]string, error)
- func (r *DependencyResolver) GetDependencyTree(templateName string) (map[string][]string, error)
- func (r *DependencyResolver) GetDependents(templateName string) []string
- func (r *DependencyResolver) ResolveDependencies(templateNames []string) ([]TemplateDefinition, error)
- func (r *DependencyResolver) TopologicalSort(templateNames []string) ([]TemplateDefinition, error)
- func (r *DependencyResolver) ValidateDependencies(templateName string) error
- type EmbeddedTemplateRegistrar
- type FileSystemReader
- type GoTemplateEngine
- func (e *GoTemplateEngine) ClearCache()
- func (e *GoTemplateEngine) DisableSandbox()
- func (e *GoTemplateEngine) EnableSandbox()
- func (e *GoTemplateEngine) ExecuteTemplate(templateName string, data interface{}) ([]byte, error)
- func (e *GoTemplateEngine) ExecuteTemplateToWriter(templateName string, data interface{}, w io.Writer) error
- func (e *GoTemplateEngine) GetTemplate(name string) (*template.Template, error)
- func (e *GoTemplateEngine) IsSandboxed() bool
- func (e *GoTemplateEngine) LoadFromFS(fsys fs.FS, pattern string) error
- func (e *GoTemplateEngine) LoadFromFile(path string) error
- func (e *GoTemplateEngine) RegisterFunction(name string, fn interface{})
- func (e *GoTemplateEngine) RegisterFunctions(funcs template.FuncMap)
- func (e *GoTemplateEngine) Render(ctx context.Context, templatePath string, data interface{}) ([]byte, error)
- func (e *GoTemplateEngine) RenderString(ctx context.Context, templateName, templateContent string, data interface{}) ([]byte, error)
- func (e *GoTemplateEngine) RenderToWriter(ctx context.Context, templatePath string, data interface{}, w io.Writer) error
- func (e *GoTemplateEngine) SetCacheEnabled(enabled bool)
- func (e *GoTemplateEngine) ValidateTemplate(templatePath string) error
- type InMemoryTemplateCache
- func (c *InMemoryTemplateCache) Clear()
- func (c *InMemoryTemplateCache) Delete(key string)
- func (c *InMemoryTemplateCache) Get(key string) (*template.Template, bool)
- func (c *InMemoryTemplateCache) GetStats() CacheStats
- func (c *InMemoryTemplateCache) Set(key string, tmpl *template.Template)
- func (c *InMemoryTemplateCache) Size() int
- type InMemoryTemplateRegistry
- func (r *InMemoryTemplateRegistry) GetTemplate(name string) (TemplateDefinition, error)
- func (r *InMemoryTemplateRegistry) GetTemplatesForEnabledServices(enabledServices []string) []TemplateDefinition
- func (r *InMemoryTemplateRegistry) GetTemplatesForProvider(provider string) []TemplateDefinition
- func (r *InMemoryTemplateRegistry) GetTemplatesForService(service string) []TemplateDefinition
- func (r *InMemoryTemplateRegistry) GetTemplatesForType(templateType TemplateType) []TemplateDefinition
- func (r *InMemoryTemplateRegistry) ListTemplates() []TemplateDefinition
- func (r *InMemoryTemplateRegistry) RegisterTemplate(template TemplateDefinition) error
- func (r *InMemoryTemplateRegistry) ResolveTemplateDependencies(templates []string) ([]TemplateDefinition, error)
- func (r *InMemoryTemplateRegistry) UnregisterTemplate(name string) error
- type MissingKeyBehavior
- type OverlayOrderingConfig
- type OverlayOrderingStrategy
- type RegistrationOptions
- type RenderCondition
- type RenderContext
- func (rc *RenderContext) Clone() *RenderContext
- func (rc *RenderContext) ToTemplateData() map[string]interface{}
- func (rc *RenderContext) Validate() error
- func (rc *RenderContext) WithFunction(name string, fn interface{}) *RenderContext
- func (rc *RenderContext) WithFunctions(funcMap template.FuncMap) *RenderContext
- func (rc *RenderContext) WithMetadata(key string, value interface{}) *RenderContext
- func (rc *RenderContext) WithMissingKeyBehavior(behavior MissingKeyBehavior) *RenderContext
- func (rc *RenderContext) WithStrictMode(strict bool) *RenderContext
- func (rc *RenderContext) WithValidation(validate bool) *RenderContext
- type RenderOptions
- type TemplateCache
- type TemplateComposer
- type TemplateComposition
- type TemplateContext
- type TemplateDefinition
- type TemplateEngine
- type TemplateMetadata
- type TemplateOverlay
- type TemplatePatch
- type TemplateRegistry
- type TemplateSandbox
- type TemplateType
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ComposeWithEngine ¶
func ComposeWithEngine(ctx context.Context, engine TemplateEngine, registry TemplateRegistry, composition TemplateComposition, data interface{}) ([]byte, error)
ComposeWithEngine is a convenience function that creates a composer and composes a template
func DangerousFunctions ¶
func DangerousFunctions() []string
DangerousFunctions returns a list of dangerous Sprig functions that are disabled in the sandbox. This is useful for documentation and error messages.
func GetTemplateDependencyGraph ¶
func GetTemplateDependencyGraph(templates []TemplateDefinition) map[string][]string
GetTemplateDependencyGraph builds a dependency graph for templates
func HasCircularDependencies ¶
func HasCircularDependencies(templates []TemplateDefinition) (bool, string)
HasCircularDependencies checks if there are circular dependencies in a set of templates
func HasTag ¶
func HasTag(template TemplateDefinition, tag string) bool
HasTag checks if a template has a specific tag
func IsDangerousFunction ¶
IsDangerousFunction checks if a function name is in the list of dangerous functions.
func MatchesProvider ¶
func MatchesProvider(template TemplateDefinition, provider string) bool
MatchesProvider checks if a template matches a given provider
func MatchesService ¶
func MatchesService(template TemplateDefinition, service string) bool
MatchesService checks if a template is associated with a given service
func RegisterGitOpsBaseTemplates ¶
func RegisterGitOpsBaseTemplates(registry TemplateRegistry, fsys fs.FS) error
RegisterGitOpsBaseTemplates registers all templates from the gitops-base-dir embedded filesystem
func RegisterGitOpsTemplates ¶
func RegisterGitOpsTemplates(registry TemplateRegistry, fsys fs.FS) error
RegisterGitOpsTemplates registers all templates from the gitops embedded filesystem
func RegisterProvisionTemplates ¶
func RegisterProvisionTemplates(registry TemplateRegistry, fsys fs.FS) error
RegisterProvisionTemplates registers all templates from the provision embedded filesystem
func RenderComposedTemplate ¶
func RenderComposedTemplate(ctx context.Context, engine TemplateEngine, registry TemplateRegistry, baseTemplate string, overlays []TemplateOverlay, data interface{}) ([]byte, error)
RenderComposedTemplate renders a template composition using the provided engine and registry
func ResetGlobalRegistry ¶
func ResetGlobalRegistry()
ResetGlobalRegistry resets the global registry for testing purposes. This should only be used in tests.
func ValidateRenderCondition ¶
func ValidateRenderCondition(condition RenderCondition) error
ValidateRenderCondition validates a render condition
func ValidateTemplateDefinition ¶
func ValidateTemplateDefinition(template TemplateDefinition) error
ValidateTemplateDefinition validates a template definition for completeness and correctness
Types ¶
type CacheEntry ¶
type CacheEntry struct {
Template *template.Template
CreatedAt time.Time
AccessedAt time.Time
AccessCount int64
}
CacheEntry represents a cached template with metadata.
type CacheStats ¶
CacheStats provides statistics about cache usage.
type ConditionType ¶
type ConditionType string
ConditionType represents the type of rendering condition
const ( ConditionTypeEquals ConditionType = "equals" ConditionTypeNotEquals ConditionType = "not_equals" ConditionTypeContains ConditionType = "contains" ConditionTypeExists ConditionType = "exists" ConditionTypeGreaterThan ConditionType = "greater_than" ConditionTypeLessThan ConditionType = "less_than" )
type ContextBuilder ¶
type ContextBuilder struct {
// contains filtered or unexported fields
}
ContextBuilder provides a fluent interface for building render contexts.
func NewContextBuilder ¶
func NewContextBuilder() *ContextBuilder
NewContextBuilder creates a new context builder.
func (*ContextBuilder) Build ¶
func (cb *ContextBuilder) Build() (*RenderContext, error)
Build builds and validates the render context.
func (*ContextBuilder) WithData ¶
func (cb *ContextBuilder) WithData(data interface{}) *ContextBuilder
WithData sets the primary data for the context.
func (*ContextBuilder) WithFunction ¶
func (cb *ContextBuilder) WithFunction(name string, fn interface{}) *ContextBuilder
WithFunction adds a custom function to the context.
func (*ContextBuilder) WithFunctions ¶
func (cb *ContextBuilder) WithFunctions(funcMap template.FuncMap) *ContextBuilder
WithFunctions adds multiple custom functions to the context.
func (*ContextBuilder) WithMetadata ¶
func (cb *ContextBuilder) WithMetadata(key string, value interface{}) *ContextBuilder
WithMetadata adds metadata to the context.
func (*ContextBuilder) WithStrictMode ¶
func (cb *ContextBuilder) WithStrictMode(strict bool) *ContextBuilder
WithStrictMode enables or disables strict mode.
func (*ContextBuilder) WithValidation ¶
func (cb *ContextBuilder) WithValidation(validate bool) *ContextBuilder
WithValidation enables or disables pre-render validation.
type DefaultTemplateComposer ¶
type DefaultTemplateComposer struct {
// contains filtered or unexported fields
}
DefaultTemplateComposer is the default implementation of TemplateComposer
func NewDefaultTemplateComposer ¶
func NewDefaultTemplateComposer(engine TemplateEngine, registry TemplateRegistry) *DefaultTemplateComposer
NewDefaultTemplateComposer creates a new default template composer
func (*DefaultTemplateComposer) ApplyOverlays ¶
func (c *DefaultTemplateComposer) ApplyOverlays(baseContent string, overlays []TemplateOverlay, data interface{}) (string, error)
ApplyOverlays applies overlays to a base template in priority order This implements Property 29: Deterministic Overlay Ordering **Validates: Requirements 7.2**
func (*DefaultTemplateComposer) ApplyPatches ¶
func (c *DefaultTemplateComposer) ApplyPatches(content string, patches []TemplatePatch, data interface{}) (string, error)
ApplyPatches applies patches to template content
Patch System Overview: The patch system supports three operations: add, remove, and replace. Each operation supports multiple path strategies for flexible content manipulation.
Path Strategies:
1. ADD Operation:
- Path "." or empty: Append to end of content
- Path "line:N": Insert after line number N (0-indexed)
- Path "pattern": Insert after first line containing pattern
- Example: {Operation: "add", Path: "line:5", Value: "new content"}
2. REMOVE Operation:
- Path "line:N": Remove line number N (0-indexed)
- Path "lines:N-M": Remove line range from N to M (inclusive)
- Path "pattern": Remove all lines containing pattern
- Example: {Operation: "remove", Path: "lines:10-15"}
3. REPLACE Operation:
- Path "line:N": Replace line number N (0-indexed)
- Path "pattern": Replace first line containing pattern
- For YAML key-value lines, preserves indentation and key
- Example: {Operation: "replace", Path: "replicas", Value: "5"}
Conditional Patches: All patches support optional conditions that must be met for the patch to apply. Example: {Operation: "add", Path: ".", Value: "debug: true", Condition: {Type: "equals", Field: "env", Value: "dev"}}
func (*DefaultTemplateComposer) Compose ¶
func (c *DefaultTemplateComposer) Compose(ctx context.Context, composition TemplateComposition, data interface{}) ([]byte, error)
Compose combines a base template with overlays and patches This implements Property 28: Overlay Application Correctness **Validates: Requirements 7.1**
func (*DefaultTemplateComposer) GetOrderingConfig ¶
func (c *DefaultTemplateComposer) GetOrderingConfig() OverlayOrderingConfig
GetOrderingConfig returns the current overlay ordering configuration
func (*DefaultTemplateComposer) SetOrderingConfig ¶
func (c *DefaultTemplateComposer) SetOrderingConfig(config OverlayOrderingConfig)
SetOrderingConfig sets the overlay ordering configuration
func (*DefaultTemplateComposer) ValidateComposition ¶
func (c *DefaultTemplateComposer) ValidateComposition(composition TemplateComposition) error
ValidateComposition validates that a composition is valid This implements Property 30: Overlay Compatibility Validation **Validates: Requirements 7.3**
type DefaultTemplateSandbox ¶
type DefaultTemplateSandbox struct {
// contains filtered or unexported fields
}
DefaultTemplateSandbox implements TemplateSandbox with a safe subset of template functions.
func NewTemplateSandbox ¶
func NewTemplateSandbox() *DefaultTemplateSandbox
NewTemplateSandbox creates a new template sandbox with default safe functions and 30-second timeout.
func NewTemplateSandboxWithTimeout ¶
func NewTemplateSandboxWithTimeout(timeout time.Duration) *DefaultTemplateSandbox
NewTemplateSandboxWithTimeout creates a new template sandbox with a custom timeout.
func (*DefaultTemplateSandbox) GetSafeFunctions ¶
func (s *DefaultTemplateSandbox) GetSafeFunctions() template.FuncMap
GetSafeFunctions returns the map of safe template functions.
func (*DefaultTemplateSandbox) RenderWithTimeout ¶
func (s *DefaultTemplateSandbox) RenderWithTimeout(tmpl string, data interface{}, timeout time.Duration) (string, error)
RenderWithTimeout renders a template with the given data and enforces a timeout. This prevents denial-of-service attacks from infinite loops or extremely slow templates.
func (*DefaultTemplateSandbox) SetActor ¶
func (s *DefaultTemplateSandbox) SetActor(actor string)
SetActor sets the actor (user/system) performing template operations
func (*DefaultTemplateSandbox) SetAuditLogger ¶
func (s *DefaultTemplateSandbox) SetAuditLogger(logger interface{})
SetAuditLogger sets the audit logger for logging template validation failures
func (*DefaultTemplateSandbox) ValidateTemplate ¶
func (s *DefaultTemplateSandbox) ValidateTemplate(tmpl string) error
ValidateTemplate validates that a template only uses safe functions. It attempts to parse the template with the safe function map and returns an error if the template references any undefined (dangerous) functions.
type DependencyResolver ¶
type DependencyResolver struct {
// contains filtered or unexported fields
}
DependencyResolver handles template dependency resolution
func NewDependencyResolver ¶
func NewDependencyResolver(registry TemplateRegistry) *DependencyResolver
NewDependencyResolver creates a new dependency resolver
func (*DependencyResolver) CanSafelyRemove ¶
func (r *DependencyResolver) CanSafelyRemove(templateName string) (bool, []string)
CanSafelyRemove checks if a template can be safely removed without breaking dependencies
func (*DependencyResolver) GetAllDependencies ¶
func (r *DependencyResolver) GetAllDependencies(templateName string) ([]string, error)
GetAllDependencies returns all direct and transitive dependencies for a template
func (*DependencyResolver) GetDependencyTree ¶
func (r *DependencyResolver) GetDependencyTree(templateName string) (map[string][]string, error)
GetDependencyTree builds a complete dependency tree for a template
func (*DependencyResolver) GetDependents ¶
func (r *DependencyResolver) GetDependents(templateName string) []string
GetDependents returns all templates that depend on the given template
func (*DependencyResolver) ResolveDependencies ¶
func (r *DependencyResolver) ResolveDependencies(templateNames []string) ([]TemplateDefinition, error)
ResolveDependencies resolves all dependencies for a set of templates Returns templates in dependency order (dependencies first)
func (*DependencyResolver) TopologicalSort ¶
func (r *DependencyResolver) TopologicalSort(templateNames []string) ([]TemplateDefinition, error)
TopologicalSort performs a topological sort on templates based on dependencies
func (*DependencyResolver) ValidateDependencies ¶
func (r *DependencyResolver) ValidateDependencies(templateName string) error
ValidateDependencies checks if all dependencies for a template exist
type EmbeddedTemplateRegistrar ¶
type EmbeddedTemplateRegistrar struct {
// contains filtered or unexported fields
}
EmbeddedTemplateRegistrar handles registration of embedded templates into the registry
func NewEmbeddedTemplateRegistrar ¶
func NewEmbeddedTemplateRegistrar(registry TemplateRegistry) *EmbeddedTemplateRegistrar
NewEmbeddedTemplateRegistrar creates a new registrar for embedded templates
func (*EmbeddedTemplateRegistrar) RegisterFromFS ¶
func (r *EmbeddedTemplateRegistrar) RegisterFromFS(fsys fs.FS, basePath string, opts RegistrationOptions) error
RegisterFromFS scans an embedded filesystem and registers all templates found
type FileSystemReader ¶
FileSystemReader provides an interface for reading files. This allows for dependency injection and testing.
type GoTemplateEngine ¶
type GoTemplateEngine struct {
// contains filtered or unexported fields
}
GoTemplateEngine implements TemplateEngine using Go's text/template package. It provides caching, custom function registration, and comprehensive error reporting. By default, it includes all Sprig functions for enhanced template capabilities.
func NewGoTemplateEngine ¶
func NewGoTemplateEngine() *GoTemplateEngine
NewGoTemplateEngine creates a new Go template engine with default settings. Caching is enabled by default for optimal performance. Sprig functions are automatically registered for enhanced template capabilities.
func (*GoTemplateEngine) ClearCache ¶
func (e *GoTemplateEngine) ClearCache()
ClearCache clears all cached templates. This forces all templates to be re-parsed on next render.
func (*GoTemplateEngine) DisableSandbox ¶
func (e *GoTemplateEngine) DisableSandbox()
DisableSandbox disables template sandboxing and restores full Sprig functions.
func (*GoTemplateEngine) EnableSandbox ¶
func (e *GoTemplateEngine) EnableSandbox()
EnableSandbox enables template sandboxing for secure rendering. When enabled, only safe template functions are available and dangerous functions (env, readFile, exec, etc.) are disabled. Templates are also subject to timeout enforcement.
func (*GoTemplateEngine) ExecuteTemplate ¶
func (e *GoTemplateEngine) ExecuteTemplate(templateName string, data interface{}) ([]byte, error)
ExecuteTemplate executes a named template from a collection with the given data. This is useful when multiple templates are loaded together and reference each other. The template must have been previously loaded via LoadFromFS or LoadFromFile.
func (*GoTemplateEngine) ExecuteTemplateToWriter ¶
func (e *GoTemplateEngine) ExecuteTemplateToWriter(templateName string, data interface{}, w io.Writer) error
ExecuteTemplateToWriter executes a named template and writes the result to the writer. This is more efficient than ExecuteTemplate when writing directly to a file or network connection.
func (*GoTemplateEngine) GetTemplate ¶
func (e *GoTemplateEngine) GetTemplate(name string) (*template.Template, error)
GetTemplate returns a parsed template by name. This is useful for direct access to the template.Template object. The template must have been previously loaded via LoadFromFS or LoadFromFile.
func (*GoTemplateEngine) IsSandboxed ¶
func (e *GoTemplateEngine) IsSandboxed() bool
IsSandboxed returns whether sandboxing is currently enabled.
func (*GoTemplateEngine) LoadFromFS ¶
func (e *GoTemplateEngine) LoadFromFS(fsys fs.FS, pattern string) error
LoadFromFS loads templates from an embedded filesystem. The pattern follows the same rules as filepath.Match. All matching templates are parsed and cached.
func (*GoTemplateEngine) LoadFromFile ¶
func (e *GoTemplateEngine) LoadFromFile(path string) error
LoadFromFile loads a single template from a file. The template is parsed and cached if caching is enabled.
func (*GoTemplateEngine) RegisterFunction ¶
func (e *GoTemplateEngine) RegisterFunction(name string, fn interface{})
RegisterFunction registers a custom function for use in templates. The function is added to the function map and will be available in all subsequently parsed templates.
func (*GoTemplateEngine) RegisterFunctions ¶
func (e *GoTemplateEngine) RegisterFunctions(funcs template.FuncMap)
RegisterFunctions registers multiple custom functions for use in templates. This is more efficient than calling RegisterFunction multiple times.
func (*GoTemplateEngine) Render ¶
func (e *GoTemplateEngine) Render(ctx context.Context, templatePath string, data interface{}) ([]byte, error)
Render renders a template with the given data. It validates the template, checks the cache, and executes the template. Returns the rendered output as bytes or an error if rendering fails.
func (*GoTemplateEngine) RenderString ¶
func (e *GoTemplateEngine) RenderString(ctx context.Context, templateName, templateContent string, data interface{}) ([]byte, error)
RenderString renders a template string with the given data. This is useful for rendering templates that are not stored in files.
func (*GoTemplateEngine) RenderToWriter ¶
func (e *GoTemplateEngine) RenderToWriter(ctx context.Context, templatePath string, data interface{}, w io.Writer) error
RenderToWriter renders a template with the given data and writes the result to the writer. This is more efficient than Render when writing directly to a file or network connection.
func (*GoTemplateEngine) SetCacheEnabled ¶
func (e *GoTemplateEngine) SetCacheEnabled(enabled bool)
SetCacheEnabled enables or disables template caching. When disabled, templates are re-parsed on every render. When enabled, parsed templates are cached for improved performance.
func (*GoTemplateEngine) ValidateTemplate ¶
func (e *GoTemplateEngine) ValidateTemplate(templatePath string) error
ValidateTemplate validates that a template exists and has valid syntax. It attempts to parse the template and returns any syntax errors.
type InMemoryTemplateCache ¶
type InMemoryTemplateCache struct {
// contains filtered or unexported fields
}
InMemoryTemplateCache implements TemplateCache with in-memory storage. It provides thread-safe access and optional TTL-based expiration.
func NewInMemoryTemplateCache ¶
func NewInMemoryTemplateCache(ttl time.Duration, maxSize int) *InMemoryTemplateCache
NewInMemoryTemplateCache creates a new in-memory template cache. If ttl is 0, entries never expire. If maxSize is 0, cache size is unlimited.
func (*InMemoryTemplateCache) Clear ¶
func (c *InMemoryTemplateCache) Clear()
Clear removes all templates from the cache.
func (*InMemoryTemplateCache) Delete ¶
func (c *InMemoryTemplateCache) Delete(key string)
Delete removes a template from the cache.
func (*InMemoryTemplateCache) Get ¶
func (c *InMemoryTemplateCache) Get(key string) (*template.Template, bool)
Get retrieves a template from the cache. Returns the template and true if found and not expired, nil and false otherwise.
func (*InMemoryTemplateCache) GetStats ¶
func (c *InMemoryTemplateCache) GetStats() CacheStats
GetStats returns cache statistics. This is useful for monitoring and optimization.
func (*InMemoryTemplateCache) Set ¶
func (c *InMemoryTemplateCache) Set(key string, tmpl *template.Template)
Set stores a template in the cache. If the cache is full, it evicts the least recently used entry.
func (*InMemoryTemplateCache) Size ¶
func (c *InMemoryTemplateCache) Size() int
Size returns the number of cached templates.
type InMemoryTemplateRegistry ¶
type InMemoryTemplateRegistry struct {
// contains filtered or unexported fields
}
InMemoryTemplateRegistry is an in-memory implementation of TemplateRegistry
func NewInMemoryTemplateRegistry ¶
func NewInMemoryTemplateRegistry() *InMemoryTemplateRegistry
NewInMemoryTemplateRegistry creates a new in-memory template registry
func (*InMemoryTemplateRegistry) GetTemplate ¶
func (r *InMemoryTemplateRegistry) GetTemplate(name string) (TemplateDefinition, error)
GetTemplate retrieves a template by name
func (*InMemoryTemplateRegistry) GetTemplatesForEnabledServices ¶
func (r *InMemoryTemplateRegistry) GetTemplatesForEnabledServices(enabledServices []string) []TemplateDefinition
GetTemplatesForEnabledServices returns all templates that are either: 1. Not associated with any service (universal templates), or 2. Associated with at least one enabled service This implements Property 9: Service-Based Template Filtering **Validates: Requirements 2.4**
func (*InMemoryTemplateRegistry) GetTemplatesForProvider ¶
func (r *InMemoryTemplateRegistry) GetTemplatesForProvider(provider string) []TemplateDefinition
GetTemplatesForProvider returns all templates compatible with a provider
func (*InMemoryTemplateRegistry) GetTemplatesForService ¶
func (r *InMemoryTemplateRegistry) GetTemplatesForService(service string) []TemplateDefinition
GetTemplatesForService returns all templates associated with a service
func (*InMemoryTemplateRegistry) GetTemplatesForType ¶
func (r *InMemoryTemplateRegistry) GetTemplatesForType(templateType TemplateType) []TemplateDefinition
GetTemplatesForType returns all templates of a specific type
func (*InMemoryTemplateRegistry) ListTemplates ¶
func (r *InMemoryTemplateRegistry) ListTemplates() []TemplateDefinition
ListTemplates returns all registered templates
func (*InMemoryTemplateRegistry) RegisterTemplate ¶
func (r *InMemoryTemplateRegistry) RegisterTemplate(template TemplateDefinition) error
RegisterTemplate registers a template in the registry This implements Property 7: Template Dependency Validation **Validates: Requirements 2.2**
func (*InMemoryTemplateRegistry) ResolveTemplateDependencies ¶
func (r *InMemoryTemplateRegistry) ResolveTemplateDependencies(templates []string) ([]TemplateDefinition, error)
ResolveTemplateDependencies resolves template dependencies in correct order
func (*InMemoryTemplateRegistry) UnregisterTemplate ¶
func (r *InMemoryTemplateRegistry) UnregisterTemplate(name string) error
UnregisterTemplate removes a template from the registry
type MissingKeyBehavior ¶
type MissingKeyBehavior int
MissingKeyBehavior defines how to handle missing keys in templates.
const ( // MissingKeyError causes an error when a key is missing MissingKeyError MissingKeyBehavior = iota // MissingKeyZero returns the zero value for missing keys MissingKeyZero // MissingKeyInvalid returns "<no value>" for missing keys (default) MissingKeyInvalid )
type OverlayOrderingConfig ¶
type OverlayOrderingConfig struct {
Strategy OverlayOrderingStrategy
// CustomSort allows providing a custom sorting function
CustomSort func(overlays []TemplateOverlay) []TemplateOverlay
}
OverlayOrderingConfig configures how overlays are ordered during composition
func DefaultOverlayOrderingConfig ¶
func DefaultOverlayOrderingConfig() OverlayOrderingConfig
DefaultOverlayOrderingConfig returns the default ordering configuration
type OverlayOrderingStrategy ¶
type OverlayOrderingStrategy string
OverlayOrderingStrategy defines how overlays should be ordered
const ( // OrderByPriorityDesc orders overlays by priority (highest first), then by name OrderByPriorityDesc OverlayOrderingStrategy = "priority-desc" // OrderByPriorityAsc orders overlays by priority (lowest first), then by name OrderByPriorityAsc OverlayOrderingStrategy = "priority-asc" // OrderByName orders overlays alphabetically by name OrderByName OverlayOrderingStrategy = "name" // OrderByRegistration orders overlays in the order they were registered OrderByRegistration OverlayOrderingStrategy = "registration" )
type RegistrationOptions ¶
type RegistrationOptions struct {
// Provider specifies the cloud provider this template is for (openstack, aws, baremetal, etc.)
Provider string
// Services lists the services this template is associated with
Services []string
// Type specifies the template type (infrastructure, service, base, overlay)
Type TemplateType
// Priority sets the rendering priority (higher values render first)
Priority int
// Description provides a human-readable description
Description string
// Version specifies the template version
Version string
// Tags provides additional categorization
Tags []string
}
RegistrationOptions provides configuration for template registration
type RenderCondition ¶
type RenderCondition struct {
Type ConditionType
Field string
Operator string
Value interface{}
}
RenderCondition defines a condition for template rendering
type RenderContext ¶
type RenderContext struct {
// Data is the primary data object passed to the template
Data interface{}
// Metadata contains additional contextual information
Metadata map[string]interface{}
// Functions contains custom template functions
Functions template.FuncMap
// Options contains rendering options
Options RenderOptions
}
RenderContext provides comprehensive context for template rendering operations. It includes configuration data, metadata, custom functions, and rendering options.
func NewRenderContext ¶
func NewRenderContext(data interface{}) *RenderContext
NewRenderContext creates a new render context with the given data.
func (*RenderContext) Clone ¶
func (rc *RenderContext) Clone() *RenderContext
Clone creates a deep copy of the render context. This is useful for creating isolated contexts for concurrent rendering.
func (*RenderContext) ToTemplateData ¶
func (rc *RenderContext) ToTemplateData() map[string]interface{}
ToTemplateData converts the render context to a map suitable for template rendering. This provides a consistent structure for accessing data and metadata in templates.
func (*RenderContext) Validate ¶
func (rc *RenderContext) Validate() error
Validate validates the render context for completeness. Returns an error if the context is invalid.
func (*RenderContext) WithFunction ¶
func (rc *RenderContext) WithFunction(name string, fn interface{}) *RenderContext
WithFunction adds a custom function to the render context. Returns the context for method chaining.
func (*RenderContext) WithFunctions ¶
func (rc *RenderContext) WithFunctions(funcMap template.FuncMap) *RenderContext
WithFunctions adds multiple custom functions to the render context. Returns the context for method chaining.
func (*RenderContext) WithMetadata ¶
func (rc *RenderContext) WithMetadata(key string, value interface{}) *RenderContext
WithMetadata adds metadata to the render context. Returns the context for method chaining.
func (*RenderContext) WithMissingKeyBehavior ¶
func (rc *RenderContext) WithMissingKeyBehavior(behavior MissingKeyBehavior) *RenderContext
WithMissingKeyBehavior sets the missing key behavior. Returns the context for method chaining.
func (*RenderContext) WithStrictMode ¶
func (rc *RenderContext) WithStrictMode(strict bool) *RenderContext
WithStrictMode enables or disables strict mode. In strict mode, missing keys cause rendering to fail. Returns the context for method chaining.
func (*RenderContext) WithValidation ¶
func (rc *RenderContext) WithValidation(validate bool) *RenderContext
WithValidation enables or disables pre-render validation. Returns the context for method chaining.
type RenderOptions ¶
type RenderOptions struct {
// StrictMode causes rendering to fail on missing keys
StrictMode bool
// MissingKeyBehavior controls how missing keys are handled
MissingKeyBehavior MissingKeyBehavior
// ValidateBeforeRender validates template syntax before rendering
ValidateBeforeRender bool
// IncludeLineNumbers includes line numbers in error messages
IncludeLineNumbers bool
}
RenderOptions configures template rendering behavior.
type TemplateCache ¶
type TemplateCache interface {
// Get retrieves a template from the cache
Get(key string) (*template.Template, bool)
// Set stores a template in the cache
Set(key string, tmpl *template.Template)
// Delete removes a template from the cache
Delete(key string)
// Clear removes all templates from the cache
Clear()
// Size returns the number of cached templates
Size() int
}
TemplateCache provides thread-safe caching of parsed templates. It supports TTL-based expiration and size limits to prevent unbounded growth.
type TemplateComposer ¶
type TemplateComposer interface {
// Compose combines a base template with overlays and patches
Compose(ctx context.Context, composition TemplateComposition, data interface{}) ([]byte, error)
// ApplyOverlays applies overlays to a base template in priority order
ApplyOverlays(baseContent string, overlays []TemplateOverlay, data interface{}) (string, error)
// ApplyPatches applies patches to template content
ApplyPatches(content string, patches []TemplatePatch, data interface{}) (string, error)
// ValidateComposition validates that a composition is valid
ValidateComposition(composition TemplateComposition) error
// SetOrderingConfig sets the overlay ordering configuration
SetOrderingConfig(config OverlayOrderingConfig)
// GetOrderingConfig returns the current overlay ordering configuration
GetOrderingConfig() OverlayOrderingConfig
}
TemplateComposer handles composition of templates with overlays and patches
type TemplateComposition ¶
type TemplateComposition struct {
BaseTemplate string
Overlays []TemplateOverlay
Patches []TemplatePatch
Conditions []RenderCondition
}
TemplateComposition represents a composition of a base template with overlays and patches
type TemplateContext ¶
type TemplateContext struct {
// Config contains the main configuration data for template rendering
Config interface{}
// Metadata contains additional metadata that may be used in templates
Metadata map[string]interface{}
// Functions contains custom template functions specific to this context
Functions template.FuncMap
}
TemplateContext provides context information for template rendering. It includes configuration data, metadata, and custom functions.
func NewTemplateContext ¶
func NewTemplateContext(config interface{}) *TemplateContext
NewTemplateContext creates a new template context with the given configuration.
func (*TemplateContext) ToMap ¶
func (tc *TemplateContext) ToMap() map[string]interface{}
ToMap converts the template context to a map suitable for template rendering.
func (*TemplateContext) WithFunction ¶
func (tc *TemplateContext) WithFunction(name string, fn interface{}) *TemplateContext
WithFunction adds a custom function to the template context.
func (*TemplateContext) WithMetadata ¶
func (tc *TemplateContext) WithMetadata(key string, value interface{}) *TemplateContext
WithMetadata adds metadata to the template context.
type TemplateDefinition ¶
type TemplateDefinition struct {
Name string
Path string
Type TemplateType
Provider string
Services []string
Dependencies []string
Conditions []RenderCondition
Metadata TemplateMetadata
}
TemplateDefinition represents a template with its metadata
func FilterByTags ¶
func FilterByTags(templates []TemplateDefinition, tags []string) []TemplateDefinition
FilterByTags returns templates that have all specified tags
func FilterByType ¶
func FilterByType(templates []TemplateDefinition, templateType TemplateType) []TemplateDefinition
FilterByType returns templates of a specific type
type TemplateEngine ¶
type TemplateEngine interface {
// Render renders a template with the given data and returns the result as bytes.
// The context can be used for cancellation and timeout control.
Render(ctx context.Context, templatePath string, data interface{}) ([]byte, error)
// RenderString renders a template string with the given data and returns the result as bytes.
RenderString(ctx context.Context, templateName, templateContent string, data interface{}) ([]byte, error)
// RenderToWriter renders a template with the given data and writes the result to the writer.
RenderToWriter(ctx context.Context, templatePath string, data interface{}, w io.Writer) error
// ValidateTemplate validates template syntax before execution.
// Returns an error if the template has syntax errors or is not found.
ValidateTemplate(templatePath string) error
// RegisterFunction registers a custom function for use in templates.
// The function must have a valid signature for template execution.
RegisterFunction(name string, fn interface{})
// RegisterFunctions registers multiple custom functions for use in templates.
RegisterFunctions(funcs template.FuncMap)
// SetCacheEnabled enables or disables template caching.
// When enabled, parsed templates are cached for improved performance.
SetCacheEnabled(enabled bool)
// ClearCache clears all cached templates, forcing re-parsing on next render.
ClearCache()
// LoadFromFS loads templates from an embedded filesystem.
LoadFromFS(fsys fs.FS, pattern string) error
// LoadFromFile loads a single template from a file.
LoadFromFile(path string) error
// ExecuteTemplate executes a named template from a collection with the given data.
// This is useful when multiple templates are loaded together and reference each other.
ExecuteTemplate(templateName string, data interface{}) ([]byte, error)
// ExecuteTemplateToWriter executes a named template and writes the result to the writer.
ExecuteTemplateToWriter(templateName string, data interface{}, w io.Writer) error
// GetTemplate returns a parsed template by name, useful for direct template.Template access.
GetTemplate(name string) (*template.Template, error)
}
TemplateEngine provides a unified interface for template rendering operations. It abstracts template processing to support multiple template formats and provides caching, validation, and comprehensive error reporting.
type TemplateMetadata ¶
type TemplateMetadata struct {
Description string
Version string
Author string
Tags []string
Priority int
}
TemplateMetadata holds additional information about a template
type TemplateOverlay ¶
type TemplateOverlay struct {
Name string
Path string
Priority int
Conditions []RenderCondition
}
TemplateOverlay represents an overlay that can be applied to a base template
type TemplatePatch ¶
type TemplatePatch struct {
Operation string // add, remove, replace
Path string // JSONPath to target
Value interface{} // New value
Condition RenderCondition
}
TemplatePatch represents a targeted modification to a template
type TemplateRegistry ¶
type TemplateRegistry interface {
RegisterTemplate(template TemplateDefinition) error
GetTemplate(name string) (TemplateDefinition, error)
GetTemplatesForProvider(provider string) []TemplateDefinition
GetTemplatesForService(service string) []TemplateDefinition
GetTemplatesForEnabledServices(enabledServices []string) []TemplateDefinition
GetTemplatesForType(templateType TemplateType) []TemplateDefinition
ResolveTemplateDependencies(templates []string) ([]TemplateDefinition, error)
ListTemplates() []TemplateDefinition
UnregisterTemplate(name string) error
}
TemplateRegistry manages template definitions with metadata and dependency resolution
func GetGlobalRegistry ¶
func GetGlobalRegistry() (TemplateRegistry, error)
GetGlobalRegistry returns the global template registry, initializing it if necessary. This function is thread-safe and will only initialize the registry once.
type TemplateSandbox ¶
type TemplateSandbox interface {
// GetSafeFunctions returns a function map containing only safe template functions
GetSafeFunctions() template.FuncMap
// ValidateTemplate validates that a template only uses safe functions
ValidateTemplate(tmpl string) error
// RenderWithTimeout renders a template with a timeout to prevent denial-of-service
RenderWithTimeout(tmpl string, data interface{}, timeout time.Duration) (string, error)
}
TemplateSandbox provides a secure template rendering environment with restricted functions. It prevents template injection attacks by disabling dangerous functions and enforcing timeouts.
type TemplateType ¶
type TemplateType string
TemplateType represents the category of a template
const ( TemplateTypeInfrastructure TemplateType = "infrastructure" TemplateTypeService TemplateType = "service" TemplateTypeBase TemplateType = "base" TemplateTypeOverlay TemplateType = "overlay" TemplateTypeConfig TemplateType = "config" )