-
Notifications
You must be signed in to change notification settings - Fork 3
/
mokku.go
75 lines (64 loc) · 1.67 KB
/
mokku.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/atotto/clipboard"
"github.com/kinbiko/mokku"
)
const usage = `Usage:
1. Copy the interface you want to mock
2. Run 'mokku'
3. Paste the mocked implementation that has been written to your clipboard`
const defaultTemplate = `
type {{.TypeName}}Mock struct { {{ range .Methods }}
{{.Name}}Func func{{.Signature}}{{ end }}
}
{{if .Methods }}{{$typeName := .TypeName}}
{{range $val := .Methods}}func (m *{{$typeName}}Mock) {{$val.Name}}{{$val.Signature}} {
if m.{{$val.Name}}Func == nil {
panic("unexpected call to {{$val.Name}}")
}
{{if $val.HasReturn}}return {{ end }}m.{{$val.Name}}Func{{$val.OrderedParams}}
}
{{ end }}{{ end }}`
func main() {
flag.Usage = func() { fmt.Println(usage) }
flag.Parse()
templateStr, err := loadTemplate(os.Getenv("MOKKU_TEMPLATE_PATH"))
if err != nil {
errorOut(err)
}
if templateStr == "" {
templateStr = defaultTemplate
}
s, err := clipboard.ReadAll()
if err != nil {
errorOut(err)
}
mock, err := mokku.Mock(mokku.Config{TemplateStr: templateStr}, []byte(s))
if err != nil {
errorOut(err)
}
if err = clipboard.WriteAll(string(mock)); err != nil {
errorOut(err)
}
}
// loadTemplate loads template string from filePath, if there is one.
func loadTemplate(filePath string) (string, error) {
if filePath == "" { // There may not be an external template path given
return "", nil
}
content, err := ioutil.ReadFile(filepath.Clean(filePath))
if err != nil {
return "", fmt.Errorf("failed to read file %s: %v", filePath, err)
}
return string(content), nil
}
func errorOut(err error) {
fmt.Fprintln(os.Stderr, err.Error())
flag.Usage()
os.Exit(1)
}