engine

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package engine provides functions to create and generate a project layout.

It contains two main functions, Initialize and Generate, which split project initialization and project generation into two parts.

Initialization

type config struct { ... }

func main() {
	ctx := context.Background()

	config, err := engine.Initialize(ctx, engine.WithFormGroups(License))
	// handle err
}

func License(c *config) *huh.Group {
	var license bool
	return huh.NewGroup(
		huh.NewConfirm().
			Title("Would you like to specify a license (optional)?").
			Value(&license),

		huh.NewSelect[string]().
			Title("Which one?").
			OptionsFunc(func() []huh.Option[string] {
				if !license {
					return nil
				}
				return huh.NewOptions(licenses...)
			}, &license).
			Validate(func(s string) error {
				if s != "" {
					c.License = &s
				}
				return nil
			}),
	)
}

Generation

type config struct {
	VCS parser.VCS
}

func main() {
	ctx := context.Background()
	destdir, _ := os.Getwd()

	// run generation
	engine.Configure(engine.WithLogger(logger), engine.WithForce(false))
	err := engine.Generate(ctx, destdir, config,
		[]engine.Parser[config]{ParserGit},
		[]engine.Generator[config]{engine.GeneratorTemplates(os.DirFS("path/to/templates"), Templates())})
	// handle err
}

func ParserGit(ctx context.Context, destdir string, config *config) error {
	vcs, err := parser.Git(destdir)
	if err != nil {
		engine.GetLogger().Warnf("failed to retrieve git vcs configuration: %v", err)
		return nil // a repository may not be a git repository
	}
	engine.GetLogger().Infof("git repository detected")

	config.VCS = vcs
	return nil
}

func Templates() []engine.Template[config] {
	name := ".gitignore"
	return []engine.Template[config]{
		{
			Delimiters: engine.DelimitersBracket(),
			// EmptyPolicy can be given to tune empty generated files removal, see the appropriate documentation
			EmptyPolicy: engine.PolicyKeepEmpty,
			// GeneratePolicy can be given to tune generation (always generate, remove or skip the file),
			// see the appropriate documentation and StaticPolicy, RemoveIf or SkipIfExists helpers
			GeneratePolicy: engine.StaticPolicy[config](engine.PolicyAlways),
			Globs:          engine.GlobsWithPart(name),
			Out:            name,
			// Patches applies further transformations to the generated file after it's written
			Patches: []string{"path/to/file.patch"},
			// Sections regenerates only delimited parts of an existing file instead of skipping it
			Sections: []engine.Section{{Begin: "# BEGIN_SECTION", End: "# END_SECTION"}},
		},
	}
}

Index

Constants

View Source
const (
	// TmplExtension is the extension for template files.
	TmplExtension = ".tmpl"

	// PartExtension is the extension for template files' subparts.
	//
	// It must be used with TmplExtension
	// and as such files with only template parts (define) can be created.
	PartExtension = ".part"

	// PatchExtension is the extension for template file patches.
	//
	// It will be used in the future to patch files altered by users to follow updates with fewer generation issues.
	PatchExtension = ".patch"
)

Variables

View Source
var ErrFailedGeneration = errors.New("some error(s) occurred during generation")

ErrFailedGeneration is returned when at least one file couldn't be properly generated.

Every generation error is logged during processing to avoid a big aggregated error at the end.

View Source
var ErrRequiredField = errors.New("required field")

ErrRequiredField is the error that can be used with huh.Validate(f func(string) error) to specify to the user that the field is required.

Functions

func ApplyPatches

func ApplyPatches[T any](fsys fs.FS, root *os.Root, tmpl Template[T], data any) error

ApplyPatches applies patches defined in input tmpl, if any.

Each patch is templatized using Go template and then patched on provided tmpl file.

func ApplySections

func ApplySections[T any](fsys fs.FS, root *os.Root, tmpl Template[T], data any) error

ApplySections regenerates each section defined in input tmpl, if any, in the already existing tmpl file, the rest of the file is kept as is.

The whole template is rendered from its Globs (nothing happens without them) and each rendered section (markers included) replaces its counterpart in the destination, user-added content outside sections is never templatized.

func ApplyTemplate

func ApplyTemplate[T any](fsys fs.FS, root *os.Root, tmpl Template[T], config T) error

ApplyTemplate generates an input Template with associated data, or only regenerates its sections when the file is kept (see ApplySections), and then applies its patches (see ApplyPatches).

The GeneratePolicy and the force option (see WithForce) decide whether the file is generated, kept, removed or skipped. A removed or skipped file gets no patches.

func Configure

func Configure(opts ...OptionFunc)

Configure applies the options functions to the global option variable (unexported).

This function should be called before calling any function within engine package in case a specific logger must be set or generation must be forced.

