Skip to content

Commit

Permalink
lint fix
Browse files Browse the repository at this point in the history
  • Loading branch information
rez1dent3 committed Dec 18, 2023
1 parent 8e33f48 commit f5348f2
Show file tree
Hide file tree
Showing 15 changed files with 117 additions and 55 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ linters:
- exhaustruct
linters-settings:
lll:
line-length: 160
line-length: 140
gci:
sections:
- Standard
Expand Down
3 changes: 2 additions & 1 deletion example/multi-files/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import (
"log"
"time"

pb "github.com/bavix/gripmock/protogen/example/multi-files"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

pb "github.com/bavix/gripmock/protogen/example/multi-files"
)

//nolint:gomnd
Expand Down
5 changes: 3 additions & 2 deletions example/multi-package/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import (
"os"
"time"

pb "github.com/bavix/gripmock/protogen/example/multi-package"
multi_package "github.com/bavix/gripmock/protogen/example/multi-package/bar"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

pb "github.com/bavix/gripmock/protogen/example/multi-package"
multi_package "github.com/bavix/gripmock/protogen/example/multi-package/bar"
)

//nolint:gomnd
Expand Down
3 changes: 2 additions & 1 deletion example/one-of/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import (
"os"
"time"

oneof "github.com/bavix/gripmock/protogen/example/one-of"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

oneof "github.com/bavix/gripmock/protogen/example/one-of"
)

//nolint:gomnd
Expand Down
3 changes: 2 additions & 1 deletion example/well_known_types/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import (
"log"
"time"

pb "github.com/bavix/gripmock/protogen/example/well_known_types"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
empty "google.golang.org/protobuf/types/known/emptypb"

pb "github.com/bavix/gripmock/protogen/example/well_known_types"
)

// in order to generate this .pb.go you need to have https://github.com/google/protobuf.git cloned
Expand Down
19 changes: 14 additions & 5 deletions internal/app/rest_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package app
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
Expand All @@ -20,6 +21,11 @@ import (
"golang.org/x/text/language"
)

var (
ErrServiceIsMissing = errors.New("service name is missing")
ErrMethodIsMissing = errors.New("method name is missing")
)

