cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Grouping flags by persistence and required

Open teocci opened this issue 3 years ago • 4 comments

Usage:
  procstrm (process-stream) [flags]

Flags:
  -C, --config-file string   Configuration file to load
  -d, --drone-id int         Drone id
  -f, --flight-id int        Flight id
  -h, --help                 help for procstrm
  -i, --input-dir string     Directory base where the mp4 videos will be stored
  -L, --log-file string      File that will receive the logger output
  -l, --log-level string     Append level to output [fatal|error|info|debug|trace] (default "info")
  -s, --server-url string    RTSP Server URL to connect.
  -S, --syslog               Logger will output into the syslog
  -t, --temp-dir string      Temporal directory where the app will work (default "./tmp")
  -u, --use-tmp              Use tmp directory to save the logs
  -v, --verbose              Run in verbose mode (default true)
  -V, --version              Print version info and exit

I'm writing an app to receive and process a RTSP stream, but I want to show a useful Usage message for beginner users.

I defined the main flags in the root like this:

func init() {
	cobra.OnInitialize(initConfig)

	app.Flags().StringVarP(&serverURL, cmdapp.SName, cmdapp.SShort, serverURL, cmdapp.SDesc)
	app.Flags().StringVarP(&dirPath, cmdapp.IName, cmdapp.IShort, dirPath, cmdapp.IDesc)

	app.Flags().Int64VarP(&droneID, cmdapp.DName, cmdapp.DShort, droneID, cmdapp.DDesc)
	app.Flags().Int64VarP(&flightID, cmdapp.FName, cmdapp.FShort, flightID, cmdapp.FDesc)

	app.Flags().BoolVarP(&useTmpDir, cmdapp.UName, cmdapp.UShort, cmdapp.UDefault, cmdapp.UDesc)

	_ = app.MarkFlagRequired(cmdapp.IName)
	_ = app.MarkFlagRequired(cmdapp.SName)

	_ = app.MarkFlagRequired(cmdapp.DName)
	_ = app.MarkFlagRequired(cmdapp.FName)

	config.AddFlags(app)
}

Basis users will just need these flags: --server-url, --input-dir, --drone-id, and --flight-id. The other flags were defined as configuration flags for more advanced operators. In this case, it will be nice to have the feature to group flags.

As you can see, flags are sorted alphabetically but not according to their priority. This, definitely, will confuse beginner users.

Usage:
  procstrm (process-stream) [flags]

Flags:
[Required]
  -d, --drone-id int         Drone id
  -f, --flight-id int        Flight id
  -i, --input-dir string     Directory base where the mp4 videos will be stored
  -s, --server-url string    RTSP Server URL to connect.
[Optional]
  -C, --config-file string   Configuration file to load
  -h, --help                 help for procstrm
  -L, --log-file string      File that will receive the logger output
  -l, --log-level string     Append level to output [fatal|error|info|debug|trace] (default "info")
  -S, --syslog               Logger will output into the syslog
  -t, --temp-dir string      Temporal directory where the app will work (default "./tmp")
  -u, --use-tmp              Use tmp directory to save the logs
  -v, --verbose              Run in verbose mode (default true)
  -V, --version              Print version info and exit

I'm trying to get a Usage output similar to this example. The output shows flags categorized by priority as well as alphabetically. I was wondering if there is anyway to group then without modifying the usage template manually? I can't not expend to much time with cosmetics because I need to implement more than 100 main functions.

Probably cobra can group the required flags automatically, making Usage more readable.

Thank you for your time in advance.

teocci avatar Nov 18 '21 09:11 teocci

Oh, I also was wondering if these anyway to add customized groups like optional or categorize them by priority or working task. They don't need to be in a sub-command but in the root command that is why I decided to customize the Usage message but it took to much time.

amissu89 avatar Nov 30 '21 00:11 amissu89

This issue is being marked as stale due to a long period of inactivity

github-actions[bot] avatar Jan 30 '22 00:01 github-actions[bot]

Thanks for the idea. I've also wished it was easier to get different groups without having to write my own templates and such.

I haven't investigated the code change required for this but it seems useful to have another option for flag grouping in the help.

johnSchnake avatar Feb 14 '22 15:02 johnSchnake

func AddRequiredHelpMessage() {
	c, flags, err := rootCmd.Traverse(os.Args[1:])
	if err != nil {
		utils.Logger.Error(err.Error())
	}
	if len(flags) != 0 {
		if flags[0] == "-h" || flags[0] == "--help" {
			c.Flags().VisitAll(func(pflag *pflag.Flag) {
				requiredAnnotation, found := pflag.Annotations[cobra.BashCompOneRequiredFlag]
				if !found {
					return
				}
				if (requiredAnnotation[0] == "true") && !pflag.Changed {
					if !strings.Contains(pflag.Usage, "(*)") {
						pflag.Usage = "(*) " + pflag.Usage
					}
				}
			})
		}
	}
}

I try workaround like this to add help info (*):

old help message: -n, --name string Project name now help message: -n, --name string (*) Project name

Also I can change "(*)" to "(required)", but I think it is too long.

alan-wr avatar Dec 26 '23 13:12 alan-wr