diff --git a/.github/workflows/reviewdog.yml b/.github/workflows/reviewdog.yml new file mode 100644 index 00000000..43a92646 --- /dev/null +++ b/.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 diff --git a/core/fx/stream_test.go b/core/fx/stream_test.go index dab08c89..4bc37f88 100644 --- a/core/fx/stream_test.go +++ b/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 })) } diff --git a/core/logx/rotatelogger.go b/core/logx/rotatelogger.go index 3219ca96..f7a4bfe0 100644 --- a/core/logx/rotatelogger.go +++ b/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 diff --git a/core/stat/internal/cpu_linux_test.go b/core/stat/internal/cpu_linux_test.go index 20be6f45..2a81457a 100644 --- a/core/stat/internal/cpu_linux_test.go +++ b/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) { diff --git a/core/syncx/donechan_test.go b/core/syncx/donechan_test.go index 3f7520b9..2db0f151 100644 --- a/core/syncx/donechan_test.go +++ b/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++ { diff --git a/core/syncx/spinlock_test.go b/core/syncx/spinlock_test.go index 5ca99d84..4fcc2bf9 100644 --- a/core/syncx/spinlock_test.go +++ b/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) diff --git a/rest/handler/authhandler_test.go b/rest/handler/authhandler_test.go index b0985e7e..53a8b7ba 100644 --- a/rest/handler/authhandler_test.go +++ b/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) diff --git a/rest/handler/contentsecurityhandler_test.go b/rest/handler/contentsecurityhandler_test.go index ca3e9aaf..4311d9ef 100644 --- a/rest/handler/contentsecurityhandler_test.go +++ b/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", diff --git a/tools/goctl/api/gogen/genroutes.go b/tools/goctl/api/gogen/genroutes.go index 3ce3ec0d..531c5426 100644 --- a/tools/goctl/api/gogen/genroutes.go +++ b/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) } diff --git a/tools/goctl/api/gogen/gensvc.go b/tools/goctl/api/gogen/gensvc.go index 2686596c..45bb99b1 100644 --- a/tools/goctl/api/gogen/gensvc.go +++ b/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) diff --git a/tools/goctl/api/javagen/gen.go b/tools/goctl/api/javagen/gen.go index fd88087e..2152d373 100644 --- a/tools/goctl/api/javagen/gen.go +++ b/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)) diff --git a/tools/goctl/api/javagen/genpacket.go b/tools/goctl/api/javagen/genpacket.go index 1f0e4422..f6b378b5 100644 --- a/tools/goctl/api/javagen/genpacket.go +++ b/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 diff --git a/tools/goctl/api/parser/g4/ast/type.go b/tools/goctl/api/parser/g4/ast/type.go index d2a18986..89055f1f 100644 --- a/tools/goctl/api/parser/g4/ast/type.go +++ b/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() diff --git a/tools/goctl/api/parser/g4/gen/api/apiparser_parser.go b/tools/goctl/api/parser/g4/gen/api/apiparser_parser.go index 938d3996..1a844b70 100644 --- a/tools/goctl/api/parser/g4/gen/api/apiparser_parser.go +++ b/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) diff --git a/tools/goctl/docker/docker.go b/tools/goctl/docker/docker.go index 2d36583f..c2befbac 100644 --- a/tools/goctl/docker/docker.go +++ b/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 } diff --git a/tools/goctl/model/sql/builderx/builder.go b/tools/goctl/model/sql/builderx/builder.go index bcf38015..be569f7c 100644 --- a/tools/goctl/model/sql/builderx/builder.go +++ b/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)) } diff --git a/tools/goctl/model/sql/gen/split.go b/tools/goctl/model/sql/gen/split.go deleted file mode 100644 index f3358540..00000000 --- a/tools/goctl/model/sql/gen/split.go +++ /dev/null @@ -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 -} diff --git a/tools/goctl/model/sql/test/utils.go b/tools/goctl/model/sql/test/utils.go index 94927967..46af015b 100644 --- a/tools/goctl/model/sql/test/utils.go +++ b/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 diff --git a/tools/goctl/rpc/generator/genpb.go b/tools/goctl/rpc/generator/genpb.go index 289b8067..f7c34354 100644 --- a/tools/goctl/rpc/generator/genpb.go +++ b/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; diff --git a/tools/goctl/util/path_test.go b/tools/goctl/util/path_test.go index 55c7be1c..c3f103d7 100644 --- a/tools/goctl/util/path_test.go +++ b/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) diff --git a/tools/goctl/util/templatex.go b/tools/goctl/util/templatex.go index d9aa5252..33d2dc23 100644 --- a/tools/goctl/util/templatex.go +++ b/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() diff --git a/zrpc/client_test.go b/zrpc/client_test.go index dc1f08e1..ba715826 100644 --- a/zrpc/client_test.go +++ b/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", }, } diff --git a/zrpc/internal/serverinterceptors/tracinginterceptor.go b/zrpc/internal/serverinterceptors/tracinginterceptor.go index 9ae9cdf1..0cd653a6 100644 --- a/zrpc/internal/serverinterceptors/tracinginterceptor.go +++ b/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) }