hzDocs

Flag: Toggle Group

Toggleable Group/Toggle Group

Togglable Group

Treat a group of flags as a radio button group in GUI, so the last flags will be reset while the flag in same group is been parsed ok and set.

Generally, both these flags should have a boolean default value. And only one flag have true value. If the rule is not obeyed, cmdr keeps the last one (true value of the flags).

Define

.ToggleGroup(toggleGroupName) can do that.

toggleGroupName makes the flags into a same toggle group. It is also used as the group name.

In phase invoking OnAction, the final value of the toggale group can be read by cmd.Store().MustBool(toggleGroupName).

Since v2.1.16, Multiple Selections for a Toggle Group is avaliable: the final selected items can be read by cmd.Store().MustStringSlice(toggleGroupName+".selected").

A sample here,

package main
 
import (
	"context"
	"os"
 
	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/cmdr/v2/examples/common"
	logz "github.com/hedzr/logg/slog"
)
 
const (
	appName = "toggle-group"
	desc    = `a sample to show u what looking of a toggleable-group option in the help screen.`
	version = cmdr.Version
	author  = `The Example Authors`
)
 
func main() {
	app := cmdr.Create(appName, version, author, desc).
		With(func(app cli.App) {}).
		WithBuilders(common.AddToggleGroupCommand).
		WithAdders().
		Build()
 
	ctx := context.Background()
	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)
	}
}

Run

In the help screen, the flags in a toggle group will be shown with a leading checkbox, just like the following output:

$ go run ./examples/toggle-group tg2 --help
toggle-group v2.1.16 ~ Copyright © 2025 by The Example Authors ~ All Rights Reserved.
 
Usage:
 
  $ toggle-group tg-test2 [Options...][files...]
 
Description:
 
  tg2 test new features,
  verbose long descriptions here.
 
Flags:
  [fruit]
    -a, --apple                               [x] the test text. (Default: true)
    -b, --banana                              [ ] the test text. (Default: false)
    -o, --orange                              [ ] the test text. (Default: false)
 
Global Flags:
  [Misc]
    -h, --help,--info,--usage                 Show this help screen (-?) [Env: HELP] (Default: true)
 
Type '-h'/'-?' or '--help' to get command help screen.
More: '-D'/'--debug', '-V'/'--version', '-#'/'--build-info', '--no-color'...
 
$ go run ./examples/toggle-group tg2 --banana --orange
*** Got fruit (toggle group): "orange"
         multiple selections: ["banana" "orange"]
 
$ go run ./examples/toggle-group tg2 --banana
*** Got fruit (toggle group): "banana"
         multiple selections: ["banana"]
 
$

And the final value banana will be retrieved properly.

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page