gomake

package module
v0.0.0-...-0cddee2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

README

go-make

A golang-based build script library, with a goals of having very few dependencies for fast execution time and enabling consistent, cross-platform build scripts.

Example

package main // file: make/main.go

import (
	. "github.com/anchore/go-make"
	"github.com/anchore/go-make/golint"
	"github.com/anchore/go-make/gotest"
)

func main() {
	Makefile(
		golint.Tasks(), // centralize common task definitions 
		gotest.Test("unit"),
		// define tasks that feel somewhat like configuration / scripts:
		Task{
			Name: "build",
			Desc:  "make a custom build task",
			Deps:  All("goreleaser:snapshot-buildfile"), // can ensure other specific tasks run first, like make dependencies
			Run: func() {
				// Run function supports: global template vars, quoting within strings,
				// obtaining & providing binny-managed executable
				Run(`goreleaser build --config {{TmpDir}}/goreleaser.yaml --clean --snapshot --single-target`)
			},
		},
		Task{
			Name:  "custom-tests",
			Desc:  "do some custom formatting stuff",
			Label: All("test"),  // runs whenever "test" runs, e.g. make test
			Run: func() {
				// failed commands have convenient links here, in this file
				Run(`go test ./test`)
			},
		},
	)
}

Also, see the build definition in this repository

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ToolDir  = "{{RootDir}}/.tool"
	Platform = "{{OS}}/{{Arch}}"
	OS       = runtime.GOOS
	Arch     = runtime.GOARCH
)
View Source
var Debug = func(format string, args ...any) {}
View Source
var Globals = Context{}
View Source
var Log = func(format string, args ...any) {
	_, _ = fmt.Fprintf(os.Stderr, LogPrefix+Tpl(format)+NewLine, args...)
}
View Source
var LogPrefix = ""
View Source
var NewLine = fmt.Sprintln()
View Source
var RootDir = func() string {
	return Tpl("{{RepoRoot}}")
}

RootDir is a function to return the root directory which builds run from

View Source
var TmpDirRoot = ""

TmpDirRoot is a directory to use as the base for temporary directories, defaults to system temp dir if empty

Functions

func All

func All[T any](values ...T) []T

func AllNotNil

func AllNotNil[T any](values ...T) []T

func BinnyInstall

func BinnyInstall(cmd string) string

BinnyInstall installs the named executable and returns an absolute path to it

func BuildFromGoSource

func BuildFromGoSource(file string, module, entrypoint, version string, opts ...ExecOpt)

func Cancel

func Cancel()

Cancel invokes the cancel call on all active

func Catch

func Catch(fn func()) (err error)

Catch handles panic values and returns any error caught

func Cd

func Cd(dir string)

Cd changes the current working directory to the provided relative or absolute directory

func Close

func Close(closeable io.Closer)

func Cwd

func Cwd() string

Cwd returns the current working directory

func DebugLog

func DebugLog(format string, args ...any)

func DelimiterSplitFlat

func DelimiterSplitFlat(delimiterSeparatedString, delimiter string) []string

func EnsureFileExists

func EnsureFileExists(file string)

EnsureFileExists halts execution if the provided file does not exist

func Exec

func Exec(cmd string, opts ...ExecOpt) error

Exec executes the given command, returning stdout and any error information

func Fetch

func Fetch(urlString string, options ...FetchOption) (contents []byte, statusCode int, statusLine string)

func FileContains

func FileContains(file, substr string) bool

FileContains indicates the given file contains the provided substring

func FileExists

func FileExists(file string) bool

FileExists indicates a file of any type (regular, directory, symlink, etc.) exists and is readable

func FindFile

func FindFile(glob string) string

FindFile finds the first matching file given a glob expression

func FindFiles

func FindFiles(glob string) []string

FindFiles finds all matching files given a glob expression

func FingerprintFiles

func FingerprintFiles(files ...string) string

FingerprintFiles hashes all files and provides a stable hash of all the contents

func FingerprintGlobs

func FingerprintGlobs(globs ...string) string

FingerprintGlobs fingerprints all files matching the provided glob expression, providing a stable hash of all contents

func Get

func Get[T any](t T, e error) T

func GitRevision

func GitRevision() string

func GitRoot

func GitRoot() string

func GoDepVersion

func GoDepVersion(module string) string

GoDepVersion returns the version found for the requested dependency in the first go.mod file found

