The Go module to build unified multitool CLI applications
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
surdeus 084859eb10 Add MIT license
The repository had no license file, which means all rights reserved by
default: nobody could legally use, copy or redistribute it, and license
detectors had nothing to report.

MIT, matching the rest of the lib/ family. Canonical text with a .txt
extension so the filename is unambiguous on case-insensitive filesystems.
2026-11-17 04:23:39 +05:00
cmd/test refactor: move to the go.mojosa.su/lib/gocli module path 2026-10-31 14:20:55 +05:00
mtool fix: flags.Usage() actually prints the help 2026-11-01 20:15:59 +05:00
.gitignore chore: ignore .codewhale session state 2026-10-24 01:06:01 +05:00
btest.sh major: changing path. 2026-03-06 16:49:44 +05:00
go.mod refactor: move to the go.mojosa.su/lib/gocli module path 2026-10-31 14:20:55 +05:00
go.sum refactor!: drop the colour handling from mtool 2026-10-24 15:14:00 +05:00
LICENSE.txt Add MIT license 2026-11-17 04:23:39 +05:00
readme.md feat: report the exit code instead of exiting, and route the writers 2026-11-01 15:45:28 +05:00

gocli

A package for command line programs in Go:

  • mtool — a multitool: many programs under one command, like git or bb.

It has no dependencies.

go get go.mojosa.su/lib/gocli

Go 1.18 or later.

mtool

Most of the work happens here. A tree of commands, each with its own flags, descriptions and usage, and a help screen built from them:

package main

import (
	"fmt"
	"os"

	"go.mojosa.su/lib/gocli/mtool"
)

func main() {
	var repeat int

	root := mtool.T("greet").Desc("say hello").Subs(
		mtool.T("hello").Func(func(flags *mtool.Flags) {
			flags.IntVar(&repeat, "n", 1, "how many times", "GREET_N")
			args := flags.Parse()

			for i := 0; i < repeat; i++ {
				fmt.Println("hello", args)
			}
		}).Desc("greet someone").
			Usage("<name>").
			Ldesc("Prints a greeting, once by default."),
	)

	root.Run(os.Args[1:])
}

That gives you the subcommand, the flags, and the help:

$ greet
Name:
  greet - say hello

Usage:
  greet <command>

Commands:
  hello greet someone

$ greet hello -h
Name:
  greet hello - greet someone

Usage:
  greet hello [options] <name>

Description:
  Prints a greeting, once by default.

Options:
  -- option terminator
  -n int
    	how many times
    	($GREET_N) (default 1)

Three things are worth knowing.

Every flag can come from the environment. The names you pass after the usage string are tried in order, and a flag passed on the command line always wins:

flags.IntVar(&repeat, "n", 1, "how many times", "GREET_N", "GREET_COUNT")

A variable holding something the flag cannot take is reported rather than silently ignored, and the flag keeps the value it had.

You can ask where a value came from. flags.WasPassed(name) is true only when the option was given on the command line, which is not the same as the value differing from the default: -n 1 counts as passed even though 1 is also the default. flags.SourceOf(name) answers "flag", "env" or "default" directly.

flags.StringVar(&addr, "addr", "", "address to listen on", "PROG_ADDR")
flags.Parse()

if !flags.WasPassed("addr") && addr == "" {
	addr = "0.0.0.0:8080" // neither the operator nor the environment said
}

That is the difference between "nobody said" and "somebody said empty", which matters when an empty value is a legitimate way to unset something.

Both answer for the parse that has already happened, so ask after Parse. A flag is only known to have been passed once the flag package has read the arguments; before that SourceOf reports the environment or the default.

Failures come back through flags.ParseErr. In the default mode a bad command line ends the process the way the flag package does, since there is no sane way to carry on. A tool that would rather decide for itself asks for the quiet mode:

root := mtool.T("prog").SoftErrors().Subs(/* ... */)

// inside a handler:
args, err := flags.ParseArgs()

The help is plain text. There are no escape sequences anywhere in it, on a terminal or in a pipe, so the output is the same in a log, a pager or a screenshot.

Embedding a tool in another program

Run ends the process, which is what a main wants and what nothing else does. Two things make a tool usable from inside a larger program.

RunArgs reports the exit code instead of exiting.

code := root.RunArgs(os.Args[1:])

The codes are the same ones Run would exit with: 0 for success and help, 1 for an unknown command or a bare listing, 2 for a failure of the flag layer. Diagnostics have already been written by the time it returns.

That matters when more than one tool runs in a process, or when one has to be dispatched from a goroutine — the first failure no longer takes everything with it, and the caller can unwind its own work:

go func() {
	defer output.Close()          // runs even when the tool fails
	if code := pin.Tool.RunArgs(args, io.Reader(os.Stdin), io.Writer(output)); code != 0 {
		failed.Store(true)
	}
}()

The flag layer still terminates unless the tool asked for SoftErrors, so pair RunArgs with SoftErrors when the run must never end the process.

WithOutput chooses where the tool renders.

root := mtool.T("prog").WithOutput(stdout, stderr).Subs(/* ... */)

Help, usage, error diagnostics and the sub command list all go through those writers, and sub commands inherit whatever the root was given, so it only needs setting once. A nil writer keeps the process's own stream, which is why existing programs are unaffected.

Before this, those writes went to os.Stdout and os.Stderr unconditionally, so a tool embedded in a pipeline could not have its help captured.