Pārlūkot izejas kodu

Feature goctl error wrap (#995)

* Add `Wrap` in file errorx.go

* Wrap error with `GoctlError`

* format code

* Refactor package `env` to `version`

* Refactor package `IsVersionGatherThan`

* fix typo

Co-authored-by: anqiansong <anqiansong@bytedance.com>
anqiansong 3 gadi atpakaļ
vecāks
revīzija
8829c31c0d

+ 5 - 5
tools/goctl/api/gogen/genhandlers.go

@@ -7,7 +7,7 @@ import (
 
 	"github.com/tal-tech/go-zero/tools/goctl/api/spec"
 	"github.com/tal-tech/go-zero/tools/goctl/config"
-	"github.com/tal-tech/go-zero/tools/goctl/internal/env"
+	"github.com/tal-tech/go-zero/tools/goctl/internal/version"
 	"github.com/tal-tech/go-zero/tools/goctl/util"
 	"github.com/tal-tech/go-zero/tools/goctl/util/format"
 	"github.com/tal-tech/go-zero/tools/goctl/vars"
@@ -58,9 +58,9 @@ func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route
 		handler = strings.Title(handler)
 	}
 
-	goctlVersion := env.GetGoctlVersion()
+	goctlVersion := version.GetGoctlVersion()
 	// todo(anqiansong): This will be removed after a certain number of production versions of goctl (probably 5)
-	after1_1_10 := env.IsVersionGatherThan(goctlVersion, "1.1.10")
+	after1_1_10 := version.IsVersionGreaterThan(goctlVersion, "1.1.10")
 	return doGenToFile(dir, handler, cfg, group, route, handlerInfo{
 		ImportPackages: genHandlerImports(group, route, rootPkg),
 		HandlerName:    handler,
@@ -113,9 +113,9 @@ func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) str
 		imports = append(imports, fmt.Sprintf("\"%s\"\n", util.JoinPackages(parentPkg, typesDir)))
 	}
 
-	currentVersion := env.GetGoctlVersion()
+	currentVersion := version.GetGoctlVersion()
 	// todo(anqiansong): This will be removed after a certain number of production versions of goctl (probably 5)
-	if !env.IsVersionGatherThan(currentVersion, "1.1.10") {
+	if !version.IsVersionGreaterThan(currentVersion, "1.1.10") {
 		imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceURL))
 	}
 

+ 7 - 9
tools/goctl/goctl.go

