genapp

package module
v0.0.0-...-655fa59 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

genapp Go Reference

codecov

A general-purpose golang code generator.

Features
  • embeds a templates repository
  • formats and check imports using golang.org/x/tools/import
  • resolve package path for a target folder, even outside the go build tree, using golang.org/x/tools/go/packages
  • expose a single Render method to execute a template and format the resulting go code

Several options are available to customize this app builder.

See it in action
Background and credits

This package has been built after the internal tooling built for go-swagger.

The motivation for this package was to factorize out that valuable component, so as to be able to build other powerful code generation tools independently from go-swagger. Further improvements may be added independently.

The original version may be found here.

There are a few differences though:

  • this version is intended to be very generic and has been stripped from any target-dependent settings
  • all it knows is that is that it should use a templates Repository to render (primarily) some go code
  • rendering may be called concurrently
  • it maintains it own set of optional settings
  • it provides a helper to generate go modules with their own go.mod
  • it can build go module-aware apps, anywhere on the building system
  • the package path resolution originally made here is complex and difficult to keep in line with go build evolutions. Our implementation hands over the heavy lifting to golang.org/x/tools/go/packages

Notice that much of the go specifics formerly found in https://github.com/go-swagger/go-swagger/blob/master/generator/language.go have now moved to the new name mangler.

Documentation

Overview

Package genapp exposes GoGenApp, a general-purpose golang code generation helper.

GoGenApp stitches together a templates repo.Repository and knows how to render generated go files.

GoGenApp may be used to initialize and update a go.mod file for the generated package.

NOTE: using the imports grouping option affects the global setting imports.LocalPrefix, and may cause side effects to other components using imports.Process.

Dependencies

This package is exposed as an independent module and imposes few dependencies.

It uses internally github.com/spf13/afero as an abstraction for a writable file system.

Code formatting relies on:

  • golang.org/x/tools/imports

Package resolution relies on:

  • golang.org/x/tools/go/packages

Go module building relies on the "go mod" command (a go compiler must be installed to use this feature).

Excluding test dependencies, it relies directly on the following github.com/fredbi/core packages:

  • github.com/fredbi/core/codegen/funcmaps
  • github.com/fredbi/core/codegen/templates-repo

And indirectly on:

  • github.com/fredbi/core/mangling
  • github.com/fredbi/core/swag/stringutils

Other dependencies found are test dependencies.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error is a sentinel error type to wrap all errors raised by the genapp package.

const ErrGenApp Error = "code generation app error"

ErrGenApp is a sentinel error for all errors raised by the genapp package.

func (Error) Error

func (e Error) Error() string

type GoGenApp

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

GoGenApp is a helper type to generate golang code.

It it is typically embedded in more complex tools.

Scope

GoGenApp roles and responsibilities are limited to:

  • load a provided template repo.Repository
  • execute templates using GoGenApp.Render
  • apply the configured code formatting rules
  • write the output target file.

go build helpers

In addition GoGenApp.GoMod may be called:

  • to resolve the target go package name
  • to create and fill a "go.mod" file

Concurrency

GoGenApp may be used to GoGenApp.Render files concurrently.

However GoGenApp.GoMod is not safe for a concurrent use.

func New

func New(templateFS fs.FS, opts ...Option) *GoGenApp

New builds a new GoGenApp with templates found on the provided fs.FS, with Option s to configure the behavior.

NOTE: templateFS may be left to nil if you provide a fully configured repo.Repository using WithTemplatesRepo.

func (*GoGenApp) GoMod

func (g *GoGenApp) GoMod(opts ...ModOption) error

GoMod initializes a go.mod file in the generated target or update and existing one with go mod tidy.

The go mod tidy command is applied to build dependencies.

All possibilities allowed by the go modules are not covered. The supported use-case is when a the package name in a folder is directly inferred from the folder name. The go.mod file may alter the path to that folder, but would always have the folder name as a base name.

Example:

Supported:

In /tmp/go-folder:

go.mod
module swagger.io/go-openapi/go-folder/v2

doc.go
package folder // <- folder is the "official" short name for "go-folder/v2"

Not supported:

In /tmp/go-folder:

go.mod
module github.com/json-iterator/go

doc.go
package jsoniterator   // <- unrelated with folder. This is possible, but tooling easily gets lost.

NOTE: this doesn't work when configuring GoGenApp with an afero.Fs which is not the os FS.

func (*GoGenApp) IsGoModRequired

func (g *GoGenApp) IsGoModRequired() (bool, error)

IsGoModRequired checks the configured output path and returns true without error if this path requires a go.mod to host buildable go source. This is the case whenever the output path is outside the go build tree.

It returns false without error if the target may be built without go.mod.

IsGoModRequired may return false and an error when other build-related errors are found.

func (*GoGenApp) PackagePath

func (g *GoGenApp) PackagePath(opts ...ModOption) (string, error)

PackagePath returns the go package path that corresponds to the output dir.

This is the base import path for all packages generated there.

PackagePath abides by go build rules to resolve a package name, and is go module-aware.

The output path may not exist yet, or if it exists, it should not contain any go code, or a package name conflict may arise.

Module path

If a module path is specified with the WithModulePath option, the package path will be moduleRoot followed by the last significant part in the output path.

Example:

With outputPath = "/tmp/go-generated/v2"

PackagePath("goswagger.io/go-openapi") => "goswagger.io/go-openapi/go-generated/v2"

