hzDocs

很多很多的标志

Flags, Lots of Flags

创建标志选项和访问它

同样的道理,你也可以创建大量的选项,它们将归属于特定构成子命令。

./examples/lots-flags/main.go
package main
 
import (
	"context"
	"fmt"
	"os"
 
	"github.com/hedzr/cmdr-loaders/local"
	"github.com/hedzr/cmdr-tests/examples/common"
	"github.com/hedzr/cmdr-tests/examples/common/cmd"
	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	logz "github.com/hedzr/logg/slog"
	"github.com/hedzr/store"
)
 
const (
	appName = "lots-flags"
)
 
func main() {
	app := chain(common.PrepareApp(
		appName,
 
		// use an option store explicitly, or a dummy store by default
		cmdr.WithStore(store.New()),
 
		// import "github.com/hedzr/cmdr-loaders/local" to get in advanced external loading features
		cmdr.WithExternalLoaders(
			local.NewConfigFileLoader(
				local.WithAlternateWriteBack(false), // disable write-back the modified state into alternative config file
				local.WithAlternateDotPrefix(false), // use '<app-name>.toml' instead of '.<app-name>.toml'
			),
			local.NewEnvVarLoader(),
		),
	)(cmd.Commands...))
 
	ctx := context.Background() // with cancel can be passed thru in your actions
	if err := app.Run(ctx); err != nil {
		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 chain(app cli.App) cli.App {
	app.Cmd("cmd").
		Description("subcommands with lots of flags here").
		With(func(b cli.CommandBuilder) {
			for i := 0; i < 15; i++ {
				b.Flg(fmt.Sprintf("option-%d", i), fmt.Sprintf("o%d", i)).
					Description(fmt.Sprintf("flag(option)-%d here", i)).
					Build()
			}
		})
	return app
}

用 cmdr 内建选项 ~~tree 来运行它,显示全部的命令层级如下:

$ FORCE_DEFAULT_ACTION=1 go run ./examples/lots-flags/ ~~tree
...

其结果像这样,

image-20250217213946371

环境变量 FORCE_DEFAULT_ACTION=1 促使 cmdr 略过你的 OnAction 转而执行一个内建的响应函数,该函数显示命中的命令(ACTIONS)以及选项参数清单。 这对于调试命令行参数会很有用。

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page