execute.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package generator
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "go-common/app/tool/gengo/namer"
  11. "go-common/app/tool/gengo/types"
  12. "golang.org/x/tools/imports"
  13. "github.com/golang/glog"
  14. )
  15. func errs2strings(errors []error) []string {
  16. strs := make([]string, len(errors))
  17. for i := range errors {
  18. strs[i] = errors[i].Error()
  19. }
  20. return strs
  21. }
  22. // ExecutePackages runs the generators for every package in 'packages'. 'outDir'
  23. // is the base directory in which to place all the generated packages; it
  24. // should be a physical path on disk, not an import path. e.g.:
  25. // /path/to/home/path/to/gopath/src/
  26. // Each package has its import path already, this will be appended to 'outDir'.
  27. func (c *Context) ExecutePackages(outDir string, packages Packages) error {
  28. var errors []error
  29. for _, p := range packages {
  30. if err := c.ExecutePackage(outDir, p); err != nil {
  31. errors = append(errors, err)
  32. }
  33. }
  34. if len(errors) > 0 {
  35. return fmt.Errorf("some packages had errors:\n%v\n", strings.Join(errs2strings(errors), "\n"))
  36. }
  37. return nil
  38. }
  39. // DefaultFileType is
  40. type DefaultFileType struct {
  41. Format func([]byte) ([]byte, error)
  42. Assemble func(io.Writer, *File)
  43. }
  44. // AssembleFile is
  45. func (ft DefaultFileType) AssembleFile(f *File, pathname string) error {
  46. glog.V(2).Infof("Assembling file %q", pathname)
  47. destFile, err := os.Create(pathname)
  48. if err != nil {
  49. return err
  50. }
  51. defer destFile.Close()
  52. b := &bytes.Buffer{}
  53. et := NewErrorTracker(b)
  54. ft.Assemble(et, f)
  55. if et.Error() != nil {
  56. return et.Error()
  57. }
  58. if formatted, err := ft.Format(b.Bytes()); err != nil {
  59. err = fmt.Errorf("unable to format file %q (%v)", pathname, err)
  60. // Write the file anyway, so they can see what's going wrong and fix the generator.
  61. if _, err2 := destFile.Write(b.Bytes()); err2 != nil {
  62. return err2
  63. }
  64. return err
  65. } else {
  66. _, err = destFile.Write(formatted)
  67. return err
  68. }
  69. }
  70. // VerifyFile is
  71. func (ft DefaultFileType) VerifyFile(f *File, pathname string) error {
  72. glog.V(2).Infof("Verifying file %q", pathname)
  73. friendlyName := filepath.Join(f.PackageName, f.Name)
  74. b := &bytes.Buffer{}
  75. et := NewErrorTracker(b)
  76. ft.Assemble(et, f)
  77. if et.Error() != nil {
  78. return et.Error()
  79. }
  80. formatted, err := ft.Format(b.Bytes())
  81. if err != nil {
  82. return fmt.Errorf("unable to format the output for %q: %v", friendlyName, err)
  83. }
  84. existing, err := ioutil.ReadFile(pathname)
  85. if err != nil {
  86. return fmt.Errorf("unable to read file %q for comparison: %v", friendlyName, err)
  87. }
  88. if bytes.Compare(formatted, existing) == 0 {
  89. return nil
  90. }
  91. // Be nice and find the first place where they differ
  92. i := 0
  93. for i < len(formatted) && i < len(existing) && formatted[i] == existing[i] {
  94. i++
  95. }
  96. eDiff, fDiff := existing[i:], formatted[i:]
  97. if len(eDiff) > 100 {
  98. eDiff = eDiff[:100]
  99. }
  100. if len(fDiff) > 100 {
  101. fDiff = fDiff[:100]
  102. }
  103. return fmt.Errorf("output for %q differs; first existing/expected diff: \n %q\n %q", friendlyName, string(eDiff), string(fDiff))
  104. }
  105. func assembleGolangFile(w io.Writer, f *File) {
  106. w.Write(f.Header)
  107. fmt.Fprintf(w, "package %v\n\n", f.PackageName)
  108. if len(f.Imports) > 0 {
  109. fmt.Fprint(w, "import (\n")
  110. for i := range f.Imports {
  111. if strings.Contains(i, "\"") {
  112. // they included quotes, or are using the
  113. // `name "path/to/pkg"` format.
  114. fmt.Fprintf(w, "\t%s\n", i)
  115. } else {
  116. fmt.Fprintf(w, "\t%q\n", i)
  117. }
  118. }
  119. fmt.Fprint(w, ")\n\n")
  120. }
  121. if f.Vars.Len() > 0 {
  122. fmt.Fprint(w, "var (\n")
  123. w.Write(f.Vars.Bytes())
  124. fmt.Fprint(w, ")\n\n")
  125. }
  126. if f.Consts.Len() > 0 {
  127. fmt.Fprint(w, "const (\n")
  128. w.Write(f.Consts.Bytes())
  129. fmt.Fprint(w, ")\n\n")
  130. }
  131. w.Write(f.Body.Bytes())
  132. }
  133. func importsWrapper(src []byte) ([]byte, error) {
  134. return imports.Process("", src, nil)
  135. }
  136. // NewGolangFile is
  137. func NewGolangFile() *DefaultFileType {
  138. return &DefaultFileType{
  139. Format: importsWrapper,
  140. Assemble: assembleGolangFile,
  141. }
  142. }
  143. // format should be one line only, and not end with \n.
  144. func addIndentHeaderComment(b *bytes.Buffer, format string, args ...interface{}) {
  145. if b.Len() > 0 {
  146. fmt.Fprintf(b, "\n// "+format+"\n", args...)
  147. } else {
  148. fmt.Fprintf(b, "// "+format+"\n", args...)
  149. }
  150. }
  151. func (c *Context) filteredBy(f func(*Context, *types.Type) bool) *Context {
  152. c2 := *c
  153. c2.Order = []*types.Type{}
  154. for _, t := range c.Order {
  155. if f(c, t) {
  156. c2.Order = append(c2.Order, t)
  157. }
  158. }
  159. return &c2
  160. }
  161. // make a new context; inheret c.Namers, but add on 'namers'. In case of a name
  162. // collision, the namer in 'namers' wins.
  163. func (c *Context) addNameSystems(namers namer.NameSystems) *Context {
  164. if namers == nil {
  165. return c
  166. }
  167. c2 := *c
  168. // Copy the existing name systems so we don't corrupt a parent context
  169. c2.Namers = namer.NameSystems{}
  170. for k, v := range c.Namers {
  171. c2.Namers[k] = v
  172. }
  173. for name, namer := range namers {
  174. c2.Namers[name] = namer
  175. }
  176. return &c2
  177. }
  178. // ExecutePackage executes a single package. 'outDir' is the base directory in
  179. // which to place the package; it should be a physical path on disk, not an
  180. // import path. e.g.: '/path/to/home/path/to/gopath/src/' The package knows its
  181. // import path already, this will be appended to 'outDir'.
  182. func (c *Context) ExecutePackage(outDir string, p Package) error {
  183. path := filepath.Join(outDir, p.Path())
  184. glog.V(2).Infof("Processing package %q, disk location %q", p.Name(), path)
  185. // Filter out any types the *package* doesn't care about.
  186. packageContext := c.filteredBy(p.Filter)
  187. os.MkdirAll(path, 0755)
  188. files := map[string]*File{}
  189. for _, g := range p.Generators(packageContext) {
  190. // Filter out types the *generator* doesn't care about.
  191. genContext := packageContext.filteredBy(g.Filter)
  192. // Now add any extra name systems defined by this generator
  193. genContext = genContext.addNameSystems(g.Namers(genContext))
  194. fileType := g.FileType()
  195. if len(fileType) == 0 {
  196. return fmt.Errorf("generator %q must specify a file type", g.Name())
  197. }
  198. f := files[g.Filename()]
  199. if f == nil {
  200. // This is the first generator to reference this file, so start it.
  201. f = &File{
  202. Name: g.Filename(),
  203. FileType: fileType,
  204. PackageName: p.Name(),
  205. Header: p.Header(g.Filename()),
  206. Imports: map[string]struct{}{},
  207. }
  208. files[f.Name] = f
  209. } else {
  210. if f.FileType != g.FileType() {
  211. return fmt.Errorf("file %q already has type %q, but generator %q wants to use type %q", f.Name, f.FileType, g.Name(), g.FileType())
  212. }
  213. }
  214. if vars := g.PackageVars(genContext); len(vars) > 0 {
  215. addIndentHeaderComment(&f.Vars, "Package-wide variables from generator %q.", g.Name())
  216. for _, v := range vars {
  217. if _, err := fmt.Fprintf(&f.Vars, "%s\n", v); err != nil {
  218. return err
  219. }
  220. }
  221. }
  222. if consts := g.PackageConsts(genContext); len(consts) > 0 {
  223. addIndentHeaderComment(&f.Consts, "Package-wide consts from generator %q.", g.Name())
  224. for _, v := range consts {
  225. if _, err := fmt.Fprintf(&f.Consts, "%s\n", v); err != nil {
  226. return err
  227. }
  228. }
  229. }
  230. if err := genContext.executeBody(&f.Body, g); err != nil {
  231. return err
  232. }
  233. if imports := g.Imports(genContext); len(imports) > 0 {
  234. for _, i := range imports {
  235. f.Imports[i] = struct{}{}
  236. }
  237. }
  238. }
  239. var errors []error
  240. for _, f := range files {
  241. finalPath := filepath.Join(path, f.Name)
  242. assembler, ok := c.FileTypes[f.FileType]
  243. if !ok {
  244. return fmt.Errorf("the file type %q registered for file %q does not exist in the context", f.FileType, f.Name)
  245. }
  246. var err error
  247. if c.Verify {
  248. err = assembler.VerifyFile(f, finalPath)
  249. } else {
  250. err = assembler.AssembleFile(f, finalPath)
  251. }
  252. if err != nil {
  253. errors = append(errors, err)
  254. }
  255. }
  256. if len(errors) > 0 {
  257. return fmt.Errorf("errors in package %q:\n%v", p.Path(), strings.Join(errs2strings(errors), "\n"))
  258. }
  259. return nil
  260. }
  261. func (c *Context) executeBody(w io.Writer, generator Generator) error {
  262. et := NewErrorTracker(w)
  263. if err := generator.Init(c, et); err != nil {
  264. return err
  265. }
  266. for _, t := range c.Order {
  267. if err := generator.GenerateType(c, t, et); err != nil {
  268. return err
  269. }
  270. }
  271. if err := generator.Finalize(c, et); err != nil {
  272. return err
  273. }
  274. return et.Error()
  275. }