Debian Codegraph @

createmock/createmock.go

raw symbols SCIP
1 // Copyright 2012 Aaron Jacobs. All Rights Reserved.
2 // Author: [email protected] (Aaron Jacobs)
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 // createmock is used to generate source code for mock versions of interfaces
17 // from installed packages.
18 package main
19
20 import (
21 "errors"
22 "flag"
23 "fmt"
24 "go/build"
25 "io/ioutil"
26 "log"
27 "os"
28 "os/exec"
29 "path"
30 "regexp"
31 "text/template"
32
33 // Ensure that the generate package, which is used by the generated code, is
34 // installed by goinstall.
35 _ "github.com/jacobsa/oglemock/generate"
36 )
37
38 var fSamePackage = flag.Bool(
39 "same_package",
40 false,
41 "Generate output appropriate for including in the same package as the "+
42 "mocked interfaces.")
43
44 // A template for generated code that is used to print the result.
45 const tmplStr = `
46 {{$interfacePkgPath := .InterfacePkgPath}}
47
48 package main
49
50 import (
51 {{range $identifier, $import := .Imports}}
52 {{$identifier}} "{{$import}}"
53 {{end}}
54 )
55
56 func getTypeForPtr(ptr interface{}) reflect.Type {
57 return reflect.TypeOf(ptr).Elem()
58 }
59
60 func main() {
61 // Reduce noise in logging output.
62 log.SetFlags(0)
63
64 interfaces := []reflect.Type{
65 {{range $typeName := .TypeNames}}
66 getTypeForPtr((*{{pathBase $interfacePkgPath}}.{{$typeName}})(nil)),
67 {{end}}
68 }
69
70 err := generate.GenerateMockSource(
71 os.Stdout,
72 "{{.OutputPkgPath}}",
73 interfaces)
74
75 if err != nil {
76 log.Fatalf("Error generating mock source: %v", err)
77 }
78 }
79 `
80
81 // A map from import identifier to package to use that identifier for,
82 // containing elements for each import needed by the generated code.
83 type importMap map[string]string
84
85 type tmplArg struct {
86 // The full path of the package from which the interfaces come.
87 InterfacePkgPath string
88
89 // The package path to assume for the generated code.
90 OutputPkgPath string
91
92 // Imports needed by the generated code.
93 Imports importMap
94
95 // Types to be mocked, relative to their package's name.
96 TypeNames []string
97 }
98
99 var unknownPackageRegexp = regexp.MustCompile(
100 `tool\.go:\d+:\d+: cannot find package "([^"]+)"`)
101
102 var undefinedInterfaceRegexp = regexp.MustCompile(`tool\.go:\d+: undefined: [\pL_0-9]+\.([\pL_0-9]+)`)
103
104 // Does the 'go build' output indicate that a package wasn't found? If so,
105 // return the name of the package.
106 func findUnknownPackage(output []byte) *string {
107 if match := unknownPackageRegexp.FindSubmatch(output); match != nil {
108 res := string(match[1])
109 return &res
110 }
111
112 return nil
113 }
114
115 // Does the 'go build' output indicate that an interface wasn't found? If so,
116 // return the name of the interface.
117 func findUndefinedInterface(output []byte) *string {
118 if match := undefinedInterfaceRegexp.FindSubmatch(output); match != nil {
119 res := string(match[1])
120 return &res
121 }
122
123 return nil
124 }
125
126 // Split out from main so that deferred calls are executed even in the event of
127 // an error.
128 func run() error {
129 // Reduce noise in logging output.
130 log.SetFlags(0)
131
132 // Check the command-line arguments.
133 flag.Parse()
134
135 cmdLineArgs := flag.Args()
136 if len(cmdLineArgs) < 2 {
137 return errors.New("Usage: createmock [package] [interface ...]")
138 }
139
140 // Create a temporary directory inside of $GOPATH to hold generated code.
141 buildPkg, err := build.Import("github.com/jacobsa/oglemock", "", build.FindOnly)
142 if err != nil {
143 return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err))
144 }
145
146 tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-")
147 if err != nil {
148 return errors.New(fmt.Sprintf("Creating temp dir: %v", err))
149 }
150
151 defer os.RemoveAll(tmpDir)
152
153 // Create a file to hold generated code.
154 codeFile, err := os.Create(path.Join(tmpDir, "tool.go"))
155 if err != nil {
156 return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err))
157 }
158
159 // Create an appropriate path for the built binary.
160 binaryPath := path.Join(tmpDir, "tool")
161
162 // Create an appropriate template argument.
163 arg := tmplArg{
164 InterfacePkgPath: cmdLineArgs[0],
165 TypeNames: cmdLineArgs[1:],
166 }
167
168 if *fSamePackage {
169 arg.OutputPkgPath = arg.InterfacePkgPath
170 } else {
171 arg.OutputPkgPath = "mock_" + path.Base(arg.InterfacePkgPath)
172 }
173
174 arg.Imports = make(importMap)
175 arg.Imports[path.Base(arg.InterfacePkgPath)] = arg.InterfacePkgPath
176 arg.Imports["generate"] = "github.com/jacobsa/oglemock/generate"
177 arg.Imports["log"] = "log"
178 arg.Imports["os"] = "os"
179 arg.Imports["reflect"] = "reflect"
180
181 // Execute the template to generate code that will itself generate the mock
182 // code. Write the code to the temp file.
183 tmpl := template.Must(
184 template.New("code").Funcs(
185 template.FuncMap{
186 "pathBase": path.Base,
187 }).Parse(tmplStr))
188 if err := tmpl.Execute(codeFile, arg); err != nil {
189 return errors.New(fmt.Sprintf("Error executing template: %v", err))
190 }
191
192 codeFile.Close()
193
194 // Attempt to build the code.
195 cmd := exec.Command("go", "build", "-o", binaryPath)
196 cmd.Dir = tmpDir
197 buildOutput, err := cmd.CombinedOutput()
198
199 if err != nil {
200 // Did the compilation fail due to the user-specified package not being found?
201 pkg := findUnknownPackage(buildOutput)
202 if pkg != nil && *pkg == arg.InterfacePkgPath {
203 return errors.New(fmt.Sprintf("Unknown package: %s", *pkg))
204 }
205
206 // Did the compilation fail due to an unknown interface?
207 if in := findUndefinedInterface(buildOutput); in != nil {
208 return errors.New(fmt.Sprintf("Unknown interface: %s", *in))
209 }
210
211 // Otherwise return a generic error.
212 return errors.New(fmt.Sprintf(
213 "%s\n\nError building generated code:\n\n"+
214 " %v\n\nPlease report this oglemock bug.",
215 buildOutput,
216 err))
217 }
218
219 // Run the binary.
220 cmd = exec.Command(binaryPath)
221 binaryOutput, err := cmd.CombinedOutput()
222
223 if err != nil {
224 return errors.New(fmt.Sprintf(
225 "%s\n\nError running generated code:\n\n"+
226 " %v\n\n Please report this oglemock bug.",
227 binaryOutput,
228 err))
229 }
230
231 // Copy its output.
232 _, err = os.Stdout.Write(binaryOutput)
233 if err != nil {
234 return errors.New(fmt.Sprintf("Error copying binary output: %v", err))
235 }
236
237 return nil
238 }
239
240 func main() {
241 if err := run(); err != nil {
242 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
243 os.Exit(1)
244 }
245 }