fix golint issues, else blocks (#457)

This commit is contained in:
Kevin Wan
2021-02-09 13:50:21 +08:00
committed by GitHub
parent 42883d0899
commit 5e969cbef0
66 changed files with 341 additions and 311 deletions

View File

@@ -21,7 +21,7 @@ func DocCommand(c *cli.Context) error {
files, err := filePathWalkDir(dir)
if err != nil {
return errors.New(fmt.Sprintf("dir %s not exist", dir))
return fmt.Errorf("dir %s not exist", dir)
}
err = os.RemoveAll(dir + "/" + docDir + "/")
@@ -31,7 +31,7 @@ func DocCommand(c *cli.Context) error {
for _, f := range files {
api, err := parser.Parse(f)
if err != nil {
return errors.New(fmt.Sprintf("parse file: %s, err: %s", f, err.Error()))
return fmt.Errorf("parse file: %s, err: %s", f, err.Error())
}
index := strings.Index(f, dir)

View File

@@ -1,7 +1,6 @@
package gogen
import (
"errors"
"fmt"
"io"
"os"
@@ -76,7 +75,7 @@ func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
func writeType(writer io.Writer, tp spec.Type) error {
structType, ok := tp.(spec.DefineStruct)
if !ok {
return errors.New(fmt.Sprintf("unspport struct type: %s", tp.Name()))
return fmt.Errorf("unspport struct type: %s", tp.Name())
}
fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name()))
@@ -84,9 +83,9 @@ func writeType(writer io.Writer, tp spec.Type) error {
if member.IsInline {
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
return err
} else {
continue
}
continue
}
if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil {

View File

@@ -216,7 +216,7 @@ func (c *componentsContext) writeMembers(writer io.Writer, tp spec.Type, indent
if ok {
return c.writeMembers(writer, pointType.Type, indent)
}
return errors.New(fmt.Sprintf("type %s not supported", tp.Name()))
return fmt.Errorf("type %s not supported", tp.Name())
}
for _, member := range definedType.Members {

View File

@@ -203,41 +203,40 @@ func (e *defaultExpr) IsNotNil() bool {
func EqualDoc(spec1, spec2 Spec) bool {
if spec1 == nil {
if spec2 != nil {
return spec2 == nil
}
if spec2 == nil {
return false
}
var expectDoc, actualDoc []Expr
expectDoc = append(expectDoc, spec2.Doc()...)
actualDoc = append(actualDoc, spec1.Doc()...)
sort.Slice(expectDoc, func(i, j int) bool {
return expectDoc[i].Line() < expectDoc[j].Line()
})
for index, each := range actualDoc {
if !each.Equal(actualDoc[index]) {
return false
}
return true
} else {
if spec2 == nil {
return false
}
var expectDoc, actualDoc []Expr
expectDoc = append(expectDoc, spec2.Doc()...)
actualDoc = append(actualDoc, spec1.Doc()...)
sort.Slice(expectDoc, func(i, j int) bool {
return expectDoc[i].Line() < expectDoc[j].Line()
})
for index, each := range actualDoc {
if !each.Equal(actualDoc[index]) {
return false
}
}
if spec1.Comment() != nil {
if spec2.Comment() == nil {
return false
}
if !spec1.Comment().Equal(spec2.Comment()) {
return false
}
} else {
if spec2.Comment() != nil {
return false
}
}
}
if spec1.Comment() != nil {
if spec2.Comment() == nil {
return false
}
if !spec1.Comment().Equal(spec2.Comment()) {
return false
}
} else {
if spec2.Comment() != nil {
return false
}
}
return true
}
@@ -295,8 +294,10 @@ func (v *ApiVisitor) getHiddenTokensToLeft(t TokenStream, channel int, containsC
}
}
}
list = append(list, v.newExprWithToken(each))
}
return list
}
@@ -307,6 +308,7 @@ func (v *ApiVisitor) getHiddenTokensToRight(t TokenStream, channel int) []Expr {
for _, each := range tokens {
list = append(list, v.newExprWithToken(each))
}
return list
}
@@ -314,6 +316,7 @@ func (v *ApiVisitor) exportCheck(expr Expr) {
if expr == nil || !expr.IsNotNil() {
return
}
if api.IsBasicType(expr.Text()) {
return
}

View File

@@ -508,9 +508,9 @@ func (s *ServiceRoute) Format() error {
func (s *ServiceRoute) GetHandler() Expr {
if s.AtHandler != nil {
return s.AtHandler.Name
} else {
return s.AtServer.Kv.Get("handler")
}
return s.AtServer.Kv.Get("handler")
}
func (a *ServiceApi) Format() error {

View File

@@ -1,7 +1,6 @@
package parser
import (
"errors"
"fmt"
"path/filepath"
"unicode"
@@ -101,7 +100,7 @@ func (p parser) fillTypes() error {
Docs: p.stringExprs(v.Doc()),
})
default:
return errors.New(fmt.Sprintf("unknown type %+v", v))
return fmt.Errorf("unknown type %+v", v)
}
}
@@ -116,16 +115,16 @@ func (p parser) fillTypes() error {
tp, err := p.findDefinedType(v.RawName)
if err != nil {
return err
} else {
member.Type = *tp
}
member.Type = *tp
}
members = append(members, member)
}
v.Members = members
types = append(types, v)
default:
return errors.New(fmt.Sprintf("unknown type %+v", v))
return fmt.Errorf("unknown type %+v", v)
}
}
p.spec.Types = types
@@ -141,7 +140,8 @@ func (p parser) findDefinedType(name string) (*spec.Type, error) {
}
}
}
return nil, errors.New(fmt.Sprintf("type %s not defined", name))
return nil, fmt.Errorf("type %s not defined", name)
}
func (p parser) fieldToMember(field *ast.TypeField) spec.Member {
@@ -172,9 +172,9 @@ func (p parser) astTypeToSpec(in ast.DataType) spec.Type {
raw := v.Literal.Text()
if api.IsBasicType(raw) {
return spec.PrimitiveType{RawName: raw}
} else {
return spec.DefineStruct{RawName: raw}
}
return spec.DefineStruct{RawName: raw}
case *ast.Interface:
return spec.InterfaceType{RawName: v.Literal.Text()}
case *ast.Map:
@@ -185,9 +185,9 @@ func (p parser) astTypeToSpec(in ast.DataType) spec.Type {
raw := v.Name.Text()
if api.IsBasicType(raw) {
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.PrimitiveType{RawName: raw}}
} else {
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}}
}
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}}
}
panic(fmt.Sprintf("unspported type %+v", in))
@@ -246,8 +246,8 @@ func (p parser) fillService() error {
for _, char := range route.Handler {
if !unicode.IsDigit(char) && !unicode.IsLetter(char) {
return errors.New(fmt.Sprintf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
route.Path, route.Handler))
return fmt.Errorf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
route.Path, route.Handler)
}
}
}
@@ -278,7 +278,7 @@ func (p parser) fillService() error {
name := item.ServiceApi.Name.Text()
if len(p.spec.Service.Name) > 0 && p.spec.Service.Name != name {
return errors.New(fmt.Sprintf("mulit service name defined %s and %s", name, p.spec.Service.Name))
return fmt.Errorf("mulit service name defined %s and %s", name, p.spec.Service.Name)
}
p.spec.Service.Name = name
}

