IndexConstantsVariablesFunctionsTypes

Overview

Package modmake provides the interface for configuring and executing a Modmake build.

All Packages

Index [link]

ConstantsVariablesFunctionsTypes

Constants [link]


EnvLinterPath [link]

EnvLinterPath = "MM_LINTER_PATH"


Variables [link]


Functions [link]


CallBuild [link]

func CallBuild(buildLocation PathString, args ...string) *Command

CallBuild allows easily referencing and calling another modmake build. os.Chdir will be called with the module root before go-running the build file, so the buildFile parameter should be relative to the module root, like any Modmake build. This is safe to use with Git submodules because a GoTools instance will be created based on the location of the Modmake build file and the closest module. CallBuild is preferable over Build.Import for building separate go modules. If you're building a component of the same go module, then use Build.Import. - buildLocation should be the filesystem path to the build (file or directory) that should be executed. CallBuild will panic if the file doesn't exist. - args are flags and steps that should be executed in the build. If none are passed, then CallBuild will panic.


CallRemote [link]

func CallRemote(module string, buildPath PathString, args ...string) Task

CallRemote will execute a Modmake build on a remote module. The module parameter is the module name and version in the same form as would be used to 'go get' the module. The buildPath parameter is the path within the module, relative to the module root, where the Modmake build is located. Finally, the args parameters are all steps and flags that should be used to invoke the build. NOTE: If the remote build relies on Git information, then this method of calling the remote build will not work. Try using TempDir with github.com/saylorsolutions/modmake/pkg/git.CloneAt to make sure the build can reference those details.


Chdir [link]

func Chdir(newWorkdir PathString, runner Runner) Task

Chdir will change the current working directory to newWorkdir and run the Runner in that context. Whether the Runner executes successfully or not, the working directory will be reset back to its original state.


ContextAware [link]

func ContextAware(r Runner) Task

ContextAware creates a Task that wraps the parameter with context handling logic. In the event that the context is done, the context's error is returned. This should not be used if custom context.Context handling is desired.


CopyFile [link]

func CopyFile(source, target PathString) Task

CopyFile creates a Runner that copies a source file to target. The source and target file names are expected to be relative to the build's working directory, unless they are absolute paths. The target file will be created or truncated as appropriate.


Download [link]

func Download(url string, location PathString) Task


Environment [link]

func Environment() EnvMap

Environment returns the currently set environment values as an EnvMap.


Error [link]

func Error(msg string, args ...any) Task

Error will create a Task returning an error, creating it by passing msg and args to fmt.Errorf.


Exec [link]

func Exec(cmdAndInitArgs ...string) *Command

Exec creates a new Command representing running an external application.


F [link]

func F(fmt string, data ...EnvMap) string

F will format a string, replacing variables with their value as found in the environment data. Additional values may be added as the second parameter, which will override values in the original environment. Variable placeholders may be specified like ${ENV_VAR_NAME}. The example below will replace ${BUILD_NUM} with a value from the environment, or an empty string. If a variable either doesn't exist in the environment, or has an empty value, then an empty string will replace the variable placeholder. str := F("My string that references build ${BUILD_NUM}") Note that the "${" prefix and "}" suffix are required, but the variable name may be space padded for readability if desired. Also, variable names are case insensitive. A default value for interpolation can be specified with a colon (":") separator after the key. In the example below, if BUILD_NUM was not defined, then the string "0" would be used instead. str := F("My string that references build ${BUILD_NUM:0}") Note that whitespace characters in default values will always be trimmed. The string "${" can still be expressed in F strings, but it must be formatted to use a default value, which means that interpolation cannot be recursive. The string output from the function call below will be "My string has a variable reference ${BUILD_NUM}". str := F("My string has a variable reference ${:$}{BUILD_NUM}")


FReader [link]

func FReader(in io.Reader, data ...EnvMap) []byte

FReader will do the same thing as F, but operates on an io.Reader expressing a stream of UTF-8 encoded bytes instead.


GetLogger [link]

func GetLogger(ctx context.Context) Logger

GetLogger gets the Logger from the given context, or creates a new one if the context doesn't have a logger.


Getwd [link]

func Getwd() (PathString, error)

Getwd gets the current working directory as a PathString like os.Getwd.


Go [link]

func Go() *GoTools

Go will retrieve or initialize an instance of GoTools. This indirection is desirable to support caching of tool chain, filesystem, and module details. This function is concurrency safe, and may be called by multiple goroutines if desired.


IfError [link]

func IfError(canErr Runner, handler Runner) Task

IfError will create a Runner with an error handler Runner that is only executed if the base Runner returns an error. If both the base Runner and the handler return an error, then the handler's error will be returned.


IfExists [link]

func IfExists(file PathString, r Runner) Task

IfExists will execute the Runner if the file exists, returning nil otherwise.


IfNotExists [link]

func IfNotExists(file PathString, r Runner) Task

IfNotExists will skip executing the Runner if the given file exists, returning nil. This is similar to the default Make behavior of skipping a task if the target file already exists.


Mkdir [link]

func Mkdir(dir PathString, perm os.FileMode) Task

Mkdir makes a directory named dir, if it doesn't exist already. If the directory already exists, then nothing is done and err will be nil. Any error encountered while making the directory is returned.


MkdirAll [link]

func MkdirAll(dir PathString, perm os.FileMode) Task

MkdirAll makes the target directory, and any directories in between. Any error encountered while making the directories is returned.


