hzDocs
hzDocs
Articles / Postshedzr.comIntroduction

Guide

Your First CLI AppConcise Version
Step by step
Concepts
CommandCommand: Invoke programCommand: Presetting ArgsCommand: RedirectToCommand: DynCommandCommand: Aliases from ConfigCommand: Event HandlersFlagFlag: RequiredFlag: Toggle GroupFlag: Valid ArgsFlag: `Head -1` styleFlag: External EditorFlag: NegatableFlag: Leading Plus Sign `+`Flag: Event Handlers解析结果Builtin Commands & Flags帮助子系统Shared App辨析Package level functionsWithOptsBackstage
Howto ...
Auto-close the ClosersRead config into structUsing is DetectorsUsing Store

References

What's New
Packages

Others

Examples
Blueprint
产品发布
产品发布之前
Concepts

Flag: Valid Args

Valid Args / Enums

Enums

Setting a flag with valid args limitation will verify the end user input with a preset set.

Totally the default value must be a string.

Define

.ValidArgs(...) can do that.

package main

import (
	"context"
	"fmt"
	"os"

	"gopkg.in/hedzr/errors.v3"

	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/is/term/color"
	logz "github.com/hedzr/logg/slog"
)

const (
	appName = "valid-args"
	desc    = `a sample to show u how to using enum values in option.`
	version = cmdr.Version
	author  = ``
)

func main() {
	app := cmdr.Create(appName, version, author, desc).
		With(func(app cli.App) {}).
		WithBuilders(validArgsCommand).
		WithAdders().
		Build()

	ctx := context.Background()
	if err := app.Run(ctx); err != nil {
		if errors.Is(err, cli.ErrValidArgs) {
			fmt.Printf(color.StripLeftTabsC(`
				The input is not in valid list:

				<font color="red">%s</red>
				`),
				err)
			os.Exit(1)
		}
		logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build
		os.Exit(app.SuggestRetCode())
	} else if rc := app.SuggestRetCode(); rc != 0 {
		os.Exit(rc)
	}
}

func validArgsCommand(parent cli.CommandBuilder) { //nolint:revive
	parent.Flg("enum", "e").
		Description("valid args option", "").
		Group("Test").
		ValidArgs("apple", "banana", "orange").
		Default("").
		Build()

	// give root command an action to handle it
	parent.OnAction(func(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
		v := cmd.Store().MustString("enum")
		println("enum value is: ", v)
		return
	})

	parent.Examples(`Try to use value-args app,

	  $ $APP -e apple
	    this command works ok.
	  $ $APP -e mongo
	    can't work because valid args are: apple, banana, and orange.
	  $ $APP --help
	    check out the valid values in help screen.
	`)
}
package examples

import (
	"github.com/hedzr/cmdr/v2/cli"
)

func AddValidArgsFlag(c cli.CommandBuilder) { //nolint:revive
	c.Flg("fruit", "fr").
		Default("").
		Description("the message.", "").
		Group("Valid Args").
		PlaceHolder("FRUIT").
		ValidArgs("apple", "banana", "orange").
		Build()
}

Run

The result of the sample app above is:

$ go run ./examples/valid-args -e mongo
The input is not in valid list:

Flag "Flg{'.enum'}" expects a valid input is in list: [apple banana orange] | cmd=Cmd{''}
exit status 1
$

额外的话题

Required

Toggle Group

Valid Args

Head Like

External Tool

Plus Sign

Event Handlers

What is Next?

How is this guide?

Last updated on

Flag: Toggle Group

Toggleable Group/Toggle Group

Flag: `Head -1` style

Head like flag

On this page

Enums
Define
Run
额外的话题