-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.go
130 lines (94 loc) · 2.17 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package command
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/TharpHuang/gofar/tools/text"
)
var protoLines = `syntax = "proto3";
package proto;
//Todo change the name of messages and service
message $Request{
string msg = 1;
}
message $Response{
string response_msg = 1;
}
service $Service{
rpc Transfer($Request) returns ($Response){}
}
`
var databaseLines = `package migration
`
var warningGen = text.TrimLeft(`
Gofar gen: no job tyep input.
Use "gofar gen <type> [arguments]"
The type are:
proto protobuf files
migrate databases migrateion files`)
func GenerateFile(jobType, fileName string) {
if jobType == "" {
fmt.Println(warningGen)
return
}
switch jobType {
case "proto":
protoFile(fileName)
case "migration":
migrationFile(fileName)
default:
fmt.Println(warningGen)
}
}
func formatName(fileName string) string {
strings.ToLower(fileName)
nameChars := []byte(fileName)
if 'a' <= nameChars[0] || nameChars[0] <= 'z' {
nameChars[0] = fileName[0] - 'a' + 'A'
}
return string(nameChars)
}
func protoFile(fileName string) {
protoPath, err := filepath.Abs("proto")
_, err = os.Stat(protoPath)
if os.IsNotExist(err) {
os.Mkdir(protoPath, 0777)
os.Chmod(protoPath, 0777)
}
filePath := filepath.Join(protoPath, fileName+".proto")
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0777)
if err != nil {
panic(err)
}
lines := strings.Replace(protoLines, "$", formatName(fileName), -1)
_, err = f.Write([]byte(lines))
if err != nil {
panic(err)
}
f.Close()
fmt.Println("create proto file success!")
}
func migrationFile(fileName string) {
dbPath, err := filepath.Abs("migration")
_, err = os.Stat(dbPath)
if os.IsNotExist(err) {
os.Mkdir(dbPath, 0777)
os.Chmod(dbPath, 0777)
}
timeStr := strconv.FormatInt(time.Now().Unix(), 10)
filePath := filepath.Join(dbPath, fileName+"_"+timeStr+".go")
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0777)
if err != nil {
panic(err)
}
lines := strings.Replace(databaseLines, "$", formatName(fileName), -1)
_, err = f.Write([]byte(lines))
if err != nil {
panic(err)
}
f.Close()
fmt.Println("Created Migration: " + filePath)
}