Skip to content
Myr

flag_groups.go

This file

Path

flag_groups.go

290 lines · 9.4 KiB · Go

Last changed by

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

History of this file

Take it

The walk stopped after 200 commits: lines older than 89d7b83 point at it.

update copyright year (#1927)Unai Martinez-Corralbefore adoption9e6b58a

line 1why, one step back
1// Copyright 2013-2023 The Cobra Authors

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 2–5why, one step back
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 at

add missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9

lines 6–7why, one step back
6//
7// http://www.apache.org/licenses/LICENSE-2.0

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 8–25why, one step back
8//
9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package cobra1617import (18 "fmt"19 "sort"20 "strings"2122 flag "github.com/spf13/pflag"23)2425const (

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

lines 26–28why, one step back
26 requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set"
27 oneRequiredAnnotation = "cobra_annotation_one_required"28 mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 29–39why, one step back
29)
3031// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors32// if the command is invoked with a subset (but not all) of the given flags.33func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {34 c.mergePersistentFlags()35 for _, v := range flagNames {36 f := c.Flags().Lookup(v)37 if f == nil {38 panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))39 }

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

line 40why, one step back
40 if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil {

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 41–46why, one step back
41 // Only errs if the flag isn't found.
42 panic(err)43 }44 }45}46

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 47–55why, one step back
47// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors
48// if the command is invoked without at least one flag from the given set of flags.49func (c *Command) MarkFlagsOneRequired(flagNames ...string) {50 c.mergePersistentFlags()51 for _, v := range flagNames {52 f := c.Flags().Lookup(v)53 if f == nil {54 panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v))55 }

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

line 56why, one step back
56 if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil {

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 57–62why, one step back
57 // Only errs if the flag isn't found.
58 panic(err)59 }60 }61}62

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 63–72why, one step back
63// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors
64// if the command is invoked with more than one flag from the given set of flags.65func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {66 c.mergePersistentFlags()67 for _, v := range flagNames {68 f := c.Flags().Lookup(v)69 if f == nil {70 panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))71 }72 // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

line 73why, one step back
73 if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil {

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 74–78why, one step back
74 panic(err)
75 }76 }77}78

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 79why, one step back
79// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

line 80why, one step back
80// first error encountered.

Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a

