gob

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 14 Imported by: 0

README

gob

Build go projects with recipes written in go.

Example

Create a go file in your project, you can name it what you want build.go for example

//go:build ignore

package main

import (
	"log/slog"

	"github.com/phillezi/gob"
)

func init() {
	logger := slog.New(gob.NewPrettyHandler(nil))
	slog.SetDefault(logger)
}

func main() {
  // takes in options
	gob.New(gob.WithDefaultTarget("all")).Add(
		"all",
    // takes in options to customize
    // can also be chaned with .For(os, arch)
    // or .Matrix([]string{"linux"}, []string{"amd64", "arm64"})
		gob.Static(),
	).Add(
		"clean",
		gob.Clean(),
	).Run()
}

To build your project you simply run:

go run build.go # the path to the file you created

Your project will be built statically for your platform and all the binaries will end up in ./bin/ by default. There are more options, like building for multiple architectures etc.

See examples for more examples.

Why

This is just a small tool that automates setting common build flags that I usually set for my go projects, such as CGO_ENABLED=0 -ldflags="-w -s" and also version tagging using git, making the version string available in the binary -ldflags="-X main.version=vX.Y.Z".

So instead of having to write:

GIT_TAG=$(git describe --tags --abbrev=0 2>/dev/null)
GIT_COMMIT=$(git rev-parse HEAD 2>/dev/null)
GIT_TAG_COMMIT=$(git rev-list -n 1 "$GIT_TAG" 2>/dev/null)

if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
    GIT_DIRTY=true
else
    GIT_DIRTY=false
fi

GIT_SHORT=${GIT_COMMIT:0:7}

if [ "$GIT_DIRTY" = false ]; then
    if [ "$GIT_TAG_COMMIT" = "$GIT_COMMIT" ]; then
        GIT_VERSION="$GIT_TAG"
    else
        GIT_VERSION="${GIT_TAG}-${GIT_SHORT}"
    fi
else
    GIT_VERSION="${GIT_TAG}-dirty-${GIT_SHORT}"
fi

# and then finally building
CGO_ENABLED=0 go build -ldflags="-w -s -X main.version=$GIT_VERSION" -o ./bin/ ./...

This can be used to do it in a cross-platform way.

You can of-course use a Makefile for this, but it adds another dependency. And this is just go code, which also makes it possible to re-use the build recipe when building Docker images with slim builder images that doesnt have Make installed.

Documentation

Overview

Package gob is the root of the gob library.

This library aims to make it possible to build go projects based on build recipies in go code.

This is heavily inspired by how zig does it, with build.zig.

Usage

You can use this library by making a go file that looks something like this:

//go build ignore package main

import "github.com/phillezi/gob"

func main() {
	b := gob.New()
	b.Add("", gob.Static())
	b.Run()
}

Index

Constants

View Source
const (
	GOOSLinux   = "linux"
	GOOSDarwin  = "darwin"
	GOOSWindows = "windows"
	GOOSFreeBSD = "freebsd"
	GOOSNetBSD  = "netbsd"
	GOOSOpenBSD = "openbsd"
	GOOSSolaris = "solaris"
	GOOSAIX     = "aix"
)

Common GOOS constants

View Source
const (
	GOARCHAMD64    = "amd64"
	GOARCHARM64    = "arm64"
	GOARCH386      = "386"
	GOARCHARM      = "arm"
	GOARCHPPC64    = "ppc64"
	GOARCHPPC64LE  = "ppc64le"
	GOARCHMIPS     = "mips"
	GOARCHMIPSLE   = "mipsle"
	GOARCHMIPS64   = "mips64"
	GOARCHMIPS64LE = "mips64le"
	GOARCHS390X    = "s390x"
	GOARCHRISCV64  = "riscv64"
)

Common GOARCH constants

Variables

View Source
var (
	ErrTargetNotFound = errors.New("target not found")
	ErrNoTargets      = errors.New("no targets defined")
)
View Source
var (
	PopularOSes   = []string{GOOSLinux, GOOSDarwin, GOOSWindows}
	PopularArches = []string{GOARCHAMD64, GOARCHARM64}
)

Functions

func GitVersion

func GitVersion() string

func PrintTargets

func PrintTargets(w io.Writer, targets map[string]Target)

PrintTargets prints available build targets in a clean format.

Types

type Builder

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

func New

func New(opts ...BuilderOption) *Builder

func (*Builder) Add

func (b *Builder) Add(name string, t Target) *Builder

func (*Builder) Default

func (b *Builder) Default(name string) *Builder

func (*Builder) Run

func (b *Builder) Run() error

type BuilderConfig

type BuilderConfig struct {
	DefaultTarget string
	Logger        *slog.Logger
	ExitOnError   *bool
	Args          []string
}

type BuilderOption

type BuilderOption func(cfg *BuilderConfig)

func WithArgs

func WithArgs(args []string) BuilderOption

func WithBuilderConfig

func WithBuilderConfig(cfg BuilderConfig) BuilderOption

func WithDefaultTarget

func WithDefaultTarget(name string) BuilderOption

func WithExitOnError

func WithExitOnError(v bool) BuilderOption

func WithLogger

func WithLogger(l *slog.Logger) BuilderOption

type CMD

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

CMD represents a generic command/task

func Clean

func Clean(opts ...Option) *CMD

Clean returns a CMD that removes the output directory

func NewCMD

func NewCMD(action func(ctx context.Context, cfg Config) error, desc string, opts ...Option) *CMD

NewCMD creates a generic command with functional options and a runnable action

func (*CMD) Run

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

Run executes the command

func (*CMD) String

func (c *CMD) String() string

String returns a description for help/pretty printing

type Config

type Config struct {
	OutDir     string
	Selector   string
	VersionVar string
	Dynamic    bool
	Env        map[string]string
}

type GoBuild

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

func Dynamic

func Dynamic(opts ...Option) *GoBuild

func Static

func Static(opts ...Option) *GoBuild

func (*GoBuild) For

func (g *GoBuild) For(goos, goarch string) *GoBuild

func (*GoBuild) Matrix

func (g *GoBuild) Matrix(oses []string, archs []string) *GoBuild

func (*GoBuild) Run

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

func (*GoBuild) String

func (g *GoBuild) String() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithConfig

func WithConfig(cfg Config) Option

func WithDynamic

func WithDynamic(v bool) Option

func WithEnv

func WithEnv(key, value string) Option

func WithOutDir

func WithOutDir(dir string) Option

func WithSelector

func WithSelector(sel string) Option

func WithVersionVar

func WithVersionVar(v string) Option

type PrettyHandler

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

func NewPrettyHandler

func NewPrettyHandler(opts *slog.HandlerOptions) *PrettyHandler

func (*PrettyHandler) Enabled

func (h *PrettyHandler) Enabled(_ context.Context, level slog.Level) bool

func (*PrettyHandler) Handle

func (h *PrettyHandler) Handle(_ context.Context, r slog.Record) error

func (*PrettyHandler) WithAttrs

func (h *PrettyHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*PrettyHandler) WithGroup

func (h *PrettyHandler) WithGroup(name string) slog.Handler

type Target

type Target interface {
	Run(ctx context.Context) error
	String() string
}

Directories

Path Synopsis
cmd
gob command
examples
matrix command
simple command

Jump to

Keyboard shortcuts

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