Skip to content
Myr

flag_groups.go

This file

Path

flag_groups.go

174 lines · 5.1 KiB · Go

Last changed by

Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24

History of this file

Take it

1// Copyright © 2022 Steve Francia <spf@spf13.com>.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516import (17	"fmt"18	"sort"19	"strings"2021	flag "github.com/spf13/pflag"22)2324const (25	requiredAsGroup   = "cobra_annotation_required_if_others_set"26	mutuallyExclusive = "cobra_annotation_mutually_exclusive"27)2829// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors30// if the command is invoked with a subset (but not all) of the given flags.31func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {32	c.mergePersistentFlags()33	for _, v := range flagNames {34		f := c.Flags().Lookup(v)35		if f == nil {36			panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))37		}38		if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {39			// Only errs if the flag isn't found.40			panic(err)41		}42	}43}4445// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors46// if the command is invoked with more than one flag from the given set of flags.47func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {48	c.mergePersistentFlags()49	for _, v := range flagNames {50		f := c.Flags().Lookup(v)51		if f == nil {52			panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))53		}54		// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.55		if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {56			panic(err)57		}58	}59}6061// validateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the62// first error encountered.63func (c *Command) validateFlagGroups() error {64	if c.DisableFlagParsing {65		return nil66	}6768	flags := c.Flags()6970	// groupStatus format is the list of flags as a unique ID,71	// then a map of each flag name and whether it is set or not.72	groupStatus := map[string]map[string]bool{}73	mutuallyExclusiveGroupStatus := map[string]map[string]bool{}74	flags.VisitAll(func(pflag *flag.Flag) {75		processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)76		processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)77	})7879	if err := validateRequiredFlagGroups(groupStatus); err != nil {80		return err81	}82	if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {83		return err84	}85	return nil86}8788func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {89	for _, fname := range flagnames {90		f := fs.Lookup(fname)91		if f == nil {92			return false93		}94	}95	return true96}9798func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {99	groupInfo, found := pflag.Annotations[annotation]100	if found {101		for _, group := range groupInfo {102			if groupStatus[group] == nil {103				flagnames := strings.Split(group, " ")104105				// Only consider this flag group at all if all the flags are defined.106				if !hasAllFlags(flags, flagnames...) {107					continue108				}109110				groupStatus[group] = map[string]bool{}111				for _, name := range flagnames {112					groupStatus[group][name] = false113				}114			}115116			groupStatus[group][pflag.Name] = pflag.Changed117		}118	}119}120121func validateRequiredFlagGroups(data map[string]map[string]bool) error {122	keys := sortedKeys(data)123	for _, flagList := range keys {124		flagnameAndStatus := data[flagList]125126		unset := []string{}127		for flagname, isSet := range flagnameAndStatus {128			if !isSet {129				unset = append(unset, flagname)130			}131		}132		if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {133			continue134		}135136		// Sort values, so they can be tested/scripted against consistently.137		sort.Strings(unset)138		return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)139	}140141	return nil142}143144func validateExclusiveFlagGroups(data map[string]map[string]bool) error {145	keys := sortedKeys(data)146	for _, flagList := range keys {147		flagnameAndStatus := data[flagList]148		var set []string149		for flagname, isSet := range flagnameAndStatus {150			if isSet {151				set = append(set, flagname)152			}153		}154		if len(set) == 0 || len(set) == 1 {155			continue156		}157158		// Sort values, so they can be tested/scripted against consistently.159		sort.Strings(set)160		return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)161	}162	return nil163}164165func sortedKeys(m map[string]map[string]bool) []string {166	keys := make([]string, len(m))167	i := 0168	for k := range m {169		keys[i] = k170		i++171	}172	sort.Strings(keys)173	return keys174}