gen.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. // codecgen generates codec.Selfer implementations for a set of types.
  4. package main
  5. import (
  6. "bufio"
  7. "bytes"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "go/ast"
  12. "go/build"
  13. "go/parser"
  14. "go/token"
  15. "math/rand"
  16. "os"
  17. "os/exec"
  18. "path/filepath"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "text/template"
  23. "time"
  24. )
  25. const genCodecPkg = "codec1978" // keep this in sync with codec.genCodecPkg
  26. const genFrunMainTmpl = `//+build ignore
  27. package main
  28. {{ if .Types }}import "{{ .ImportPath }}"{{ end }}
  29. func main() {
  30. {{ $.PackageName }}.CodecGenTempWrite{{ .RandString }}()
  31. }
  32. `
  33. // const genFrunPkgTmpl = `//+build codecgen
  34. const genFrunPkgTmpl = `
  35. package {{ $.PackageName }}
  36. import (
  37. {{ if not .CodecPkgFiles }}{{ .CodecPkgName }} "{{ .CodecImportPath }}"{{ end }}
  38. "os"
  39. "reflect"
  40. "bytes"
  41. "strings"
  42. "go/format"
  43. )
  44. func CodecGenTempWrite{{ .RandString }}() {
  45. fout, err := os.Create("{{ .OutFile }}")
  46. if err != nil {
  47. panic(err)
  48. }
  49. defer fout.Close()
  50. var out bytes.Buffer
  51. var typs []reflect.Type
  52. {{ range $index, $element := .Types }}
  53. var t{{ $index }} {{ . }}
  54. typs = append(typs, reflect.TypeOf(t{{ $index }}))
  55. {{ end }}
  56. {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(&out, "{{ .BuildTag }}", "{{ .PackageName }}", "{{ .RandString }}", {{ .NoExtensions }}, {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}NewTypeInfos(strings.Split("{{ .StructTags }}", ",")), typs...)
  57. bout, err := format.Source(out.Bytes())
  58. if err != nil {
  59. fout.Write(out.Bytes())
  60. panic(err)
  61. }
  62. fout.Write(bout)
  63. }
  64. `
  65. // Generate is given a list of *.go files to parse, and an output file (fout).
  66. //
  67. // It finds all types T in the files, and it creates 2 tmp files (frun).
  68. // - main package file passed to 'go run'
  69. // - package level file which calls *genRunner.Selfer to write Selfer impls for each T.
  70. // We use a package level file so that it can reference unexported types in the package being worked on.
  71. // Tool then executes: "go run __frun__" which creates fout.
  72. // fout contains Codec(En|De)codeSelf implementations for every type T.
  73. //
  74. func Generate(outfile, buildTag, codecPkgPath string,
  75. uid int64,
  76. goRunTag string, st string,
  77. regexName, notRegexName *regexp.Regexp,
  78. deleteTempFile, noExtensions bool,
  79. infiles ...string) (err error) {
  80. // For each file, grab AST, find each type, and write a call to it.
  81. if len(infiles) == 0 {
  82. return
  83. }
  84. if outfile == "" || codecPkgPath == "" {
  85. err = errors.New("outfile and codec package path cannot be blank")
  86. return
  87. }
  88. if uid < 0 {
  89. uid = -uid
  90. }
  91. if uid == 0 {
  92. rr := rand.New(rand.NewSource(time.Now().UnixNano()))
  93. uid = 101 + rr.Int63n(9777)
  94. }
  95. // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails).
  96. // Also, ImportDir(...) must take an absolute path.
  97. lastdir := filepath.Dir(outfile)
  98. absdir, err := filepath.Abs(lastdir)
  99. if err != nil {
  100. return
  101. }
  102. pkg, err := build.Default.ImportDir(absdir, build.AllowBinary)
  103. if err != nil {
  104. return
  105. }
  106. type tmplT struct {
  107. CodecPkgName string
  108. CodecImportPath string
  109. ImportPath string
  110. OutFile string
  111. PackageName string
  112. RandString string
  113. BuildTag string
  114. StructTags string
  115. Types []string
  116. CodecPkgFiles bool
  117. NoExtensions bool
  118. }
  119. tv := tmplT{
  120. CodecPkgName: genCodecPkg,
  121. OutFile: outfile,
  122. CodecImportPath: codecPkgPath,
  123. BuildTag: buildTag,
  124. RandString: strconv.FormatInt(uid, 10),
  125. StructTags: st,
  126. NoExtensions: noExtensions,
  127. }
  128. tv.ImportPath = pkg.ImportPath
  129. if tv.ImportPath == tv.CodecImportPath {
  130. tv.CodecPkgFiles = true
  131. tv.CodecPkgName = "codec"
  132. } else {
  133. // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
  134. tv.ImportPath = stripVendor(tv.ImportPath)
  135. }
  136. astfiles := make([]*ast.File, len(infiles))
  137. for i, infile := range infiles {
  138. if filepath.Dir(infile) != lastdir {
  139. err = errors.New("in files must all be in same directory as outfile")
  140. return
  141. }
  142. fset := token.NewFileSet()
  143. astfiles[i], err = parser.ParseFile(fset, infile, nil, 0)
  144. if err != nil {
  145. return
  146. }
  147. if i == 0 {
  148. tv.PackageName = astfiles[i].Name.Name
  149. if tv.PackageName == "main" {
  150. // codecgen cannot be run on types in the 'main' package.
  151. // A temporary 'main' package must be created, and should reference the fully built
  152. // package containing the types.
  153. // Also, the temporary main package will conflict with the main package which already has a main method.
  154. err = errors.New("codecgen cannot be run on types in the 'main' package")
  155. return
  156. }
  157. }
  158. }
  159. // keep track of types with selfer methods
  160. // selferMethods := []string{"CodecEncodeSelf", "CodecDecodeSelf"}
  161. selferEncTyps := make(map[string]bool)
  162. selferDecTyps := make(map[string]bool)
  163. for _, f := range astfiles {
  164. for _, d := range f.Decls {
  165. // if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && fd.Recv.NumFields() == 1 {
  166. if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && len(fd.Recv.List) == 1 {
  167. recvType := fd.Recv.List[0].Type
  168. if ptr, ok := recvType.(*ast.StarExpr); ok {
  169. recvType = ptr.X
  170. }
  171. if id, ok := recvType.(*ast.Ident); ok {
  172. switch fd.Name.Name {
  173. case "CodecEncodeSelf":
  174. selferEncTyps[id.Name] = true
  175. case "CodecDecodeSelf":
  176. selferDecTyps[id.Name] = true
  177. }
  178. }
  179. }
  180. }
  181. }
  182. // now find types
  183. for _, f := range astfiles {
  184. for _, d := range f.Decls {
  185. if gd, ok := d.(*ast.GenDecl); ok {
  186. for _, dd := range gd.Specs {
  187. if td, ok := dd.(*ast.TypeSpec); ok {
  188. // if len(td.Name.Name) == 0 || td.Name.Name[0] > 'Z' || td.Name.Name[0] < 'A' {
  189. if len(td.Name.Name) == 0 {
  190. continue
  191. }
  192. // only generate for:
  193. // struct: StructType
  194. // primitives (numbers, bool, string): Ident
  195. // map: MapType
  196. // slice, array: ArrayType
  197. // chan: ChanType
  198. // do not generate:
  199. // FuncType, InterfaceType, StarExpr (ptr), etc
  200. switch td.Type.(type) {
  201. case *ast.StructType, *ast.Ident, *ast.MapType, *ast.ArrayType, *ast.ChanType:
  202. // only add to tv.Types iff
  203. // - it matches per the -r parameter
  204. // - it doesn't match per the -nr parameter
  205. // - it doesn't have any of the Selfer methods in the file
  206. if regexName.FindStringIndex(td.Name.Name) != nil &&
  207. notRegexName.FindStringIndex(td.Name.Name) == nil &&
  208. !selferEncTyps[td.Name.Name] &&
  209. !selferDecTyps[td.Name.Name] {
  210. tv.Types = append(tv.Types, td.Name.Name)
  211. }
  212. }
  213. }
  214. }
  215. }
  216. }
  217. }
  218. if len(tv.Types) == 0 {
  219. return
  220. }
  221. // we cannot use ioutil.TempFile, because we cannot guarantee the file suffix (.go).
  222. // Also, we cannot create file in temp directory,
  223. // because go run will not work (as it needs to see the types here).
  224. // Consequently, create the temp file in the current directory, and remove when done.
  225. // frun, err = ioutil.TempFile("", "codecgen-")
  226. // frunName := filepath.Join(os.TempDir(), "codecgen-"+strconv.FormatInt(time.Now().UnixNano(), 10)+".go")
  227. frunMainName := "codecgen-main-" + tv.RandString + ".generated.go"
  228. frunPkgName := "codecgen-pkg-" + tv.RandString + ".generated.go"
  229. if deleteTempFile {
  230. defer os.Remove(frunMainName)
  231. defer os.Remove(frunPkgName)
  232. }
  233. // var frunMain, frunPkg *os.File
  234. if _, err = gen1(frunMainName, genFrunMainTmpl, &tv); err != nil {
  235. return
  236. }
  237. if _, err = gen1(frunPkgName, genFrunPkgTmpl, &tv); err != nil {
  238. return
  239. }
  240. // remove outfile, so "go run ..." will not think that types in outfile already exist.
  241. os.Remove(outfile)
  242. // execute go run frun
  243. cmd := exec.Command("go", "run", "-tags", "codecgen.exec safe "+goRunTag, frunMainName) //, frunPkg.Name())
  244. var buf bytes.Buffer
  245. cmd.Stdout = &buf
  246. cmd.Stderr = &buf
  247. if err = cmd.Run(); err != nil {
  248. err = fmt.Errorf("error running 'go run %s': %v, console: %s",
  249. frunMainName, err, buf.Bytes())
  250. return
  251. }
  252. os.Stdout.Write(buf.Bytes())
  253. return
  254. }
  255. func gen1(frunName, tmplStr string, tv interface{}) (frun *os.File, err error) {
  256. os.Remove(frunName)
  257. if frun, err = os.Create(frunName); err != nil {
  258. return
  259. }
  260. defer frun.Close()
  261. t := template.New("")
  262. if t, err = t.Parse(tmplStr); err != nil {
  263. return
  264. }
  265. bw := bufio.NewWriter(frun)
  266. if err = t.Execute(bw, tv); err != nil {
  267. return
  268. }
  269. if err = bw.Flush(); err != nil {
  270. return
  271. }
  272. return
  273. }
  274. // copied from ../gen.go (keep in sync).
  275. func stripVendor(s string) string {
  276. // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
  277. // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
  278. const vendorStart = "vendor/"
  279. const vendorInline = "/vendor/"
  280. if i := strings.LastIndex(s, vendorInline); i >= 0 {
  281. s = s[i+len(vendorInline):]
  282. } else if strings.HasPrefix(s, vendorStart) {
  283. s = s[len(vendorStart):]
  284. }
  285. return s
  286. }
  287. func main() {
  288. o := flag.String("o", "", "out file")
  289. c := flag.String("c", genCodecPath, "codec path")
  290. t := flag.String("t", "", "build tag to put in file")
  291. r := flag.String("r", ".*", "regex for type name to match")
  292. nr := flag.String("nr", "^$", "regex for type name to exclude")
  293. rt := flag.String("rt", "", "tags for go run")
  294. st := flag.String("st", "codec,json", "struct tag keys to introspect")
  295. x := flag.Bool("x", false, "keep temp file")
  296. _ = flag.Bool("u", false, "*IGNORED - kept for backwards compatibility*: Allow unsafe use")
  297. d := flag.Int64("d", 0, "random identifier for use in generated code")
  298. nx := flag.Bool("nx", false, "no extensions")
  299. flag.Parse()
  300. if err := Generate(*o, *t, *c, *d, *rt, *st,
  301. regexp.MustCompile(*r), regexp.MustCompile(*nr), !*x, *nx,
  302. flag.Args()...); err != nil {
  303. fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err)
  304. os.Exit(1)
  305. }
  306. }