Configure should be called only once per process before Generate call. Each call fully replaces the previously configured options rather than merging with them.

func ExecuteTemplate

func ExecuteTemplate(tmpl *template.Template, data any, root *os.Root, name string, policy EmptyPolicy, mode os.FileMode) error

ExecuteTemplate runs tmpl.Execute with input data and writes the result into given name inside root.

When ExecuteTemplate is called, it rewrites name only when its content changes and always reevaluates its permissions.

The input mode sets the requested file mode for the generated file (e.g. files.RwRR, files.RwxRxRxRx), defaulting to files.RwRR when not provided.

The system umask (see files.Umask) is always applied on top (mode &^ umask, no-op on non-compatible platforms).

func Forced

func Forced() bool

Forced returns true if the options' force is provided.

It means that generation should be forced and as such all generated files should be regenerated unless ones expected to be removed.

func FuncMap

func FuncMap() template.FuncMap

FuncMap returns a minimal template.FuncMap.

It can be extended with WithFuncMap.

func Generate

func Generate[T any](ctx context.Context, destdir string, config T, parsers []Parser[T], generators []Generator[T]) error

Generate is the main function of the engine package. It takes a configuration, parsers and generators.

It executes all given parsers, in order, and then runs all provided generators concurrently to apply or remove templates.

func GlobsWithPart

func GlobsWithPart(src string) []string

GlobsWithPart returns a slice of two elements, one with src + TmplExtension and the other with a real glob, corresponding to all part files of the src template.

Example:

GlobsWithPart("path/to/file.yml") -> []string{"path/to/file.yml.tmpl", "path/to/file-*.part.tmpl"}

func Initialize

func Initialize[T any](ctx context.Context, opts ...InitializeOption[T]) (T, error)

Initialize initializes a new project and returns the resulting configuration.

All user inputs are configured through WithFormGroups option.

func IsEmpty

func IsEmpty(content []byte, policy EmptyPolicy) bool

IsEmpty returns true if the given content is considered empty according to the provided policy.

A file is expected to be removed if:

  • it's empty
  • it contains only the generated notice
  • the policy is set to Keep

Note: lines with the generated notice are completely stripped. In case of additional comments, keep them out of the generated notice line.

func IsGenerated

func IsGenerated(out string) (bool, error)

IsGenerated returns true if out is owned by generation.

A file is owned by generation if:

  • the generated notice opens one of its first 3 lines
  • it does not exist
  • it is empty

func NewLoggerURL

func NewLoggerURL(transport http.RoundTripper) http.RoundTripper

NewLoggerURL creates an http.RoundTripper that will log request URLs.

func ToSlug

func ToSlug(in string) string

ToSlug transforms an input string into its slug representation, keeping only letters and numbers and replacing everything else by the dash '-'.

Types

type Delimiters

type Delimiters struct {
	// EndDelim is the end delimiter of a Go template statement, i.e. >> or }} or ]], etc.
	EndDelim string

	// StartDelim is the start delimiter of a Go template statement, i.e. << or {{ or [[, etc.
	StartDelim string
}

Delimiters represents the pair of start and end delimiters for Go template substitution.

func DelimitersBracket

func DelimitersBracket() Delimiters

DelimitersBracket returns Go template delimiters {{ and }}.

func DelimitersChevron

func DelimitersChevron() Delimiters

DelimitersChevron returns Go template delimiters << and >>.

func DelimitersSquareBracket

func DelimitersSquareBracket() Delimiters

DelimitersSquareBracket returns Go template delimiters [[ and ]].

type EmptyPolicy

type EmptyPolicy int

EmptyPolicy defines the policy to apply when a generated file is empty.

By default, the policy is set to PolicyRemoveEmpty, meaning that a generated file will be removed if it is empty or contains only the notice "Code generated by [\w\-\/]+; DO NOT EDIT.".

const (
	// PolicyKeepEmpty will keep the file if it exists and is empty.
	PolicyKeepEmpty EmptyPolicy = iota + 1

	// PolicyRemoveEmpty will remove the file if it exists and is empty.
	//
	// This is the default behavior.
	PolicyRemoveEmpty
)

type FormGroup

type FormGroup[T any] func(config *T) *huh.Group

FormGroup is the function signature for functions reading user inputs.

type GeneratePolicy

type GeneratePolicy int

GeneratePolicy defines the policy for generating a given file.

By default, the policy is set to PolicyDefault.