View File

@@ -160,11 +160,11 @@ func pathForRoute(route spec.Route, group spec.Group) string {
prefix := group.GetAnnotation("pathPrefix")
if len(prefix) == 0 {
return "\"" + route.Path + "\""
} else {
prefix = strings.TrimPrefix(prefix, `"`)
prefix = strings.TrimSuffix(prefix, `"`)
return fmt.Sprintf(`"%s/%s"`, prefix, strings.TrimPrefix(route.Path, "/"))
}
prefix = strings.TrimPrefix(prefix, `"`)
prefix = strings.TrimSuffix(prefix, `"`)
return fmt.Sprintf(`"%s/%s"`, prefix, strings.TrimPrefix(route.Path, "/"))
}
func pathHasParams(route spec.Route) bool {

View File

@@ -146,7 +146,8 @@ func writeMembers(writer io.Writer, tp spec.Type, isParam bool) error {
if ok {
return writeMembers(writer, pointType.Type, isParam)
}
return errors.New(fmt.Sprintf("type %s not supported", tp.Name()))
return fmt.Errorf("type %s not supported", tp.Name())
}
members := definedType.GetBodyMembers()

View File

@@ -19,20 +19,20 @@ func genImports(withCache, timeImport bool) (string, error) {
return "", err
}
return buffer.String(), nil
} else {
text, err := util.LoadTemplate(category, importsWithNoCacheTemplateFile, template.ImportsNoCache)
if err != nil {
return "", err
}
buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{
"time": timeImport,
})
if err != nil {
return "", err
}
return buffer.String(), nil
}
text, err := util.LoadTemplate(category, importsWithNoCacheTemplateFile, template.ImportsNoCache)
if err != nil {
return "", err
}
buffer, err := util.With("import").Parse(text).Execute(map[string]interface{}{
"time": timeImport,
})
if err != nil {
return "", err
}
return buffer.String(), nil
}

