Skip to content
Myr

Refactor flags mechanisms

Before adoption: this commit came in with the history the project adopted, so no landing records it.

I think It's more obvious now to understand the inheritance of flags. Fix #403 Fix #404 Performance improvements: benchmark old ns/op new ns/op delta BenchmarkInheritedFlags-4 6536 5595 -14.40% BenchmarkLocalFlags-4 3193 3235 +1.32% benchmark old allocs new allocs delta BenchmarkInheritedFlags-4 49 39 -20.41% BenchmarkLocalFlags-4 23 21 -8.70% benchmark old bytes new bytes delta BenchmarkInheritedFlags-4 2040 1000 -50.98% BenchmarkLocalFlags-4 1008 544 -46.03%

authored by Albert Nigmatzianov · committed by Albert Nigmatzianov · parent a3cd8ab · Browse files · 2 files+91 added−102 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+91 added−102 removed

  • other:+91 added−102 removed

2 files+91 added−102 removed

modified:cobra_test.go+31 added-22 removed
1 unmodified line
23import (4 "bytes"5 "fmt"6 "os"6 "reflect"7 "runtime"8 "strings"9 "testing"
1 unmodified line
1112 "github.com/spf13/pflag"13)1416var _ = fmt.Println17var _ = os.Stderr1815var tp, te, tt, t1, tr []string16var rootPersPre, echoPre, echoPersPre, timesPersPre []string17var flagb1, flagb2, flagb3, flagbr, flagbp bool18var flags1, flags2a, flags2b, flags3, outs string
142 unmodified lines
161 cmdRootSameName.ResetFlags()162 cmdRootWithRun.ResetFlags()163 cmdSubNoRun.ResetFlags()164 cmdCustomFlags.ResetFlags()165 cmdVersion1.ResetFlags()166 cmdVersion2.ResetFlags()167168 cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)170 cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")171 cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")172 cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")169 cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour")174 cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")175 cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")176 cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)177 cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")170 cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")171 cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")172 cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")173 cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")174 cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")175 cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")176 cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")177 cmdTimes.Flags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)178 cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)179 cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")181 cmdVersion1.ResetFlags()182 cmdVersion2.ResetFlags()180 cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")181}182183func commandInit() {184 cmdEcho.ResetCommands()
670 unmodified lines
855 t.Errorf("InheritedFlags expected to contain strone, Got: nil")856 }857 if inherited.Lookup("strtwo") != nil {858 t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")861859 }860}861862func TestNoNRunnableRootCommandNilInput(t *testing.T) {
283 unmodified lines
1146 t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")1147 }1148}11491153func TestFlagOnPflagCommandLine(t *testing.T) {1154 flagName := "flagOnCommandLine"1155 pflag.CommandLine.String(flagName, "", "about my flag")1156 r := fullSetupTest("--help")11571158 checkResultContains(t, r, flagName)1159}11601150func TestAddTemplateFunctions(t *testing.T) {1151 AddTemplateFunc("t", func() bool { return true })1152 AddTemplateFuncs(template.FuncMap{1153 "f": func() bool { return false },
19 unmodified lines
1173 if strings.Count(r.Output, "Usage:") != 1 {1174 t.Error("Usage output is not printed exactly once")1175 }1176}11771178func BenchmarkInheritedFlags(b *testing.B) {1179 initialize()1180 cmdEcho.AddCommand(cmdTimes)1181 b.ResetTimer()11821183 for i := 0; i < b.N; i++ {1184 cmdTimes.InheritedFlags()1185 }1186}11871188func BenchmarkLocalFlags(b *testing.B) {1189 initialize()1190 cmdEcho.AddCommand(cmdTimes)1191 b.ResetTimer()11921193 for i := 0; i < b.N; i++ {1194 cmdTimes.LocalFlags()1195 }1196}
modified:command.go+60 added-80 removed
64 unmodified lines
65 // Set of flags childrens of this command will inherit66 pflags *flag.FlagSet67 // Flags that are declared specifically by this command (not inherited).68 lflags *flag.FlagSet69 // Inherited flags.70 iflags *flag.FlagSet71 // All persistent flags of cmd's parents.72 parentsPflags *flag.FlagSet73 // SilenceErrors is an option to quiet errors down stream74 SilenceErrors bool75 // Silence Usage is an option to silence usage when an error occurs.76 SilenceUsage bool
470 unmodified lines
547}548549// VisitParents visits all parents of the command and invokes fn on each parent.550func (c *Command) VisitParents(fn func(*Command)) {547 var traverse func(*Command) *Command548549 traverse = func(x *Command) *Command {550 if x != c {551 fn(x)552 }553 if x.HasParent() {554 return traverse(x.parent)555 }556 return x551 if c.HasParent() {552 fn(c.Parent())553 c.Parent().VisitParents(fn)554 }558 traverse(c)555}556557// Root finds root command.558func (c *Command) Root() *Command {563 var findRoot func(*Command) *Command564565 findRoot = func(x *Command) *Command {566 if x.HasParent() {567 return findRoot(x.parent)559 if c.HasParent() {560 return c.Parent().Root()568 }569 return x561 }571572 return findRoot(c)562 return c563}564565// ArgsLenAtDash will return the length of f.Args at the moment when a -- was566// found during arg parsing. This allows your program to know which args were
335 unmodified lines
902 c.Println(x.Name())903 }904 if x.HasFlags() {905 x.flags.VisitAll(func(f *flag.Flag) {916 if x.HasPersistentFlags() {917 if x.persistentFlag(f.Name) == nil {918 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")919 } else {920 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")921 }906 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {907 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")908 } else {909 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")910 }911 })
150 unmodified lines
1062 if c.flags == nil {1063 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1064 c.flags.SetOutput(c.OutOrStderr())1065 }10661067 return c.flags1068}10691070// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
11 unmodified lines
10821083// LocalFlags returns the local FlagSet specifically set in the current command.1084func (c *Command) LocalFlags() *flag.FlagSet {1085 c.mergePersistentFlags()1086 c.updateParentsPersistentFlags()10871100 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1101 c.lflags.VisitAll(func(f *flag.Flag) {1102 local.AddFlag(f)1103 })1104 if !c.HasParent() {1105 flag.CommandLine.VisitAll(func(f *flag.Flag) {1106 if local.Lookup(f.Name) == nil {1107 local.AddFlag(f)1108 }1109 })1088 if c.lflags == nil {1089 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1090 c.lflags.SetOutput(c.OutOrStderr())1091 }1111 return local10921093 flags := c.Flags()1094 c.lflags.SortFlags = flags.SortFlags10951096 addToLocal := func(f *flag.Flag) {1097 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1098 c.lflags.AddFlag(f)1099 }1100 }1101 c.flags.VisitAll(addToLocal)1102 c.PersistentFlags().VisitAll(addToLocal)1103 return c.lflags1104}11051106// InheritedFlags returns all flags which were inherited from parents commands.1107func (c *Command) InheritedFlags() *flag.FlagSet {1108 c.mergePersistentFlags()1109 c.updateParentsPersistentFlags()11101111 if c.iflags == nil {1118 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1112 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1113 }11141115 local := c.LocalFlags()11161121 var rmerge func(x *Command)11221123 rmerge = func(x *Command) {1124 if x.HasPersistentFlags() {1125 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1126 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1127 inherited.AddFlag(f)1117 c.parentsPflags.VisitAll(func(f *flag.Flag) {1118 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1119 c.iflags.AddFlag(f)1128 }1129 })1120 }1131 if x.HasParent() {1132 rmerge(x.parent)1133 }1134 }1121 })11221136 if c.HasParent() {1137 rmerge(c.parent)1138 }11391140 return inherited1123 return c.iflags1124}11251126// NonInheritedFlags returns all flags which were not inherited from parent commands.1127func (c *Command) NonInheritedFlags() *flag.FlagSet {
97 unmodified lines
1225func (c *Command) Parent() *Command {1226 return c.parent1227}12281246func (c *Command) mergePersistentFlags() {1247 var rmerge func(x *Command)12481249 // Save the set of local flags1250 if c.lflags == nil {1251 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1252 c.lflags.SetOutput(c.OutOrStderr())1253 addtolocal := func(f *flag.Flag) {1254 c.lflags.AddFlag(f)1255 }1256 c.Flags().VisitAll(addtolocal)1257 c.PersistentFlags().VisitAll(addtolocal)1229func (c *Command) updateParentsPersistentFlags() {1230 if c.parentsPflags == nil {1231 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1232 c.parentsPflags.SetOutput(c.OutOrStderr())1233 }1259 rmerge = func(x *Command) {1260 if !x.HasParent() {1261 flag.CommandLine.VisitAll(func(f *flag.Flag) {1262 if x.PersistentFlags().Lookup(f.Name) == nil {1263 x.PersistentFlags().AddFlag(f)12341235 c.VisitParents(func(x *Command) {1236 if x.HasPersistentFlags() {1237 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1238 if c.parentsPflags.Lookup(f.Name) == nil {1239 c.parentsPflags.AddFlag(f)1240 }1241 })1242 }1243 })1244}12451246func (c *Command) mergePersistentFlags() {1247 flags := c.Flags()12481249 merge := func(x *Command) {1250 if x.HasPersistentFlags() {1251 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1269 if c.Flags().Lookup(f.Name) == nil {1270 c.Flags().AddFlag(f)1252 if flags.Lookup(f.Name) == nil {1253 flags.AddFlag(f)1254 }1255 })1256 }1274 if x.HasParent() {1275 rmerge(x.parent)1276 }1257 }12781279 rmerge(c)1258 merge(c)1259 c.VisitParents(merge)1260}