feat: Replace cli to cobra (#1855)

* Replace cli

* Replace cli

* Replace cli

* Format code

* Add compare case

* Add compare case

* Add compare case

* Support go style flag

* Support go style flag

* Add test case
This commit is contained in:
anqiansong
2022-05-07 15:40:11 +08:00
committed by GitHub
parent 51472004a3
commit 5383e29ce6
61 changed files with 1858 additions and 1590 deletions

View File

@@ -6,30 +6,57 @@ import (
"path/filepath"
"strings"
"github.com/urfave/cli"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/rpc/generator"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
// VarStringOutput describes the output.
VarStringOutput string
// VarStringHome describes the goctl home.
VarStringHome string
// VarStringRemote describes the remote git repository.
VarStringRemote string
// VarStringBranch describes the git branch.
VarStringBranch string
// VarStringSliceGoOut describes the go output.
VarStringSliceGoOut []string
// VarStringSliceGoGRPCOut describes the grpc output.
VarStringSliceGoGRPCOut []string
// VarStringSlicePlugin describes the protoc plugin.
VarStringSlicePlugin []string
// VarStringSliceProtoPath describes the proto path.
VarStringSliceProtoPath []string
// VarStringSliceGoOpt describes the go options.
VarStringSliceGoOpt []string
// VarStringSliceGoGRPCOpt describes the grpc options.
VarStringSliceGoGRPCOpt []string
// VarStringStyle describes the style of output files.
VarStringStyle string
// VarStringZRPCOut describes the zRPC output.
VarStringZRPCOut string
// VarBoolIdea describes whether idea or not
VarBoolIdea bool
// VarBoolVerbose describes whether verbose.
VarBoolVerbose bool
)
// RPCNew is to generate rpc greet service, this greet service can speed
// up your understanding of the zrpc service structure
func RPCNew(c *cli.Context) error {
if c.NArg() == 0 {
cli.ShowCommandHelpAndExit(c, "new", 1)
}
rpcname := c.Args().First()
func RPCNew(_ *cobra.Command, args []string) error {
rpcname := args[0]
ext := filepath.Ext(rpcname)
if len(ext) > 0 {
return fmt.Errorf("unexpected ext: %s", ext)
}
style := c.String("style")
home := c.String("home")
remote := c.String("remote")
branch := c.String("branch")
verbose := c.Bool("verbose")
style := VarStringStyle
home := VarStringHome
remote := VarStringRemote
branch := VarStringBranch
verbose := VarBoolVerbose
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote, branch)
if len(repo) > 0 {
@@ -60,12 +87,12 @@ func RPCNew(c *cli.Context) error {
ctx.Output = filepath.Dir(src)
ctx.ProtocCmd = fmt.Sprintf("protoc -I=%s %s --go_out=%s --go-grpc_out=%s", filepath.Dir(src), filepath.Base(src), filepath.Dir(src), filepath.Dir(src))
grpcOptList := c.StringSlice("go-grpc_opt")
grpcOptList := VarStringSliceGoGRPCOpt
if len(grpcOptList) > 0 {
ctx.ProtocCmd += " --go-grpc_opt=" + strings.Join(grpcOptList, ",")
}
goOptList := c.StringSlice("go_opt")
goOptList := VarStringSliceGoOpt
if len(goOptList) > 0 {
ctx.ProtocCmd += " --go_opt=" + strings.Join(goOptList, ",")
}
@@ -75,17 +102,12 @@ func RPCNew(c *cli.Context) error {
}
// RPCTemplate is the entry for generate rpc template
func RPCTemplate(c *cli.Context) error {
func RPCTemplate(_ *cobra.Command, _ []string) error {
console.Warning("deprecated: goctl rpc template -o is deprecated and will be removed in the future, use goctl rpc -o instead")
if c.NumFlags() == 0 {
cli.ShowCommandHelpAndExit(c, "template", 1)
}
protoFile := c.String("o")
home := c.String("home")
remote := c.String("remote")
branch := c.String("branch")
protoFile := VarStringOutput
home := VarStringHome
remote := VarStringRemote
branch := VarStringBranch
if len(remote) > 0 {
repo, _ := util.CloneIntoGitHome(remote, branch)
if len(repo) > 0 {

View File

@@ -6,7 +6,7 @@ import (
"path/filepath"
"strings"
"github.com/urfave/cli"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/rpc/generator"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
@@ -16,37 +16,26 @@ var (
errInvalidGrpcOutput = errors.New("ZRPC: missing --go-grpc_out")
errInvalidGoOutput = errors.New("ZRPC: missing --go_out")
errInvalidZrpcOutput = errors.New("ZRPC: missing zrpc output, please use --zrpc_out to specify the output")
errInvalidInput = errors.New("ZRPC: missing source")
errMultiInput = errors.New("ZRPC: only one source is expected")
)
// ZRPC generates grpc code directly by protoc and generates
// zrpc code by goctl.
func ZRPC(c *cli.Context) error {
if c.NumFlags() == 0 {
cli.ShowCommandHelpAndExit(c, "protoc", 1)
}
args := c.Parent().Args()
protocArgs := removeGoctlFlag(args)
func ZRPC(cmd *cobra.Command, args []string) error {
protocArgs := wrapProtocCmd("protoc", args)
pwd, err := os.Getwd()
if err != nil {
return err
}
source, err := getSourceProto(c.Args(), pwd)
if err != nil {
return err
}
grpcOutList := c.StringSlice("go-grpc_out")
goOutList := c.StringSlice("go_out")
zrpcOut := c.String("zrpc_out")
style := c.String("style")
home := c.String("home")
remote := c.String("remote")
branch := c.String("branch")
verbose := c.Bool("verbose")
source := args[0]
grpcOutList := VarStringSliceGoGRPCOut
goOutList := VarStringSliceGoOut
zrpcOut := VarStringZRPCOut
style := VarStringStyle
home := VarStringHome
remote := VarStringRemote
branch := VarStringBranch
verbose := VarBoolVerbose
if len(grpcOutList) == 0 {
return errInvalidGrpcOutput
}
@@ -116,64 +105,25 @@ func ZRPC(c *cli.Context) error {
return g.Generate(&ctx)
}
func removeGoctlFlag(args []string) []string {
var ret []string
var step int
for step < len(args) {
arg := args[step]
switch {
case arg == "--style", arg == "--home",
arg == "--zrpc_out", arg == "--verbose",
arg == "-v", arg == "--remote",
arg == "--branch":
step += 2
continue
case strings.HasPrefix(arg, "--style="),
strings.HasPrefix(arg, "--home="),
strings.HasPrefix(arg, "--verbose="),
strings.HasPrefix(arg, "-v="),
strings.HasPrefix(arg, "--remote="),
strings.HasPrefix(arg, "--branch="),
strings.HasPrefix(arg, "--zrpc_out="):
step += 1
continue
}
step += 1
ret = append(ret, arg)
func wrapProtocCmd(name string, args []string) []string {
ret := append([]string{name}, args...)
for _, protoPath := range VarStringSliceProtoPath {
ret = append(ret, "--proto_path", protoPath)
}
for _, goOpt := range VarStringSliceGoOpt {
ret = append(ret, "--go_opt", goOpt)
}
for _, goGRPCOpt := range VarStringSliceGoGRPCOpt {
ret = append(ret, "--go-grpc_opt", goGRPCOpt)
}
for _, goOut := range VarStringSliceGoOut {
ret = append(ret, "--go_out", goOut)
}
for _, goGRPCOut := range VarStringSliceGoGRPCOut {
ret = append(ret, "--go-grpc_out", goGRPCOut)
}
for _, plugin := range VarStringSlicePlugin {
ret = append(ret, "--plugin="+plugin)
}
return ret
}
func getSourceProto(args []string, pwd string) (string, error) {
var source []string
for _, p := range args {
if strings.HasSuffix(p, ".proto") {
source = append(source, p)
}
}
switch len(source) {
case 0:
return "", errInvalidInput
case 1:
isAbs := filepath.IsAbs(source[0])
if isAbs {
return source[0], nil
}
abs := filepath.Join(pwd, source[0])
return abs, nil
default:
return "", errMultiInput
}
}
func removePluginFlag(goOut string) string {
goOut = strings.ReplaceAll(goOut, "plugins=", "")
index := strings.LastIndex(goOut, ":")
if index < 0 {
return goOut
}
return goOut[index+1:]
}

View File

@@ -1,125 +0,0 @@
package cli
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
type test struct {
source []string
expected string
expectedErr error
}
func Test_GetSourceProto(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
console.Error(err.Error())
return
}
testData := []test{
{
source: []string{"a.proto"},
expected: filepath.Join(pwd, "a.proto"),
},
{
source: []string{"/foo/bar/a.proto"},
expected: "/foo/bar/a.proto",
},
{
source: []string{"a.proto", "b.proto"},
expectedErr: errMultiInput,
},
{
source: []string{"", "--go_out=."},
expectedErr: errInvalidInput,
},
}
for _, d := range testData {
ret, err := getSourceProto(d.source, pwd)
if d.expectedErr != nil {
assert.Equal(t, d.expectedErr, err)
continue
}
assert.Equal(t, d.expected, ret)
}
}
func Test_RemoveGoctlFlag(t *testing.T) {
testData := []test{
{
source: strings.Fields("protoc foo.proto --go_out=. --go_opt=bar --zrpc_out=. --style go-zero --home=foo"),
expected: "protoc foo.proto --go_out=. --go_opt=bar",
},
{
source: strings.Fields("foo bar foo.proto"),
expected: "foo bar foo.proto",
},
{
source: strings.Fields("protoc foo.proto --go_out . --style=go_zero --home ."),
expected: "protoc foo.proto --go_out .",
},
{
source: strings.Fields(`protoc foo.proto --go_out . --style="go_zero" --home="."`),
expected: "protoc foo.proto --go_out .",
},
{
source: strings.Fields(`protoc foo.proto --go_opt=. --zrpc_out . --style=goZero --home=bar`),
expected: "protoc foo.proto --go_opt=.",
},
{
source: strings.Fields(`protoc foo.proto --go_opt=. --zrpc_out="bar" --style=goZero --home=bar`),
expected: "protoc foo.proto --go_opt=.",
},
{
source: strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. foo.proto`),
expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
},
{
source: strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. --remote=foo --branch=bar foo.proto`),
expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
},
{
source: strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. --remote foo --branch bar foo.proto`),
expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
},
}
for _, e := range testData {
cmd := strings.Join(removeGoctlFlag(e.source), " ")
assert.Equal(t, e.expected, cmd)
}
}
func Test_RemovePluginFlag(t *testing.T) {
testData := []test{
{
source: strings.Fields("plugins=grpc:."),
expected: ".",
},
{
source: strings.Fields("plugins=g1,g2:."),
expected: ".",
},
{
source: strings.Fields("g1,g2:."),
expected: ".",
},
{
source: strings.Fields("plugins=g1,g2:foo"),
expected: "foo",
},
}
for _, e := range testData {
data := removePluginFlag(e.source[0])
assert.Equal(t, e.expected, data)
}
}