// Package options holds the flags that every command has and reads // them back. package options import ( "fmt" "strconv" "github.com/spf13/cobra" "sneak.berlin/go/keyfunc/internal/mnemonic" ) // Add gives a command the flags that every command has. They are // persistent, so every command below it has them too. func Add(cmd *cobra.Command) { cmd.PersistentFlags().String( "mnemonic-command", "", "shell command whose output is the mnemonic", ) cmd.PersistentFlags().StringP( "index", "n", "0", "which key to derive, as a decimal `number`", ) } // Index returns the key index the user asked for. func Index(cmd *cobra.Command) (uint32, error) { return Decimal(cmd, "index") } // Decimal reads the named string flag as a number written in decimal // digits only: a leading zero is still decimal, and a base prefix, an // underscore or a sign is refused. The back-quoted word in the usage // of such a flag is what --help shows as its type. func Decimal(cmd *cobra.Command, name string) (uint32, error) { text, err := cmd.Flags().GetString(name) if err != nil { return 0, fmt.Errorf("reading --%s: %w", name, err) } number, err := strconv.ParseUint(text, 10, 32) if err != nil { return 0, fmt.Errorf( "reading --%s as a decimal number: %w", name, err, ) } return uint32(number), nil } // Mnemonic returns the mnemonic, from the first source that has one. func Mnemonic(cmd *cobra.Command) (string, error) { command, err := cmd.Flags().GetString("mnemonic-command") if err != nil { return "", fmt.Errorf("reading the mnemonic command: %w", err) } return mnemonic.Read(cmd.Context(), command) }