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: 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)
	}
}
package examples

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

// AddRequiredFlag _
//
// Sample code,
//
//	app.RootBuilder(common.AddRequiredFlag)
//
// Or,
//
//	app := cmdr.Create(appName, version, author, desc).
//		WithBuilders(common.AddRequiredFlag).
//		Build()
//	app.Run(context.TODO())
func AddRequiredFlag(c cli.CommandBuilder) { //nolint:revive
	c.Flg("required", "r").
		Default("").
		Required(true).
		Description("the required text string wanted.", "").
		Group("Test").
		Build()
}

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

额外的话题

Required

Toggle Group

Valid Args

Head Like

External Tool

Plus Sign

Event Handlers

What is Next?

How is this guide?

Last updated on

Flag

What is Flags

Flag: Toggle Group

Toggleable Group/Toggle Group

On this page

The required flag
Define
Run
额外的话题