-
Notifications
You must be signed in to change notification settings - Fork 0
/
genmain.go
81 lines (71 loc) · 2.24 KB
/
genmain.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
package generator
import (
_ "embed"
"fmt"
"path/filepath"
"strings"
conf "github.com/zhangbao138208/goctls/config"
"github.com/zhangbao138208/goctls/rpc/parser"
"github.com/zhangbao138208/goctls/util"
"github.com/zhangbao138208/goctls/util/format"
"github.com/zhangbao138208/goctls/util/pathx"
)
//go:embed main.tpl
var mainTemplate string
type MainServiceTemplateData struct {
Service string
ServerPkg string
Pkg string
}
// GenMain generates the main file of the rpc service, which is a rpc service program call entry
func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config,
c *ZRpcContext) error {
mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
if err != nil {
return err
}
fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename))
imports := make([]string, 0)
pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package)
svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)
configImport := fmt.Sprintf(`"%v"`, ctx.GetConfig().Package)
imports = append(imports, configImport, pbImport, svcImport)
var serviceNames []MainServiceTemplateData
for _, e := range proto.Service {
var (
remoteImport string
serverPkg string
)
if !c.Multiple {
serverPkg = "server"
remoteImport = fmt.Sprintf(`"%v"`, ctx.GetServer().Package)
} else {
childPkg, err := ctx.GetServer().GetChildPackage(e.Name)
if err != nil {
return err
}
serverPkg = filepath.Base(childPkg + "Server")
remoteImport = fmt.Sprintf(`%s "%v"`, serverPkg, childPkg)
}
imports = append(imports, remoteImport)
serviceNames = append(serviceNames, MainServiceTemplateData{
Service: parser.CamelCase(e.Name),
ServerPkg: serverPkg,
Pkg: proto.PbPackage,
})
}
text, err := pathx.LoadTemplate(category, mainTemplateFile, mainTemplate)
if err != nil {
return err
}
etcFileName, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
if err != nil {
return err
}
return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]any{
"serviceName": etcFileName,
"imports": strings.Join(imports, pathx.NL),
"pkg": proto.PbPackage,
"serviceNames": serviceNames,
}, fileName, false)
}