main.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // This program reads all assertion functions from the assert package and
  2. // automatically generates the corresponding requires and forwarded assertions
  3. package main
  4. import (
  5. "bytes"
  6. "flag"
  7. "fmt"
  8. "go/ast"
  9. "go/build"
  10. "go/doc"
  11. "go/format"
  12. "go/importer"
  13. "go/parser"
  14. "go/token"
  15. "go/types"
  16. "io"
  17. "io/ioutil"
  18. "log"
  19. "os"
  20. "path"
  21. "strings"
  22. "text/template"
  23. "github.com/ernesto-jimenez/gogen/imports"
  24. )
  25. var (
  26. pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package")
  27. outputPkg = flag.String("output-package", "", "package for the resulting code")
  28. tmplFile = flag.String("template", "", "What file to load the function template from")
  29. out = flag.String("out", "", "What file to write the source code to")
  30. )
  31. func main() {
  32. flag.Parse()
  33. scope, docs, err := parsePackageSource(*pkg)
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. importer, funcs, err := analyzeCode(scope, docs)
  38. if err != nil {
  39. log.Fatal(err)
  40. }
  41. if err := generateCode(importer, funcs); err != nil {
  42. log.Fatal(err)
  43. }
  44. }
  45. func generateCode(importer imports.Importer, funcs []testFunc) error {
  46. buff := bytes.NewBuffer(nil)
  47. tmplHead, tmplFunc, err := parseTemplates()
  48. if err != nil {
  49. return err
  50. }
  51. // Generate header
  52. if err := tmplHead.Execute(buff, struct {
  53. Name string
  54. Imports map[string]string
  55. }{
  56. *outputPkg,
  57. importer.Imports(),
  58. }); err != nil {
  59. return err
  60. }
  61. // Generate funcs
  62. for _, fn := range funcs {
  63. buff.Write([]byte("\n\n"))
  64. if err := tmplFunc.Execute(buff, &fn); err != nil {
  65. return err
  66. }
  67. }
  68. code, err := format.Source(buff.Bytes())
  69. if err != nil {
  70. return err
  71. }
  72. // Write file
  73. output, err := outputFile()
  74. if err != nil {
  75. return err
  76. }
  77. defer output.Close()
  78. _, err = io.Copy(output, bytes.NewReader(code))
  79. return err
  80. }
  81. func parseTemplates() (*template.Template, *template.Template, error) {
  82. tmplHead, err := template.New("header").Parse(headerTemplate)
  83. if err != nil {
  84. return nil, nil, err
  85. }
  86. if *tmplFile != "" {
  87. f, err := ioutil.ReadFile(*tmplFile)
  88. if err != nil {
  89. return nil, nil, err
  90. }
  91. funcTemplate = string(f)
  92. }
  93. tmpl, err := template.New("function").Parse(funcTemplate)
  94. if err != nil {
  95. return nil, nil, err
  96. }
  97. return tmplHead, tmpl, nil
  98. }
  99. func outputFile() (*os.File, error) {
  100. filename := *out
  101. if filename == "-" || (filename == "" && *tmplFile == "") {
  102. return os.Stdout, nil
  103. }
  104. if filename == "" {
  105. filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go"
  106. }
  107. return os.Create(filename)
  108. }
  109. // analyzeCode takes the types scope and the docs and returns the import
  110. // information and information about all the assertion functions.
  111. func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) {
  112. testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface)
  113. importer := imports.New(*outputPkg)
  114. var funcs []testFunc
  115. // Go through all the top level functions
  116. for _, fdocs := range docs.Funcs {
  117. // Find the function
  118. obj := scope.Lookup(fdocs.Name)
  119. fn, ok := obj.(*types.Func)
  120. if !ok {
  121. continue
  122. }
  123. // Check function signature has at least two arguments
  124. sig := fn.Type().(*types.Signature)
  125. if sig.Params().Len() < 2 {
  126. continue
  127. }
  128. // Check first argument is of type testingT
  129. first, ok := sig.Params().At(0).Type().(*types.Named)
  130. if !ok {
  131. continue
  132. }
  133. firstType, ok := first.Underlying().(*types.Interface)
  134. if !ok {
  135. continue
  136. }
  137. if !types.Implements(firstType, testingT) {
  138. continue
  139. }
  140. funcs = append(funcs, testFunc{*outputPkg, fdocs, fn})
  141. importer.AddImportsFrom(sig.Params())
  142. }
  143. return importer, funcs, nil
  144. }
  145. // parsePackageSource returns the types scope and the package documentation from the package
  146. func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) {
  147. pd, err := build.Import(pkg, ".", 0)
  148. if err != nil {
  149. return nil, nil, err
  150. }
  151. fset := token.NewFileSet()
  152. files := make(map[string]*ast.File)
  153. fileList := make([]*ast.File, len(pd.GoFiles))
  154. for i, fname := range pd.GoFiles {
  155. src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname))
  156. if err != nil {
  157. return nil, nil, err
  158. }
  159. f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors)
  160. if err != nil {
  161. return nil, nil, err
  162. }
  163. files[fname] = f
  164. fileList[i] = f
  165. }
  166. cfg := types.Config{
  167. Importer: importer.Default(),
  168. }
  169. info := types.Info{
  170. Defs: make(map[*ast.Ident]types.Object),
  171. }
  172. tp, err := cfg.Check(pkg, fset, fileList, &info)
  173. if err != nil {
  174. return nil, nil, err
  175. }
  176. scope := tp.Scope()
  177. ap, _ := ast.NewPackage(fset, files, nil, nil)
  178. docs := doc.New(ap, pkg, 0)
  179. return scope, docs, nil
  180. }
  181. type testFunc struct {
  182. CurrentPkg string
  183. DocInfo *doc.Func
  184. TypeInfo *types.Func
  185. }
  186. func (f *testFunc) Qualifier(p *types.Package) string {
  187. if p == nil || p.Name() == f.CurrentPkg {
  188. return ""
  189. }
  190. return p.Name()
  191. }
  192. func (f *testFunc) Params() string {
  193. sig := f.TypeInfo.Type().(*types.Signature)
  194. params := sig.Params()
  195. p := ""
  196. comma := ""
  197. to := params.Len()
  198. var i int
  199. if sig.Variadic() {
  200. to--
  201. }
  202. for i = 1; i < to; i++ {
  203. param := params.At(i)
  204. p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier))
  205. comma = ", "
  206. }
  207. if sig.Variadic() {
  208. param := params.At(params.Len() - 1)
  209. p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier))
  210. }
  211. return p
  212. }
  213. func (f *testFunc) ForwardedParams() string {
  214. sig := f.TypeInfo.Type().(*types.Signature)
  215. params := sig.Params()
  216. p := ""
  217. comma := ""
  218. to := params.Len()
  219. var i int
  220. if sig.Variadic() {
  221. to--
  222. }
  223. for i = 1; i < to; i++ {
  224. param := params.At(i)
  225. p += fmt.Sprintf("%s%s", comma, param.Name())
  226. comma = ", "
  227. }
  228. if sig.Variadic() {
  229. param := params.At(params.Len() - 1)
  230. p += fmt.Sprintf("%s%s...", comma, param.Name())
  231. }
  232. return p
  233. }
  234. func (f *testFunc) Comment() string {
  235. return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1)
  236. }
  237. func (f *testFunc) CommentWithoutT(receiver string) string {
  238. search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name)
  239. replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name)
  240. return strings.Replace(f.Comment(), search, replace, -1)
  241. }
  242. var headerTemplate = `/*
  243. * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
  244. * THIS FILE MUST NOT BE EDITED BY HAND
  245. */
  246. package {{.Name}}
  247. import (
  248. {{range $path, $name := .Imports}}
  249. {{$name}} "{{$path}}"{{end}}
  250. )
  251. `
  252. var funcTemplate = `{{.Comment}}
  253. func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool {
  254. return assert.{{.DocInfo.Name}}({{.ForwardedParams}})
  255. }`