/
gen.go
100 lines (80 loc) · 2.1 KB
/
gen.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
package gen
import (
"bufio"
"bytes"
"errors"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/ffelipelimao/gobuilder/cmd/gen/tmpls"
)
type Object struct {
Name string
Fields map[string]string
}
func Start(name string, fields string, destination string) error {
if name == "" {
return errors.New("missing -n flag value")
}
object, err := createObject(name, fields)
if err != nil {
return err
}
filename := strings.ToLower(fmt.Sprintf("%s.go", object.Name))
createFile(tmpls.MockBuilderTmpl, filename, object, destination)
return nil
}
func createObject(name string, fields string) (Object, error) {
fieldsMapper := make(map[string]string)
fieldsCloven := strings.Split(fields, ",")
for _, f := range fieldsCloven {
fieldsClovenByType := strings.Split(f, "-")
if len(fieldsClovenByType) < 2 {
return Object{}, errors.New("there's one field who is not in Name-type")
}
key := fieldsClovenByType[0]
value := fieldsClovenByType[1]
v := checkSymbols(value)
fieldsMapper[key] = v
}
return Object{
Name: name,
Fields: fieldsMapper,
}, nil
}
func checkSymbols(value string) string {
if strings.HasPrefix(value, "p") {
return strings.Replace(value, "p", "*", -1)
}
if strings.HasPrefix(value, "a") {
return strings.Replace(value, "a", "[]", -1)
}
return value
}
func createFile(MockBuilderTmpl string, outputFile string, data Object, destination string) {
tmpl := template.Must(template.New("").
Parse(MockBuilderTmpl))
var processed bytes.Buffer
err := tmpl.Execute(&processed, data)
if err != nil {
log.Fatalf("Unable to parse data into template: %v\n", err)
}
formatted, err := format.Source(processed.Bytes())
if err != nil {
log.Fatalf("Could not format processed template: %v\n", err)
}
fmt.Println("Writing file: ", outputFile)
if _, err := os.Stat(destination); os.IsNotExist(err) {
os.MkdirAll(destination, 0700)
}
path := filepath.Join(destination, outputFile)
newFilePath := filepath.FromSlash(path)
f, _ := os.Create(newFilePath)
w := bufio.NewWriter(f)
w.WriteString(string(formatted))
w.Flush()
}