type StubsServer struct {
stubs *storage.StubStorage
convertor *yaml2json.Convertor
Expand Down Expand Up @@ -48,7 +54,7 @@ func NewRestServer(path string) (*StubsServer, error) {
return server, nil
}

// deprecated code
// deprecated code.
type findStubPayload struct {
ID *uuid.UUID `json:"id,omitempty"`
Service string `json:"service"`
Expand All @@ -62,6 +68,7 @@ func (h *StubsServer) ServiceReady() {
}

func (h *StubsServer) Liveness(w http.ResponseWriter, _ *http.Request) {
//nolint:errchkjson
_ = json.NewEncoder(w).Encode(rest.MessageOK{Message: "ok", Time: h.clock.Now()})
}

Expand All @@ -74,6 +81,7 @@ func (h *StubsServer) Readiness(w http.ResponseWriter, _ *http.Request) {

w.Header().Set("Content-Type", "application/json")

//nolint:errchkjson
_ = json.NewEncoder(w).Encode(rest.MessageOK{Message: "ok", Time: h.clock.Now()})
}

Expand Down Expand Up @@ -207,6 +215,7 @@ func (h *StubsServer) SearchStubs(w http.ResponseWriter, r *http.Request) {
return
}

//nolint:errchkjson
_ = json.NewEncoder(w).Encode(output)
}

Expand All @@ -217,11 +226,13 @@ func (h *StubsServer) responseError(err error, w http.ResponseWriter) {
}

func (h *StubsServer) writeResponseError(err error, w http.ResponseWriter) {
//nolint:errchkjson
_ = json.NewEncoder(w).Encode(map[string]string{
"error": err.Error(),
})
}

//nolint:cyclop
func (h *StubsServer) readStubs(path string) {
files, err := os.ReadDir(path)
if err != nil {
Expand Down Expand Up @@ -275,13 +286,11 @@ func (h *StubsServer) readStubs(path string) {

func validateStub(stub *storage.Stub) error {
if stub.Service == "" {
//fixme
//nolint:goerr113
return fmt.Errorf("service name can't be empty")
return ErrServiceIsMissing
}

if stub.Method == "" {
return fmt.Errorf("method name can't be emtpy")
return ErrMethodIsMissing
}

// due to golang implementation
Expand Down
18 changes: 14 additions & 4 deletions internal/app/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type closeMatch struct {
headerExpect map[string]interface{}
}

//nolint:cyclop
func findStub(stubStorage *storage.StubStorage, stub *findStubPayload) (*storage.Output, error) {
stubs, err := stubStorage.ItemsBy(stub.Service, stub.Method, stub.ID)
if errors.Is(err, storage.ErrServiceNotFound) {
Expand Down Expand Up @@ -51,6 +52,7 @@ func findStub(stubStorage *storage.StubStorage, stub *findStubPayload) (*storage
}

var closestMatch []closeMatch

for _, strange := range stubs {
cmpData, cmpDataErr := inputCmp(strange.Input, stub.Data)
if cmpDataErr != nil {
Expand Down Expand Up @@ -137,6 +139,7 @@ func stubNotFoundError(stub *findStubPayload, closestMatches []closeMatch) error
rank float32
match closeMatch
}{0, closeMatch{}}

for _, closeMatchValue := range closestMatches {
rank := rankMatch(string(expectString), closeMatchValue.expect)

Expand Down Expand Up @@ -171,6 +174,7 @@ func stubNotFoundError(stub *findStubPayload, closestMatches []closeMatch) error
// the higher the better.
func rankMatch(expect string, closeMatch map[string]interface{}) float32 {
occurrence := 0

for key, value := range closeMatch {
if fuzzy.Match(key+":", expect) {
occurrence++
Expand All @@ -185,18 +189,22 @@ func rankMatch(expect string, closeMatch map[string]interface{}) float32 {
return 0
}
totalFields := len(closeMatch) * 2

return float32(occurrence) / float32(totalFields)
}

func regexMatch(expect, actual interface{}) bool {
var expectedStr, expectedStringOk = expect.(string)
var actualStr, actualStringOk = actual.(string)
var (
expectedStr, expectedStringOk = expect.(string)
actualStr, actualStringOk = actual.(string)
)

if expectedStringOk && actualStringOk {
match, err := regexp.Match(expectedStr, []byte(actualStr))
match, err := regexp.MatchString(expectedStr, actualStr)
if err != nil {
log.Printf("Error on matching regex %s with %s error:%v\n", expect, actual, err)
}

return match
}

Expand All @@ -215,14 +223,15 @@ func matches(expect, actual map[string]interface{}) bool {
return find(expect, actual, true, false, regexMatch)
}

//nolint:cyclop
func find(expect, actual interface{}, acc, exactMatch bool, f matchFunc) bool {
// circuit brake
if !acc {
return false
}

//nolint:nestif
if expectArrayValue, expectArrayOk := expect.([]interface{}); expectArrayOk {

actualArrayValue, actualArrayOk := actual.([]interface{})
if !actualArrayOk {
return false
Expand All @@ -244,6 +253,7 @@ func find(expect, actual interface{}, acc, exactMatch bool, f matchFunc) bool {
return acc
}

//nolint:nestif
if expectMapValue, expectMapOk := expect.(map[string]interface{}); expectMapOk {
actualMapValue, actualMapOk := actual.(map[string]interface{})
if !actualMapOk {
Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/patcher/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestWriterWrapper_OptionUpdate(t *testing.T) {
pile, err := os.OpenFile(
"./../../../protogen/example/multi-files/file1.proto",
os.O_RDONLY,
0444,
0o444,
)
require.NoError(t, err)

Expand Down
36 changes: 25 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (

var buildRelease string //nolint:gochecknoglobals

//nolint:funlen,cyclop
func main() {
conf, err := config.Load()
if err != nil {
Expand All @@ -48,16 +49,16 @@ func main() {
ctx = logger.WithContext(ctx)

// deprecated. will be removed in 3.x
grpcPort := flag.String("grpc-port", conf.GRPC.Port, "Deprecated: use ENV GRPC_PORT. Port of gRPC tcp server")
grpcBindAddr := flag.String("grpc-listen", conf.GRPC.Host, "Deprecated: use ENV GRPC_HOST. Adress the gRPC server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine")
adminPort := flag.String("admin-port", conf.HTTP.Port, "Deprecated: use ENV HTTP_PORT. Port of stub admin server")
adminBindAddr := flag.String("admin-listen", conf.HTTP.Host, "Deprecated: use ENV HTTP_HOST. Adress the admin server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine")
grpcPort := flag.String("grpc-port", conf.GRPC.Port, "Deprecated: use ENV GRPC_PORT. Port of gRPC tcp server") //nolint:lll
grpcBindAddr := flag.String("grpc-listen", conf.GRPC.Host, "Deprecated: use ENV GRPC_HOST. Address the gRPC server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine") //nolint:lll
adminPort := flag.String("admin-port", conf.HTTP.Port, "Deprecated: use ENV HTTP_PORT. Port of stub admin server") //nolint:lll
adminBindAddr := flag.String("admin-listen", conf.HTTP.Host, "Deprecated: use ENV HTTP_HOST. Address the admin server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine") //nolint:lll

outputPointer := flag.String("output", "", "directory to output server.go. Default is $GOPATH/src/grpc/")
flag.StringVar(outputPointer, "o", *outputPointer, "alias for -output")

stubPath := flag.String("stub", "", "Path where the stub files are (Optional)")
imports := flag.String("imports", "/protobuf,/googleapis", "comma separated imports path. default path /protobuf,/googleapis is where gripmock Dockerfile install WKT protos")
imports := flag.String("imports", "/protobuf,/googleapis", "comma separated imports path. default path /protobuf,/googleapis is where gripmock Dockerfile install WKT protos") //nolint:lll

flag.Parse()

Expand All @@ -73,6 +74,7 @@ func main() {
os.Args = append(os.Args[:1], os.Args[2:]...)
}

//nolint:godox
// fixme: move validation of required arguments to a separate service
logger.Info().Str("release", buildRelease).Msg("Starting GripMock")
if os.Getenv("GOPATH") == "" {
Expand Down Expand Up @@ -120,7 +122,7 @@ func main() {
run, chErr := runGrpcServer(ctx, output)

// This is a kind of crutch, but now there is no other solution.
//I have an idea to combine gripmock and grpcmock services into one, then this check will be easier to do.
// I have an idea to combine gripmock and grpcmock services into one, then this check will be easier to do.
// Checking the grpc port of the service. If the port appears, the service has started successfully.
go func() {
var d net.Dialer
Expand All @@ -129,6 +131,7 @@ func main() {
dialCtx, cancel := context.WithTimeout(ctx, time.Second)

conn, err := d.DialContext(dialCtx, conf.GRPC.Network, conf.GRPCAddr())

cancel()

if err == nil && conn != nil {
Expand Down Expand Up @@ -167,7 +170,7 @@ type protocParam struct {
imports []string
}

func getProtodirs(ctx context.Context, protoPath string, imports []string) []string {
func getProtodirs(_ context.Context, protoPath string, imports []string) []string {
// deduced proto dir from proto path
splitPath := strings.Split(protoPath, "/")
protoDir := ""
Expand All @@ -177,11 +180,13 @@ func getProtodirs(ctx context.Context, protoPath string, imports []string) []str

// search protoDir prefix
protoDirIdx := -1

for i := range imports {
dir := path.Join("protogen", imports[i])
if strings.HasPrefix(protoDir, dir) {
protoDir = dir
protoDirIdx = i

break
}
}
Expand All @@ -193,8 +198,10 @@ func getProtodirs(ctx context.Context, protoPath string, imports []string) []str
if i == protoDirIdx {
continue
}

protoDirs = append(protoDirs, dir)
}

return protoDirs
}

Expand Down Expand Up @@ -228,32 +235,38 @@ func generateProtoc(ctx context.Context, param protocParam) {

// append gopackage in proto files if doesn't have any.
func fixGoPackage(ctx context.Context, protoPaths []string) []string {
var results []string
results := make([]string, 0, len(protoPaths))

for _, protoPath := range protoPaths {
pile, err := os.OpenFile(protoPath, os.O_RDONLY, 0600)
pile, err := os.OpenFile(protoPath, os.O_RDONLY, 0o600)
if err != nil {
zerolog.Ctx(ctx).Err(err).Msgf("unable to open protofile %s", protoPath)

continue
}

defer pile.Close()

packageName := "protogen/" + strings.Trim(filepath.Dir(protoPath), "/")

if err := os.MkdirAll(packageName, 0666); err != nil {
if err := os.MkdirAll(packageName, 0o666); err != nil {
zerolog.Ctx(ctx).Err(err).Msgf("unable to create temp dir %s", protoPath)

continue
}

tmp, err := os.Create(filepath.Join(packageName, filepath.Base(protoPath)))
if err != nil {
zerolog.Ctx(ctx).Err(err).Msgf("unable to create temp file %s", protoPath)

continue
}

defer tmp.Close()

if _, err = io.Copy(patcher.NewWriterWrapper(tmp, packageName), pile); err != nil {
zerolog.Ctx(ctx).Err(err).Msgf("unable to copy file %s", protoPath)

continue
}

Expand All @@ -264,7 +277,7 @@ func fixGoPackage(ctx context.Context, protoPaths []string) []string {
}

func runGrpcServer(ctx context.Context, output string) (*exec.Cmd, <-chan error) {
run := exec.CommandContext(ctx, "go", "run", output+"server.go")
run := exec.CommandContext(ctx, "go", "run", output+"server.go") //nolint:gosec
run.Stdout = os.Stdout
run.Stderr = os.Stderr

Expand All @@ -275,6 +288,7 @@ func runGrpcServer(ctx context.Context, output string) (*exec.Cmd, <-chan error)

zerolog.Ctx(ctx).Info().Int("pid", run.Process.Pid).Msg("gRPC-service started")
runErr := make(chan error)

go func() {
runErr <- run.Wait()
}()
Expand Down
Loading

0 comments on commit f5348f2

Please sign in to comment.