github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/cli/pflags/cmd/root.go (about) 1 package cmd 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "strings" 8 9 "github.com/lyft/flytestdlib/cli/pflags/api" 10 "github.com/lyft/flytestdlib/logger" 11 "github.com/spf13/cobra" 12 ) 13 14 var ( 15 pkg string 16 defaultValuesVariable string 17 shouldBindDefaultVariable bool 18 ) 19 20 var root = cobra.Command{ 21 Use: "pflags MyStructName --package myproject/mypackage", 22 Args: cobra.ExactArgs(1), 23 RunE: generatePflagsProvider, 24 Example: ` 25 // go:generate pflags MyStruct 26 type MyStruct struct { 27 BoolValue bool ` + "`json:\"bl\" pflag:\"true\"`" + ` 28 NestedType NestedType ` + "`json:\"nested\"`" + ` 29 IntArray []int ` + "`json:\"ints\" pflag:\"[]int{12%2C1}\"`" + ` 30 } 31 `, 32 } 33 34 func init() { 35 root.Flags().StringVarP(&pkg, "package", "p", ".", "Determines the source/destination package.") 36 root.Flags().StringVar(&defaultValuesVariable, "default-var", "defaultConfig", "Points to a variable to use to load default configs. If specified & found, it'll be used instead of the values specified in the tag.") 37 root.Flags().BoolVar(&shouldBindDefaultVariable, "bind-default-var", false, "The generated PFlags Set will bind fields to the default variable.") 38 } 39 40 func Execute() error { 41 return root.Execute() 42 } 43 44 func generatePflagsProvider(cmd *cobra.Command, args []string) error { 45 structName := args[0] 46 if structName == "" { 47 return fmt.Errorf("need to specify a struct name") 48 } 49 50 ctx := context.Background() 51 gen, err := api.NewGenerator(pkg, structName, defaultValuesVariable, shouldBindDefaultVariable) 52 if err != nil { 53 return err 54 } 55 56 provider, err := gen.Generate(ctx) 57 if err != nil { 58 return err 59 } 60 61 var buf bytes.Buffer 62 defer buf.Reset() 63 64 logger.Infof(ctx, "Generating PFlags for type [%v.%v.%v]\n", gen.GetTargetPackage().Path(), gen.GetTargetPackage().Name(), structName) 65 66 outFilePath := fmt.Sprintf("%s_flags.go", strings.ToLower(structName)) 67 err = provider.WriteCodeFile(outFilePath) 68 if err != nil { 69 return err 70 } 71 72 tOutFilePath := fmt.Sprintf("%s_flags_test.go", strings.ToLower(structName)) 73 return provider.WriteTestFile(tOutFilePath) 74 }