generator.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 generator
  14. import (
  15. "bytes"
  16. "io"
  17. "k8s.io/gengo/namer"
  18. "k8s.io/gengo/parser"
  19. "k8s.io/gengo/types"
  20. )
  21. // Package contains the contract for generating a package.
  22. type Package interface {
  23. // Name returns the package short name.
  24. Name() string
  25. // Path returns the package import path.
  26. Path() string
  27. // Filter should return true if this package cares about this type.
  28. // Otherwise, this type will be omitted from the type ordering for
  29. // this package.
  30. Filter(*Context, *types.Type) bool
  31. // Header should return a header for the file, including comment markers.
  32. // Useful for copyright notices and doc strings. Include an
  33. // autogeneration notice! Do not include the "package x" line.
  34. Header(filename string) []byte
  35. // Generators returns the list of generators for this package. It is
  36. // allowed for more than one generator to write to the same file.
  37. // A Context is passed in case the list of generators depends on the
  38. // input types.
  39. Generators(*Context) []Generator
  40. }
  41. type File struct {
  42. Name string
  43. FileType string
  44. PackageName string
  45. Header []byte
  46. Imports map[string]struct{}
  47. Vars bytes.Buffer
  48. Consts bytes.Buffer
  49. Body bytes.Buffer
  50. }
  51. type FileType interface {
  52. AssembleFile(f *File, path string) error
  53. VerifyFile(f *File, path string) error
  54. }
  55. // Packages is a list of packages to generate.
  56. type Packages []Package
  57. // Generator is the contract for anything that wants to do auto-generation.
  58. // It's expected that the io.Writers passed to the below functions will be
  59. // ErrorTrackers; this allows implementations to not check for io errors,
  60. // making more readable code.
  61. //
  62. // The call order for the functions that take a Context is:
  63. // 1. Filter() // Subsequent calls see only types that pass this.
  64. // 2. Namers() // Subsequent calls see the namers provided by this.
  65. // 3. PackageVars()
  66. // 4. PackageConsts()
  67. // 5. Init()
  68. // 6. GenerateType() // Called N times, once per type in the context's Order.
  69. // 7. Imports()
  70. //
  71. // You may have multiple generators for the same file.
  72. type Generator interface {
  73. // The name of this generator. Will be included in generated comments.
  74. Name() string
  75. // Filter should return true if this generator cares about this type.
  76. // (otherwise, GenerateType will not be called.)
  77. //
  78. // Filter is called before any of the generator's other functions;
  79. // subsequent calls will get a context with only the types that passed
  80. // this filter.
  81. Filter(*Context, *types.Type) bool
  82. // If this generator needs special namers, return them here. These will
  83. // override the original namers in the context if there is a collision.
  84. // You may return nil if you don't need special names. These names will
  85. // be available in the context passed to the rest of the generator's
  86. // functions.
  87. //
  88. // A use case for this is to return a namer that tracks imports.
  89. Namers(*Context) namer.NameSystems
  90. // Init should write an init function, and any other content that's not
  91. // generated per-type. (It's not intended for generator specific
  92. // initialization! Do that when your Package constructs the
  93. // Generators.)
  94. Init(*Context, io.Writer) error
  95. // Finalize should write finish up functions, and any other content that's not
  96. // generated per-type.
  97. Finalize(*Context, io.Writer) error
  98. // PackageVars should emit an array of variable lines. They will be
  99. // placed in a var ( ... ) block. There's no need to include a leading
  100. // \t or trailing \n.
  101. PackageVars(*Context) []string
  102. // PackageConsts should emit an array of constant lines. They will be
  103. // placed in a const ( ... ) block. There's no need to include a leading
  104. // \t or trailing \n.
  105. PackageConsts(*Context) []string
  106. // GenerateType should emit the code for a particular type.
  107. GenerateType(*Context, *types.Type, io.Writer) error
  108. // Imports should return a list of necessary imports. They will be
  109. // formatted correctly. You do not need to include quotation marks,
  110. // return only the package name; alternatively, you can also return
  111. // imports in the format `name "path/to/pkg"`. Imports will be called
  112. // after Init, PackageVars, PackageConsts, and GenerateType, to allow
  113. // you to keep track of what imports you actually need.
  114. Imports(*Context) []string
  115. // Preferred file name of this generator, not including a path. It is
  116. // allowed for multiple generators to use the same filename, but it's
  117. // up to you to make sure they don't have colliding import names.
  118. // TODO: provide per-file import tracking, removing the requirement
  119. // that generators coordinate..
  120. Filename() string
  121. // A registered file type in the context to generate this file with. If
  122. // the FileType is not found in the context, execution will stop.
  123. FileType() string
  124. }
  125. // Context is global context for individual generators to consume.
  126. type Context struct {
  127. // A map from the naming system to the names for that system. E.g., you
  128. // might have public names and several private naming systems.
  129. Namers namer.NameSystems
  130. // All the types, in case you want to look up something.
  131. Universe types.Universe
  132. // All the user-specified packages. This is after recursive expansion.
  133. Inputs []string
  134. // The canonical ordering of the types (will be filtered by both the
  135. // Package's and Generator's Filter methods).
  136. Order []*types.Type
  137. // A set of types this context can process. If this is empty or nil,
  138. // the default "golang" filetype will be provided.
  139. FileTypes map[string]FileType
  140. // If true, Execute* calls will just verify that the existing output is
  141. // correct. (You may set this after calling NewContext.)
  142. Verify bool
  143. // Allows generators to add packages at runtime.
  144. builder *parser.Builder
  145. }
  146. // NewContext generates a context from the given builder, naming systems, and
  147. // the naming system you wish to construct the canonical ordering from.
  148. func NewContext(b *parser.Builder, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) {
  149. universe, err := b.FindTypes()
  150. if err != nil {
  151. return nil, err
  152. }
  153. c := &Context{
  154. Namers: namer.NameSystems{},
  155. Universe: universe,
  156. Inputs: b.FindPackages(),
  157. FileTypes: map[string]FileType{
  158. GolangFileType: NewGolangFile(),
  159. },
  160. builder: b,
  161. }
  162. for name, systemNamer := range nameSystems {
  163. c.Namers[name] = systemNamer
  164. if name == canonicalOrderName {
  165. orderer := namer.Orderer{Namer: systemNamer}
  166. c.Order = orderer.OrderUniverse(universe)
  167. }
  168. }
  169. return c, nil
  170. }
  171. // AddDir adds a Go package to the context. The specified path must be a single
  172. // go package import path. GOPATH, GOROOT, and the location of your go binary
  173. // (`which go`) will all be searched, in the normal Go fashion.
  174. // Deprecated. Please use AddDirectory.
  175. func (ctxt *Context) AddDir(path string) error {
  176. return ctxt.builder.AddDirTo(path, &ctxt.Universe)
  177. }
  178. // AddDirectory adds a Go package to the context. The specified path must be a
  179. // single go package import path. GOPATH, GOROOT, and the location of your go
  180. // binary (`which go`) will all be searched, in the normal Go fashion.
  181. func (ctxt *Context) AddDirectory(path string) (*types.Package, error) {
  182. return ctxt.builder.AddDirectoryTo(path, &ctxt.Universe)
  183. }