const (
	// PolicyAlways generates the file on every run, even when it was edited by hand.
	//
	// Patches are applied afterwards.
	PolicyAlways GeneratePolicy = iota + 1

	// PolicyDefault generates the file when it's owned by generation (see IsGenerated) or when generation is forced (see WithForce).
	//
	// Otherwise, the existing file is kept and only its sections are regenerated.
	// Patches are applied in both cases.
	PolicyDefault

	// PolicyRemove removes the file (or directory) when it exists, instead of generating it.
	//
	// It applies even when generation is forced, and no sections or patches are applied.
	PolicyRemove

	// PolicySkip leaves the file untouched, whether it exists or not.
	//
	// It applies even when generation is forced, and no sections or patches are applied.
	PolicySkip
)

func SkipIfExists

func SkipIfExists(path string, otherwise GeneratePolicy) GeneratePolicy

SkipIfExists returns PolicySkip when the path exists, and otherwise in other cases.

It's meant to be called inside a GeneratePolicyFunc with its path, for files generated once and then left to the user.

Unlike PolicyDefault, an existing file is kept even when generation is forced (see WithForce), with or without the generated notice.

type GeneratePolicyFunc

type GeneratePolicyFunc[T any] func(path string, config T) GeneratePolicy

GeneratePolicyFunc returns the GeneratePolicy of a Template, given its output path (prefixed with the generation root directory) and the configuration.

func RemoveIf

func RemoveIf[T any](remove func(T) bool, otherwise GeneratePolicy) GeneratePolicyFunc[T]

RemoveIf returns a GeneratePolicyFunc removing the output file when remove returns true, and applying otherwise in other cases.

func StaticPolicy

func StaticPolicy[T any](policy GeneratePolicy) GeneratePolicyFunc[T]

StaticPolicy returns a GeneratePolicyFunc always returning the given policy, regardless of the output file path and configuration.

type Generator

type Generator[T any] func(ctx context.Context, root *os.Root, config T) error

Generator is the function to generate a specific part of target repository.

Generators are called once all parsers have finished (parsers run sequentially, in their input order), with the resulting aggregated configuration.

All generators given to Generate run concurrently with one another. An implementation must not assume any run order relative to other generators and must be safe for concurrent use, since it may be invoked alongside other Generator[T] from the same Generate call.

A returned error is only logged, to avoid one big aggregated error at the end of Generate. A returned ErrFailedGeneration is not logged, since it signals the generator already logged its own error.

func GeneratorModules

func GeneratorModules[T any, M Module](fsys fs.FS, modules func(config T) []M, templates []Template[M]) Generator[T]

GeneratorModules is a generator applying all input templates inside each module directory.

The modules function extracts the modules slice from the parsed configuration.

Each Template.Out is relative to each module where it will be generated and Template.GeneratePolicy is up to the characteristics of a given module.

Errors encountered during templates generation are logged, in that case a final error being ErrFailedGeneration is returned.

func GeneratorTemplates

func GeneratorTemplates[T any](fsys fs.FS, templates []Template[T]) Generator[T]

GeneratorTemplates is a simple generator taking as input a filesystem and all templates to apply.

Errors encountered during templates generation are logged, in that case a final error being ErrFailedGeneration is returned.

type InitializeOption

type InitializeOption[T any] func(initializeOptions[T]) initializeOptions[T]

InitializeOption represents an option to be given to Initialize function.

func WithFormGroups

func WithFormGroups[T any](inputs ...FormGroup[T]) InitializeOption[T]