@@ -6,6 +6,8 @@ import (
 	"runtime"
 
 	"github.com/logrusorgru/aurora"
+	"github.com/urfave/cli"
+
 	"github.com/tal-tech/go-zero/core/load"
 	"github.com/tal-tech/go-zero/core/logx"
 	"github.com/tal-tech/go-zero/core/stat"
@@ -21,6 +23,8 @@ import (
 	"github.com/tal-tech/go-zero/tools/goctl/api/validate"
 	"github.com/tal-tech/go-zero/tools/goctl/configgen"
 	"github.com/tal-tech/go-zero/tools/goctl/docker"
+	"github.com/tal-tech/go-zero/tools/goctl/internal/errorx"
+	"github.com/tal-tech/go-zero/tools/goctl/internal/version"
 	"github.com/tal-tech/go-zero/tools/goctl/kube"
 	"github.com/tal-tech/go-zero/tools/goctl/model/mongo"
 	model "github.com/tal-tech/go-zero/tools/goctl/model/sql/command"
@@ -28,12 +32,10 @@ import (
 	rpc "github.com/tal-tech/go-zero/tools/goctl/rpc/cli"
 	"github.com/tal-tech/go-zero/tools/goctl/tpl"
 	"github.com/tal-tech/go-zero/tools/goctl/upgrade"
-	"github.com/urfave/cli"
 )
 
 var (
-	buildVersion = "1.1.11-beta-1"
-	commands     = []cli.Command{
+	commands = []cli.Command{
 		{
 			Name:   "upgrade",
 			Usage:  "upgrade goctl to latest version",
@@ -648,14 +650,10 @@ func main() {
 
 	app := cli.NewApp()
 	app.Usage = "a cli tool to generate code"
-	app.Version = fmt.Sprintf("%s %s/%s", buildVersion, runtime.GOOS, runtime.GOARCH)
+	app.Version = fmt.Sprintf("%s %s/%s", version.BuildVersion, runtime.GOOS, runtime.GOARCH)
 	app.Commands = commands
 	// cli already print error messages
 	if err := app.Run(os.Args); err != nil {
-		fmt.Println(aurora.Red("error: " + err.Error()))
+		fmt.Println(aurora.Red(errorx.Wrap(err).Error()))
 	}
 }
-
-func init() {
-	os.Setenv("GOCTL_VERSION", buildVersion)
-}

+ 15 - 0
tools/goctl/internal/errorx/errorx._test.go

@@ -0,0 +1,15 @@
+package errorx
+
+import (
+	"errors"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestWrap(t *testing.T) {
+	err := errors.New("foo")
+	err = Wrap(err)
+	_, ok := err.(*GoctlError)
+	assert.True(t, ok)
+}

+ 44 - 0
tools/goctl/internal/errorx/errorx.go

@@ -0,0 +1,44 @@
+package errorx
+
+import (
+	"fmt"
+	"runtime"
+	"strings"
+
+	"github.com/tal-tech/go-zero/tools/goctl/internal/version"
+)
+
+var errorFormat = `goctl: generation error: %+v
+goctl version: %s
+%s`
+
+type GoctlError struct {
+	message []string
+	err     error
+}
+
+func (e *GoctlError) Error() string {
+	detail := wrapMessage(e.message...)
+	v := fmt.Sprintf("%s %s/%s", version.BuildVersion, runtime.GOOS, runtime.GOARCH)
+	return fmt.Sprintf(errorFormat, e.err, v, detail)
+}
+
+// Wrap wraps an error with goctl version and message.
+func Wrap(err error, message ...string) error {
+	e, ok := err.(*GoctlError)
+	if ok {
+		return e
+	}
+
+	return &GoctlError{
+		message: message,
+		err:     err,
+	}
+}
+
+func wrapMessage(message ...string) string {
+	if len(message) == 0 {
+		return ""
+	}
+	return fmt.Sprintf(`message: %s`, strings.Join(message, "\n"))
+}

+ 8 - 14
tools/goctl/internal/env/env.go → tools/goctl/internal/version/version.go

@@ -1,28 +1,22 @@
-package env
+package version
 
 import (
 	"encoding/json"
-	"os"
 	"strings"
 )
 
-// GetGoctlVersion obtains from the environment variable GOCTL_VERSION, prior to 1.1.11,
-// the goctl version was 1.1.10 by default.
-// the goctl version is set at runtime in the environment variable GOCTL_VERSION,
-// see the detail at https://github.com/tal-tech/go-zero/blob/master/tools/goctl/goctl.go
+const BuildVersion = "1.1.11-beta-2"
+
+// GetGoctlVersion returns BuildVersion
 func GetGoctlVersion() string {
-	currentVersion := os.Getenv("GOCTL_VERSION")
-	if currentVersion == "" {
-		currentVersion = "1.1.10"
-	}
-	return currentVersion
+	return BuildVersion
 }
 
 var tag = map[string]int{"pre-alpha": 0, "alpha": 1, "pre-bata": 2, "beta": 3, "released": 4, "": 5}
 
-// IsVersionGatherThan compares whether the current goctl version
-// is gather than the target version
-func IsVersionGatherThan(version, target string) bool {
+// IsVersionGreaterThan compares whether the current goctl version
+// is greater than the target version
+func IsVersionGreaterThan(version, target string) bool {
 	versionNumber, versionTag := convertVersion(version)
 	targetVersionNumber, targetTag := convertVersion(target)
 	if versionNumber > targetVersionNumber {

+ 6 - 6
tools/goctl/internal/env/env_test.go → tools/goctl/internal/version/version_test.go

@@ -1,4 +1,4 @@
-package env
+package version
 
 import (
 	"testing"
@@ -25,9 +25,9 @@ func Test_convertVersion(t *testing.T) {
 }
 
 func Test_IsVersionGatherThan(t *testing.T) {
-	assert.False(t, IsVersionGatherThan("0.11", "1.1"))
-	assert.True(t, IsVersionGatherThan("0.112", "0.1"))
-	assert.True(t, IsVersionGatherThan("1.1.10", "1.0.111"))
-	assert.True(t, IsVersionGatherThan("1.1.10", "1.1.10-pre"))
-	assert.True(t, IsVersionGatherThan("1.1.11-pre", "1.1.10"))
+	assert.False(t, IsVersionGreaterThan("0.11", "1.1"))
+	assert.True(t, IsVersionGreaterThan("0.112", "0.1"))
+	assert.True(t, IsVersionGreaterThan("1.1.10", "1.0.111"))
+	assert.True(t, IsVersionGreaterThan("1.1.10", "1.1.10-pre"))
+	assert.True(t, IsVersionGreaterThan("1.1.11-pre", "1.1.10"))
 }

+ 5 - 3
tools/goctl/util/templatex.go

@@ -5,6 +5,8 @@ import (
 	goformat "go/format"
 	"io/ioutil"
 	"text/template"
+
+	"github.com/tal-tech/go-zero/tools/goctl/internal/errorx"
 )
 
 const regularPerm = 0o666
@@ -54,12 +56,12 @@ func (t *DefaultTemplate) SaveTo(data interface{}, path string, forceUpdate bool
 func (t *DefaultTemplate) Execute(data interface{}) (*bytes.Buffer, error) {
 	tem, err := template.New(t.name).Parse(t.text)
 	if err != nil {
-		return nil, err
+		return nil, errorx.Wrap(err, "template parse error:", t.text)
 	}
 
 	buf := new(bytes.Buffer)
 	if err = tem.Execute(buf, data); err != nil {
-		return nil, err
+		return nil, errorx.Wrap(err, "template execute error:", t.text)
 	}
 
 	if !t.goFmt {
@@ -68,7 +70,7 @@ func (t *DefaultTemplate) Execute(data interface{}) (*bytes.Buffer, error) {
 
 	formatOutput, err := goformat.Source(buf.Bytes())
 	if err != nil {
-		return nil, err
+		return nil, errorx.Wrap(err, "go format error:", string(buf.Bytes()))
 	}
 
 	buf.Reset()