forked from micro/micro
/
new.go
216 lines (184 loc) · 4.57 KB
/
new.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
// Package new generates micro service templates
package new
import (
"fmt"
"go/build"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"text/template"
"time"
tmpl "github.com/tickoalcantara12/micro/v3/client/cli/new/template"
"github.com/tickoalcantara12/micro/v3/cmd"
"github.com/tickoalcantara12/micro/v3/cmd/usage"
"github.com/urfave/cli/v2"
"github.com/xlab/treeprint"
)
func protoComments(goDir, alias string) []string {
return []string{
"\ndownload protoc zip packages (protoc-$VERSION-$PLATFORM.zip) and install:\n",
"visit https://github.com/protocolbuffers/protobuf/releases",
"\ncompile the proto file " + alias + ".proto:\n",
"cd " + alias,
"make init",
"go mod vendor",
"make proto\n",
}
}
type config struct {
// foo
Alias string
// github.com/micro/foo
Dir string
// $GOPATH/src/github.com/micro/foo
GoDir string
// $GOPATH
GoPath string
// UseGoPath
UseGoPath bool
// Files
Files []file
// Comments
Comments []string
}
type file struct {
Path string
Tmpl string
}
func write(c config, file, tmpl string) error {
fn := template.FuncMap{
"title": func(s string) string {
return strings.ReplaceAll(strings.Title(s), "-", "")
},
"dehyphen": func(s string) string {
return strings.ReplaceAll(s, "-", "")
},
"lower": func(s string) string {
return strings.ToLower(s)
},
}
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
t, err := template.New("f").Funcs(fn).Parse(tmpl)
if err != nil {
return err
}
return t.Execute(f, c)
}
func create(c config) error {
// check if dir exists
if _, err := os.Stat(c.Dir); !os.IsNotExist(err) {
return fmt.Errorf("%s already exists", c.Dir)
}
// create usage report
u := usage.New("new")
// a single request/service
u.Metrics.Count["requests"] = uint64(1)
u.Metrics.Count["services"] = uint64(1)
// send report
go usage.Report(u)
// just wait
<-time.After(time.Millisecond * 250)
fmt.Printf("Creating service %s\n\n", c.Alias)
t := treeprint.New()
// write the files
for _, file := range c.Files {
f := filepath.Join(c.Dir, file.Path)
dir := filepath.Dir(f)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
}
addFileToTree(t, file.Path)
if err := write(c, f, file.Tmpl); err != nil {
return err
}
}
// print tree
fmt.Println(t.String())
for _, comment := range c.Comments {
fmt.Println(comment)
}
// just wait
<-time.After(time.Millisecond * 250)
return nil
}
func addFileToTree(root treeprint.Tree, file string) {
split := strings.Split(file, "/")
curr := root
for i := 0; i < len(split)-1; i++ {
n := curr.FindByValue(split[i])
if n != nil {
curr = n
} else {
curr = curr.AddBranch(split[i])
}
}
if curr.FindByValue(split[len(split)-1]) == nil {
curr.AddNode(split[len(split)-1])
}
}
func Run(ctx *cli.Context) error {
dir := ctx.Args().First()
if len(dir) == 0 {
fmt.Println("specify service name")
return nil
}
// check if the path is absolute, we don't want this
// we want to a relative path so we can install in GOPATH
if path.IsAbs(dir) {
fmt.Println("require relative path as service will be installed in GOPATH")
return nil
}
var goPath string
var goDir string
goPath = build.Default.GOPATH
// don't know GOPATH, runaway....
if len(goPath) == 0 {
fmt.Println("unknown GOPATH")
return nil
}
// attempt to split path if not windows
if runtime.GOOS == "windows" {
goPath = strings.Split(goPath, ";")[0]
} else {
goPath = strings.Split(goPath, ":")[0]
}
goDir = filepath.Join(goPath, "src", path.Clean(dir))
c := config{
Alias: dir,
Comments: protoComments(goDir, dir),
Dir: dir,
GoDir: goDir,
GoPath: goPath,
UseGoPath: false,
Files: []file{
{"main.go", tmpl.MainSRV},
{"handler/" + dir + ".go", tmpl.HandlerSRV},
{"proto/" + dir + ".proto", tmpl.ProtoSRV},
{"Makefile", tmpl.Makefile},
{"README.md", tmpl.Readme},
{".gitignore", tmpl.GitIgnore},
},
}
// set gomodule
if os.Getenv("GO111MODULE") != "off" {
c.Files = append(c.Files, file{"go.mod", tmpl.Module})
}
// create the files
return create(c)
}
func init() {
cmd.Register(&cli.Command{
Name: "new",
Usage: "Create a service template",
Description: `'micro new' scaffolds a new service skeleton. Example: 'micro new helloworld && cd helloworld'`,
Action: Run,
})
}