Debian Codegraph @

args/args.go

raw
1 /*
2 Copyright 2015 The Kubernetes Authors.
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 args has common command-line flags for generation programs.
18 package args
19
20 import (
21 "bytes"
22 goflag "flag"
23 "fmt"
24 "io/ioutil"
25 "os"
26 "path/filepath"
27 "strconv"
28 "strings"
29 "time"
30
31 "k8s.io/gengo/generator"
32 "k8s.io/gengo/namer"
33 "k8s.io/gengo/parser"
34
35 "github.com/spf13/pflag"
36 )
37
38 // Default returns a defaulted GeneratorArgs. You may change the defaults
39 // before calling AddFlags.
40 func Default() *GeneratorArgs {
41 return &GeneratorArgs{
42 OutputBase: DefaultSourceTree(),
43 GoHeaderFilePath: filepath.Join(DefaultSourceTree(), "k8s.io/gengo/boilerplate/boilerplate.go.txt"),
44 GeneratedBuildTag: "ignore_autogenerated",
45 GeneratedByCommentTemplate: "// Code generated by GENERATOR_NAME. DO NOT EDIT.",
46 defaultCommandLineFlags: true,
47 }
48 }
49
50 // GeneratorArgs has arguments that are passed to generators.
51 type GeneratorArgs struct {
52 // Which directories to parse.
53 InputDirs []string
54
55 // Source tree to write results to.
56 OutputBase string
57
58 // Package path within the source tree.
59 OutputPackagePath string
60
61 // Output file name.
62 OutputFileBaseName string
63
64 // Where to get copyright header text.
65 GoHeaderFilePath string
66
67 // If GeneratedByCommentTemplate is set, generate a "Code generated by" comment
68 // below the bloilerplate, of the format defined by this string.
69 // Any instances of "GENERATOR_NAME" will be replaced with the name of the code generator.
70 GeneratedByCommentTemplate string
71
72 // If true, only verify, don't write anything.
73 VerifyOnly bool
74
75 // If true, include *_test.go files
76 IncludeTestFiles bool
77
78 // GeneratedBuildTag is the tag used to identify code generated by execution
79 // of this type. Each generator should use a different tag, and different
80 // groups of generators (external API that depends on Kube generations) should
81 // keep tags distinct as well.
82 GeneratedBuildTag string
83
84 // Any custom arguments go here
85 CustomArgs interface{}
86
87 // If specified, trim the prefix from OutputPackagePath before writing files.
88 TrimPathPrefix string
89
90 // Whether to use default command line flags
91 defaultCommandLineFlags bool
92 }
93
94 // WithoutDefaultFlagParsing disables implicit addition of command line flags and parsing.
95 func (g *GeneratorArgs) WithoutDefaultFlagParsing() *GeneratorArgs {
96 g.defaultCommandLineFlags = false
97 return g
98 }
99
100 func (g *GeneratorArgs) AddFlags(fs *pflag.FlagSet) {
101 fs.StringSliceVarP(&g.InputDirs, "input-dirs", "i", g.InputDirs, "Comma-separated list of import paths to get input types from.")
102 fs.StringVarP(&g.OutputBase, "output-base", "o", g.OutputBase, "Output base; defaults to $GOPATH/src/ or ./ if $GOPATH is not set.")
103 fs.StringVarP(&g.OutputPackagePath, "output-package", "p", g.OutputPackagePath, "Base package path.")
104 fs.StringVarP(&g.OutputFileBaseName, "output-file-base", "O", g.OutputFileBaseName, "Base name (without .go suffix) for output files.")
105 fs.StringVarP(&g.GoHeaderFilePath, "go-header-file", "h", g.GoHeaderFilePath, "File containing boilerplate header text. The string YEAR will be replaced with the current 4-digit year.")
106 fs.BoolVar(&g.VerifyOnly, "verify-only", g.VerifyOnly, "If true, only verify existing output, do not write anything.")
107 fs.StringVar(&g.GeneratedBuildTag, "build-tag", g.GeneratedBuildTag, "A Go build tag to use to identify files generated by this command. Should be unique.")
108 fs.StringVar(&g.TrimPathPrefix, "trim-path-prefix", g.TrimPathPrefix, "If set, trim the specified prefix from --output-package when generating files.")
109 }
110
111 // LoadGoBoilerplate loads the boilerplate file passed to --go-header-file.
112 func (g *GeneratorArgs) LoadGoBoilerplate() ([]byte, error) {
113 b, err := ioutil.ReadFile(g.GoHeaderFilePath)
114 if err != nil {
115 return nil, err
116 }
117 b = bytes.Replace(b, []byte("YEAR"), []byte(strconv.Itoa(time.Now().UTC().Year())), -1)
118
119 if g.GeneratedByCommentTemplate != "" {
120 if len(b) != 0 {
121 b = append(b, byte('\n'))
122 }
123 generatorName := filepath.Base(os.Args[0])
124 // Strip the extension from the name to normalize output between *nix and Windows.
125 generatorName = generatorName[:len(generatorName)-len(filepath.Ext(generatorName))]
126 generatedByComment := strings.Replace(g.GeneratedByCommentTemplate, "GENERATOR_NAME", generatorName, -1)
127 s := fmt.Sprintf("%s\n\n", generatedByComment)
128 b = append(b, []byte(s)...)
129 }
130 return b, nil
131 }
132
133 // NewBuilder makes a new parser.Builder and populates it with the input
134 // directories.
135 func (g *GeneratorArgs) NewBuilder() (*parser.Builder, error) {
136 b := parser.New()
137
138 // flag for including *_test.go
139 b.IncludeTestFiles = g.IncludeTestFiles
140
141 // Ignore all auto-generated files.
142 b.AddBuildTags(g.GeneratedBuildTag)
143
144 for _, d := range g.InputDirs {
145 var err error
146 if strings.HasSuffix(d, "/...") {
147 err = b.AddDirRecursive(strings.TrimSuffix(d, "/..."))
148 } else {
149 err = b.AddDir(d)
150 }
151 if err != nil {
152 return nil, fmt.Errorf("unable to add directory %q: %v", d, err)
153 }
154 }
155 return b, nil
156 }
157
158 // DefaultSourceTree returns the /src directory of the first entry in $GOPATH.
159 // If $GOPATH is empty, it returns "./". Useful as a default output location.
160 func DefaultSourceTree() string {
161 paths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))
162 if len(paths) > 0 && len(paths[0]) > 0 {
163 return filepath.Join(paths[0], "src")
164 }
165 return "./"
166 }
167
168 // Execute implements main().
169 // If you don't need any non-default behavior, use as:
170 // args.Default().Execute(...)
171 func (g *GeneratorArgs) Execute(nameSystems namer.NameSystems, defaultSystem string, pkgs func(*generator.Context, *GeneratorArgs) generator.Packages) error {
172 if g.defaultCommandLineFlags {
173 g.AddFlags(pflag.CommandLine)
174 pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)
175 pflag.Parse()
176 }
177
178 b, err := g.NewBuilder()
179 if err != nil {
180 return fmt.Errorf("Failed making a parser: %v", err)
181 }
182
183 // pass through the flag on whether to include *_test.go files
184 b.IncludeTestFiles = g.IncludeTestFiles
185
186 c, err := generator.NewContext(b, nameSystems, defaultSystem)
187 if err != nil {
188 return fmt.Errorf("Failed making a context: %v", err)
189 }
190
191 c.TrimPathPrefix = g.TrimPathPrefix
192
193 c.Verify = g.VerifyOnly
194 packages := pkgs(c, g)
195 if err := c.ExecutePackages(g.OutputBase, packages); err != nil {
196 return fmt.Errorf("Failed executing generator: %v", err)
197 }
198
199 return nil
200 }