MoveFile [link]

func MoveFile(source, target PathString) Task

MoveFile creates a Runner that will move the file indicated by source to target. The source and target file names are expected to be relative to the build's working directory, unless they are absolute paths. The target file will be created or truncated as appropriate.


NewAppBuild [link]

func NewAppBuild(appName, mainPath, version string) *AppBuild

NewAppBuild creates a new AppBuild with the given details. Empty values are not allowed and will result in a panic. If mainPath is not prefixed with the module name, then it will be added.


NewBuild [link]

func NewBuild() *Build

NewBuild constructs a new Build with the standard structure. This includes the following steps: - tools for installing and verifying required tooling. - generate for code generation. - test for running unit tests. - benchmark for running benchmarks. This step will be skipped in Build.Execute by default, unless included with a flag or called for explicitly. - build for building binaries. - package for building distributable artifacts.


NewStep [link]

func NewStep(name, description string) *Step

NewStep creates a new Step with the given name and description. If no description is given (indicated by an empty string), then the default description "No description" will be assigned. By default, Step.Run will do nothing, have no dependencies, and have no before/after hooks.


NoOp [link]

func NoOp() Task

NoOp is a Task placeholder that immediately returns nil.


PackageGoInstall [link]

func PackageGoInstall() AppPackageFunc

PackageGoInstall will copy the binary to GOPATH/bin. This is the default packaging for the AppBuild generated install step.


PackageTar [link]

func PackageTar() AppPackageFunc

PackageTar will package the binary into a tar.gz. This is the default for non-windows builds.


PackageZip [link]

func PackageZip() AppPackageFunc

PackageZip will package the binary into a zip. This is the default for windows builds.


Path [link]

func Path(path string, segments ...string) PathString

Path creates a new PathString from the input path segments.


Plain [link]

func Plain(fn func()) Task

Plain is a convenience function that translates a no-argument, no-return function into a Task, combining the logic of WithoutContext and WithoutErr.


Print [link]

func Print(msg string, args ...any) Task

Print will create a Runner that logs an informational message.


RemoveDir [link]

func RemoveDir(file PathString) Task

RemoveDir will create a Runner that removes the directory specified and all of its contents from the filesystem. If the directory doesn't exist, then this Runner returns nil. Any other error encountered while removing the directory is returned.


RemoveFile [link]

func RemoveFile(file PathString) Task

RemoveFile will create a Runner that removes the specified file from the filesystem. If the file doesn't exist, then this Runner returns nil. Any other error encountered while removing the file is returned.


Script [link]

func Script(fns ...Runner) Task

Script will execute each Task in order, returning the first error.


SetLogOutput [link]

func SetLogOutput(w io.Writer)

SetLogOutput defines where logs should be written. By default, logs are written to stderr.


SetStepDebug [link]

func SetStepDebug(printDebug bool)

SetStepDebug sets the global policy on debug step logs.


Tar [link]

func Tar(location PathString) *TarArchive

Tar will create a new TarArchive to contextualize follow-on operations that act on a tar.gz file. Adding a ".tar.gz" suffix to the location path string is recommended, but not required.


TempDir [link]

func TempDir(pattern string, fn func(tmp PathString) Task) Task

TempDir will create a temporary directory at the system's default temp location with the provided pattern, like os.MkdirTemp. The created PathString will be passed to the given function for use. The temp directory will be removed after this Task returns, or if the function panics.


TempDirAt [link]

func TempDirAt(location, pattern string, fn func(tmp PathString) Task) Task

TempDirAt will operate just like TempDir, but allows specifying a location for the creation of the temp directory.


UserHomeDir [link]

func UserHomeDir() (PathString, error)

UserHomeDir will return the current user's home directory as a PathString.


WithGroup [link]

func WithGroup(ctx context.Context, group string) (context.Context, Logger)

WithGroup appends a group to the context's Logger as a way to indicate a hierarchy of logging contexts.


WithLogger [link]

func WithLogger(ctx context.Context, name string) (context.Context, Logger)

WithLogger creates a new Logger, sets the given name, and sets the Logger value in the returned context.


WithoutContext [link]

func WithoutContext(fn func() error) Task

WithoutContext is a convenience function that handles the inbound context.Context in cases where it isn't needed. If the context is cancelled when this Task executes, then the context's error will be returned.


WithoutErr [link]

func WithoutErr(fn func(context.Context)) Task

WithoutErr is a convenience function that allows passing a function that should never return an error and translating it to a Task. The returned Task will recover panics by returning them as errors.


Zip [link]

func Zip(location PathString) *ZipArchive

Zip will create a new ZipArchive to contextualize follow-on operations that act on a zip file. Adding a ".zip" suffix to the location path string is recommended, but not required.


Types [link]


AppBuild [link]

type AppBuild struct {
	// Has unexported fields.
}

AppBuild is a somewhat opinionated abstraction over the common pattern of building a static executable, including packaging. The build step may be customized as needed, and different OS/Arch variants may be created as needed. Each built executable will be output to ${MODROOT}/build/${APP}_${VARIANT_NAME}/${APP} Default packaging will write a zip or tar.gz to ${MODROOT}/dist/${APP}/${APP}_${VARIANT_NAME}_${VERSION}.(zip|tar.gz) Each variant may override or remove its packaging step.

AppBuild.AsBuild [link]

func (a *AppBuild) AsBuild() *Build

