Skip to content

Commit

Permalink
fix: client windows bug && reuse code && consts (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
chaoranz758 authored Oct 18, 2023
1 parent e149312 commit 6f9c032
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 62 deletions.
28 changes: 20 additions & 8 deletions pkg/client/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,31 @@ func check(ca *config.ClientArgument) error {

// Generate the project under gopath, use the relative path as the package name
if strings.HasPrefix(ca.Cwd, ca.GoSrc) {
if gopkg, err := filepath.Rel(ca.GoSrc, ca.Cwd); err != nil {
if goPkg, err := filepath.Rel(ca.GoSrc, ca.Cwd); err != nil {
return fmt.Errorf("get relative path to GOPATH/src failed: %s", err)
} else {
ca.GoPkg = gopkg
ca.GoPkg = goPkg
}

if ca.GoMod == "" {
ca.GoMod = ca.GoPkg
}
if ca.GoMod != "" && ca.GoMod != ca.GoPkg {
return fmt.Errorf("module name: %s is not the same with GoPkg under GoPath: %s", ca.GoMod, ca.GoPkg)
if utils.IsWindows() {
ca.GoMod = strings.ReplaceAll(ca.GoPkg, consts.BackSlash, consts.Slash)
} else {
ca.GoMod = ca.GoPkg
}
}
if ca.GoMod == "" {
ca.GoMod = ca.GoPkg

if ca.GoMod != "" {
if utils.IsWindows() {
goPkgSlash := strings.ReplaceAll(ca.GoPkg, consts.BackSlash, consts.Slash)
if goPkgSlash != ca.GoMod {
return fmt.Errorf("module name: %s is not the same with GoPkg under GoPath: %s", ca.GoMod, goPkgSlash)
}
} else {
if ca.GoMod != ca.GoPkg {
return fmt.Errorf("module name: %s is not the same with GoPkg under GoPath: %s", ca.GoMod, ca.GoPkg)
}
}
}
}
return nil
Expand Down
4 changes: 2 additions & 2 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ func Client(c *config.ClientArgument) error {
if args.Use != "" {
out := strings.TrimSpace(out.String())
if strings.HasSuffix(out, thriftgo.TheUseOptionMessage) {
replaceThriftVersion(&args)
utils.ReplaceThriftVersion(args.IDLType)
}
}
os.Exit(1)
}
replaceThriftVersion(&args)
utils.ReplaceThriftVersion(args.IDLType)
case consts.HTTP:
args := hzConfig.NewArgument()
utils.SetHzVerboseLog(c.Verbose)
Expand Down
15 changes: 0 additions & 15 deletions pkg/client/kitex.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"flag"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
Expand Down Expand Up @@ -193,17 +192,3 @@ func checkKitexArgs(a *kargs.Arguments) (err error) {
a.OutputPath = curpath
return nil
}

func replaceThriftVersion(args *kargs.Arguments) {
if args.IDLType == "thrift" {
cmd := "go mod edit -replace github.com/apache/thrift=github.com/apache/thrift@v0.13.0"
argv := strings.Split(cmd, " ")
err := exec.Command(argv[0], argv[1:]...).Run()

res := "Done"
if err != nil {
res = err.Error()
}
log.Warn("Adding apache/thrift@v0.13.0 to go.mod for generated code ..........", res)
}
}
35 changes: 25 additions & 10 deletions pkg/common/utils/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@ import (
"strings"

"github.com/cloudwego/cwgo/pkg/consts"
"github.com/cloudwego/kitex/tool/internal_pkg/log"
)

func GetGOPATH() (gopath string, err error) {
ps := filepath.SplitList(os.Getenv("GOPATH"))
ps := filepath.SplitList(os.Getenv(consts.GOPATH))
if len(ps) > 0 {
gopath = ps[0]
}
if gopath == "" {
cmd := exec.Command("go", "env", "GOPATH")
cmd := exec.Command(consts.Go, consts.Env, consts.GOPATH)
var out bytes.Buffer
cmd.Stderr = &out
cmd.Stdout = &out
Expand All @@ -54,7 +55,7 @@ func GetGOPATH() (gopath string, err error) {
if !isExist {
return "", err
}
return strings.Replace(gopath, "/", string(os.PathSeparator), -1), nil
return strings.Replace(gopath, consts.Slash, string(os.PathSeparator), -1), nil
}

// GetBuildGoPaths returns the list of Go path directories.
Expand All @@ -64,13 +65,13 @@ func GetBuildGoPaths() []string {
if p == "" || p == build.Default.GOROOT {
continue
}
if strings.HasPrefix(p, "~") {
if strings.HasPrefix(p, consts.Tilde) {
continue
}
all = append(all, p)
}
for k, v := range all {
if strings.HasSuffix(v, "/") || strings.HasSuffix(v, string(os.PathSeparator)) {
if strings.HasSuffix(v, consts.Slash) || strings.HasSuffix(v, string(os.PathSeparator)) {
v = v[:len(v)-1]
}
all[k] = v
Expand All @@ -84,10 +85,10 @@ var goModReg = regexp.MustCompile(`^\s*module\s+(\S+)\s*`)
// the root directory. When the go.mod is found, its module name and path will be returned.
func SearchGoMod(cwd string, recurse bool) (moduleName, path string, found bool) {
for {
path = filepath.Join(cwd, "go.mod")
path = filepath.Join(cwd, consts.GoMod)
data, err := ioutil.ReadFile(path)
if err == nil {
for _, line := range strings.Split(string(data), "\n") {
for _, line := range strings.Split(string(data), consts.LineBreak) {
m := goModReg.FindStringSubmatch(line)
if m != nil {
return m[1], cwd, true
Expand All @@ -112,20 +113,20 @@ func SearchGoMod(cwd string, recurse bool) (moduleName, path string, found bool)
}

func InitGoMod(module string) error {
isExist, err := PathExist("go.mod")
isExist, err := PathExist(consts.GoMod)
if err != nil {
return err
}
if isExist {
return nil
}
gg, err := exec.LookPath("go")
gg, err := exec.LookPath(consts.Go)
if err != nil {
return err
}
cmd := &exec.Cmd{
Path: gg,
Args: []string{"go", "mod", "init", module},
Args: []string{consts.Go, consts.Mod, consts.Init, module},
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Expand All @@ -137,3 +138,17 @@ func InitGoMod(module string) error {
func IsWindows() bool {
return consts.SysType == consts.WindowsOS
}

func ReplaceThriftVersion(idlType string) {
if idlType == consts.Thrift {
cmd := "go mod edit -replace github.com/apache/thrift=github.com/apache/thrift@v0.13.0"
argv := strings.Split(cmd, consts.BlackSpace)
err := exec.Command(argv[0], argv[1:]...).Run()

res := "Done"
if err != nil {
res = err.Error()
}
log.Warn("Adding apache/thrift@v0.13.0 to go.mod for generated code ..........", res)
}
}
4 changes: 3 additions & 1 deletion pkg/common/utils/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"net/url"
"os/exec"
"strings"

"github.com/cloudwego/cwgo/pkg/consts"
)

func GitClone(gitURL, path string) error {
Expand All @@ -37,7 +39,7 @@ func GitPath(gitURL string) (string, error) {
if err != nil {
return "", err
}
p := strings.Split(strings.Trim(u.Path, ""), "/")
p := strings.Split(strings.Trim(u.Path, ""), consts.Slash)
path := p[len(p)-1]
return path[:len(path)-4], nil
}
3 changes: 2 additions & 1 deletion pkg/common/utils/hz.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package utils
import (
"path"

"github.com/cloudwego/cwgo/pkg/consts"
"github.com/cloudwego/hertz/cmd/hz/util/logs"
)

Expand All @@ -31,6 +32,6 @@ func SetHzVerboseLog(v bool) {
}

func IsHzNew(outputDir string) bool {
exist, _ := PathExist(path.Join(outputDir, ".hz"))
exist, _ := PathExist(path.Join(outputDir, consts.HzFile))
return !exist
}
8 changes: 6 additions & 2 deletions pkg/common/utils/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

package utils

import "strings"
import (
"strings"

"github.com/cloudwego/cwgo/pkg/consts"
)

type FlagStringSlice []string

Expand All @@ -32,7 +36,7 @@ func (f *FlagStringSlice) Set(value string) error {
func StringSliceSpilt(s []string) []string {
var ret []string
for _, v := range s {
ret = append(ret, strings.Split(v, " ")...)
ret = append(ret, strings.Split(v, consts.BlackSpace)...)
}
return ret
}
16 changes: 15 additions & 1 deletion pkg/consts/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ const (
DB = "db"
)

const Protobuf = "protobuf"
const (
Thrift = "thrift"
Protobuf = "protobuf"
)

// SysType is the running program's operating system type
const SysType = runtime.GOOS
Expand All @@ -46,6 +49,8 @@ const (
BackSlash = "\\"
BlackSpace = " "
Comma = ";"
Tilde = "~"
LineBreak = "\n"
)

// Package Name
Expand All @@ -56,6 +61,7 @@ const (
DefaultKitexModelDir = "kitex_gen"
DefaultDbOutDir = "biz/dal/query"
Standard = "standard"
CurrentDir = "."
)

// File Name
Expand All @@ -66,6 +72,8 @@ const (
SuffixGit = ".git"
DefaultDbOutFile = "gen.go"
Main = "main.go"
GoMod = "go.mod"
HzFile = ".hz"
)

// Registration Center
Expand Down Expand Up @@ -95,6 +103,12 @@ const (
)

const (
Go = "go"
GOPATH = "GOPATH"
Env = "env"
Mod = "mod"
Init = "init"

OutDir = "out_dir"
Verbose = "verbose"
Template = "template"
Expand Down
19 changes: 2 additions & 17 deletions pkg/server/kitex.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"go/printer"
"go/token"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
Expand Down Expand Up @@ -147,13 +146,13 @@ func checkKitexArgs(a *kargs.Arguments) (err error) {
return fmt.Errorf("GOPATH is not set")
}

gosrc := filepath.Join(gopath, "src")
gosrc := filepath.Join(gopath, consts.Src)
gosrc, err = filepath.Abs(gosrc)
if err != nil {
log.Warn("Get GOPATH/src path failed:", err.Error())
os.Exit(1)
}
curpath, err := filepath.Abs(".")
curpath, err := filepath.Abs(consts.CurrentDir)
if err != nil {
log.Warn("Get current path failed:", err.Error())
os.Exit(1)
Expand Down Expand Up @@ -202,20 +201,6 @@ func checkKitexArgs(a *kargs.Arguments) (err error) {
return nil
}

func replaceThriftVersion(args *kargs.Arguments) {
if args.IDLType == "thrift" {
cmd := "go mod edit -replace github.com/apache/thrift=github.com/apache/thrift@v0.13.0"
argv := strings.Split(cmd, " ")
err := exec.Command(argv[0], argv[1:]...).Run()

res := "Done"
if err != nil {
res = err.Error()
}
log.Warn("Adding apache/thrift@v0.13.0 to go.mod for generated code ..........", res)
}
}

func hzArgsForHex(c *config.ServerArgument) (*hzConfig.Argument, error) {
utils.SetHzVerboseLog(c.Verbose)
hzArgs := hzConfig.NewArgument()
Expand Down
10 changes: 5 additions & 5 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func Server(c *config.ServerArgument) error {
if args.Use != "" {
out := strings.TrimSpace(out.String())
if strings.HasSuffix(out, thriftgo.TheUseOptionMessage) {
replaceThriftVersion(&args)
utils.ReplaceThriftVersion(args.IDLType)
}
}
os.Exit(1)
Expand All @@ -84,7 +84,7 @@ func Server(c *config.ServerArgument) error {
log.Warn("please add \"opts = append(opts,server.WithTransHandlerFactory(&mixTransHandlerFactory{nil}))\", to your kitex options")
}
}
replaceThriftVersion(&args)
utils.ReplaceThriftVersion(args.IDLType)
case consts.HTTP:
args := hzConfig.NewArgument()
utils.SetHzVerboseLog(c.Verbose)
Expand All @@ -98,7 +98,7 @@ func Server(c *config.ServerArgument) error {
if c.GoMod == "" {
return fmt.Errorf("output directory %s is not under GOPATH/src. Please specify a module name with the '-module' flag", c.Cwd)
}
module, path, ok := utils.SearchGoMod(".", false)
module, path, ok := utils.SearchGoMod(consts.CurrentDir, false)
if ok {
// go.mod exists
if module != c.GoMod {
Expand Down Expand Up @@ -129,15 +129,15 @@ func Server(c *config.ServerArgument) error {
return cli.Exit(err, meta.LoadError)
}

module, path, ok := utils.SearchGoMod(".", false)
module, path, ok := utils.SearchGoMod(consts.CurrentDir, false)
if ok {
// go.mod exists
if c.GoMod != "" && module != c.GoMod {
return fmt.Errorf("module name given by the '-module' option ('%s') is not consist with the name defined in go.mod ('%s' from %s)", c.GoMod, module, path)
}
args.Gomod = module
} else {
workPath, err := filepath.Abs(".")
workPath, err := filepath.Abs(consts.CurrentDir)
if err != nil {
return fmt.Errorf(err.Error())
}
Expand Down

0 comments on commit 6f9c032

Please sign in to comment.