forked from cweill/gotests
/
output.go
56 lines (49 loc) · 1.24 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package output
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"golang.org/x/tools/imports"
"github.com/cweill/gotests/internal/models"
"github.com/cweill/gotests/internal/render"
)
type Options struct {
PrintInputs bool
Subtests bool
}
func Process(head *models.Header, funcs []*models.Function, opt *Options) ([]byte, error) {
tf, err := ioutil.TempFile("", "gotests_")
if err != nil {
return nil, fmt.Errorf("ioutil.TempFile: %v", err)
}
defer tf.Close()
defer os.Remove(tf.Name())
b := &bytes.Buffer{}
if err := writeTests(b, head, funcs, opt); err != nil {
return nil, err
}
out, err := imports.Process(tf.Name(), b.Bytes(), nil)
if err != nil {
return nil, fmt.Errorf("imports.Process: %v", err)
}
return out, nil
}
func IsFileExist(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
func writeTests(w io.Writer, head *models.Header, funcs []*models.Function, opt *Options) error {
b := bufio.NewWriter(w)
if err := render.Header(b, head); err != nil {
return fmt.Errorf("render.Header: %v", err)
}
for _, fun := range funcs {
if err := render.TestFunction(b, fun, opt.PrintInputs, opt.Subtests); err != nil {
return fmt.Errorf("render.TestFunction: %v", err)
}
}
return b.Flush()
}