-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
89 lines (72 loc) · 1.77 KB
/
run.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
package mocky
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
func Run(flags Flags) error {
if flags.OutputPath == nil {
flags.OutputPath = DefaultOutputPath
}
interfaces, err := Parse(flags.InterfaceDir)
if err != nil {
return fmt.Errorf("failed to parse dir %s: %w", flags.InterfaceDir, err)
}
var ifaceToGenerate *Interface
for _, iface := range interfaces {
if flags.InterfaceName == iface.Name {
ifaceToGenerate = &iface
break
}
}
if ifaceToGenerate == nil {
return fmt.Errorf("interface '%s' not found", flags.InterfaceName)
}
fpath := flags.OutputPath(flags)
log.Printf("writing to file %s", fpath)
f, err := os.Create(fpath)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", fpath, err)
}
defer f.Close()
err = Generate(f, *ifaceToGenerate)
if err != nil {
return fmt.Errorf("failed to generate: %w", err)
}
return nil
}
func DefaultOutputPath(f Flags) string {
fname := fmt.Sprintf("mock_%s.go", strings.ToLower(f.InterfaceName))
return filepath.Join(f.InterfaceDir, fname)
}
type Flags struct {
InterfaceDir string
InterfaceName string
OutputPath func(Flags) string
}
func ParseFlags() (Flags, error) {
fs := flag.NewFlagSet("mocky", flag.ExitOnError)
output := Flags{}
fs.StringVar(&output.InterfaceDir, "d", "", "directory containing .go file with interface")
fs.StringVar(&output.InterfaceName, "i", "", "name of interface to mock (case sensitive)")
err := fs.Parse(os.Args[1:])
if err != nil {
return Flags{}, err
}
if len(output.InterfaceDir) == 0 {
d, err := os.Getwd()
if err != nil {
return Flags{}, err
}
output.InterfaceDir = d
}
if len(output.InterfaceName) == 0 {
fmt.Printf("You must provide an interface name\n")
fs.Usage()
os.Exit(1)
}
return output, nil
}