-
Notifications
You must be signed in to change notification settings - Fork 10
/
commands.go
122 lines (107 loc) · 2.37 KB
/
commands.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"io"
"io/ioutil"
"os"
"path/filepath"
atgen "github.com/aktsk/atgen/lib"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
)
var commands = []*cli.Command{
commandGen,
//commandDiff,
}
var commandGen = &cli.Command{
Name: "gen",
Usage: "Generate test code",
Description: `
Generete test code according to yaml and template.
`,
Action: doGen,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "templateDir",
Aliases: []string{"t"},
Value: ".",
Usage: "template directory that has template yaml and code",
},
&cli.StringFlag{
Name: "outputDir",
Aliases: []string{"o"},
Value: ".",
Usage: "output directory to write generated test files",
},
},
}
func doGen(c *cli.Context) error {
templateDir := c.String("templateDir")
outputDir := c.String("outputDir")
testFiles, err := filepath.Glob(filepath.Join(templateDir, "*_test.go"))
if err != nil {
return errors.WithStack(err)
}
for _, testFile := range testFiles {
base := filepath.Base(testFile)
if base != "template_test.go" {
src := filepath.Join(templateDir, base)
dest := filepath.Join(outputDir, base)
err := copyFile(src, dest)
if err != nil {
return errors.WithStack(err)
}
}
}
yamlFiles, err := filepath.Glob(filepath.Join(templateDir, "*.y*ml"))
if err != nil {
return errors.WithStack(err)
}
for _, yamlFile := range yamlFiles {
generator := atgen.Generator{
Yaml: yamlFile,
Template: filepath.Join(templateDir, "template_test.go"),
TemplateDir: templateDir,
OutputDir: outputDir,
}
err := generator.ParseYaml()
if err != nil {
return errors.WithStack(err)
}
err = generator.Generate()
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func copyFile(s, d string) error {
src, err := os.Open(s)
if err != nil {
return errors.WithStack(err)
}
defer src.Close()
dstdir := filepath.Dir(d)
tmpdst, err := ioutil.TempFile(dstdir, "tmp-")
if err != nil {
return errors.WithStack(err)
}
defer (func() {
if tmpdst != nil {
f := tmpdst.Name()
_ = tmpdst.Close()
_ = os.Remove(f)
}
})()
_, err = io.Copy(tmpdst, src)
if err != nil {
return errors.WithStack(err)
}
if err = tmpdst.Close(); err != nil {
return errors.WithStack(err)
}
if err = os.Rename(tmpdst.Name(), d); err != nil {
return errors.WithStack(err)
}
tmpdst = nil
return nil
}