AsBuild generates a modmake Build from the steps in this AppBuild. This is useful in the case where additional customization is needed. Note that changing the AppBuild after calling this method has no effect on the generated Build.

AppBuild.Build [link]

func (a *AppBuild) Build(bf AppBuildFunc) *AppBuild

Build allows customizing the GoBuild used to build all variants, which may be further customized for a specific AppVariant.

AppBuild.HostVariant [link]

func (a *AppBuild) HostVariant() *AppVariant

HostVariant creates an AppVariant with the current host's GOOS and GOARCH settings. Packaging will be disabled by default for this variant.

AppBuild.Install [link]

func (a *AppBuild) Install(pf AppPackageFunc) *AppBuild

Install allows specifying the AppPackageFunc used for installation. This defaults to PackageGoInstall.

AppBuild.NamedVariant [link]

func (a *AppBuild) NamedVariant(variant, os, arch string) *AppVariant

NamedVariant creates an AppVariant much like AppBuild.Variant, but with a custom variant name.

AppBuild.Variant [link]

func (a *AppBuild) Variant(os, arch string) *AppVariant

Variant creates an AppVariant with the given OS and architecture settings.


AppBuildFunc [link]

type AppBuildFunc func(gb *GoBuild)

AppBuildFunc is a function used to customize an AppBuild or AppVariant's build step.

AppBuildFunc.Then [link]

func (bf AppBuildFunc) Then(other AppBuildFunc) AppBuildFunc


AppPackageFunc [link]

type AppPackageFunc func(binaryPath, destDir PathString, app, variant, version string) Task

AppPackageFunc is a function used to customize an AppVariant's package step.

AppPackageFunc.Then [link]

func (pf AppPackageFunc) Then(other AppPackageFunc) AppPackageFunc


AppVariant [link]

type AppVariant struct {
	// Has unexported fields.
}

AppVariant is a variant of an AppBuild with an OS/Arch specified.

AppVariant.Build [link]

func (v *AppVariant) Build(bf AppBuildFunc) *AppVariant

Build sets the AppBuildFunc specific to this variant. AppBuildFunc.Then may be used to combine multiple build customizations.

AppVariant.NoPackage [link]

func (v *AppVariant) NoPackage() *AppVariant

NoPackage will mark this variant as one that doesn't include a packaging step.

AppVariant.Package [link]

func (v *AppVariant) Package(pf AppPackageFunc) *AppVariant

Package sets the AppPackageFunc specific to this variant. AppPackageFunc.Then may be used to combine multiple package steps.


Build [link]

type Build struct {
	// Has unexported fields.
}

Build is a collection of related Steps. Together, they form the structure and basis for a build pipeline.

Build.AddNewStep [link]

func (b *Build) AddNewStep(name, description string, run Runner) *Step

AddNewStep is a shortcut for adding a new step to a build.

Build.AddStep [link]

func (b *Build) AddStep(step *Step)

AddStep adds an existing custom step to the build.

Build.Benchmark [link]

func (b *Build) Benchmark() *Step

Benchmark allows easily referencing the benchmark Step.

Build.Build [link]

func (b *Build) Build() *Step

Build allows easily referencing the build Step.

Build.Execute [link]

func (b *Build) Execute(args ...string)

Execute executes a Build as configured, as if it were a CLI application. It takes string arguments to allow overriding the default of capturing os.Args. Run this with the -h flag to see usage information. If an error occurs within Execute, then the error will be logged and os.Exit will be called with a non-zero exit code. Note that the build will attempt to change its working directory to the root of the module, so all filesystem paths should be relative to the root. GoTools.ToModulePath may be useful to adhere to this constraint.

Build.ExecuteErr [link]

func (b *Build) ExecuteErr(args ...string) (err error)

ExecuteErr executes a Build as configured, as if it were a CLI application, and returns an error if anything goes wrong. It takes string arguments to allow overriding the default of capturing os.Args. Run this with the -h flag to see usage information. If an error occurs within Execute, then the error will be logged and os.Exit will be called with a non-zero exit code. Note that the build will attempt to change its working directory to the root of the module, so all filesystem paths should be relative to the root. GoTools.ToModulePath may be useful to adhere to this constraint.

Build.Generate [link]

func (b *Build) Generate() *Step

Generate allows easily referencing the generate Step.

Build.Graph [link]

func (b *Build) Graph(verbose bool)

Build.Import [link]

func (b *Build) Import(prefix string, other *Build)

Import will import all steps in the given build, with the given prefix applied and a colon separator. No dependencies on the imported steps will be applied to the current build, dependencies must be applied on the parent Build after importing. This is used to integrate build steps of components in the same go module. For building a separate go module (like a Git submodule, for example), use CallBuild.

func (b *Build) ImportAndLink(prefix string, other *Build)

ImportAndLink will import the build, and make its standard steps a dependency of the parent Build's standard steps.

Build.ImportApp [link]

func (b *Build) ImportApp(a *AppBuild)

ImportApp imports an AppBuild as a new Build, attaching its build and package steps as dependencies of the parent build's steps.

Build.Lint [link]

func (b *Build) Lint(version string) *Linter

Lint will enable code linting support for this module, and returns the Linter for further configuration. The version parameter must be either "latest" or a string that can describe a version of a go module. The default path for invoking the linter is "${GOBIN}/golangci-lint", using GoTools.GOBIN. The environment variable MM_LINTER_PATH (see EnvLinterPath) can be used to override the invocation path to the golangci-lint executable.

