Skip to content

Generate command line argument parsing code from Go comments.

License

Notifications You must be signed in to change notification settings

steverusso/goclap

Repository files navigation

goclap

Go Reference GitHub CI Go Report Card

go install github.com/steverusso/goclap@latest

A pre-build tool to generate command line argument parsing code from Go comments. The idea is inspired by the clap Rust crate, specifically its use of documentation and proc macros.

Example

The following is taken from examples/simple/main.go.

//go:generate goclap -type mycli

...

// Print a string with the option to make it uppercase.
type mycli struct {
	// Make the input string all uppercase.
	//
	// clap:opt upper
	toUpper bool
	// The input string.
	//
	// clap:arg_required
	input string
}

func main() {
	c := mycli{}
	c.Parse(os.Args[1:])

	s := c.input
	if c.toUpper {
		s = strings.ToUpper(s)
	}

	fmt.Println(s)
}

By running go generate (assuming goclap is installed), the mycli struct, its fields, and their comments will be used to generate code for parsing command line arguments into a mycli. That code will be placed in a file named clap.gen.go (see the simple example's one). The program can then be built with go build.

Running ./simple -u hello will output "HELLO", and running ./simple -h will output the following help message:

simple - Print a string with the option to make it uppercase

usage:
   simple [options] <input>

options:
   -upper   Make the input string all uppercase
   -h       Show this help message

arguments:
   <input>   The input string

Building

To just build the project as is, run go build. If you have task installed, you can run task get-tools to install the latest versions of (goimports, gofumpt, and staticcheck). Once you have those tools, you can run task to format, build, and lint the code, or you can run task install to format, lint, and install goclap.

Projects Using Goclap

License

This is free and unencumbered software released into the public domain. Please see the UNLICENSE file for more information.