-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
301 lines (266 loc) · 6.89 KB
/
main.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"bytes"
"fmt"
"html"
"html/template"
"io"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/gobuffalo/packr"
"gopkg.in/yaml.v2"
)
type Config struct {
Overwrite string
Name string
Version string
Author string
Description string
Usage string
VCSHost string
Folder string
Flags []Flag
Commands []Command
CommandMap string
License License
Imports []Import
}
type License struct {
Header string
Copyright string
Text string
}
type Command struct {
Name string
Usage string
Description string
Flags []Flag
Commands []Command
Buffer string
Package string
FuncPkg string
Debug string
Header string
Copyright string
}
type Import struct {
Name string
}
type Flag struct {
Name string
Type string
Default string
Usage string
}
var box packr.Box
var overwrite bool
func initBox() {
box = packr.NewBox("./templates")
}
func main() {
if len(os.Args) != 2 {
usage()
}
initBox()
filename := os.Args[1]
config := new(Config)
source, err := ioutil.ReadFile(filename)
checkErr(err)
err = yaml.Unmarshal(source, &config)
checkErr(err)
validation(config)
addLicense(config)
updateLicense(config)
var buf bytes.Buffer
checkErr(err)
//recursive commands update
appPath := createAppPath(config.VCSHost, config.Author, config.Name, config.Folder)
commandPath := appPath + "/command"
os.MkdirAll(commandPath, 0755)
imports := make([]Import, 0)
buf = recursiveUpdate(config.Commands, &config.Commands[0], commandPath, commandPath, &imports, config.License)
str := strings.Replace(buf.String(), "#", "\"", -1)
config.CommandMap = str
for i, val := range imports {
out := strings.Split(val.Name, config.VCSHost)
if len(out) == 2 {
imports[i].Name = config.VCSHost + out[1]
}
}
config.Imports = imports
// Add commands.go file
var tempbuf bytes.Buffer
execBufTemplate("commands.go.tmpl", &tempbuf, config)
str = html.UnescapeString(tempbuf.String())
file, err := os.Create(appPath + "/commands.go")
file.WriteString(str)
file.Close()
checkErr(err)
//Add main.go file
execTemplate("main.go.tmpl", appPath+"/main.go", config)
runGoFormat(config.VCSHost, config.Author, config.Name, config.Folder)
}
// runs go format on all generated go files
func runGoFormat(VCSHost string, user string, app string, folder string) {
gopath := VCSHost + "/" + user + "/" + app
if len(folder) > 1 {
gopath = VCSHost + "/" + user + "/" + app + "/" + folder
}
_, _ = exec.Command("go", "fmt", gopath).Output()
// checkErr(err)
}
// recursively updates commands buffer
func recursiveUpdate(commands []Command, callback *Command, directory string, commandPath string, imports *[]Import, license License) bytes.Buffer {
var buf bytes.Buffer
currDirectory := directory
for _, element := range commands {
element.Package = path.Base(currDirectory)
element.FuncPkg = ""
element.Copyright = license.Copyright
element.Header = license.Header
funcpkg := currDirectory
out := strings.Split(funcpkg, commandPath)
if len(out) == 2 {
funcpkg = out[1]
splits := strings.Split(funcpkg, "/")
funcpkg = camelCase(splits)
element.FuncPkg = funcpkg + ""
}
createCommandFile(currDirectory+"/"+element.Name+".go", element)
if element.Commands != nil {
directory = currDirectory + "/" + element.Name
os.MkdirAll(directory, 0755)
imp := Import{Name: directory}
*imports = append(*imports, imp)
recursiveUpdate(element.Commands, &element, directory, commandPath, imports, license)
}
execBufTemplate("command.arr.go.tmpl", &buf, element)
callback.Buffer = buf.String()
}
return buf
}
// Generates Camel case string
func camelCase(splits []string) string {
for index, element := range splits {
splits[index] = strings.Title(element)
}
return strings.Join(splits, "")
}
// Generates App Path
func createAppPath(VCSHost string, user string, appname string, folder string) string {
gopath := os.Getenv("GOPATH")
if len(gopath) < 1 {
gopath = userHomeDir() + "/go"
}
apppath := gopath + "/src/" + VCSHost + "/" + user + "/" + appname
if len(folder) > 1 {
apppath = apppath + "/" + folder
}
os.MkdirAll(apppath, 0755)
return apppath
}
// returns user home directory
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func username() string {
user, _ := user.Current()
return user.Username
}
// creates individual command files
func createCommandFile(filename string, command Command) {
path, _ := filepath.Abs(filename)
execTemplate("commands/command.go.tmpl", path, command)
}
// writes templates to the writer
func execBufTemplate(file string, wr io.Writer, data interface{}) {
dat, err := box.Find(file)
tmpl, err := template.New("test").Funcs(funcMap()).Parse(string(dat))
checkErr(err)
err = tmpl.Execute(wr, data)
checkErr(err)
}
// writes templates to the writer
func execTemplate(file string, outfile string, data interface{}) {
if !fileExists(outfile) || overwrite {
wr, err := os.OpenFile(outfile, os.O_WRONLY|os.O_CREATE, 0644)
checkErr(err)
dat, err := box.Find(file)
checkErr(err)
tmpl, err := template.New("test").Funcs(funcMap()).Parse(string(dat))
checkErr(err)
err = tmpl.Execute(wr, data)
checkErr(err)
wr.Close()
}
}
// checks error and panics
func checkErr(e error) {
if e != nil {
panic(e)
}
}
// function map for templates
func funcMap() template.FuncMap {
return template.FuncMap{
"title": strings.Title,
"toUpper": strings.ToUpper,
}
}
func addLicense(config *Config) {
path := createAppPath(config.VCSHost, config.Author, config.Name, "")
execTemplate("LICENSE.tmpl", path+"/LICENSE", config.License)
}
func updateLicense(config *Config) {
commentHeader(&config.License.Header)
commentHeader(&config.License.Copyright)
}
func commentHeader(variable *string) {
if len(*variable) > 1 {
*variable = "// " + *variable
}
}
func validation(config *Config) {
randomString := "myapp"
requiredVariable(&config.VCSHost, "config.vcshost", "github.com")
requiredVariable(&config.Author, "config.author", username())
requiredVariable(&config.Name, "config.name", randomString)
requiredVariable(&config.Folder, "config.folder", "")
overwrite = false
if config.Overwrite == "true" {
overwrite = true
}
}
func requiredVariable(variable *string, name string, def string) {
if len(*variable) < 1 {
fmt.Printf("WARN : Variable %s not set in yml document. Using default: %s\n", name, def)
*variable = def
}
}
func fileExists(file string) bool {
ret := true
if _, err := os.Stat(file); os.IsNotExist(err) {
ret = false
}
return ret
}
func usage() {
fmt.Println("A simplified go cli generator")
fmt.Println("Usage: ")
fmt.Println("clig <yml-document>")
fmt.Println("clig clig.yml")
os.Exit(0)
}