Build.LintLatest [link]

func (b *Build) LintLatest() *Linter

LintLatest is the same as Build.Lint, but will use "latest" as the version.

Build.Package [link]

func (b *Build) Package() *Step

Package allows easily referencing the package step.

Build.Step [link]

func (b *Build) Step(name string) *Step

Build.StepOk [link]

func (b *Build) StepOk(name string) (*Step, bool)

Build.Steps [link]

func (b *Build) Steps() []string

Build.Test [link]

func (b *Build) Test() *Step

Test allows easily referencing the test Step.

Build.Tools [link]

func (b *Build) Tools() *Step

Tools allows easily referencing the tools Step.

Build.Workdir [link]

func (b *Build) Workdir(workdir string) *Build

Workdir sets the working directory for running build steps. Defaults to the current working directory of the calling executable.


Command [link]

type Command struct {
	// Has unexported fields.
}

Command.Arg [link]

func (i *Command) Arg(args ...string) *Command

Arg adds the given arguments to the Command.

Command.CaptureStdin [link]

func (i *Command) CaptureStdin() *Command

CaptureStdin will make the Command pass os.Stdin to the executed process.

Command.Env [link]

func (i *Command) Env(key, value string) *Command

Env sets an environment variable for the running Command.

Command.LeadingArg [link]

func (i *Command) LeadingArg(args ...string) *Command

Command.LogGroup [link]

func (i *Command) LogGroup(group string) *Command

LogGroup specifies a logging group to which this Command is associated.

Command.OptArg [link]

func (i *Command) OptArg(condition bool, args ...string) *Command

OptArg will add the specified arg(s) if the condition evaluates to true.

Command.Output [link]

func (i *Command) Output(w io.Writer) *Command

Output will redirect all data written to either stdout or stderr to w.

Command.Run [link]

func (i *Command) Run(ctx context.Context) error

Command.Silent [link]

func (i *Command) Silent() *Command

Silent will prevent command output.

Command.Stderr [link]

func (i *Command) Stderr(w io.Writer) *Command

Stderr will capture all data written to the Command's stderr stream and write it to w.

Command.Stdout [link]

func (i *Command) Stdout(w io.Writer) *Command

Stdout will capture all data written to the Command's stdout stream and write it to w.

Command.Task [link]

func (i *Command) Task() Task

Command.TrailingArg [link]

func (i *Command) TrailingArg(args ...string) *Command

Command.WorkDir [link]

func (i *Command) WorkDir(workdir PathString) *Command

WorkDir sets the working directory in which to execute the Command.


EnvMap [link]

type EnvMap map[string]string

EnvMap is a specialized map for holding environment variables that are used to interpolate strings. Note that map keys are changed to a consistent case when merged with the environment values. So if multiple keys with the same characters but different cases are merged, then the eventual merged value is non-deterministic.


GoBuild [link]

type GoBuild struct {
	// Has unexported fields.
}

GoBuild.AddressSanitizer [link]

func (b *GoBuild) AddressSanitizer() *GoBuild

AddressSanitizer will enable interoperation with address sanitizer. Not all build targets are supported.

GoBuild.Arch [link]

func (b *GoBuild) Arch(arch string) *GoBuild

Arch will set the CPU architecture for the go build command using the GOARCH environment variable.

GoBuild.BuildArchive [link]

func (b *GoBuild) BuildArchive() *GoBuild

BuildArchive builds listed non-main packages into .a files. Packages named main are ignored.

GoBuild.BuildCArchive [link]

func (b *GoBuild) BuildCArchive() *GoBuild

BuildCArchive builds the listed main package, plus all packages it imports, into a C archive file. The only callable symbols will be those functions exported using a cgo //export comment. Requires exactly one main package to be listed.

GoBuild.BuildCShared [link]

func (b *GoBuild) BuildCShared() *GoBuild

BuildCShared builds the listed main package, plus all packages it imports, into a C shared library. The only callable symbols will be those functions exported using a cgo //import comment. Requires exactly one main package to be listed.

GoBuild.BuildExe [link]

func (b *GoBuild) BuildExe() *GoBuild

BuildExe will build the listed main packages and everything they import into executables. Packages not named main are ignored.

GoBuild.BuildPie [link]

func (b *GoBuild) BuildPie() *GoBuild

BuildPie will build the listed main packages and everything they import into position independent executables (PIE). Packages not named main are ignored.

GoBuild.BuildPlugin [link]

func (b *GoBuild) BuildPlugin() *GoBuild

BuildPlugin builds the listed main packages, plus all packages that they import, into a Go plugin. Packages not named main are ignored. Note that this is not supported on all build targets, and as far as I know, there are still issues today with plugins. Use at your own risk.

GoBuild.BuildShared [link]

func (b *GoBuild) BuildShared() *GoBuild

BuildShared will combine all the listed non-main packages into a single shared library that will be used when building with the -linkshared option. Packages named main are ignored.

GoBuild.CgoEnabled [link]

func (b *GoBuild) CgoEnabled(enabled bool) *GoBuild

GoBuild.ChangeDir [link]

func (b *GoBuild) ChangeDir(newDir PathString) *GoBuild

ChangeDir will change the working directory from the default to a new location. If an absolute path cannot be derived from newDir, then this function will panic.

GoBuild.DryRun [link]

func (b *GoBuild) DryRun() *GoBuild

