Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit 22bbf0d

Browse files
authored
Merge pull request #184 from golang/output
Use a temp file to communicate with the reflect program.
2 parents 87f106f + c4f5911 commit 22bbf0d

File tree

1 file changed

+44
-7
lines changed

1 file changed

+44
-7
lines changed

mockgen/reflect.go

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,38 @@ func writeProgram(importPath string, symbols []string) ([]byte, error) {
4949
return program.Bytes(), nil
5050
}
5151

52-
// run the given command and parse the output as a model.Package.
53-
func run(command string) (*model.Package, error) {
52+
// run the given program and parse the output as a model.Package.
53+
func run(program string) (*model.Package, error) {
54+
f, err := ioutil.TempFile("", "")
55+
filename := f.Name()
56+
defer os.Remove(filename)
57+
if err := f.Close(); err != nil {
58+
return nil, err
59+
}
60+
5461
// Run the program.
55-
cmd := exec.Command(command)
56-
var stdout bytes.Buffer
57-
cmd.Stdout = &stdout
62+
cmd := exec.Command(program, "-output", filename)
63+
cmd.Stdout = os.Stdout
5864
cmd.Stderr = os.Stderr
5965
if err := cmd.Run(); err != nil {
6066
return nil, err
6167
}
6268

69+
f, err = os.Open(filename)
70+
if err != nil {
71+
return nil, err
72+
}
73+
6374
// Process output.
6475
var pkg model.Package
65-
if err := gob.NewDecoder(&stdout).Decode(&pkg); err != nil {
76+
if err := gob.NewDecoder(f).Decode(&pkg); err != nil {
77+
return nil, err
78+
}
79+
80+
if err := f.Close(); err != nil {
6681
return nil, err
6782
}
83+
6884
return &pkg, nil
6985
}
7086

@@ -154,6 +170,7 @@ package main
154170
155171
import (
156172
"encoding/gob"
173+
"flag"
157174
"fmt"
158175
"os"
159176
"path"
@@ -164,7 +181,11 @@ import (
164181
pkg_ {{printf "%q" .ImportPath}}
165182
)
166183
184+
var output = flag.String("output", "", "The output file name, or empty to use stdout.")
185+
167186
func main() {
187+
flag.Parse()
188+
168189
its := []struct{
169190
sym string
170191
typ reflect.Type
@@ -189,7 +210,23 @@ func main() {
189210
intf.Name = it.sym
190211
pkg.Interfaces = append(pkg.Interfaces, intf)
191212
}
192-
if err := gob.NewEncoder(os.Stdout).Encode(pkg); err != nil {
213+
214+
outfile := os.Stdout
215+
if len(*output) != 0 {
216+
var err error
217+
outfile, err = os.Create(*output)
218+
if err != nil {
219+
fmt.Fprintf(os.Stderr, "failed to open output file %q", *output)
220+
}
221+
defer func() {
222+
if err := outfile.Close(); err != nil {
223+
fmt.Fprintf(os.Stderr, "failed to close output file %q", *output)
224+
os.Exit(1)
225+
}
226+
}()
227+
}
228+
229+
if err := gob.NewEncoder(outfile).Encode(pkg); err != nil {
193230
fmt.Fprintf(os.Stderr, "gob encode: %v\n", err)
194231
os.Exit(1)
195232
}

0 commit comments

Comments
 (0)