View File

@@ -5,7 +5,7 @@ import (
)
var (
unSupportDDL = errors.New("unexpected type")
tableBodyIsNotFound = errors.New("create table spec not found")
errPrimaryKey = errors.New("unexpected join primary key")
errUnsupportDDL = errors.New("unexpected type")
errTableBodyNotFound = errors.New("create table spec not found")
errPrimaryKey = errors.New("unexpected join primary key")
)

View File

@@ -52,7 +52,7 @@ func Parse(ddl string) (*Table, error) {
ddlStmt, ok := stmt.(*sqlparser.DDL)
if !ok {
return nil, unSupportDDL
return nil, errUnsupportDDL
}
action := ddlStmt.Action
@@ -63,7 +63,7 @@ func Parse(ddl string) (*Table, error) {
tableName := ddlStmt.NewName.Name.String()
tableSpec := ddlStmt.TableSpec
if tableSpec == nil {
return nil, tableBodyIsNotFound
return nil, errTableBodyNotFound
}
columns := tableSpec.Columns

View File

@@ -14,7 +14,7 @@ func TestParsePlainText(t *testing.T) {
func TestParseSelect(t *testing.T) {
_, err := Parse("select * from user")
assert.Equal(t, unSupportDDL, err)
assert.Equal(t, errUnsupportDDL, err)
}
func TestParseCreateTable(t *testing.T) {

View File

@@ -39,10 +39,9 @@ func forChksumHandler(file string, next http.Handler) http.Handler {
if chksum == r.Header.Get(contentMd5Header) {
w.WriteHeader(http.StatusNotModified)
return
} else {
w.Header().Set(contentMd5Header, chksum)
}
w.Header().Set(contentMd5Header, chksum)
next.ServeHTTP(w, r)
})
}

View File

@@ -7,21 +7,19 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
)
var moduleCheckErr = errors.New("the work directory must be found in the go mod or the $GOPATH")
var errModuleCheck = errors.New("the work directory must be found in the go mod or the $GOPATH")
type (
ProjectContext struct {
WorkDir string
// Name is the root name of the project
// eg: go-zero、greet
Name string
// Path identifies which module a project belongs to, which is module value if it's a go mod project,
// or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet
Path string
// Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
Dir string
}
)
type ProjectContext struct {
WorkDir string
// Name is the root name of the project
// eg: go-zero、greet
Name string
// Path identifies which module a project belongs to, which is module value if it's a go mod project,
// or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet
Path string
// Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
Dir string
}
// Prepare checks the project which module belongs to,and returns the path and module.
// workDir parameter is the directory of the source of generating code,

View File

@@ -25,7 +25,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) {
goPath := buildContext.GOPATH
goSrc := filepath.Join(goPath, "src")
if !util.FileExists(goSrc) {
return nil, moduleCheckErr
return nil, errModuleCheck
}
wd, err := filepath.Abs(workDir)
@@ -34,7 +34,7 @@ func projectFromGoPath(workDir string) (*ProjectContext, error) {
}
if !strings.HasPrefix(wd, goSrc) {
return nil, moduleCheckErr
return nil, errModuleCheck
}
projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator))