hzDocs

Flag: Required

Required Flag

The required flag

A required flag request end user must have input it at least once. If not, cmdr will deny the further processing and exit.

The backstage algorithm is checking the hit-times of all of the meeting requied flags in parsing time. The zero (0) hit-times value would cause the failed verification.

Define

.Required() 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/cmdr/v2/examples/common"
	"github.com/hedzr/is/term/color"
	logz "github.com/hedzr/logg/slog"
)
 
const (
	appName = "required"
	desc    = `a sample to show u what error raised by a missed required flag.`
	version = cmdr.Version
	author  = `The Example Authors`
)
 
func main() {
	app := cmdr.Create(appName, version, author, desc).
		With(func(app cli.App) {
			app.OnAction(func(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
        msg := cmd.Store().MustString("required")
				println(`Hello, World.`, msg)
				return
			})
		}).
		WithBuilders(common.AddRequiredFlag).
		WithAdders().
		Build()
 
	ctx := context.Background()
	if err := app.Run(ctx); err != nil {
		if errors.Is(err, cli.ErrRequiredFlag) {
			fmt.Printf(color.StripLeftTabsC(`
				The <b>REQUIRED</b> Flag not present:
 
				<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)
	}
}

Run

The feedback of unsatisfied required flag looks like:

$ go run ./examples/required/
The REQUIRED Flag not present:
 
Flag "Flg{'.required'}" is REQUIRED | cmd=Cmd{''}
$
 
$ go run ./examples/required/ -r xyz
Hello, World. xyz

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page