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%
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
Provenance
- Commit
6202b59- Tree
9ede460- Author
Albert Nigmatzianov <albertnigma@gmail.com>- Committer
Albert Nigmatzianov <albertnigma@gmail.com>- Parent
a3cd8ab
2 files changed+91 added−102 removed
modified:cobra_test.go+31 added-22 removed
1 unmodified line2 3 import (4 "bytes"5 "fmt"6- "os"6 "reflect"7 "runtime"8 "strings"9 "testing"1 unmodified line11 12 "github.com/spf13/pflag"13 )14 16-var _ = fmt.Println17-var _ = os.Stderr18-15 var tp, te, tt, t1, tr []string16 var rootPersPre, echoPre, echoPersPre, timesPersPre []string17 var flagb1, flagb2, flagb3, flagbr, flagbp bool18 var flags1, flags2a, flags2b, flags3, outs string142 unmodified lines161 cmdRootSameName.ResetFlags()162 cmdRootWithRun.ResetFlags()163 cmdSubNoRun.ResetFlags()164 cmdCustomFlags.ResetFlags()165+ cmdVersion1.ResetFlags()166+ cmdVersion2.ResetFlags()167+168 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 }182 183 func commandInit() {184 cmdEcho.ResetCommands()670 unmodified lines855 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")861-859 }860 }861 862 func TestNoNRunnableRootCommandNilInput(t *testing.T) {283 unmodified lines1146 t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")1147 }1148 }1149 1153-func TestFlagOnPflagCommandLine(t *testing.T) {1154- flagName := "flagOnCommandLine"1155- pflag.CommandLine.String(flagName, "", "about my flag")1156- r := fullSetupTest("--help")1157-1158- checkResultContains(t, r, flagName)1159-}1160-1150 func TestAddTemplateFunctions(t *testing.T) {1151 AddTemplateFunc("t", func() bool { return true })1152 AddTemplateFuncs(template.FuncMap{1153 "f": func() bool { return false },19 unmodified lines1173 if strings.Count(r.Output, "Usage:") != 1 {1174 t.Error("Usage output is not printed exactly once")1175 }1176 }1177+1178+func BenchmarkInheritedFlags(b *testing.B) {1179+ initialize()1180+ cmdEcho.AddCommand(cmdTimes)1181+ b.ResetTimer()1182+1183+ for i := 0; i < b.N; i++ {1184+ cmdTimes.InheritedFlags()1185+ }1186+}1187+1188+func BenchmarkLocalFlags(b *testing.B) {1189+ initialize()1190+ cmdEcho.AddCommand(cmdTimes)1191+ b.ResetTimer()1192+1193+ for i := 0; i < b.N; i++ {1194+ cmdTimes.LocalFlags()1195+ }1196+}modified:command.go+60 added-80 removed
64 unmodified lines65 // 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 bool470 unmodified lines547 }548 549 // VisitParents visits all parents of the command and invokes fn on each parent.550 func (c *Command) VisitParents(fn func(*Command)) {547- var traverse func(*Command) *Command548-549- 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 }556 557 // Root finds root command.558 func (c *Command) Root() *Command {563- var findRoot func(*Command) *Command564-565- 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 }571-572- return findRoot(c)562+ return c563 }564 565 // 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 were335 unmodified lines902 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 lines1062 if c.flags == nil {1063 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1064 c.flags.SetOutput(c.OutOrStderr())1065 }1066+1067 return c.flags1068 }1069 1070 // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.11 unmodified lines1082 1083 // LocalFlags returns the local FlagSet specifically set in the current command.1084 func (c *Command) LocalFlags() *flag.FlagSet {1085 c.mergePersistentFlags()1086+ c.updateParentsPersistentFlags()1087 1100- 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 local1092+1093+ flags := c.Flags()1094+ c.lflags.SortFlags = flags.SortFlags1095+1096+ 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 }1105 1106 // InheritedFlags returns all flags which were inherited from parents commands.1107 func (c *Command) InheritedFlags() *flag.FlagSet {1108 c.mergePersistentFlags()1109+ c.updateParentsPersistentFlags()1110 1111+ if c.iflags == nil {1118- inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1112+ c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1113+ }1114+1115 local := c.LocalFlags()1116 1121- var rmerge func(x *Command)1122-1123- 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+ })1122 1136- if c.HasParent() {1137- rmerge(c.parent)1138- }1139-1140- return inherited1123+ return c.iflags1124 }1125 1126 // NonInheritedFlags returns all flags which were not inherited from parent commands.1127 func (c *Command) NonInheritedFlags() *flag.FlagSet {97 unmodified lines1225 func (c *Command) Parent() *Command {1226 return c.parent1227 }1228 1246-func (c *Command) mergePersistentFlags() {1247- var rmerge func(x *Command)1248-1249- // 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)1229+func (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)1234+1235+ 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+}1245+1246+func (c *Command) mergePersistentFlags() {1247+ flags := c.Flags()1248+1249+ 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 }1278-1279- rmerge(c)1258+ merge(c)1259+ c.VisitParents(merge)1260 }