Skip to content

Commit

Permalink
Merge pull request #81 from bavix/remove-fix-gopackage.sh
Browse files Browse the repository at this point in the history
Remove fix gopackage.sh
  • Loading branch information
rez1dent3 authored Dec 12, 2023
2 parents 89b8c13 + 9362ad7 commit 6f3f67b
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 63 deletions.
8 changes: 2 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ FROM golang:${BUILD_ARG_GO_VERSION}-alpine${BUILD_ARG_ALPINE_VERSION} AS builder

# install tools (bash, git, protobuf, protoc-gen-go, protoc-grn-go-grpc)
RUN apk -U --no-cache add bash git protobuf curl &&\
go install -v google.golang.org/protobuf/cmd/protoc-gen-go@latest &&\
go install -v google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest &&\
go install -v -ldflags "-s -w" google.golang.org/protobuf/cmd/protoc-gen-go@latest &&\
go install -v -ldflags "-s -w" google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest &&\
# cloning well-known-types
git clone --depth=1 https://github.com/protocolbuffers/protobuf.git /protobuf-repo &&\
mv /protobuf-repo/src/ /protobuf/ &&\
Expand All @@ -19,10 +19,6 @@ RUN apk -U --no-cache add bash git protobuf curl &&\

COPY . /go/src/github.com/bavix/gripmock

# create necessary dirs and export fix_gopackage.sh
RUN mkdir /proto /stubs &&\
ln -s /go/src/github.com/bavix/gripmock/fix_gopackage.sh /bin/

RUN cd /go/src/github.com/bavix/gripmock/protoc-gen-gripmock &&\
go install -v -ldflags "-s -w" &&\
cd /go/src/github.com/bavix/gripmock &&\
Expand Down
46 changes: 0 additions & 46 deletions fix_gopackage.sh

This file was deleted.

44 changes: 33 additions & 11 deletions gripmock.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
package main

import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"strings"
"syscall"
"time"

"github.com/bavix/gripmock/internal/pkg/patcher"
_ "github.com/bavix/gripmock/protogen"
"github.com/bavix/gripmock/stub"
)
Expand Down Expand Up @@ -185,23 +187,43 @@ func generateProtoc(param protocParam) {
if err != nil {
log.Fatal("Fail on protoc ", err)
}

}

// append gopackage in proto files if doesn't have any.
func fixGoPackage(protoPaths []string) []string {
fixgopackage := exec.Command("fix_gopackage.sh", protoPaths...)
buf := &bytes.Buffer{}
fixgopackage.Stdout = buf
fixgopackage.Stderr = os.Stderr
err := fixgopackage.Run()
if err != nil {
log.Println("error on fixGoPackage", err)
var results []string

for _, protoPath := range protoPaths {
pile, err := os.OpenFile(protoPath, os.O_RDONLY, 0600)
if err != nil {
fmt.Printf("сan't open protofile %s: %v", protoPath, err)
continue
}
defer pile.Close()

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

if err := os.MkdirAll(packageName, 0666); err != nil {
fmt.Printf("сan't create temp dir %s: %v", protoPath, err)
continue
}

tmp, err := os.Create(filepath.Join(packageName, filepath.Base(protoPath)))
if err != nil {
fmt.Printf("сan't create temp file %s: %v", protoPath, err)
continue
}
defer tmp.Close()

if _, err = io.Copy(patcher.NewWriterWrapper(tmp, packageName), pile); err != nil {
fmt.Printf("unable to copy file %s: %v", protoPath, err)
continue
}

return protoPaths
results = append(results, tmp.Name())
}

return strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
return results
}

func runGrpcServer(output string) (*exec.Cmd, <-chan error) {
Expand Down
50 changes: 50 additions & 0 deletions internal/pkg/patcher/writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package patcher

import (
"errors"
"fmt"
"io"
"regexp"
)

var (
optionGoPackageRegexp = regexp.MustCompile("option go_package.+;\n?")
syntaxRegexp = regexp.MustCompile("syntax.+;\n?")
ErrSyntaxNotFound = errors.New("proto syntax not found")
)

type fileWriterWrapper struct {
writer io.Writer
packageName string
}

func NewWriterWrapper(writer io.Writer, packageName string) io.Writer {
return &fileWriterWrapper{writer: writer, packageName: packageName}
}

func (f *fileWriterWrapper) Write(p []byte) (int, error) {
const (
syntaxIndexes = 2
prefix = "github.com/bavix/gripmock"
)

n := len(p)
goPackage := []byte(fmt.Sprintf("option go_package = \"%s/%s\";\n", prefix, f.packageName))

if optionGoPackageRegexp.Match(p) {
_, err := f.writer.Write(optionGoPackageRegexp.ReplaceAll(p, goPackage))

return n, err
}

indexes := syntaxRegexp.FindIndex(p)
if len(indexes) != syntaxIndexes {
return 0, ErrSyntaxNotFound
}

_, err := f.writer.Write(
append(p[:indexes[1]], append(goPackage, p[indexes[1]:]...)...),
)

return n, err
}
84 changes: 84 additions & 0 deletions internal/pkg/patcher/writer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package patcher_test

import (
"bytes"
"io"
"os"
"testing"

"github.com/stretchr/testify/require"

"github.com/bavix/gripmock/internal/pkg/patcher"
)

func TestWriterWrapper_OptionUpdate(t *testing.T) {
pile, err := os.OpenFile(
"./../../../protogen/example/multi-files/file1.proto",
os.O_RDONLY,
0444,
)
require.NoError(t, err)

var result bytes.Buffer

tmp := patcher.NewWriterWrapper(&result, "patcher/v1")

_, err = io.Copy(tmp, pile)
require.NoError(t, err)
require.NoError(t, pile.Close())

require.Contains(t, result.String(), "github.com/bavix/gripmock/protogen/patcher/v1")
}

func TestWriterWrapper_OptionInsert(t *testing.T) {
pile := bytes.NewReader([]byte(`syntax = "proto3";
package multifiles;
service Gripmock1 {
rpc SayHello (Request1) returns (Reply1);
}
message Request1 {
string name = 1;
}
message Reply1 {
string message = 1;
int32 return_code = 2;
}`))

var result bytes.Buffer

tmp := patcher.NewWriterWrapper(&result, "patcher/v2")

_, err := io.Copy(tmp, pile)
require.NoError(t, err)

require.Contains(t, result.String(), "github.com/bavix/gripmock/protogen/patcher/v2")
}

func TestWriterWrapper_SyntaxError(t *testing.T) {
pile := bytes.NewReader([]byte(`
package multifiles;
service Gripmock1 {
rpc SayHello (Request1) returns (Reply1);
}
message Request1 {
string name = 1;
}
message Reply1 {
string message = 1;
int32 return_code = 2;
}`))

var result bytes.Buffer

tmp := patcher.NewWriterWrapper(&result, "patcher/v3")

_, err := io.Copy(tmp, pile)
require.ErrorIs(t, patcher.ErrSyntaxNotFound, err)
}

0 comments on commit 6f3f67b

Please sign in to comment.