diff --git a/templates-repo/options.go b/templates-repo/options.go index 0d81a09..bf24767 100644 --- a/templates-repo/options.go +++ b/templates-repo/options.go @@ -29,13 +29,14 @@ type ( // options holds the settings of a repository, the sources it is yet to read, and the first // option that rejected its arguments. options struct { - sources []source - funcs template.FuncMap - extensions []string - roots []string - coverPrefix string - err error - coverage bool + sources []source + funcs template.FuncMap + extensions []string + roots []string + coverPrefix string + err error + coverage bool + templateOption string } ) @@ -258,3 +259,25 @@ func WithCoverage(prefix string) Option { return o } } + +// MissingKeyBehavior exposes the options provided by [template.Template]. +type MissingKeyBehavior string + +const ( + MissingKeyBehaviorDefault MissingKeyBehavior = "missingkey=default" + MissingKeyBehaviorZero MissingKeyBehavior = "missingkey=zero" + MissingKeyBehaviorError MissingKeyBehavior = "missingkey=error" +) + +// WithMissingKey instructs templates to be built with the options provided by [template.Template]: +// +// - [MissingKeyBehaviorDefault]: execution continues on missing keys on maps, the value is set to "". +// - [MissingKeyBehaviorZero]: execution continues with the value set to the zero value of the element type. +// - [MissingKeyBehaviorError]: execution stops with an error +func WithMissingKey(onMissingKey MissingKeyBehavior) Option { + return func(o options) options { + o.templateOption = string(onMissingKey) + + return o + } +} diff --git a/templates-repo/repository.go b/templates-repo/repository.go index abf91e6..014ac71 100644 --- a/templates-repo/repository.go +++ b/templates-repo/repository.go @@ -434,6 +434,10 @@ func parseAssets(assets []asset, settings options) (parsedAssets, error) { fmt.Errorf("could not parse template %q from asset %q: %w: %w", owner, item.path, err, ErrTemplateRepo) } + if settings.templateOption != "" { + tpl = tpl.Option(settings.templateOption) + } + declaredHere := make(map[string]*declared, len(tpl.Templates())) for _, found := range tpl.Templates() { if found.Tree == nil {