If the module root is empty, the resolver will resort to your local go build tree, either relying either on GOPATH or on the first parent go module.

Example:

Building from "$HOME/src/github.com/fredbi/core/genapp" with outputpath = "./go-generated/v2"

PackagePath("") => "github.com/fredbi/core/genapp/go-generated/v2"

Packages outside of the go build tree

If you want to build outside of the build tree, the module root is required: use WithModulePath. In that case, you will need to create a go module there with the returned package path before code generation is started.

Notice that the calling process should have a write access to the output path, as GoGenApp.PackagePath simulates the go build process by temporarily creating the folder if it is missing.

func (*GoGenApp) Render

func (g *GoGenApp) Render(template string, target string, data any) error

Render data using a template from a template repository repo.Repository.

The repository is initialized on the first call.

The target tells Render where to place the result on the output FS. The target path is relative to the output path of the GoGenApp and must be a valid relative path on the running OS.

If the target is located in a folder, the latter will be created automatically.

By default, the generated output is subject to go format and go imports.

Concurrency

Render may be used concurrently.

func (*GoGenApp) Templates

func (g *GoGenApp) Templates() *repo.Repository

Templates returns the inner templates repo.Repository used for code generation.

This provides the ability to reload or dump templates.

type ModOption

type ModOption func(*modOptions)

ModOption configures settings for the generated go module.

func WithGoVersion

func WithGoVersion(version string) ModOption

WithGoVersion overrides the default go module requirement on the required minimum version of the go compiler.

The go version provided should be a semver tag of the form "{major}.{minor}.{patch}", e.g. "1.24.3".

This is equivalent to the command "go mod tidy -go={version}".

func WithModulePath

func WithModulePath(pth string) ModOption

WithModulePath overrides the default go module fully qualified name when creating a go mod.

Notice that the path is sanitized to force the use slashes (not os.PathSeparator) and cleaned with path.Clean.

This is equivalent to the command "go mod init {pth}".

type Option

type Option func(*options)

Option to configure a GoGenApp.

func SetFormatGroupPrefixes

func SetFormatGroupPrefixes(prefixes ...string) Option

SetFormatGroupPrefixes overrides all default prefixes used to group imports when formatting code.

Setting prefixes to an empty list disables the grouping of imports.

NOTE: this affects the global setting imports.LocalPrefix, and may cause side effects to other components using imports.Process.

Applies only if go import is enabled. This is disabled when using WithFormatter.

func SetTemplateOptions

func SetTemplateOptions(templatesOptions ...repo.Option) Option

SetTemplateOptions overrides defaults repo.Option s to configure the templates repository.

Specifying an empty list disables any default options (such as the default func map).

func WithFormatGroupPrefixes

func WithFormatGroupPrefixes(prefixes ...string) Option

WithFormatGroupPrefixes adds local prefixes to group imports when formating code.

The default is to group imports to "github.com/fredbi/core".

NOTE: this affects the global setting imports.LocalPrefix, and may cause side effects on other components using imports.Process.

Applies only if go import is enabled. This is disabled when using WithFormatter.

func WithFormatTabWidth

func WithFormatTabWidth(tabWidth int) Option

WithFormatTabWidth specifies the width of indentation tabs used when formatting go code.

The default is 2. Notice that go defaults to 8.

This is disabled when using WithFormatter.

func WithFormatter

func WithFormatter(formatter func(name string, content []byte) ([]byte, error)) Option

WithFormatter allows for injecting a custom source code formatter.

The default uses formatting and imports check from the golang.org/x/tools library: imports.Process.

func WithOutputAferoFS

func WithOutputAferoFS(fs afero.Fs) Option

WithOutputAferoFS specifies the output file system as an afero.Fs.

By default, the local os file system is used. This is primarily intended for testing.

func WithOutputPath

func WithOutputPath(path string) Option

WithOutputPath specifies the location of generated files on the os file system.

All rendered files are relative to that path.

func WithSkipCheckImport

func WithSkipCheckImport(skipped bool) Option

WithSkipCheckImport instructs the rendering not to run go imports on the generated code.

Import check is enabled by default. You may disable imports check and keep simple code formatting. This option is essentially intended for testing and debugging generated code.

This is disabled when using WithFormatter.

func WithSkipFormat

func WithSkipFormat(skipped bool) Option

WithSkipFormat instructs the rendering not to format the generated code.

Format is enabled by default. If formatting is disabled, import check is disabled too. This option is essentially intended for testing and debugging generated code.

This is disabled when using WithFormatter.

func WithSkipFormatFunc

func WithSkipFormatFunc(skipFunc func(name string) (skipped bool)) Option

The default is to skip formatting on files that don't have the ".go" extension. This setting is disabled if you enable WithSkipFormat (disabled for all files).

func WithTemplatesRepo

func WithTemplatesRepo(templates *repo.Repository) Option

WithTemplatesRepo specifies the templates repository directly, so you have full control.

This overrides [WithTemplatesOptions].

By default, a templates repo is created with the templates provided by [WithTemplates].

func WithTemplatesRepoOptions

func WithTemplatesRepoOptions(templatesOptions ...repo.Option) Option

WithTemplatesRepoOptions adds repo.Option s to configure the templates repository.

The default options used for the templates repository are profiled for golang generation by other tools in github.com/fredbi/core modules:

Jump to

Keyboard shortcuts

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