/
cmd.go
450 lines (377 loc) · 11.5 KB
/
cmd.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package cmd
import (
"bytes"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/cnf/structhash"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/errors"
"github.com/pubgo/funk/generic"
"github.com/pubgo/funk/log"
"github.com/pubgo/funk/pathutil"
"github.com/pubgo/funk/recovery"
"github.com/pubgo/funk/strutil"
"github.com/urfave/cli/v2"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/pluginpb"
yaml "gopkg.in/yaml.v3"
"github.com/pubgo/protobuild/internal/modutil"
"github.com/pubgo/protobuild/internal/shutil"
"github.com/pubgo/protobuild/internal/typex"
"github.com/pubgo/protobuild/version"
)
var (
cfg Cfg
protoCfg = "protobuf.yaml"
modPath = filepath.Join(os.Getenv("GOPATH"), "pkg", "mod")
pwd = assert.Exit1(os.Getwd())
logger = log.GetLogger("proto-build")
//binPath = []string{os.ExpandEnv("$HOME/bin"), os.ExpandEnv("$HOME/.local/bin"), os.ExpandEnv("./bin")}
)
func Main() *cli.App {
var force bool
var app = &cli.App{
Name: "protobuf build",
Usage: "protobuf generation, configuration and management",
Version: version.Version,
Flags: typex.Flags{
&cli.StringFlag{
Name: "conf",
Aliases: typex.Strs{"c"},
Usage: "protobuf config path",
Value: protoCfg,
Destination: &protoCfg,
},
},
Action: func(context *cli.Context) error {
in := assert.Must1(io.ReadAll(os.Stdin))
req := &pluginpb.CodeGeneratorRequest{}
assert.Must(proto.Unmarshal(in, req))
var opts protogen.Options
plg := assert.Must1(opts.New(req))
for _, f := range plg.Files {
if !f.Generate {
continue
}
log.Printf("%s\n", f.GeneratedFilenamePrefix)
}
var params []string
var plgName string
for _, p := range strings.Split(req.GetParameter(), ",") {
if strings.HasPrefix(p, "__wrapper") {
names := strings.Split(p, "=")
plgName = strings.TrimSpace(names[len(names)-1])
} else {
params = append(params, p)
}
}
if len(params) > 0 {
req.Parameter = generic.Ptr(strings.Join(params, ","))
}
for _, p := range cfg.Plugins {
if p.Name != plgName {
continue
}
log.Printf("%#v\n", p)
if p.Shell != "" {
cccc := shutil.Shell(strings.TrimSpace(p.Shell))
cccc.Stdin = bytes.NewBuffer(assert.Must1(proto.Marshal(req)))
assert.Must(cccc.Run())
break
}
if p.Docker != "" {
cccc := shutil.Shell("docker run -i --rm " + p.Docker)
cccc.Stdin = bytes.NewBuffer(assert.Must1(proto.Marshal(req)))
assert.Must(cccc.Run())
break
}
}
return nil
},
Before: func(ctx *cli.Context) error {
defer recovery.Exit()
content := assert.Must1(os.ReadFile(protoCfg))
assert.Must(yaml.Unmarshal(content, &cfg))
cfg.Vendor = strutil.FirstFnNotEmpty(func() string {
return cfg.Vendor
}, func() string {
protoPath := filepath.Join(pwd, ".proto")
if pathutil.IsExist(protoPath) {
return protoPath
}
return ""
}, func() string {
goModPath := filepath.Dir(modutil.GoModPath())
if goModPath == "" {
panic("没有找到项目go.mod文件")
}
return filepath.Join(goModPath, ".proto")
})
assert.Must(pathutil.IsNotExistMkDir(cfg.Vendor))
// protobuf文件检查
for _, dep := range cfg.Depends {
assert.If(dep.Name == "" || dep.Url == "", "name和url都不能为空")
}
checksum := fmt.Sprintf("%x", structhash.Sha1(cfg, 1))
if cfg.Checksum != checksum {
cfg.Checksum = checksum
cfg.changed = true
}
return nil
},
Commands: cli.Commands{
fmtCmd(),
&cli.Command{
Name: "gen",
Usage: "编译protobuf文件",
Action: func(ctx *cli.Context) error {
defer recovery.Exit()
var protoList sync.Map
var basePlugin = cfg.BasePlugin
for i := range cfg.Root {
if pathutil.IsNotExist(cfg.Root[i]) {
log.Printf("file %s not found", cfg.Root[i])
continue
}
assert.Must(filepath.Walk(cfg.Root[i], func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
for _, e := range cfg.Excludes {
if strings.HasPrefix(path, e) {
return filepath.SkipDir
}
}
return nil
}
if !strings.HasSuffix(info.Name(), ".proto") {
return nil
}
protoList.Store(filepath.Dir(path), struct{}{})
return nil
}))
}
protoList.Range(func(key, _ interface{}) bool {
var in = key.(string)
var data = ""
var base = fmt.Sprintf("protoc -I %s -I %s", cfg.Vendor, pwd)
logger.Info().Msgf("includes=%q", cfg.Includes)
for i := range cfg.Includes {
base += fmt.Sprintf(" -I %s", cfg.Includes[i])
}
var retagOut = ""
var retagOpt = ""
for i := range cfg.Plugins {
var plg = cfg.Plugins[i]
var name = plg.Name
// 指定plugin path
if plg.Path != "" {
plg.Path = assert.Must1(exec.LookPath(plg.Path))
assert.If(pathutil.IsNotExist(plg.Path), "plugin path notfound, path=%s", plg.Path)
data += fmt.Sprintf(" --plugin=protoc-gen-%s=%s", name, plg.Path)
}
var out = func() string {
// https://github.com/pseudomuto/protoc-gen-doc
// 目录特殊处理
if name == "doc" {
var out = filepath.Join(plg.Out, in)
assert.Must(pathutil.IsNotExistMkDir(out))
return out
}
if plg.Out != "" {
return plg.Out
}
if basePlugin != nil && basePlugin.Out != "" {
return basePlugin.Out
}
return "."
}()
_ = pathutil.IsNotExistMkDir(out)
var opts = plg.Opt
if basePlugin != nil && basePlugin.Paths != "" && !plg.SkipBase {
var hasPath = func() bool {
for _, opt := range opts {
if strings.HasPrefix(opt, "paths=") {
return true
}
}
return false
}
var hasModule = func() bool {
for _, opt := range opts {
if strings.HasPrefix(opt, "module=") {
return true
}
}
return false
}
if !hasPath() && basePlugin.Paths != "" {
opts = append(opts, fmt.Sprintf("paths=%s", basePlugin.Paths))
}
if !hasModule() && basePlugin.Module != "" {
opts = append(opts, fmt.Sprintf("module=%s", basePlugin.Module))
}
}
if plg.Shell != "" || plg.Docker != "" {
opts = append(opts, "__wrapper="+name)
data += fmt.Sprintf(" --plugin=protoc-gen-%s=%s", name, assert.Must1(exec.LookPath(os.Args[0])))
}
if name == "retag" {
retagOut = fmt.Sprintf(" --%s_out=%s", name, out)
retagOpt = fmt.Sprintf(" --%s_opt=%s", name, strings.Join(opts, ","))
continue
}
data += fmt.Sprintf(" --%s_out=%s", name, out)
if len(opts) > 0 {
data += fmt.Sprintf(" --%s_opt=%s", name, strings.Join(opts, ","))
}
}
data = base + data + " " + filepath.Join(in, "*.proto")
logger.Info().Msg(data)
assert.Must(shutil.Shell(data).Run(), data)
if retagOut != "" && retagOpt != "" {
data = base + retagOut + retagOpt + " " + filepath.Join(in, "*.proto")
}
logger.Info().Msg(data)
assert.Must(shutil.Shell(data).Run(), data)
return true
})
return nil
},
},
&cli.Command{
Name: "vendor",
Usage: "同步项目protobuf依赖到.proto中",
Flags: typex.Flags{
&cli.BoolFlag{
Name: "force",
Usage: "protobuf force vendor",
Aliases: []string{"f"},
Value: force,
Destination: &force,
},
},
Action: func(ctx *cli.Context) error {
defer recovery.Exit()
var changed bool
// 解析go.mod并获取所有pkg版本
var versions = modutil.LoadVersions()
for i, dep := range cfg.Depends {
var url = os.ExpandEnv(dep.Url)
// url是本地目录, 不做检查
if pathutil.IsDir(url) {
continue
}
var v = strutil.FirstFnNotEmpty(func() string {
return versions[url]
}, func() string {
return dep.Version
}, func() string {
// go.mod中version不存在, 并且protobuf.yaml也没有指定
// go pkg缓存
var localPkg, err = os.ReadDir(filepath.Dir(filepath.Join(modPath, url)))
assert.Must(err)
var _, name = filepath.Split(url)
for j := range localPkg {
if !localPkg[j].IsDir() {
continue
}
if strings.HasPrefix(localPkg[j].Name(), name+"@") {
return strings.TrimPrefix(localPkg[j].Name(), name+"@")
}
}
return ""
})
if v == "" || pathutil.IsNotExist(fmt.Sprintf("%s/%s@%s", modPath, url, v)) {
changed = true
if v == "" {
fmt.Println("go", "get", "-d", url+"/...")
assert.Must(shutil.Shell("go", "get", "-d", url+"/...").Run())
} else if pathutil.IsNotExist(fmt.Sprintf("%s/%s@%s", modPath, url, v)) {
fmt.Println("go", "get", "-d", fmt.Sprintf("%s@%s", url, v))
assert.Must(shutil.Shell("go", "get", "-d", fmt.Sprintf("%s@%s", url, v)).Run())
}
// 再次解析go.mod然后获取版本信息
versions = modutil.LoadVersions()
v = versions[url]
assert.If(v == "", "%s version为空", url)
}
cfg.Depends[i].Version = v
}
var buf bytes.Buffer
var enc = yaml.NewEncoder(&buf)
enc.SetIndent(2)
defer enc.Close()
assert.Must(enc.Encode(cfg))
assert.Must(os.WriteFile(protoCfg, buf.Bytes(), 0666))
if !changed && !cfg.changed && !force {
fmt.Println("No changes")
return nil
}
// 删除老的protobuf文件
logger.Info().Str("vendor", cfg.Vendor).Msg("delete old vendor")
_ = os.RemoveAll(cfg.Vendor)
for _, dep := range cfg.Depends {
if dep.Name == "" || dep.Url == "" {
continue
}
var url = os.ExpandEnv(dep.Url)
var v = dep.Version
// 加载版本
if v != "" {
url = fmt.Sprintf("%s@%s", url, v)
}
// 加载路径
url = filepath.Join(url, dep.Path)
if pathutil.IsNotExist(url) {
url = filepath.Join(modPath, url)
}
fmt.Println(url)
url = assert.Must1(filepath.Abs(url))
var newUrl = filepath.Join(cfg.Vendor, dep.Name)
assert.Must(filepath.Walk(url, func(path string, info fs.FileInfo, err error) (gErr error) {
if err != nil {
return err
}
defer recovery.Err(&gErr, func(err error) error {
return errors.WrapTag(err,
errors.T("path", path),
errors.T("name", info.Name()),
)
})
if info.IsDir() {
return nil
}
if !strings.HasSuffix(info.Name(), ".proto") {
return nil
}
var newPath = filepath.Join(newUrl, strings.TrimPrefix(path, url))
assert.Must(pathutil.IsNotExistMkDir(filepath.Dir(newPath)))
assert.Must1(copyFile(newPath, path))
return nil
}))
}
return nil
},
},
},
}
return app
}
func copyFile(dstFilePath string, srcFilePath string) (written int64, err error) {
srcFile, err := os.Open(srcFilePath)
defer srcFile.Close()
assert.Must(err, "打开源文件错误", srcFilePath)
dstFile, err := os.Create(dstFilePath)
defer srcFile.Close()
assert.Must(err, "打开目标文件错误", dstFilePath)
return io.Copy(dstFile, srcFile)
}