Skip to content

仓库 files navigation

cli

GoDoc CI Docs

An intentionally minimal Go package for building CLI applications. It extends the standard library's flag package with nested subcommands and flags anywhere, then gets out of the way.

Docs: https://pressly.github.io/cli

  • flagtype adds common flag.Value types for slices, enums, maps, URLs, and regular expressions. Useful when the standard library's built-in flag types are not enough.
  • graceful runs servers, workers, and batch jobs with signal-aware cancellation and bounded shutdown.
  • xflag parses flags anywhere in the argument list. It is useful with the standard library's flag package when cmd arg --flag should work like cmd --flag arg.

Installation

go get github.com/pressly/cli@latest

Requires Go 1.27 or higher.

Quick Start

root := &cli.Command{
	Name:  "echo",
	Usage: "echo [flags] <text>...",
	Flags: cli.FlagsFunc(func(f *flag.FlagSet) {
		f.Bool("capitalize", false, "capitalize the input")
	}),
	Exec: func(ctx context.Context, s *cli.State) error {
		text := strings.Join(s.Args, " ")
		// GetFlag uses generic methods, available in Go 1.27.
		if s.GetFlag[bool]("capitalize") {
			text = strings.ToUpper(text)
		}
		fmt.Fprintln(s.Stdout, text)
		return nil
	},
}
if err := cli.ParseAndRun(ctx, root, os.Args[1:], nil); err != nil {
	fmt.Fprintf(os.Stderr, "error: %v\n", err)
	os.Exit(1)
}

ParseAndRun parses the command hierarchy, handles --help, and runs the selected command.

The command above gets usable help without extra setup:

Usage:
  echo [flags] <text>...

Flags:
  --capitalize    capitalize the input

For subcommands, inherited, local, and required flags, custom help, usage errors, and subpackages, see the documentation. More complete programs live in examples.

Acknowledgements

There are many great CLI libraries out there, but I always felt they were too heavy for my needs.

Inspired by Peter Bourgon's ff library, especially its v3 branch, which was close to what I wanted. v4 took a different direction, but I wanted to keep the simplicity of v3. This library carries that idea forward.

License

This project is licensed under the MIT License - see the LICENSE file for details.

关于

Simple Go library for creating CLI apps with subcommands and flexible flags

Topics

Resources

Stars

40 stars

关注者

1 watching

复刻s

发布

Used by

贡献者

Languages