repo

package module
v0.0.0-...-3befc1a Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

Templates repository

The templates repository is a cache for collecting golang text templates.

Features:

  • unique template key built on top of a tree of template files
  • caches compiled templates from assets on a file system, possibly embedded
  • automatically resolves dependencies
  • supports overlays: templates may be overridden from another source
  • supports protected templates, to guard sensitive templates against unwanted overrides
  • concurrency-safe
  • generate documentation for your templates from comments in source

Functionality exposed as a separate module:

Documentation

Overview

Package repo exposes a Repository to cache templates.

The Repository can load assets from any fs.FS or from raw []bytes.

It resolves dependencies automatically and supports templates overriding.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string
const ErrTemplateRepo Error = "template repo error"

func (Error) Error

func (e Error) Error() string

type Option

type Option func(*options)

Option defines settings for the template repository.

Settings

* provide a file system, including an "embed.FS" (the default is the actual file system supported by the os) * include a functions map template.FuncMap to supplement template builtins (none is provided by default), * define protected templates (none is protected by default) * disable check on protected templates (check is enabled by default) * define supported template file extensions (the default is ".gotmpl") * define skipped subdirectories when using Repository.Load (the default is to skip "contrib" folders)

func WithAllowOverride

func WithAllowOverride(enabled bool) Option

func WithCoverProfile

func WithCoverProfile(enabled bool) Option

func WithDumpTemplate

func WithDumpTemplate(text string) Option

func WithExtensions

func WithExtensions(ext ...string) Option

func WithFS

func WithFS(fs fs.FS) Option

func WithFuncMap

func WithFuncMap(funcs template.FuncMap) Option

func WithManglingOptions

func WithManglingOptions(opts ...mangling.Option) Option

func WithParseComments

func WithParseComments(enabled bool) Option

func WithReadFileFS

func WithReadFileFS(fs fs.ReadFileFS) Option

func WithSkipDirectories

func WithSkipDirectories(dir ...string) Option

type Repository

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

Repository is a cache for golang text templates.

A fresh Repository is initialized with New.

Default settings may be altered using Option s.

Supported templates

The Repository supports golang text template.Template. html templates are not supported at this moment.

The default file extension for template assets is ".gotmpl".

You may change the list of supported extensions using WithExtensions. Any asset with an extensions that is not in this list is ignored.

Structure

The Repository organizes all resolved templates from the source templates directory on fs.FS as a flat index of named templates.

Example:

The template defined in file "{root}/cli/generate.gotmpl" would be later called as "cliGenerate".

Templates defined in dfferent folders would therefore never conflict. However, inner templates (using inner "{{ define }}" statements) are resolved at the same level.

You should therefore make sure that you don't define the same template several times in the same folder.

Template dependencies

When complex templates call each other, or define inner "{{ define ...}}" templates, the graph of dependencies may become hard to resolve.

The [Repository) solves this by checking all inner definitions and dependencies at loading time and ensure that all dependencies are resolved for each dependent template.

All templates defined in the

Overlays

You may reload templates from an alternate source and override existing templates.

Using Repository.LoadOverlay allows to specify the prefix to strip when producing unique template names.

Protected templates

Using Repository.AddFile or Repository.LoadOverlay, it is possible to override already loaded templates.

Protected templates are a configuration that prevents undesirable overrides to occur.

You may define which templates are protected with Repository.SetProtected.

Concurrency

The repository may be used concurrently: templates are compiled and dependencies resolved early when loading a directory or a template asset.

Loading may also be carried out concurrently. However, the outcome of dependency resolution may depend on the order in which loading occurs.

func New

func New(opts ...Option) *Repository

New creates a new template repository.

func (*Repository) AddFile

func (r *Repository) AddFile(filename string, data []byte) error

AddFile adds or replace a single template asset to the repository.

It creates a new template based on the asset name and the template content.

The name of the template, to be retrieved using Repository.Get, is built from the asset name:

- It trims the extension from the end and converts the name using swag.ToJSONName - This strips directory separators and camel-cases the next letter.

Example:

file validation/primitive.gotmpl is referred to as "validationPrimitive"

The asset is not added if it contains a definition for a template that is protected.

The newly added asset should not add new dependencies: these should be already loaded.

If you are not sure about the order of dependencies, prefer Repository.Load or Repository.LoadOverlay to resolve dependencies only after all file assets are loaded.

func (*Repository) AddProtected

func (r *Repository) AddProtected(protectedTemplates ...string)

AddProtected protects already loaded templates.

func (*Repository) Clone

func (r *Repository) Clone(opts ...Option) *Repository

Clone builds a clone of a repository. with cloned maps of templates. Compiled templates are shallow clone.

The clone may be parameterized with options that differ from the original.

func (*Repository) Dump

func (r *Repository) Dump(w io.Writer)

Dump prints out a dump of all the defined templates to some io.Writer, where they are defined and what their dependencies are.

This is intended to produce a documentation for your templates. The default formatting is a markdown document. You may customize how the dump is formatted with the option WithDumpTemplate in New.

func (*Repository) Get

func (r *Repository) Get(name string) (*template.Template, error)

Get returns a named template from the repository, ensuring that all dependent templates are loaded.

It yields an error if the requested template or any template it depends on is not defined in the repository.

Repository.Get may be called concurrently.

func (*Repository) Load

func (r *Repository) Load(templatePath string) error

Load will walk the specified path and add to the repository each template asset it finds in this tree.

func (*Repository) LoadOverlay

func (r *Repository) LoadOverlay(overlayPath, prefix string) error

LoadOverlay loads templates from a directory as an overlay.

The directory name is stripped from the name prefix, so templates in this folder may override existing templates.

Example:

If we define the following structure:

templates/headers.gotmpl
templates/contrib/override/headers.gotmpl

Then Repository.LoadOverlay("./contrib/override", "contrib/override") would replace the template "headers" by the template located in "contrib/override".

If no prefix is provided the directory name (without leading . or /) is used.

Overlay templates must ensure that they provide the right dependencies.

If an overlay redefines an existing dependency, this dependency will be taken into account on by overridden templates. Templates that are not overridden and have been already resolved won't resolve to the new dependency.

func (*Repository) MustGet

func (r *Repository) MustGet(name string) *template.Template

MustGet retrieves a template by its name, or panics if it fails.

Repository.MustGet may be called concurrently.

func (*Repository) SetProtected

func (r *Repository) SetProtected(protected map[string]bool)

SetProtected defines the map of protected templates, by their name.

Template names mapped to true are protected, and unprotected from overrides otherwise.

Using Repository.SetProtected(map[string]bool{}) would unprotected all templates.

Setting protected templates that are not loaded yet has not effect.

Directories

Path Synopsis
Package funcmaps propose different language-oriented funcmaps.
Package funcmaps propose different language-oriented funcmaps.