-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
297 lines (251 loc) · 5.31 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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"go/build"
"go/format"
"io"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"golang.org/x/tools/txtar"
)
//go:generate go run tools/txtar/main.go -strip "_template/" _template template.go
func main() {
var s Skeleton
flag.BoolVar(&s.OverWrite, "overwrite", false, "overwrite all file")
flag.BoolVar(&s.Cmd, "cmd", true, "create cmd directory")
flag.StringVar(&s.Checker, "checker", "unit", "checker which is used in main.go (unit,single,multi)")
flag.BoolVar(&s.Plugin, "plugin", true, "create plugin directory")
flag.StringVar(&s.Type, "type", "inspect", "type of skeleton code (inspect|ssa|codegen)")
flag.BoolVar(&s.Mod, "mod", true, "generate empty go.mod")
flag.StringVar(&s.ImportPath, "path", "", "import path")
flag.Parse()
s.ExeName = os.Args[0]
s.Args = flag.Args()
switch s.Checker {
case "unit", "single", "multi":
// noop
default:
s.Checker = "unit"
}
if s.Type == "codegen" {
if s.Checker != "single" {
s.Checker = "single"
}
s.Plugin = false
}
if err := s.Run(); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}
type Skeleton struct {
ExeName string
Args []string
Dir string
ImportPath string
OverWrite bool
Cmd bool
Checker string
Plugin bool
Mode Mode
Type string
Mod bool
}
type Mode int
const (
ModeRemoveAndCreateNew Mode = iota
ModeConfirm
ModeCreateNewFile
)
type TemplateData struct {
Pkg string
ImportPath string
Cmd bool
Plugin bool
Checker string
Type string
Mod bool
GoVer string
}
func (s *Skeleton) Run() error {
// go1.xx.yy -> 1.xx
// go1.xx -> 1.xx
gover := strings.Join(strings.Split(runtime.Version(), ".")[:2], ".")[2:]
td := &TemplateData{
Cmd: s.Cmd,
Plugin: s.Plugin,
Checker: s.Checker,
Type: s.Type,
Mod: s.Mod,
GoVer: gover,
}
if len(s.Args) < 1 {
if s.ImportPath != "" {
s.Dir = s.ImportPath
td.Pkg = path.Base(s.ImportPath)
} else {
return errors.New("package must be specified")
}
} else {
s.Dir = s.Args[0]
td.Pkg = path.Base(s.Args[0])
}
switch s.Type {
case "inspect", "ssa", "codegen":
default:
return fmt.Errorf("unexpected type: %s", s.Type)
}
cwd, err := os.Getwd()
if err != nil {
return err
}
td.ImportPath = s.importPath(cwd)
if td.ImportPath == "" {
const format = "%s must be executed in GOPATH or -path option must be specified"
return fmt.Errorf(format, s.ExeName)
}
exist, err := isExist(s.Dir)
if err != nil {
return err
}
if exist && !s.OverWrite {
if exit := s.selectMode(s.Dir); exit {
return nil
}
}
if err := s.createAll(td); err != nil {
return err
}
return nil
}
func (s *Skeleton) importPath(cwd string) string {
if s.ImportPath != "" {
return s.ImportPath
}
for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
if gopath == "" {
continue
}
src := filepath.Join(gopath, "src")
if strings.HasPrefix(cwd, src) {
rel, err := filepath.Rel(src, cwd)
if err != nil {
return ""
}
return path.Join(filepath.ToSlash(rel), filepath.ToSlash(s.Dir))
}
}
return ""
}
func (s *Skeleton) selectMode(dir string) bool {
fmt.Printf("%s already exist, remove?\n", dir)
fmt.Println("[1] No(Exit)")
fmt.Println("[2] Remove and create new directory")
fmt.Println("[3] Overwrite existing files with confirmation")
fmt.Println("[4] Create new files only")
fmt.Print("(default is 1) >")
var m string
fmt.Scanln(&m)
switch m {
case "2":
s.Mode = ModeRemoveAndCreateNew
case "3":
s.Mode = ModeConfirm
case "4":
s.Mode = ModeCreateNewFile
default:
// exit
return true
}
return false
}
func (s *Skeleton) createAll(td *TemplateData) error {
if s.Mode == ModeRemoveAndCreateNew {
if err := os.RemoveAll(s.Dir); err != nil {
return err
}
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, td); err != nil {
return err
}
ar := txtar.Parse(buf.Bytes())
for _, f := range ar.Files {
if err := s.createFile(f); err != nil {
return err
}
}
return nil
}
func (s *Skeleton) createFile(f txtar.File) (rerr error) {
if len(bytes.TrimSpace(f.Data)) == 0 {
return nil
}
path := filepath.Join(s.Dir, filepath.FromSlash(f.Name))
exist, err := isExist(path)
if err != nil {
return err
}
if exist {
switch s.Mode {
case ModeConfirm:
fmt.Printf("%s already exit, replace? [y/N] >", path)
var yn string
fmt.Scanln(&yn)
switch strings.ToLower(yn) {
case "y", "yes":
// continue
default:
// skip
fmt.Println("skip", path)
return nil
}
case ModeCreateNewFile:
// skip
fmt.Println("skip", path)
return nil
}
}
if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
return err
}
w, err := os.Create(path)
if err != nil {
return err
}
defer func() {
if err := w.Close(); err != nil && rerr == nil {
rerr = err
}
}()
// format a go file
data := f.Data
if filepath.Ext(path) == ".go" {
data, err = format.Source(data)
if err != nil {
return err
}
}
r := bytes.NewReader(data)
if _, err := io.Copy(w, r); err != nil {
return err
}
fmt.Println("create", path)
return nil
}
func isExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}