func HandleErrors

func HandleErrors()

HandleErrors is a utility to make errors and error codes handled prettier

func InDir

func InDir(dir string, run func())

InDir executes the given function in the provided directory, returning to the current working directory upon completion

func InGitClone

func InGitClone(repo, branch string, fn func())

func InTempDir

func InTempDir(fn func())

InTempDir executes with current working directory in a new temporary directory, restoring cwd and removing all contents of the temp directory upon completion

func IsBinnyManagedTool

func IsBinnyManagedTool(cmd string) bool

func IsDir

func IsDir(dir string) bool

IsDir indicates the provided directory exists and is a directory

func IsRegularFile

func IsRegularFile(name string) bool

IsRegularFile indicates the provided file exists and is a regular file, not a directory or symlink

func LogErr

func LogErr(err error)

func Makefile

func Makefile(tasks ...Task)

func NoErr

func NoErr(e error)

func PathJoin

func PathJoin(paths ...string) string

PathJoin joins paths together using OS-appropriate separator

func ReadFile

func ReadFile(file string) string

ReadFile reads the file and returns the contents as a string

func ReadGoMod

func ReadGoMod() *modfile.File

ReadGoMod reads the first go.mod found

func RepoRoot

func RepoRoot() string

func Rmdir

func Rmdir(dir string)

Rmdir removes the given directory, first verifying it is a subdirectory of RootDir

func Run

func Run(cmd ...string)

Run a command, logging with current stdout / stderr

func RunBinny

func RunBinny()

func RunE

func RunE(cmd ...string) (string, string, error)

RunE runs a command, returning stdout, stderr, err

func RunGoTask

func RunGoTask()

func RunTools

func RunTools()

func RunWithOptions

func RunWithOptions(cmd string, opts ...ExecOpt)

func ShellSplit

func ShellSplit(s string) []string

ShellSplit splits a string at spaces, taking into account shell quotes and {{template directives}}

func SplitFlat

func SplitFlat(commaSeparatedString string) []string

func Throw

func Throw(err error)

Throw panics with a stack trace

func ToolPath

func ToolPath(toolName string) string

func Tpl

func Tpl(template string, args ...map[string]any) string

func WithTempDir

func WithTempDir(fn func(dir string))

WithTempDir creates a temporary directory, provided for the duration of the function call, removing all contents upon completion

func WriteFile

func WriteFile(path, contents string)

WriteFile writes the provided contents to a file

Types

type Context

type Context map[string]any

func (*Context) Append

func (c *Context) Append(key string, value any)

type ExecOpt

type ExecOpt func(*exec.Cmd)

ExecOpt is used to alter the command used in Exec calls

func ExecArgs

func ExecArgs(args ...string) ExecOpt

ExecArgs appends args to the command

func ExecEnv

func ExecEnv(key, val string) ExecOpt

ExecEnv adds an environment variable to the command

func ExecErrToFile

func ExecErrToFile(path string) ExecOpt

func ExecOpts

func ExecOpts(opts ...ExecOpt) ExecOpt

ExecOpts combines all opts into a single one

func ExecOut

func ExecOut(stdout io.Writer, stderr ...io.Writer) ExecOpt

ExecOut sends stdout to the writer, and optionally stderr

func ExecOutToFile

func ExecOutToFile(path string) ExecOpt

func ExecStd

func ExecStd() ExecOpt

ExecStd executes with output mapped to the current process' stdout, stderr, stdin

func Ldflags

func Ldflags(flags ...string) ExecOpt

type FetchOption

type FetchOption func(req *http.Request)

func FetchHeaders

func FetchHeaders(headers map[string]string) FetchOption

type OkError

type OkError struct{}

OkError is used to proceed normally

type StackTraceError

type StackTraceError struct {
	Err      any
	ExitCode int
	Stack    []string
}

StackTraceError provides nicer stack information

func (*StackTraceError) Error

func (s *StackTraceError) Error() string

type Task

type Task struct {
	Name   string
	Desc   string
	Quiet  bool
	Deps   []string
	Labels []string
	Tasks  []Task
	Run    func()
}

func RollupTask

func RollupTask(name string, desc string, deps ...string) Task

type ToolContext

type ToolContext struct {
	RootDir string
	ToolDir string
}

Directories

Path Synopsis
tasks

Jump to

Keyboard shortcuts

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