line 81why, one step back
81func (c *Command) ValidateFlagGroups() error {

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 82–90why, one step back
82 if c.DisableFlagParsing {
83 return nil84 }8586 flags := c.Flags()8788 // groupStatus format is the list of flags as a unique ID,89 // then a map of each flag name and whether it is set or not.90 groupStatus := map[string]map[string]bool{}

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 91why, one step back
91 oneRequiredGroupStatus := map[string]map[string]bool{}

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 92–93why, one step back
92 mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
93 flags.VisitAll(func(pflag *flag.Flag) {

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

lines 94–96why, one step back
94 processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
95 processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)96 processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 97–101why, one step back
97 })
9899 if err := validateRequiredFlagGroups(groupStatus); err != nil {100 return err101 }

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 102–104why, one step back
102 if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {
103 return err104 }

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 105–132why, one step back
105 if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
106 return err107 }108 return nil109}110111func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {112 for _, fname := range flagnames {113 f := fs.Lookup(fname)114 if f == nil {115 return false116 }117 }118 return true119}120121func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {122 groupInfo, found := pflag.Annotations[annotation]123 if found {124 for _, group := range groupInfo {125 if groupStatus[group] == nil {126 flagnames := strings.Split(group, " ")127128 // Only consider this flag group at all if all the flags are defined.129 if !hasAllFlags(flags, flagnames...) {130 continue131 }132

Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43

line 133why, one step back
133 groupStatus[group] = make(map[string]bool, len(flagnames))

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 134–166why, one step back
134 for _, name := range flagnames {
135 groupStatus[group][name] = false136 }137 }138139 groupStatus[group][pflag.Name] = pflag.Changed140 }141 }142}143144func validateRequiredFlagGroups(data map[string]map[string]bool) error {145 keys := sortedKeys(data)146 for _, flagList := range keys {147 flagnameAndStatus := data[flagList]148149 unset := []string{}150 for flagname, isSet := range flagnameAndStatus {151 if !isSet {152 unset = append(unset, flagname)153 }154 }155 if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {156 continue157 }158159 // Sort values, so they can be tested/scripted against consistently.160 sort.Strings(unset)161 return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)162 }163164 return nil165}166

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 167–187why, one step back
167func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {
168 keys := sortedKeys(data)169 for _, flagList := range keys {170 flagnameAndStatus := data[flagList]171 var set []string172 for flagname, isSet := range flagnameAndStatus {173 if isSet {174 set = append(set, flagname)175 }176 }177 if len(set) >= 1 {178 continue179 }180181 // Sort values, so they can be tested/scripted against consistently.182 sort.Strings(set)183 return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList)184 }185 return nil186}187

Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83

lines 188–218why, one step back
188func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
189 keys := sortedKeys(data)190 for _, flagList := range keys {191 flagnameAndStatus := data[flagList]192 var set []string193 for flagname, isSet := range flagnameAndStatus {194 if isSet {195 set = append(set, flagname)196 }197 }198 if len(set) == 0 || len(set) == 1 {199 continue200 }201202 // Sort values, so they can be tested/scripted against consistently.203 sort.Strings(set)204 return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)205 }206 return nil207}208209func sortedKeys(m map[string]map[string]bool) []string {210 keys := make([]string, len(m))211 i := 0212 for k := range m {213 keys[i] = k214 i++215 }216 sort.Strings(keys)217 return keys218}

Update shell completion to respect flag groups (#1659)Marc Khouzambefore adoption5f2ec3c

lines 219–221why, one step back
219
220// enforceFlagGroupsForCompletion will do the following:221// - when a flag in a group is present, other flags in the group will be marked required

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 222why, one step back
222// - when none of the flags in a one-required group are present, all flags in the group will be marked required

Update shell completion to respect flag groups (#1659)Marc Khouzambefore adoption5f2ec3c

lines 223–231why, one step back
223// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
224// This allows the standard completion logic to behave appropriately for flag groups225func (c *Command) enforceFlagGroupsForCompletion() {226 if c.DisableFlagParsing {227 return228 }229230 flags := c.Flags()231 groupStatus := map[string]map[string]bool{}

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 232why, one step back
232 oneRequiredGroupStatus := map[string]map[string]bool{}

Update shell completion to respect flag groups (#1659)Marc Khouzambefore adoption5f2ec3c

lines 233–234why, one step back
233 mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
234 c.Flags().VisitAll(func(pflag *flag.Flag) {

Consistent annotation names (#2140)Nir Sofferbefore adoption5c2c1d6

lines 235–237why, one step back
235 processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)
236 processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)237 processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)

Update shell completion to respect flag groups (#1659)Marc Khouzambefore adoption5f2ec3c

lines 238–248why, one step back
238 })
239240 // If a flag that is part of a group is present, we make all the other flags241 // of that group required so that the shell completion suggests them automatically242 for flagList, flagnameAndStatus := range groupStatus {243 for _, isSet := range flagnameAndStatus {244 if isSet {245 // One of the flags of the group is set, mark the other ones as required246 for _, fName := range strings.Split(flagList, " ") {247 _ = c.MarkFlagRequired(fName)248 }

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 249–255why, one step back
249 }
250 }251 }252253 // If none of the flags of a one-required group are present, we make all the flags254 // of that group required so that the shell completion suggests them automatically255 for flagList, flagnameAndStatus := range oneRequiredGroupStatus {

Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43

line 256why, one step back
256 isSet := false

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 257why, one step back
257

Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43

line 258why, one step back
258 for _, isSet = range flagnameAndStatus {

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

line 259why, one step back
259 if isSet {

Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43

line 260why, one step back
260 break

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 261–265why, one step back
261 }
262 }263264 // None of the flags of the group are set, mark all flags in the group265 // as required

Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43

line 266why, one step back
266 if !isSet {

Add 'one required flag' group (#1952)Martijn Eversbefore adoptionc81c46a

lines 267–268why, one step back
267 for _, fName := range strings.Split(flagList, " ") {
268 _ = c.MarkFlagRequired(fName)

Update shell completion to respect flag groups (#1659)Marc Khouzambefore adoption5f2ec3c

lines 269–290why, one step back
269 }
270 }271 }272273 // If a flag that is mutually exclusive to others is present, we hide the other274 // flags of that group so the shell completion does not suggest them275 for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {276 for flagName, isSet := range flagnameAndStatus {277 if isSet {278 // One of the flags of the mutually exclusive group is set, mark the other ones as hidden279 // Don't mark the flag that is already set as hidden because it may be an280 // array or slice flag and therefore must continue being suggested281 for _, fName := range strings.Split(flagList, " ") {282 if fName != flagName {283 flag := c.Flags().Lookup(fName)284 flag.Hidden = true285 }286 }287 }288 }289 }290}