DryRun will print the commands, but not run them.

GoBuild.Env [link]

func (b *GoBuild) Env(key, value string) *GoBuild

GoBuild.ForceRebuild [link]

func (b *GoBuild) ForceRebuild() *GoBuild

ForceRebuild will force all source to be recompiled, rather than relying on build cache.

GoBuild.GoCompileFlags [link]

func (b *GoBuild) GoCompileFlags(flags ...string) *GoBuild

GoCompileFlags sets arguments to pass to each go tool compile invocation.

GoBuild.LinkerFlags [link]

func (b *GoBuild) LinkerFlags(flags ...string) *GoBuild

LinkerFlags sets linker flags (ldflags) values for this build.

GoBuild.MemorySanitizer [link]

func (b *GoBuild) MemorySanitizer() *GoBuild

MemorySanitizer will enable interoperation with memory sanitizer. Not all build targets are supported.

GoBuild.OS [link]

func (b *GoBuild) OS(os string) *GoBuild

OS sets the target OS for the go build command using the GOOS environment variable.

GoBuild.OutputFilename [link]

func (b *GoBuild) OutputFilename(filename PathString) *GoBuild

OutputFilename specifies the name of the built artifact.

GoBuild.PrintCommands [link]

func (b *GoBuild) PrintCommands() *GoBuild

PrintCommands will print commands as they are executed.

GoBuild.PrintPackages [link]

func (b *GoBuild) PrintPackages() *GoBuild

PrintPackages will print the names of built packages.

GoBuild.Private [link]

func (b *GoBuild) Private(privateHosts ...string) *GoBuild

Private specifies private hosts that should not go through proxy.golang.org for resolution.

GoBuild.RaceDetector [link]

func (b *GoBuild) RaceDetector() *GoBuild

RaceDetector will enable race detection.

GoBuild.Run [link]

func (b *GoBuild) Run(ctx context.Context) error

GoBuild.SetVariable [link]

func (b *GoBuild) SetVariable(pkg, varName, value string) *GoBuild

SetVariable sets an ldflag to set a variable at build time. The pkg parameter should be main, or the fully-qualified package name. The variable referenced doesn't have to be exposed (starting with a capital letter). # Examples It's a little counter-intuitive how this works, but it's based on how the go tools themselves work. # Main package Given a module named 'example.com/me/myproject', and a package directory named 'build' with go files in package 'main', the pkg parameter should just be 'main'. # Non-main package Given a module named 'example.com/me/myproject', and a package directory named 'build' with go files in package 'other', the pkg parameter should be 'example.com/me/myproject/build'. GoTools.ToModulePackage is provided as a convenience to make it easier to create these reference strings. See this article for more examples. [this article]: https://programmingpercy.tech/blog/modify-variables-during-build/

GoBuild.Silent [link]

func (b *GoBuild) Silent() *GoBuild

GoBuild.StripDebugSymbols [link]

func (b *GoBuild) StripDebugSymbols() *GoBuild

StripDebugSymbols will remove debugging information from the built artifact, reducing file size. Assumes TrimPath as well.

GoBuild.Tags [link]

func (b *GoBuild) Tags(tags ...string) *GoBuild

Tags sets build tags to be activated.

GoBuild.Task [link]

func (b *GoBuild) Task() Task

GoBuild.TrimPath [link]

func (b *GoBuild) TrimPath() *GoBuild

TrimPath will remove build host filesystem path prefix information from the binary.

GoBuild.Verbose [link]

func (b *GoBuild) Verbose() *GoBuild

Verbose will print both commands and built packages.

GoBuild.Workdir [link]

func (b *GoBuild) Workdir(workdir PathString) *GoBuild


GoClean [link]

