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>
master
anqiansong 3 years ago committed by GitHub
parent b42f3fa047
commit 8829c31c0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -7,7 +7,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "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/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"
"github.com/tal-tech/go-zero/tools/goctl/util/format" "github.com/tal-tech/go-zero/tools/goctl/util/format"
"github.com/tal-tech/go-zero/tools/goctl/vars" "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) 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) // 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{ return doGenToFile(dir, handler, cfg, group, route, handlerInfo{
ImportPackages: genHandlerImports(group, route, rootPkg), ImportPackages: genHandlerImports(group, route, rootPkg),
HandlerName: handler, 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))) 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) // 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)) imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceURL))
} }

@ -6,6 +6,8 @@ import (
"runtime" "runtime"
"github.com/logrusorgru/aurora" "github.com/logrusorgru/aurora"
"github.com/urfave/cli"
"github.com/tal-tech/go-zero/core/load" "github.com/tal-tech/go-zero/core/load"
"github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stat" "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/api/validate"
"github.com/tal-tech/go-zero/tools/goctl/configgen" "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/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/kube"
"github.com/tal-tech/go-zero/tools/goctl/model/mongo" "github.com/tal-tech/go-zero/tools/goctl/model/mongo"
model "github.com/tal-tech/go-zero/tools/goctl/model/sql/command" 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" 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/tpl"
"github.com/tal-tech/go-zero/tools/goctl/upgrade" "github.com/tal-tech/go-zero/tools/goctl/upgrade"
"github.com/urfave/cli"
) )
var ( var (
buildVersion = "1.1.11-beta-1" commands = []cli.Command{
commands = []cli.Command{
{ {
Name: "upgrade", Name: "upgrade",
Usage: "upgrade goctl to latest version", Usage: "upgrade goctl to latest version",
@ -648,14 +650,10 @@ func main() {
app := cli.NewApp() app := cli.NewApp()
app.Usage = "a cli tool to generate code" 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 app.Commands = commands
// cli already print error messages // cli already print error messages
if err := app.Run(os.Args); err != nil { 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)
}

@ -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)
}

@ -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"))
}

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

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

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

Loading…
Cancel
Save