reflect.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright 2012 Google Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mockgen
  15. // This file contains the model construction by reflection.
  16. import (
  17. "bytes"
  18. "encoding/gob"
  19. "go/build"
  20. "io/ioutil"
  21. "os"
  22. "os/exec"
  23. "path/filepath"
  24. "runtime"
  25. "text/template"
  26. "github.com/otokaze/mock/mockgen/model"
  27. )
  28. func writeProgram(importPath string, symbols []string) ([]byte, error) {
  29. var program bytes.Buffer
  30. data := reflectData{
  31. ImportPath: importPath,
  32. Symbols: symbols,
  33. }
  34. if err := reflectProgram.Execute(&program, &data); err != nil {
  35. return nil, err
  36. }
  37. return program.Bytes(), nil
  38. }
  39. // run the given program and parse the output as a model.Package.
  40. func run(program string) (*model.Package, error) {
  41. f, _ := ioutil.TempFile("", "")
  42. filename := f.Name()
  43. defer os.Remove(filename)
  44. if err := f.Close(); err != nil {
  45. return nil, err
  46. }
  47. // Run the program.
  48. cmd := exec.Command(program, "-output", filename)
  49. cmd.Stdout = os.Stdout
  50. cmd.Stderr = os.Stderr
  51. if err := cmd.Run(); err != nil {
  52. return nil, err
  53. }
  54. f, err := os.Open(filename)
  55. if err != nil {
  56. return nil, err
  57. }
  58. // Process output.
  59. var pkg model.Package
  60. if err := gob.NewDecoder(f).Decode(&pkg); err != nil {
  61. return nil, err
  62. }
  63. if err := f.Close(); err != nil {
  64. return nil, err
  65. }
  66. return &pkg, nil
  67. }
  68. // runInDir writes the given program into the given dir, runs it there, and
  69. // parses the output as a model.Package.
  70. func runInDir(program []byte, dir string) (*model.Package, error) {
  71. // We use TempDir instead of TempFile so we can control the filename.
  72. tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_")
  73. if err != nil {
  74. return nil, err
  75. }
  76. defer func() { os.RemoveAll(tmpDir) }()
  77. const progSource = "prog.go"
  78. var progBinary = "prog.bin"
  79. if runtime.GOOS == "windows" {
  80. // Windows won't execute a program unless it has a ".exe" suffix.
  81. progBinary += ".exe"
  82. }
  83. if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil {
  84. return nil, err
  85. }
  86. cmdArgs := []string{}
  87. cmdArgs = append(cmdArgs, "build")
  88. if buildFlags != "" {
  89. cmdArgs = append(cmdArgs, buildFlags)
  90. }
  91. cmdArgs = append(cmdArgs, "-o", progBinary, progSource)
  92. // Build the program.
  93. cmd := exec.Command("go", cmdArgs...)
  94. cmd.Dir = tmpDir
  95. cmd.Stdout = os.Stdout
  96. cmd.Stderr = os.Stderr
  97. if err := cmd.Run(); err != nil {
  98. return nil, err
  99. }
  100. return run(filepath.Join(tmpDir, progBinary))
  101. }
  102. // Reflect get pkg with reflect.
  103. func Reflect(importPath string, symbols []string) (*model.Package, error) {
  104. // TODO: sanity check arguments
  105. if execOnly != "" {
  106. return run(execOnly)
  107. }
  108. program, err := writeProgram(importPath, symbols)
  109. if err != nil {
  110. return nil, err
  111. }
  112. if progOnly {
  113. os.Stdout.Write(program)
  114. os.Exit(0)
  115. }
  116. wd, _ := os.Getwd()
  117. // Try to run the program in the same directory as the input package.
  118. if p, err := build.Import(importPath, wd, build.FindOnly); err == nil {
  119. dir := p.Dir
  120. if p, err := runInDir(program, dir); err == nil {
  121. return p, nil
  122. }
  123. }
  124. // Since that didn't work, try to run it in the current working directory.
  125. if p, err := runInDir(program, wd); err == nil {
  126. return p, nil
  127. }
  128. // Since that didn't work, try to run it in a standard temp directory.
  129. return runInDir(program, "")
  130. }
  131. type reflectData struct {
  132. ImportPath string
  133. Symbols []string
  134. }
  135. // This program reflects on an interface value, and prints the
  136. // gob encoding of a model.Package to standard output.
  137. // JSON doesn't work because of the model.Type interface.
  138. var reflectProgram = template.Must(template.New("program").Parse(`
  139. package main
  140. import (
  141. "encoding/gob"
  142. "flag"
  143. "fmt"
  144. "os"
  145. "path"
  146. "reflect"
  147. "github.com/otokaze/mock/mockgen/model"
  148. pkg_ {{printf "%q" .ImportPath}}
  149. )
  150. var output = flag.String("output", "", "The output file name, or empty to use stdout.")
  151. func main() {
  152. flag.Parse()
  153. its := []struct{
  154. sym string
  155. typ reflect.Type
  156. }{
  157. {{range .Symbols}}
  158. { {{printf "%q" .}}, reflect.TypeOf((*pkg_.{{.}})(nil)).Elem()},
  159. {{end}}
  160. }
  161. pkg := &model.Package{
  162. // NOTE: This behaves contrary to documented behaviour if the
  163. // package name is not the final component of the import path.
  164. // The reflect package doesn't expose the package name, though.
  165. Name: path.Base({{printf "%q" .ImportPath}}),
  166. }
  167. for _, it := range its {
  168. intf, err := model.InterfaceFromInterfaceType(it.typ)
  169. if err != nil {
  170. fmt.Fprintf(os.Stderr, "Reflection: %v\n", err)
  171. os.Exit(1)
  172. }
  173. intf.Name = it.sym
  174. pkg.Interfaces = append(pkg.Interfaces, intf)
  175. }
  176. outfile := os.Stdout
  177. if len(*output) != 0 {
  178. var err error
  179. outfile, err = os.Create(*output)
  180. if err != nil {
  181. fmt.Fprintf(os.Stderr, "failed to open output file %q", *output)
  182. }
  183. defer func() {
  184. if err := outfile.Close(); err != nil {
  185. fmt.Fprintf(os.Stderr, "failed to close output file %q", *output)
  186. os.Exit(1)
  187. }
  188. }()
  189. }
  190. if err := gob.NewEncoder(outfile).Encode(pkg); err != nil {
  191. fmt.Fprintf(os.Stderr, "gob encode: %v\n", err)
  192. os.Exit(1)
  193. }
  194. }
  195. `))