فهرست منبع

ci: add reviewdog (#1096)

Kevin Wan 3 سال پیش
والد
کامیت
65905b914d

+ 19 - 0
.github/workflows/reviewdog.yml

@@ -0,0 +1,19 @@
+name: reviewdog
+on: [pull_request]
+jobs:
+  staticcheck:
+    name: runner / staticcheck
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v2
+      - uses: reviewdog/action-staticcheck@v1
+        with:
+          github_token: ${{ secrets.github_token }}
+          # Change reviewdog reporter if you need [github-pr-check,github-check,github-pr-review].
+          reporter: github-pr-review
+          # Report all results.
+          filter_mode: nofilter
+          # Exit with 1 when it find at least one finding.
+          fail_on_error: true
+          # Set staticcheck flags
+          staticcheck_flags: -checks=inherit,-SA1019,-SA1029,-SA5008

+ 4 - 4
core/fx/stream_test.go

@@ -395,16 +395,16 @@ func assetEqual(t *testing.T, except, data interface{}) {
 
 func TestStream_AnyMach(t *testing.T) {
 	assetEqual(t, false, Just(1, 2, 3).AnyMach(func(item interface{}) bool {
-		return 4 == item.(int)
+		return item.(int) == 4
 	}))
 	assetEqual(t, false, Just(1, 2, 3).AnyMach(func(item interface{}) bool {
-		return 0 == item.(int)
+		return item.(int) == 0
 	}))
 	assetEqual(t, true, Just(1, 2, 3).AnyMach(func(item interface{}) bool {
-		return 2 == item.(int)
+		return item.(int) == 2
 	}))
 	assetEqual(t, true, Just(1, 2, 3).AnyMach(func(item interface{}) bool {
-		return 2 == item.(int)
+		return item.(int) == 2
 	}))
 }
 

+ 0 - 1
core/logx/rotatelogger.go

@@ -47,7 +47,6 @@ type (
 		done     chan lang.PlaceholderType
 		rule     RotateRule
 		compress bool
-		keepDays int
 		// can't use threading.RoutineGroup because of cycle import
 		waitGroup sync.WaitGroup
 		closeOnce sync.Once

+ 3 - 1
core/stat/internal/cpu_linux_test.go

@@ -7,7 +7,9 @@ import (
 )
 
 func TestRefreshCpu(t *testing.T) {
-	assert.True(t, RefreshCpu() >= 0)
+	assert.NotPanics(t, func() {
+		RefreshCpu()
+	})
 }
 
 func BenchmarkRefreshCpu(b *testing.B) {

+ 2 - 4
core/syncx/donechan_test.go

@@ -19,10 +19,8 @@ func TestDoneChanDone(t *testing.T) {
 
 	waitGroup.Add(1)
 	go func() {
-		select {
-		case <-doneChan.Done():
-			waitGroup.Done()
-		}
+		<-doneChan.Done()
+		waitGroup.Done()
 	}()
 
 	for i := 0; i < 5; i++ {

+ 0 - 2
core/syncx/spinlock_test.go

@@ -30,8 +30,6 @@ func TestSpinLockRace(t *testing.T) {
 	var wait sync.WaitGroup
 	wait.Add(1)
 	go func() {
-		lock.Lock()
-		lock.Unlock()
 		wait.Done()
 	}()
 	time.Sleep(time.Millisecond * 100)

+ 2 - 1
rest/handler/authhandler_test.go

@@ -16,7 +16,8 @@ func TestAuthHandlerFailed(t *testing.T) {
 	req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
 	handler := Authorize("B63F477D-BBA3-4E52-96D3-C0034C27694A", WithUnauthorizedCallback(
 		func(w http.ResponseWriter, r *http.Request, err error) {
-			w.Header().Set("X-Test", "test")
+			assert.NotNil(t, err)
+			w.Header().Set("X-Test", err.Error())
 			w.WriteHeader(http.StatusUnauthorized)
 			_, err = w.Write([]byte("content"))
 			assert.Nil(t, err)

+ 1 - 2
rest/handler/contentsecurityhandler_test.go

@@ -275,8 +275,7 @@ func TestContentSecurityHandler_UnsignedCallback_WrongTime(t *testing.T) {
 		})
 	handler := contentSecurityHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
 
-	var reader io.Reader
-	reader = strings.NewReader("hello")
+	reader := strings.NewReader("hello")
 	setting := requestSettings{
 		method:      http.MethodPost,
 		url:         "http://localhost/a/b?c=d&e=f",

+ 2 - 3
tools/goctl/api/gogen/genroutes.go

@@ -197,9 +197,8 @@ func getRoutes(api *spec.ApiSpec) ([]group, error) {
 		}
 		middleware := g.GetAnnotation("middleware")
 		if len(middleware) > 0 {
-			for _, item := range strings.Split(middleware, ",") {
-				groupedRoutes.middlewares = append(groupedRoutes.middlewares, item)
-			}
+			groupedRoutes.middlewares = append(groupedRoutes.middlewares,
+				strings.Split(middleware, ",")...)
 		}
 		routes = append(routes, groupedRoutes)
 	}

+ 0 - 6
tools/goctl/api/gogen/gensvc.go

@@ -39,12 +39,6 @@ func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpe
 		return err
 	}
 
-	authNames := getAuths(api)
-	var auths []string
-	for _, item := range authNames {
-		auths = append(auths, fmt.Sprintf("%s config.AuthConfig", item))
-	}
-
 	var middlewareStr string
 	var middlewareAssignment string
 	middlewares := getMiddleware(api)

+ 1 - 5
tools/goctl/api/javagen/gen.go

@@ -28,11 +28,7 @@ func JavaCommand(c *cli.Context) error {
 		return err
 	}
 
-	packetName := api.Service.Name
-	if strings.HasSuffix(packetName, "-api") {
-		packetName = packetName[:len(packetName)-4]
-	}
-
+	packetName := strings.TrimSuffix(api.Service.Name, "-api")
 	logx.Must(util.MkdirIfNotExist(dir))
 	logx.Must(genPacket(dir, packetName, api))
 	logx.Must(genComponents(dir, packetName, api))

+ 1 - 4
tools/goctl/api/javagen/genpacket.go

@@ -204,10 +204,7 @@ func processUri(route spec.Route) string {
 			}
 		}
 	}
-	result := builder.String()
-	if strings.HasSuffix(result, " + \"") {
-		result = result[:len(result)-4]
-	}
+	result := strings.TrimSuffix(builder.String(), " + \"")
 	if strings.HasPrefix(result, "/") {
 		result = strings.TrimPrefix(result, "/")
 		result = "\"" + result

+ 0 - 3
tools/goctl/api/parser/g4/ast/type.go

@@ -5,7 +5,6 @@ import (
 	"sort"
 
 	"github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/gen/api"
-	"github.com/tal-tech/go-zero/tools/goctl/api/util"
 )
 
 type (
@@ -155,8 +154,6 @@ func (v *ApiVisitor) VisitTypeStruct(ctx *api.TypeStructContext) interface{} {
 	var st TypeStruct
 	st.Name = v.newExprWithToken(ctx.GetStructName())
 
-	if util.UnExport(ctx.GetStructName().GetText()) {
-	}
 	if ctx.GetStructToken() != nil {
 		structExpr := v.newExprWithToken(ctx.GetStructToken())
 		structTokenText := ctx.GetStructToken().GetText()

+ 0 - 6
tools/goctl/api/parser/g4/gen/api/apiparser_parser.go

@@ -1087,7 +1087,6 @@ func (p *ApiParserParser) ImportBlock() (localctx IImportBlockContext) {
 	}
 	p.SetState(105)
 	p.GetErrorHandler().Sync(p)
-	_la = p.GetTokenStream().LA(1)
 
 	for ok := true; ok; ok = _la == ApiParserParserSTRING {
 		{
@@ -1447,7 +1446,6 @@ func (p *ApiParserParser) InfoSpec() (localctx IInfoSpecContext) {
 	}
 	p.SetState(120)
 	p.GetErrorHandler().Sync(p)
-	_la = p.GetTokenStream().LA(1)
 
 	for ok := true; ok; ok = _la == ApiParserParserID {
 		{
@@ -4102,7 +4100,6 @@ func (p *ApiParserParser) AtServer() (localctx IAtServerContext) {
 	}
 	p.SetState(245)
 	p.GetErrorHandler().Sync(p)
-	_la = p.GetTokenStream().LA(1)
 
 	for ok := true; ok; ok = _la == ApiParserParserID {
 		{
@@ -4627,7 +4624,6 @@ func (p *ApiParserParser) AtDoc() (localctx IAtDocContext) {
 	case ApiParserParserID:
 		p.SetState(277)
 		p.GetErrorHandler().Sync(p)
-		_la = p.GetTokenStream().LA(1)
 
 		for ok := true; ok; ok = _la == ApiParserParserID {
 			{
@@ -5461,7 +5457,6 @@ func (p *ApiParserParser) ServiceName() (localctx IServiceNameContext) {
 	p.EnterOuterAlt(localctx, 1)
 	p.SetState(322)
 	p.GetErrorHandler().Sync(p)
-	_la = p.GetTokenStream().LA(1)
 
 	for ok := true; ok; ok = _la == ApiParserParserID {
 		{
@@ -5575,7 +5570,6 @@ func (p *ApiParserParser) Path() (localctx IPathContext) {
 	p.EnterOuterAlt(localctx, 1)
 	p.SetState(341)
 	p.GetErrorHandler().Sync(p)
-	_la = p.GetTokenStream().LA(1)
 
 	for ok := true; ok; ok = _la == ApiParserParserT__10 || _la == ApiParserParserT__11 {
 		p.SetState(341)

+ 1 - 2
tools/goctl/docker/docker.go

@@ -11,7 +11,6 @@ import (
 
 	"github.com/logrusorgru/aurora"
 	"github.com/tal-tech/go-zero/tools/goctl/util"
-	ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
 	"github.com/urfave/cli"
 )
 
@@ -128,7 +127,7 @@ func generateDockerfile(goFile string, port int, args ...string) error {
 	}
 	defer out.Close()
 
-	text, err := ctlutil.LoadTemplate(category, dockerTemplateFile, dockerTemplate)
+	text, err := util.LoadTemplate(category, dockerTemplateFile, dockerTemplate)
 	if err != nil {
 		return err
 	}

+ 2 - 2
tools/goctl/model/sql/builderx/builder.go

@@ -105,13 +105,13 @@ func RawFieldNames(in interface{}, postgresSql ...bool) []string {
 		fi := typ.Field(i)
 		if tagv := fi.Tag.Get(dbTag); tagv != "" {
 			if pg {
-				out = append(out, fmt.Sprintf("%s", tagv))
+				out = append(out, tagv)
 			} else {
 				out = append(out, fmt.Sprintf("`%s`", tagv))
 			}
 		} else {
 			if pg {
-				out = append(out, fmt.Sprintf("%s", fi.Name))
+				out = append(out, fi.Name)
 			} else {
 				out = append(out, fmt.Sprintf("`%s`", fi.Name))
 			}

+ 0 - 22
tools/goctl/model/sql/gen/split.go

@@ -1,22 +0,0 @@
-package gen
-
-import "regexp"
-
-func (g *defaultGenerator) split(source string) []string {
-	reg := regexp.MustCompile(createTableFlag)
-	index := reg.FindAllStringIndex(source, -1)
-	list := make([]string, 0)
-
-	for i := len(index) - 1; i >= 0; i-- {
-		subIndex := index[i]
-		if len(subIndex) == 0 {
-			continue
-		}
-		start := subIndex[0]
-		ddl := source[start:]
-		list = append(list, ddl)
-		source = source[:start]
-	}
-
-	return list
-}

+ 0 - 10
tools/goctl/model/sql/test/utils.go

@@ -14,16 +14,6 @@ import (
 // ErrNotFound is the alias of sql.ErrNoRows
 var ErrNotFound = sql.ErrNoRows
 
-func desensitize(datasource string) string {
-	// remove account
-	pos := strings.LastIndex(datasource, "@")
-	if 0 <= pos && pos+1 < len(datasource) {
-		datasource = datasource[pos+1:]
-	}
-
-	return datasource
-}
-
 func escape(input string) string {
 	var b strings.Builder
 

+ 1 - 1
tools/goctl/rpc/generator/genpb.go

@@ -102,7 +102,7 @@ func (g *DefaultGenerator) GenPb(ctx DirContext, protoImportPath []string, proto
 	_, err = execx.Run(command, "")
 	if err != nil {
 		if strings.Contains(err.Error(), googleProtocGenGoErr) {
-			return errors.New(`Unsupported plugin protoc-gen-go which installed from the following source:
+			return errors.New(`unsupported plugin protoc-gen-go which installed from the following source:
 google.golang.org/protobuf/cmd/protoc-gen-go, 
 github.com/protocolbuffers/protobuf-go/cmd/protoc-gen-go;
 

+ 1 - 0
tools/goctl/util/path_test.go

@@ -11,6 +11,7 @@ import (
 
 func TestReadLink(t *testing.T) {
 	dir, err := ioutil.TempDir("", "go-zero")
+	assert.Nil(t, err)
 	symLink := filepath.Join(dir, "test")
 	pwd, err := os.Getwd()
 	assertError(err, t)

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

@@ -13,10 +13,9 @@ const regularPerm = 0o666
 
 // DefaultTemplate is a tool to provides the text/template operations
 type DefaultTemplate struct {
-	name     string
-	text     string
-	goFmt    bool
-	savePath string
+	name  string
+	text  string
+	goFmt bool
 }
 
 // With returns a instance of DefaultTemplate
@@ -70,7 +69,7 @@ func (t *DefaultTemplate) Execute(data interface{}) (*bytes.Buffer, error) {
 
 	formatOutput, err := goformat.Source(buf.Bytes())
 	if err != nil {
-		return nil, errorx.Wrap(err, "go format error:", string(buf.Bytes()))
+		return nil, errorx.Wrap(err, "go format error:", buf.String())
 	}
 
 	buf.Reset()

+ 1 - 1
zrpc/client_test.go

@@ -64,7 +64,7 @@ func TestDepositServer_Deposit(t *testing.T) {
 			2000.00,
 			nil,
 			codes.DeadlineExceeded,
-			fmt.Sprintf("context deadline exceeded"),
+			"context deadline exceeded",
 		},
 	}
 

+ 1 - 1
zrpc/internal/serverinterceptors/tracinginterceptor.go

@@ -45,7 +45,7 @@ func StreamTracingInterceptor(serviceName string) grpc.StreamServerInterceptor {
 			return handler(srv, ss)
 		}
 
-		ctx, span := trace.StartServerSpan(ctx, carrier, serviceName, info.FullMethod)
+		_, span := trace.StartServerSpan(ctx, carrier, serviceName, info.FullMethod)
 		defer span.Finish()
 		return handler(srv, ss)
 	}