github.com/galaxyobe/gen@v0.0.0-20220910125335-392fa8f0990f/pkg/custom_args/args.go (about) 1 /* 2 Copyright 2022 Galaxyobe. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package custom_args 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/spf13/pflag" 24 "k8s.io/gengo/args" 25 26 "github.com/galaxyobe/gen/third_party/gengo/parser" 27 ) 28 29 // CustomArgs is used tby the go2idl framework to pass custom_args specific to this 30 // generator. 31 type CustomArgs struct { 32 *args.GeneratorArgs 33 BoundingDirs []string // Only deal with types rooted under these dirs. 34 TrimPackagePath string // If specified, trim the path from PackagePath before writing files. 35 } 36 37 func NewCustomArgs(args *args.GeneratorArgs) *CustomArgs { 38 customArgs := &CustomArgs{ 39 GeneratorArgs: args, 40 } 41 args.CustomArgs = customArgs 42 return customArgs 43 } 44 45 func (a *CustomArgs) AddFlags(fs *pflag.FlagSet) { 46 fs.StringSliceVar(&a.BoundingDirs, "bounding-dirs", a.BoundingDirs, 47 "Comma-separated list of import paths which bound the types for which deep-copies will be generated.") 48 fs.StringVar(&a.TrimPackagePath, "trim-package-path", a.TrimPackagePath, 49 "If set, trim the specified path from PackagePath when generating files.") 50 } 51 52 // NewBuilder makes a new parser.Builder and populates it with the input 53 // directories. 54 func (a *CustomArgs) NewBuilder() (*parser.Builder, error) { 55 b := parser.New() 56 57 // flag for including *_test.go 58 b.IncludeTestFiles = a.IncludeTestFiles 59 60 // Ignore all auto-generated files. 61 b.AddBuildTags(a.GeneratedBuildTag) 62 63 for _, d := range a.InputDirs { 64 var err error 65 if strings.HasSuffix(d, "/...") { 66 err = b.AddDirRecursive(strings.TrimSuffix(d, "/...")) 67 } else { 68 err = b.AddDir(d) 69 } 70 if err != nil { 71 return nil, fmt.Errorf("unable to add directory %q: %v", d, err) 72 } 73 } 74 return b, nil 75 }