args.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package args has common command-line flags for generation programs.
  14. package args
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "k8s.io/kubernetes/cmd/libs/go2idl/generator"
  25. "k8s.io/kubernetes/cmd/libs/go2idl/namer"
  26. "k8s.io/kubernetes/cmd/libs/go2idl/parser"
  27. "k8s.io/kubernetes/cmd/libs/go2idl/types"
  28. utilflag "k8s.io/kubernetes/pkg/util/flag"
  29. "k8s.io/kubernetes/pkg/util/logs"
  30. "github.com/spf13/pflag"
  31. )
  32. // Default returns a defaulted GeneratorArgs. You may change the defaults
  33. // before calling AddFlags.
  34. func Default() *GeneratorArgs {
  35. generatorArgs := &GeneratorArgs{
  36. OutputBase: DefaultSourceTree(),
  37. GoHeaderFilePath: filepath.Join(DefaultSourceTree(), "k8s.io/kubernetes/hack/boilerplate/boilerplate.go.txt"),
  38. GeneratedBuildTag: "ignore_autogenerated",
  39. }
  40. generatorArgs.AddFlags(pflag.CommandLine)
  41. return generatorArgs
  42. }
  43. // GeneratorArgs has arguments that are passed to generators.
  44. type GeneratorArgs struct {
  45. // Which directories to parse.
  46. InputDirs []string
  47. // Source tree to write results to.
  48. OutputBase string
  49. // Package path within the source tree.
  50. OutputPackagePath string
  51. // Output file name.
  52. OutputFileBaseName string
  53. // Where to get copyright header text.
  54. GoHeaderFilePath string
  55. // If true, only verify, don't write anything.
  56. VerifyOnly bool
  57. // GeneratedBuildTag is the tag used to identify code generated by execution
  58. // of this type. Each generator should use a different tag, and different
  59. // groups of generators (external API that depends on Kube generations) should
  60. // keep tags distinct as well.
  61. GeneratedBuildTag string
  62. // Any custom arguments go here
  63. CustomArgs interface{}
  64. }
  65. func (g *GeneratorArgs) AddFlags(fs *pflag.FlagSet) {
  66. fs.StringSliceVarP(&g.InputDirs, "input-dirs", "i", g.InputDirs, "Comma-separated list of import paths to get input types from.")
  67. fs.StringVarP(&g.OutputBase, "output-base", "o", g.OutputBase, "Output base; defaults to $GOPATH/src/ or ./ if $GOPATH is not set.")
  68. fs.StringVarP(&g.OutputPackagePath, "output-package", "p", g.OutputPackagePath, "Base package path.")
  69. fs.StringVarP(&g.OutputFileBaseName, "output-file-base", "O", g.OutputFileBaseName, "Base name (without .go suffix) for output files.")
  70. 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.")
  71. fs.BoolVar(&g.VerifyOnly, "verify-only", g.VerifyOnly, "If true, only verify existing output, do not write anything.")
  72. fs.StringVar(&g.GeneratedBuildTag, "build-tag", g.GeneratedBuildTag, "A Go build tag to use to identify files generated by this command. Should be unique.")
  73. }
  74. // LoadGoBoilerplate loads the boilerplate file passed to --go-header-file.
  75. func (g *GeneratorArgs) LoadGoBoilerplate() ([]byte, error) {
  76. b, err := ioutil.ReadFile(g.GoHeaderFilePath)
  77. if err != nil {
  78. return nil, err
  79. }
  80. b = bytes.Replace(b, []byte("YEAR"), []byte(strconv.Itoa(time.Now().Year())), -1)
  81. return b, nil
  82. }
  83. // NewBuilder makes a new parser.Builder and populates it with the input
  84. // directories.
  85. func (g *GeneratorArgs) NewBuilder() (*parser.Builder, error) {
  86. b := parser.New()
  87. // Ignore all auto-generated files.
  88. b.AddBuildTags(g.GeneratedBuildTag)
  89. for _, d := range g.InputDirs {
  90. var err error
  91. if strings.HasSuffix(d, "/...") {
  92. err = b.AddDirRecursive(strings.TrimSuffix(d, "/..."))
  93. } else {
  94. err = b.AddDir(d)
  95. }
  96. if err != nil {
  97. return nil, fmt.Errorf("unable to add directory %q: %v", d, err)
  98. }
  99. }
  100. return b, nil
  101. }
  102. // InputIncludes returns true if the given package is a (sub) package of one of
  103. // the InputDirs.
  104. func (g *GeneratorArgs) InputIncludes(p *types.Package) bool {
  105. for _, dir := range g.InputDirs {
  106. if strings.HasPrefix(p.Path, dir) {
  107. return true
  108. }
  109. }
  110. return false
  111. }
  112. // DefaultSourceTree returns the /src directory of the first entry in $GOPATH.
  113. // If $GOPATH is empty, it returns "./". Useful as a default output location.
  114. func DefaultSourceTree() string {
  115. paths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))
  116. if len(paths) > 0 && len(paths[0]) > 0 {
  117. return filepath.Join(paths[0], "src")
  118. }
  119. return "./"
  120. }
  121. // Execute implements main().
  122. // If you don't need any non-default behavior, use as:
  123. // args.Default().Execute(...)
  124. func (g *GeneratorArgs) Execute(nameSystems namer.NameSystems, defaultSystem string, pkgs func(*generator.Context, *GeneratorArgs) generator.Packages) error {
  125. utilflag.InitFlags()
  126. logs.InitLogs()
  127. b, err := g.NewBuilder()
  128. if err != nil {
  129. return fmt.Errorf("Failed making a parser: %v", err)
  130. }
  131. c, err := generator.NewContext(b, nameSystems, defaultSystem)
  132. if err != nil {
  133. return fmt.Errorf("Failed making a context: %v", err)
  134. }
  135. c.Verify = g.VerifyOnly
  136. packages := pkgs(c, g)
  137. if err := c.ExecutePackages(g.OutputBase, packages); err != nil {
  138. return fmt.Errorf("Failed executing generator: %v", err)
  139. }
  140. return nil
  141. }