Skip to content

Commit

Permalink
feat(goctl): create an api that supports custom module names
Browse files Browse the repository at this point in the history
  • Loading branch information
Twacqwq authored and kevwan committed Feb 1, 2024
1 parent 786a801 commit a37272d
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 12 deletions.
1 change: 1 addition & 0 deletions tools/goctl/api/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func init() {
newCmdFlags.StringVar(&new.VarStringRemote, "remote")
newCmdFlags.StringVar(&new.VarStringBranch, "branch")
newCmdFlags.StringVarWithDefaultValue(&new.VarStringStyle, "style", config.DefaultFormat)
newCmdFlags.StringVar(&new.VarStringModule, "module")

pluginCmdFlags.StringVarP(&plugin.VarStringPlugin, "plugin", "p")
pluginCmdFlags.StringVar(&plugin.VarStringDir, "dir")
Expand Down
9 changes: 6 additions & 3 deletions tools/goctl/api/gogen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ var (
VarStringBranch string
// VarStringStyle describes the style of output files.
VarStringStyle string
// VarStringModule describes the go.mod module name.
VarStringModule string
)

// GoCommand gen go project files from command line
Expand All @@ -49,6 +51,7 @@ func GoCommand(_ *cobra.Command, _ []string) error {
home := VarStringHome
remote := VarStringRemote
branch := VarStringBranch
module := VarStringModule
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote, branch)
if len(repo) > 0 {
Expand All @@ -66,11 +69,11 @@ func GoCommand(_ *cobra.Command, _ []string) error {
return errors.New("missing -dir")
}

return DoGenProject(apiFile, dir, namingStyle)
return DoGenProject(apiFile, dir, module, namingStyle)
}

// DoGenProject gen go project files with api file
func DoGenProject(apiFile, dir, style string) error {
func DoGenProject(apiFile, dir, module, style string) error {
api, err := parser.Parse(apiFile)
if err != nil {
return err
Expand All @@ -86,7 +89,7 @@ func DoGenProject(apiFile, dir, style string) error {
}

logx.Must(pathx.MkdirIfNotExist(dir))
rootPkg, err := golang.GetParentPackage(dir)
rootPkg, err := golang.GetParentPackage(dir, module)
if err != nil {
return err
}
Expand Down
37 changes: 36 additions & 1 deletion tools/goctl/api/gogen/gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/pkg/env"
"github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"golang.org/x/mod/modfile"
)

var (
Expand Down Expand Up @@ -48,6 +49,8 @@ var (
noStructTagApi string
//go:embed testdata/nest_type_api.api
nestTypeApi string
//go:embed testdata/test_api_service.api
apiSericeApi string
)

func TestParser(t *testing.T) {
Expand Down Expand Up @@ -267,20 +270,47 @@ func TestCamelStyle(t *testing.T) {
validateWithCamel(t, filename, "GoZero")
}

func TestCustomModule(t *testing.T) {
dir := "demo"
filename := "greet.api"
err := os.WriteFile(filename, []byte(apiSericeApi), os.ModePerm)
assert.Nil(t, err)
defer os.RemoveAll(filename)

module := "custom-module"
defer func() {
_ = os.RemoveAll(dir)
}()

err = DoGenProject(filename, dir, module, "gozero")
assert.Nil(t, err)

err = initCustomMod(dir, module)
assert.Nil(t, err)

modFile := filepath.Join(".", dir, "go.mod")
modBytes, err := os.ReadFile(modFile)
assert.Nil(t, err)
goMod, err := modfile.Parse(modFile, modBytes, nil)
assert.Nil(t, err)
assert.Equal(t, goMod.Module.Syntax.Token[1], module)
}

func validate(t *testing.T, api string) {
validateWithCamel(t, api, "gozero")
}

func validateWithCamel(t *testing.T, api, camel string) {
dir := "workspace"
module := ""
defer func() {
os.RemoveAll(dir)
}()
err := pathx.MkdirIfNotExist(dir)
assert.Nil(t, err)
err = initMod(dir)
assert.Nil(t, err)
err = DoGenProject(api, dir, camel)
err = DoGenProject(api, dir, module, camel)
assert.Nil(t, err)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".go") {
Expand All @@ -297,6 +327,11 @@ func initMod(mod string) error {
return err
}

func initCustomMod(dir, mod string) error {
_, err := execx.Run("go mod init "+mod, dir)
return err
}

func validateCode(code string) error {
_, err := goformat.Source([]byte(code))
return err
Expand Down
14 changes: 14 additions & 0 deletions tools/goctl/api/gogen/testdata/test_api_service.api
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
syntax = "v1"

type Request {
Name string `path:"name,options=you|me"`
}

type Response {
Message string `json:"message"`
}

service demo-api {
@handler DemoHandler
get /from/:name (Request) returns (Response)
}
4 changes: 3 additions & 1 deletion tools/goctl/api/new/newservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ var (
VarStringBranch string
// VarStringStyle describes the style of output files.
VarStringStyle string
// VarStringModule describes the go.mod module name.
VarStringModule string
)

// CreateServiceCommand fast create service
Expand Down Expand Up @@ -83,6 +85,6 @@ func CreateServiceCommand(_ *cobra.Command, args []string) error {
return err
}

err = gogen.DoGenProject(apiFilePath, abs, VarStringStyle)
err = gogen.DoGenProject(apiFilePath, abs, VarStringModule, VarStringStyle)
return err
}
1 change: 1 addition & 0 deletions tools/goctl/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ require (
go.uber.org/multierr v1.9.0 // indirect
go.uber.org/zap v1.24.0 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/oauth2 v0.14.0 // indirect
golang.org/x/sync v0.5.0 // indirect
Expand Down
3 changes: 3 additions & 0 deletions tools/goctl/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
Expand Down Expand Up @@ -283,6 +285,7 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM=
golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
3 changes: 2 additions & 1 deletion tools/goctl/internal/flags/default_en.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"home": "{{.global.home}}",
"remote": "{{.global.remote}}",
"branch": "{{.global.branch}}",
"style": "{{.global.style}}"
"style": "{{.global.style}}",
"module": "The module name of the service"
},
"validate": {
"short": "Validate api file",
Expand Down
9 changes: 7 additions & 2 deletions tools/goctl/pkg/golang/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)

func GetParentPackage(dir string) (string, error) {
func GetParentPackage(dir, module string) (string, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return "", err
}

projectCtx, err := ctx.Prepare(abs)
var projectCtx *ctx.ProjectContext
if module != "" {
projectCtx, err = ctx.PrepareBasedOnModule(abs, module)
} else {
projectCtx, err = ctx.Prepare(abs)
}
if err != nil {
return "", err
}
Expand Down
9 changes: 5 additions & 4 deletions tools/goctl/quickstart/mono.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func initAPIFlags() error {

gogen.VarStringDir = apiWorkDir
gogen.VarStringAPI = apiFilename
gogen.VarStringModule = "greet"
return nil
}

Expand All @@ -65,17 +66,17 @@ func (m mono) createAPIProject() {
configPath := filepath.Join(apiWorkDir, "internal", "config")
svcPath := filepath.Join(apiWorkDir, "internal", "svc")
typesPath := filepath.Join(apiWorkDir, "internal", "types")
svcPkg, err := golang.GetParentPackage(svcPath)
svcPkg, err := golang.GetParentPackage(svcPath, gogen.VarStringModule)
logx.Must(err)
typesPkg, err := golang.GetParentPackage(typesPath)
typesPkg, err := golang.GetParentPackage(typesPath, gogen.VarStringModule)
logx.Must(err)
configPkg, err := golang.GetParentPackage(configPath)
configPkg, err := golang.GetParentPackage(configPath, gogen.VarStringModule)
logx.Must(err)

var rpcClientPkg string
if m.callRPC {
rpcClientPath := filepath.Join(rpcWorkDir, "greet")
rpcClientPkg, err = golang.GetParentPackage(rpcClientPath)
rpcClientPkg, err = golang.GetParentPackage(rpcClientPath, gogen.VarStringModule)
logx.Must(err)
}

Expand Down
17 changes: 17 additions & 0 deletions tools/goctl/util/ctx/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ func Prepare(workDir string) (*ProjectContext, error) {
return background(workDir)
}

// PrepareBasedOnModule checks the project which module belongs to,and returns the path and module.
// workDir parameter is the directory of the source of generating code,
// module parameter is the module name of the project,
// where can be found the project path and the project module,
func PrepareBasedOnModule(workDir, module string) (*ProjectContext, error) {
ctx, err := background(workDir)
if err == nil {
return ctx, nil
}

_, err = execx.Run("go mod init "+module, workDir)
if err != nil {
return nil, err
}
return background(workDir)
}

func background(workDir string) (*ProjectContext, error) {
isGoMod, err := IsGoMod(workDir)
if err != nil {
Expand Down

0 comments on commit a37272d

Please sign in to comment.