Skip to Content
gnux

Go library

Use the gnux engines, tools and shell from a Go program.

gnux is a Go module as well as a binary. Everything the commands do is available to a Go program at three levels: a single tool's engine, a tool by name, or a whole script.

Requirements

A Go module on Go 1.26 or newer. The engines depend only on the standard library and github.com/mattn/go-isatty; cobra is compiled only into the command-line packages under cmd/.

go get github.com/braswelljr/gnux

An engine

Each tool has an engine package under core/ named after the GNU tool: core/rm, core/cp, core/ls and so on. An engine takes the options the flags would set and the streams to read and write; the zero value of its Options is the tool with no flags.

package main

import (
	"errors"
	"log"

	"github.com/braswelljr/gnux/core"
	"github.com/braswelljr/gnux/core/rm"
)

func main() {
	// rmx -rf build dist
	engine := rm.New(rm.Options{Recursive: true, Force: true}, core.Stdio())

	err := engine.Run([]string{"build", "dist"})
	if errors.Is(err, core.ErrFailed) {
		// Some paths could not be removed; the diagnostics already went to stderr.
		log.Fatal("cleanup incomplete")
	}
}

Streams

core.Stdio() wires an engine to the process's own streams and core.Discard() silences it. To capture output, build a core.Streams from any reader and writers:

var out, errs bytes.Buffer
streams := core.Streams{In: strings.NewReader(""), Out: &out, Err: &errs}

Errors

Every engine follows one convention.

Returned errorMeaning
nilsuccess
core.ErrFailedit ran, something failed, and the diagnostics are already written
*core.UsageErrorthe arguments were wrong
*core.ExitErrora specific exit status, for tools whose status carries meaning

A tool by name

cmd.RunTool runs a tool from its name and arguments, exactly as the command line would, and returns the exit status instead of exiting. It accepts the gnux name or the GNU one.

status, ok := cmd.RunTool("rmx", []string{"-rf", "build"}, core.Stdio())

A script

cmd.NewShell builds a gnux shell whose commands are the tools. It runs a script in-process, the same on every platform.

sh := cmd.NewShell(shell.Options{ErrExit: true}, core.Stdio())
sh.Set("OUT", "dist")

err := sh.RunString(`
mkdirx -p $OUT
cpx -r assets $OUT/
lsx -l $OUT
`)

The shell reaches the tools only through its Exec function, so a program can also construct one with shell.New and supply its own command set - to restrict a script to a few tools, or to add commands of its own.

Injection points

Engines expose the things that normally need a terminal, a clock or the real environment as fields - PromptFn, RemoveFn, Now, Getenv and the like - so they can be driven, and tested, from code.

On this page