type GoClean struct {
	*Command

// Has unexported fields. }

GoClean.BuildCache [link]

func (c *GoClean) BuildCache() *GoClean

GoClean.FuzzCache [link]

func (c *GoClean) FuzzCache() *GoClean

GoClean.ModCache [link]

func (c *GoClean) ModCache() *GoClean

GoClean.Run [link]

func (c *GoClean) Run(ctx context.Context) error

GoClean.Task [link]

func (c *GoClean) Task() Task

GoClean.TestCache [link]

func (c *GoClean) TestCache() *GoClean


GoTools [link]

type GoTools struct {
	// Has unexported fields.
}

GoTools provides some utility functions for interacting with the go tool chain. To get an instance of GoTools, use the Go function. Upon first invocation, Go will cache filesystem and module details for reference later. To invalidate this cache, use GoTools.InvalidateCache. If your build logic needs to cross into another go module, try using CallBuild.

GoTools.Benchmark [link]

func (g *GoTools) Benchmark(pattern string) *Command

GoTools.BenchmarkAll [link]

func (g *GoTools) BenchmarkAll() *Command

GoTools.Build [link]

func (g *GoTools) Build(targets ...string) *GoBuild

Build creates a GoBuild to hold parameters for a new go build run.

GoTools.Clean [link]

func (g *GoTools) Clean() *GoClean

GoTools.Command [link]

func (g *GoTools) Command(command string, args ...string) *Command

GoTools.Format [link]

func (g *GoTools) Format(patterns ...string) *Command

GoTools.FormatAll [link]

func (g *GoTools) FormatAll() *Command

GoTools.GOBIN [link]

func (g *GoTools) GOBIN() PathString

GOBIN resolves the installation path of tools the same way that 'go install' does for installing them, allowing for more consistent tool invocation behavior. The order of resolution is as follows: - If the GOBIN environment variable is defined, then this path will be returned. - If the GOPATH environment variable is defined, then "$GOPATH/bin" will be returned. - If the user's home directory can be resolved, then the "go/bin" path relative to the user's home directory will be returned. - If none of the above paths can be returned, then the current working directory will be returned. See 'go help install' for more details.

GoTools.Generate [link]

func (g *GoTools) Generate(patterns ...string) *Command

GoTools.GenerateAll [link]

func (g *GoTools) GenerateAll() *Command

GoTools.Get [link]

func (g *GoTools) Get(pkg string) *Command

GoTools.GetEnv [link]

func (g *GoTools) GetEnv(key string) string

GetEnv will call "go env $key", and return the value of the named environment variable. If an error occurs, then the call will panic. If the value of GOBIN is requested, then GoTools.GOBIN will be invoked instead.

GoTools.GetUpdated [link]

func (g *GoTools) GetUpdated(pkg string) *Command

GoTools.Install [link]

func (g *GoTools) Install(pkg string) *Command

GoTools.InvalidateCache [link]

func (g *GoTools) InvalidateCache()

InvalidateCache will break the instance cache, forcing the next call to Go to scan the filesystem's information again.

GoTools.ModTidy [link]

func (g *GoTools) ModTidy() *Command

ModTidy will download missing module cache information, and tidy up dependency details.

GoTools.ModuleName [link]

func (g *GoTools) ModuleName() string

ModuleName returns the name of the current module as specified in the go.mod.

GoTools.ModuleRoot [link]

func (g *GoTools) ModuleRoot() PathString

ModuleRoot returns a filesystem path to the root of the current module.

GoTools.PinLatestV1 [link]

func (g *GoTools) PinLatestV1(minorVersion int) *GoTools

PinLatestV1 will replace the cached GoTools instance with one pinned to the latest patch version of the specified minor version. To revert back to the system go version, use GoTools.InvalidateCache. Note: For safety reasons, unstable release candidate versions are not considered. If there is not a stable version available, then this function will panic.

GoTools.Run [link]

func (g *GoTools) Run(target string, args ...string) *Command

GoTools.Test [link]

func (g *GoTools) Test(patterns ...string) *Command

GoTools.TestAll [link]

func (g *GoTools) TestAll() *Command

GoTools.ToModulePackage [link]

func (g *GoTools) ToModulePackage(pkg string) string

ToModulePackage is specifically provided to construct a package reference for GoBuild.SetVariable by prepending the module name to the package name, separated by '/'. This is not necessary for setting variables in the main package, as 'main' can be used instead. // When run in a module named 'example.com/me/myproject', // this will output 'example.com/me/myproject/other'. Go().ToModulePackage("other") See GoBuild.SetVariable for more details.

GoTools.ToModulePath [link]

func (g *GoTools) ToModulePath(dir string) string

ToModulePath takes a path to a file or directory within the module, relative to the module root, and translates it to a module path. If a path to a file is given, then a module path to the file's parent directory is returned. If ToModulePath is unable to stat the given path, then this function will panic. For example, given a module name of 'github.com/example/mymodule', and a relative path of 'app/main.go', the module path 'github.com/example/mymodule/app' is returned.

GoTools.Vet [link]

func (g *GoTools) Vet(patterns ...string) *Command

GoTools.VetAll [link]

func (g *GoTools) VetAll() *Command

GoTools.WorkSync [link]

func (g *GoTools) WorkSync() *Command

WorkSync will synchronize dependencies between modules in a Go workspace project.


Linter [link]

type Linter struct {
	// Has unexported fields.
}

Linter provides a means to configure the linter in various ways. The current version uses golangci-lint, and the Linter.Arg method is provided to pass arguments specific to that tool.

Linter.Arg [link]

func (lint *Linter) Arg(args ...string) *Linter

Arg allows passing unmapped arguments to the golangci-lint invocation.

Linter.Disable [link]

func (lint *Linter) Disable(check string, others ...string) *Linter

Disable marks given check(s) as disabled.

Linter.Enable [link]

func (lint *Linter) Enable(check string, others ...string) *Linter

Enable marks given check(s) as enabled.

Linter.EnableSecurityScanning [link]

func (lint *Linter) EnableSecurityScanning() *Linter

Linter.Run [link]

func (lint *Linter) Run(ctx context.Context) error

Linter.Target [link]

func (lint *Linter) Target(target string, otherTargets ...string) *Linter

Target will target specific files/directories for linting. If no target is specified, then "./..." will be used by default. Note that - when used in a multi-module workspace - "./..." will not cross module boundaries. Sub-module folders must be added explicitly to be scanned.

Linter.Verbose [link]

func (lint *Linter) Verbose() *Linter


Logger [link]

type Logger interface {
	// Info writes an informational log message to output.
	Info(msg string, args ...any)
	// Warn writes a warning message to output, and should be used sparingly.
	Warn(msg string, args ...any)
	// Error writes an error message to output, and should indicate a failure to perform a requested action.
	Error(msg string, args ...any)
	// Debug writes an informational log message to output that is only useful for debugging build logic.
	Debug(msg string, args ...any)
	// WrapErr wraps the given error with log context.
	// This is only done if the error is not already a wrapped error.
	WrapErr(err error) error
}


PathString [link]

type PathString string

PathString is a string that represents a filesystem path. String inputs to all PathString functions, including Path, is expected to be a filesystem path with forward slash ('/') separators. These will be translated to actual OS filesystem path strings, making them incompatible with module path strings on Windows.

PathString.Abs [link]

func (p PathString) Abs() (PathString, error)

Abs attempts to translate the PathString into an absolute path using filepath.Abs.

PathString.Base [link]

func (p PathString) Base() PathString

Base calls filepath.Base on the string representation of this PathString, returning the last element of the path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

PathString.Cat [link]

func (p PathString) Cat() ([]byte, error)

Cat will - assuming the PathString points to a file - read all data from the file and return it as a byte slice.

PathString.Chdir [link]

func (p PathString) Chdir() error

Chdir changes the current working directory to the named directory like os.Chdir.

PathString.CopyTo [link]

func (p PathString) CopyTo(other PathString) error

CopyTo copies the contents of the file referenced by this PathString to the file referenced by other, creating or truncating the file.

PathString.Create [link]

func (p PathString) Create() (*os.File, error)

Create will create or truncate the named file like os.Create.

PathString.Dir [link]

func (p PathString) Dir() PathString

Dir calls filepath.Dir on the string representation of this PathString, returning all but the last element of the path. After dropping the final element, Dir calls filepath.Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

PathString.Exists [link]

func (p PathString) Exists() bool

Exists returns true if the path references an existing file or directory.

PathString.Ext [link]

func (p PathString) Ext() string

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.

PathString.IsDir [link]

func (p PathString) IsDir() bool

IsDir returns true if this PathString references an existing directory.

PathString.IsFile [link]

func (p PathString) IsFile() bool

IsFile returns true if this PathString references a file that exists, and it is not a directory.

PathString.Join [link]

func (p PathString) Join(segments ...string) PathString

Join will append path segments to this PathString and return a new PathString.

PathString.JoinPath [link]

func (p PathString) JoinPath(segments ...PathString) PathString

JoinPath will append PathString segments to this PathString and return a new PathString.

PathString.Mkdir [link]

func (p PathString) Mkdir(mode os.FileMode) error

Mkdir creates a new directory with the specified name and permissions like os.Mkdir.

PathString.MkdirAll [link]

func (p PathString) MkdirAll(mode os.FileMode) error

MkdirAll creates the named directory and any non-existent path in between like os.MkdirAll.

PathString.Open [link]

func (p PathString) Open() (*os.File, error)

Open opens the named file for reading like os.Open.

PathString.OpenFile [link]

func (p PathString) OpenFile(flag int, mode os.FileMode) (*os.File, error)

OpenFile is a generalized open call like os.OpenFile.

PathString.ReadFile [link]

func (p PathString) ReadFile() ([]byte, error)

ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

PathString.Rel [link]

func (p PathString) Rel(other PathString) (PathString, error)

Rel attempts to construct a relative path to other, with the current PathString as the base, much like filepath.Rel.

PathString.Remove [link]

func (p PathString) Remove() error

Remove removes the named file or directory like os.Remove.

PathString.RemoveAll [link]

func (p PathString) RemoveAll() error

RemoveAll removes the path and any children it contains like os.RemoveAll.

PathString.Stat [link]

func (p PathString) Stat() (os.FileInfo, error)

Stat will return os.FileInfo for the file referenced by this PathString like os.Stat.

PathString.String [link]

func (p PathString) String() string

String returns this PathString as a string.

PathString.ToSlash [link]

func (p PathString) ToSlash() string

ToSlash will change the PathString to use slash separators if the OS representation is different.

PathString.WriteFile [link]

func (p PathString) WriteFile(data []byte, perm os.FileMode) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.


RunState [link]

type RunState int

RunState indicates the state of a Step.


Runner [link]

type Runner interface {
	// Run should immediately execute in the current goroutine when called to ensure predictable build semantics.
	// Run may initiate other goroutines, but they should complete and be cleaned up before Run returns.
	Run(context.Context) error
}

Runner is any type that may be executed with a context.Context, and could return an error.


Step [link]

type Step struct {
	// Has unexported fields.
}

Step is a step in a Build, a consistent fixture that may be invoked. A Step may depend on others to set up pre-conditions that must be done before this Step executes. Additionally, a Step may have actions that take place before and/or after this Step runs. Operations on a Step will change the underlying logic. The current Step will be returned as a convenience to allow chaining multiple mutations.

Step.AfterRun [link]

func (s *Step) AfterRun(op Runner) *Step

AfterRun adds an operation that will execute after this Step's operation. AfterRun operations will execute before any Step that depends on this Step.

Step.BeforeRun [link]

func (s *Step) BeforeRun(op Runner) *Step

BeforeRun adds an operation that will execute before this Step's operation. BeforeRun operations will execute after this Step's dependencies, but before the operation performed during this Step.

Step.Debounce [link]

func (s *Step) Debounce(interval time.Duration) Task

Debounce Deprecated: use a Task if debounce or multiple executions are needed.

Step.DependsOn [link]

func (s *Step) DependsOn(dependency *Step) *Step

DependsOn makes this Step depend on the given Step. The given step must execute successfully for this Step to be executed.

Step.DependsOnRunner [link]

func (s *Step) DependsOnRunner(name, description string, fn Runner) *Step

DependsOnRunner wraps the given Runner in a Step using the name and description parameters, and calls DependsOn with it.

Step.Does [link]

func (s *Step) Does(operation Runner) *Step

Does specifies the operation that should happen as a result of executing this Step.

Step.DryRun [link]

func (s *Step) DryRun(ctx context.Context) error

Step.ResetState [link]

func (s *Step) ResetState() *Step

ResetState resets the state of a Step such that it can be run again. This includes all of its dependencies.

Step.Run [link]

func (s *Step) Run(ctx context.Context) error

Step.Skip [link]

func (s *Step) Skip() *Step

Skip will skip execution of this step, including its before/after hooks. Dependencies will still be executed unless SkipDependencies is executed.

Step.SkipDependencies [link]

func (s *Step) SkipDependencies() *Step

SkipDependencies will prevent running dependency Steps for this Step.

Step.UnSkip [link]

func (s *Step) UnSkip() *Step

UnSkip is the opposite of Skip, and is useful in the case where a Step is skipped by default.


StepContextError [link]

type StepContextError struct {
	LogName  string
	LogGroup string
	// Has unexported fields.
}

StepContextError.Error [link]

func (err *StepContextError) Error() string

StepContextError.Unwrap [link]

func (err *StepContextError) Unwrap() error


TarArchive [link]

type TarArchive struct {
	// Has unexported fields.
}

TarArchive represents a Runner that performs operations on a tar archive that uses gzip compression. The Runner is created with Tar.

TarArchive.AddFile [link]

func (t *TarArchive) AddFile(sourcePath PathString) *TarArchive

AddFile adds the referenced file with the same archive path as what is given. The archive path will be converted to slash format.

TarArchive.AddFileWithPath [link]

func (t *TarArchive) AddFileWithPath(sourcePath, archivePath PathString) *TarArchive

AddFileWithPath adds the referenced file with an archive path specified. The archive path will be converted to slash format.

TarArchive.Create [link]

func (t *TarArchive) Create() Task

Create will return a Runner that creates a new tar file with the given files loaded. If a file with the given name already exists, then it will be truncated first. Ensure that all files referenced with AddFile (or AddFileWithPath) and directories exist before running this Runner, because it doesn't try to create them.

TarArchive.Extract [link]

func (t *TarArchive) Extract(extractDir PathString) Task

Extract will extract the named tar archive to the given directory. Any errors encountered while doing so will be immediately returned.

TarArchive.Update [link]

func (t *TarArchive) Update() Task

Update will return a Runner that creates a new tar file with the given files loaded. If a file with the given name already exists, then it will be updated. If a file with the given name does not exist, then this Runner will return an error. Ensure that all files referenced with AddFile (or AddFileWithPath) and directories exist before running this Runner, because it doesn't try to create them.


Task [link]

type Task func(ctx context.Context) error

Task is a convenient way to make a function that satisfies the Runner interface, and allows for more flexible invocation options.

Task.Catch [link]

func (t Task) Catch(catch func(error) Task) Task

Catch runs the catch function if this Task returns an error.

Task.Debounce [link]

func (t Task) Debounce(interval time.Duration) Task

Debounce will ensure that the returned Task can only be executed once per interval.

Task.Finally [link]

func (t Task) Finally(finally func(err error) error) Task

Finally can be used to run a function after a Task executes, regardless whether it was successful. The given function will receive the error returned from the base Task. If the given function returns a non-nil error, it will be returned from the produced function. Otherwise, the error from the underlying Task will be returned.

Task.LogGroup [link]

func (t Task) LogGroup(group string) Task

LogGroup sets a logging group for the Task, and attaches the logging context if an error is returned. See WithGroup and [Logger.WrapErr] for details.

Task.Once [link]

func (t Task) Once() Task

Once ensures that the returned Task can only be executed at most once.

Task.Run [link]

func (t Task) Run(ctx context.Context) error

Task.Then [link]

func (t Task) Then(other Runner) Task

Then returns a Task that runs if this Task executed successfully.


ZipArchive [link]

type ZipArchive struct {
	// Has unexported fields.
}

ZipArchive represents a Runner that performs operations on a tar archive that uses gzip compression. The Runner is created with Zip.

ZipArchive.AddFile [link]

func (z *ZipArchive) AddFile(sourcePath PathString) *ZipArchive

AddFile adds the referenced file with the same archive path as what is given. The archive path will be converted to slash format.

ZipArchive.AddFileWithPath [link]

func (z *ZipArchive) AddFileWithPath(sourcePath, archivePath PathString) *ZipArchive

AddFileWithPath adds the referenced file with an archive path specified. The archive path will be converted to slash format.

ZipArchive.Create [link]

func (z *ZipArchive) Create() Task

Create will return a Runner that creates a new zip file with the given files loaded. If a file with the given name already exists, then it will be truncated first. Ensure that all files referenced with AddFile (or AddFileWithPath) and directories exist before running this Runner, because it doesn't try to create them.

ZipArchive.Extract [link]

func (z *ZipArchive) Extract(extractDir PathString) Task

Extract will extract the named zip archive to the given directory. Any errors encountered while doing so will be immediately returned.

ZipArchive.Update [link]

func (z *ZipArchive) Update() Task

Update will return a Runner that creates a new zip file with the given files loaded. If a file with the given name already exists, then it will be updated. If a file with the given name does not exist, then this Runner will return an error. Ensure that all files referenced with AddFile (or AddFileWithPath) and directories exist before running this Runner, because it doesn't try to create them.