WithFormGroups sets (it overrides the previously defined functions every time it's called) the functions reading user inputs in Initialize function.

func WithTeaOptions

func WithTeaOptions[T any](opts ...tea.ProgramOption) InitializeOption[T]

WithTeaOptions sets the slice of tea.ProgramOption for huh form tuning.

type Logger

type Logger interface {
	// Debugf logs with the DEBUG level.
	Debugf(format string, args ...any)

	// Errorf logs with the ERROR level.
	Errorf(format string, args ...any)

	// Infof logs with the INFO level.
	Infof(format string, args ...any)

	// Warnf logs with the WARN level.
	Warnf(format string, args ...any)
}

Logger is a simplified interface for logging purposes.

Implementations must be safe for concurrent use, since Generate calls generators (and therefore the logger) from multiple goroutines.

func GetLogger

func GetLogger() Logger

GetLogger returns global logger if it exists or a noop logger.

func NewTestLogger

func NewTestLogger(writer io.Writer) Logger

NewTestLogger creates a new logger with the input writer.

This logger is expected to be used in tests. In no way should it be used in production since it's unoptimized.

type Module

type Module interface {
	// Dir returns the module location, relative to the generation destination directory, with slashes as separators.
	Dir() string
}

Module is implemented by any per-directory configuration a monorepository is composed of.

It's the input type of GeneratorModules, which generates a slice of templates inside each module directory instead of the repository root.

type OptionFunc

type OptionFunc func(options) options

OptionFunc is the function signature for engine options to be provided in Configure.

func WithForce

func WithForce(force bool) OptionFunc

WithForce sets the engine force option when calling Configure with this option.

The force option can then be used to force generation inside Generator[T].

func WithFuncMap

func WithFuncMap(funcs template.FuncMap) OptionFunc

WithFuncMap adds a custom FuncMap to all templating calls.

func WithLogger

func WithLogger(logger Logger) OptionFunc

WithLogger sets the engine logger when calling Configure with this option.

A nil logger falls back to a no-op logger (see GetLogger).

type Parser

type Parser[T any] func(ctx context.Context, destdir string, config *T) error

Parser is the function to parse a specific part of target repository.

Parsers run first, sequentially in their input order, and each receives the configuration as a pointer so it can accumulate detected information for later parsers and generators to use.

type Section

type Section struct {
	// Begin is the marker opening the section (e.g. "<!-- BEGIN_BADGES -->").
	Begin string

	// End is the marker closing the section (e.g. "<!-- END_BADGES -->").
	End string
}

Section represents a delimited part of a file, regenerated alone when the whole file isn't.

type Template

type Template[T any] struct {
	// Delimiters is the pair of delimiters used to parse template file(s).
	Delimiters

	// EmptyPolicy is the policy to apply when the generated file is empty.
	EmptyPolicy EmptyPolicy

	// GeneratePolicy returns the generation policy of the current file (see GeneratePolicyFunc).
	//
	// When nil, the default behavior applies (see PolicyDefault).
	//
	// Use StaticPolicy for a policy independent of the output path and configuration,
	// RemoveIf to remove the file depending on the configuration,
	// or SkipIfExists to generate the file only once.
	GeneratePolicy GeneratePolicyFunc[T]

	// Globs is the slice of globs or specific files to parse during Go templating.
	//
	// It allows the current file to be split into multiple template files
	// with "define" Go template statements to help readability (use GlobsWithPart function to help generate globs easily).
	//
	// Note that the first element must be the raw path to main template file.
	//
	// Example:
	// 	[]string{"path/to/file.yml.tmpl", "path/to/file-*.part.tmpl"}
	Globs []string

	// Mode sets the requested file mode for the generated file (e.g. files.RwRR, files.RwxRxRxRx),
	// defaulting to files.RwRR when not provided.
	//
	// The system umask is always applied on top (mode &^ umask, no-op on non-compatible platforms),
	// matching standard POSIX file-creation semantics, meaning the effective mode may be more
	// restrictive than requested depending on the running user's umask.
	Mode os.FileMode

	// Out is the output file path.
	//
	// It must be the full path to destination directory with the filename.
	Out string

	// Patches is the slice of patches to apply on the file, with or without globs.
	//
	// Patches are applied in the slice order after the file is generated with globs or its sections are regenerated.
	// Additionally, patches are also templatized with Go template.
	//
	// A patch should have a name of the form "path/to/file.patch.tmpl" or "path/to/file.diff.tmpl"
	// (but it doesn't really matter since the name is given in the slice)
	// and should be a git diff file.
	//
	// Example:
	//
	//	diff --git a/<path/to/file> b/<path/to/file>
	//	index <some hash>..<some hash> 100644
	// 	--- a/<path/to/file>
	// 	+++ b/<path/to/file>
	// 	@@ -R,r +R,r @@
	//	+...
	//	-...
	//	+...
	//	...
	//
	// See https://en.wikipedia.org/wiki/Diff#Unified_format
	Patches []string

	// Sections is the slice of delimited parts regenerated alone when the out file isn't generated as a whole
	// (it means the policy is PolicyDefault, generation isn't forced and IsGenerated returns false).
	//
	// The whole template is rendered from Globs (sections are ignored without them), then the rendered part
	// from the first Begin marker to the next End marker replaces the same part of the out file, markers included.
	// A rendered value containing a marker shifts the section bounds.
	//
	// A section missing from the rendered template or with a missing marker in the out file is skipped,
	// the rest of the file is always kept as is.
	//
	// Example:
	//
	//	[]Section{{Begin: "<!-- BEGIN_BADGES -->", End: "<!-- END_BADGES -->"}}
	Sections []Section
}

Template represents a template file to be parsed and generated.

Directories

Path Synopsis
Package files provides helpers to read, write and validate files, and to locate files across a directory tree.
Package files provides helpers to read, write and validate files, and to locate files across a directory tree.
Package generator exposes a bunch of functions to be wrapped with engine.Generator function signature.
Package generator exposes a bunch of functions to be wrapped with engine.Generator function signature.
Package parser provides a bunch of functions to be wrapped with engine.Parser function signature.
Package parser provides a bunch of functions to be wrapped with engine.Parser function signature.

Jump to

Keyboard shortcuts

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