diff --git a/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-main.go b/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-main.go deleted file mode 100644 index 76322ecc..00000000 --- a/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-main.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "os" - - "google.golang.org/grpc/grpclog" -) - -func main() { - err := run() - if err != nil { - grpclog.Errorf("server was shutdown with errors: %v", err) - os.Exit(1) - } -} - diff --git a/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-run.go b/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-run.go deleted file mode 100644 index 485f8be3..00000000 --- a/_tests/e2e/.snapshots/TestE2E_withModules--cmd-server-run.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "github.com/srvc/appctx" - - "github.com/izumin5210/grapi/pkg/grapiserver" -) - -func run() error { - // Application context - ctx := appctx.Global() - - s := grapiserver.New( - grapiserver.WithDefaultLogger(), - grapiserver.WithServers( - // TODO - ), - ) - return s.Serve(ctx) -} - diff --git a/_tests/e2e/.snapshots/TestE2E_withModules--grapi.toml b/_tests/e2e/.snapshots/TestE2E_withModules--grapi.toml deleted file mode 100644 index 5b763733..00000000 --- a/_tests/e2e/.snapshots/TestE2E_withModules--grapi.toml +++ /dev/null @@ -1,26 +0,0 @@ -package = "testuser.sampleapp" - -[grapi] -server_dir = "./app/server" - -[protoc] -protos_dir = "./api/protos" -out_dir = "./api" -import_dirs = [ - "./api/protos", - '{{ module "github.com/grpc-ecosystem/grpc-gateway" }}', - '{{ module "github.com/grpc-ecosystem/grpc-gateway" }}/third_party/googleapis', -] - - [[protoc.plugins]] - name = "go" - args = { plugins = "grpc", paths = "source_relative" } - - [[protoc.plugins]] - name = "grpc-gateway" - args = { logtostderr = true, paths = "source_relative" } - - [[protoc.plugins]] - name = "swagger" - args = { logtostderr = true } - diff --git a/_tests/e2e/.snapshots/TestE2E_withModules--tools.go b/_tests/e2e/.snapshots/TestE2E_withModules--tools.go deleted file mode 100644 index 210f0e62..00000000 --- a/_tests/e2e/.snapshots/TestE2E_withModules--tools.go +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by github.com/izumin5210/gex. DO NOT EDIT. - -// +build tools - -package tools - -// tool dependencies -import ( - _ "github.com/golang/protobuf/protoc-gen-go" - _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway" - _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger" - _ "github.com/izumin5210/gex/cmd/gex" - _ "github.com/izumin5210/grapi/cmd/grapi" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-command" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-scaffold-service" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-service" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-type" -) - -// If you want to use tools, please run the following command: -// go generate ./tools.go -// -//go:generate go build -v -o=./bin/protoc-gen-go github.com/golang/protobuf/protoc-gen-go -//go:generate go build -v -o=./bin/protoc-gen-grpc-gateway github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -//go:generate go build -v -o=./bin/protoc-gen-swagger github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -//go:generate go build -v -o=./bin/gex github.com/izumin5210/gex/cmd/gex -//go:generate go build -v -o=./bin/grapi github.com/izumin5210/grapi/cmd/grapi -//go:generate go build -v -o=./bin/grapi-gen-command github.com/izumin5210/grapi/cmd/grapi-gen-command -//go:generate go build -v -o=./bin/grapi-gen-scaffold-service github.com/izumin5210/grapi/cmd/grapi-gen-scaffold-service -//go:generate go build -v -o=./bin/grapi-gen-service github.com/izumin5210/grapi/cmd/grapi-gen-service -//go:generate go build -v -o=./bin/grapi-gen-type github.com/izumin5210/grapi/cmd/grapi-gen-type - diff --git a/_tests/e2e/main_test.go b/_tests/e2e/main_test.go deleted file mode 100644 index cea7139d..00000000 --- a/_tests/e2e/main_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package main - -import ( - "bytes" - "context" - "flag" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "net" - "net/http" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "testing" - "time" - - "github.com/bradleyjkemp/cupaloy/v2" - "golang.org/x/tools/go/packages/packagestest" -) - -var ( - grapiCmd = flag.String("grapi", "grapi", "path of grapi command") - grapiURL = flag.String("grapi-url", "", "url for replacing github.com/izumin5210/grapi") - revision = flag.String("revision", "", "target revision") -) - -func TestE2E_withModules(t *testing.T) { - invokeE2ETest(t, packagestest.Modules) -} - -func TestE2E_withDep(t *testing.T) { - t.SkipNow() - invokeE2ETest(t, packagestest.GOPATH) -} - -func invokeE2ETest(t *testing.T, exporter packagestest.Exporter) { - t.Helper() - - exported := packagestest.Export(t, exporter, []packagestest.Module{ - {Name: "sampleapp", Files: map[string]interface{}{".keep": ""}}, - }) - defer exported.Cleanup() - - rootPath := exported.Config.Dir - exported.Config.Dir = filepath.Dir(rootPath) - checkNoErr(t, os.RemoveAll(rootPath)) - - // init - { - args := []string{"--debug", "init", "--package", "testuser.sampleapp"} - if *grapiURL != "" { - // Add replacements later - args = append(args, "--replace-grapi="+*grapiURL) - } else if *revision != "" { - args = append(args, "--revision="+*revision) - } else { - args = append(args, "--HEAD") - } - if exporter.Name() == "GOPATH" { - args = append(args, "--use-dep") - } - args = append(args, filepath.Base(rootPath)) - invoke(t, exported, exec.Command(*grapiCmd, args...)) - checkExistence(t, rootPath) - t.Log("Initialize a project successfully") - } - - exported.Config.Dir = rootPath - - ignoreFiles := map[string]struct{}{ - "/go.mod": struct{}{}, - "/go.sum": struct{}{}, - } - - err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error { - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if info.IsDir() { - return nil - } - rel := strings.TrimPrefix(path, rootPath) - if _, ok := ignoreFiles[rel]; ok { - return nil - } - if strings.HasPrefix(rel, "/bin/") { - return nil - } - - t.Run(rel, func(t *testing.T) { - data, err := ioutil.ReadFile(path) - if err != nil { - t.Errorf("failed to open %s: %v", path, err) - } - - cupaloy.SnapshotT(t, string(data)) - }) - - return nil - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // generate service - { - invoke(t, exported, exec.Command(*grapiCmd, "--debug", "g", "service", "book", "list")) - checkExistence(t, filepath.Join(rootPath, "app", "server", "book_server.go")) - t.Log("Generate a service successfully") - } - - port := getFreePort(t) - updateRun(t, rootPath, port) - updateServerImpl(t, rootPath) - - // run server - { - t.Log("Start the server") - cmd := exec.Command(*grapiCmd, "--debug", "server") - sdCh := make(chan struct{}, 1) - go func() { - defer close(sdCh) - invoke(t, exported, cmd) - }() - - startedAt := time.Now() - var ( - resp *http.Response - retryCnt int - err error - ) - - for { - func() { - defer recover() - resp, err = http.Get(fmt.Sprintf("http://localhost:%d/books", port)) - }() - if err != nil && time.Since(startedAt) < 120*time.Second { - time.Sleep(5 * time.Second) - retryCnt++ - } else { - break - } - } - - if err != nil { - t.Fatalf("Unexpected error (retry count: %d): %v", retryCnt, err) - } - - if got, want := resp.StatusCode, 200; got != want { - t.Errorf("Response status is %d, want %d", got, want) - } - - t.Log("HTTP Request successfully") - - sendSignal(t, cmd, os.Interrupt) - toCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - select { - case <-sdCh: - t.Log("Shutdown server successfully") - case <-toCtx.Done(): - t.Log("Deadline exceeded stopping server") - sendSignal(t, cmd, os.Kill) - <-sdCh - } - } -} - -func invoke(t *testing.T, exported *packagestest.Exported, cmd *exec.Cmd) { - t.Helper() - cmd.Dir = exported.Config.Dir - for _, kv := range exported.Config.Env { - if strings.HasPrefix(kv, "GOPROXY=") { - continue - } - cmd.Env = append(cmd.Env, kv) - } - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err := cmd.Run() - if err != nil { - t.Fatalf("failed to execute command %v: %v", cmd, err) - } -} - -func checkNoErr(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func checkExistence(t *testing.T, path string) { - t.Helper() - _, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - t.Fatalf("%s does not exist: %v", path, err) - } - t.Fatalf("failed to check file existence: %v", err) - } -} - -func getFreePort(t *testing.T) int { - t.Helper() - lis, err := net.Listen("tcp", ":0") - checkNoErr(t, err) - defer lis.Close() - - return lis.Addr().(*net.TCPAddr).Port -} - -func sendSignal(t *testing.T, cmd *exec.Cmd, sig os.Signal) { - t.Helper() - checkNoErr(t, cmd.Process.Signal(sig)) -} - -type visitor struct { - VisitFunc func(ast.Visitor, ast.Node) ast.Visitor -} - -func (v *visitor) Visit(node ast.Node) ast.Visitor { - return v.VisitFunc(v, node) -} - -func updateRun(t *testing.T, rootPath string, port int) { - data, err := ioutil.ReadFile(filepath.Join(rootPath, "cmd", "server", "run.go")) - checkNoErr(t, err) - - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "", data, parser.DeclarationErrors) - checkNoErr(t, err) - - ast.Walk(&visitor{ - VisitFunc: func(v ast.Visitor, n ast.Node) ast.Visitor { - switch n := n.(type) { - case *ast.GenDecl: - if n.Tok == token.IMPORT { - n.Specs = append(n.Specs, &ast.ImportSpec{ - Path: &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote("sampleapp/app/server"), - }, - }) - } - case *ast.CallExpr: - switch fun := n.Fun.(type) { - case *ast.SelectorExpr: - switch fun.Sel.Name { - case "New": - n.Args = append(n.Args, &ast.CallExpr{ - Fun: &ast.SelectorExpr{ - X: ast.NewIdent("grapiserver"), - Sel: ast.NewIdent("WithGatewayAddr"), - }, - Args: []ast.Expr{ - &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote("tcp"), - }, - &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote(fmt.Sprintf(":%d", port)), - }, - }, - }) - case "WithServers": - n.Args = append(n.Args, &ast.CallExpr{ - Fun: &ast.SelectorExpr{ - X: ast.NewIdent("server"), - Sel: ast.NewIdent("NewBookServiceServer"), - }, - }) - } - } - } - return v - }, - }, f) - - buf := new(bytes.Buffer) - err = format.Node(buf, token.NewFileSet(), f) - checkNoErr(t, err) - err = ioutil.WriteFile(filepath.Join(rootPath, "cmd", "server", "run.go"), buf.Bytes(), 0755) - checkNoErr(t, err) -} - -func updateServerImpl(t *testing.T, rootPath string) { - data, err := ioutil.ReadFile(filepath.Join(rootPath, "app", "server", "book_server.go")) - checkNoErr(t, err) - - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "", data, parser.DeclarationErrors) - checkNoErr(t, err) - - ast.Walk(&visitor{ - VisitFunc: func(v ast.Visitor, n ast.Node) ast.Visitor { - switch n := n.(type) { - case *ast.GenDecl: - if n.Tok == token.IMPORT { - n.Specs = []ast.Spec{ - &ast.ImportSpec{ - Path: &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote("context"), - }, - }, - &ast.ImportSpec{ - Path: &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote("github.com/izumin5210/grapi/pkg/grapiserver"), - }, - }, - &ast.ImportSpec{ - Name: &ast.Ident{Name: "api_pb"}, - Path: &ast.BasicLit{ - Kind: token.STRING, - Value: strconv.Quote("sampleapp/api"), - }, - }, - } - } - case *ast.FuncDecl: - if n.Name.Name == "ListBooks" { - n.Body.List = []ast.Stmt{ - &ast.ReturnStmt{ - Results: []ast.Expr{ - &ast.UnaryExpr{ - X: &ast.CompositeLit{ - Type: &ast.SelectorExpr{ - X: ast.NewIdent("api_pb"), - Sel: ast.NewIdent("ListBooksResponse"), - }, - }, - Op: token.AND, - }, - &ast.Ident{Name: "nil"}, - }, - }, - } - } - } - return v - }, - }, f) - - buf := new(bytes.Buffer) - err = format.Node(buf, token.NewFileSet(), f) - checkNoErr(t, err) - err = ioutil.WriteFile(filepath.Join(rootPath, "app", "server", "book_server.go"), buf.Bytes(), 0755) - checkNoErr(t, err) -} diff --git a/cmd/grapi-gen-command/.snapshots/TestCommand-simple-generate-cmd-foo-run.go b/cmd/grapi-gen-command/.snapshots/TestCommand-simple-generate-cmd-foo-run.go deleted file mode 100644 index 2538cd42..00000000 --- a/cmd/grapi-gen-command/.snapshots/TestCommand-simple-generate-cmd-foo-run.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "os" -) - -func main() { - os.Exit(run()) -} - -func run() int { - fmt.Println("It works!") - return 0 -} - diff --git a/cmd/grapi-gen-command/main.go b/cmd/grapi-gen-command/main.go index 2a1d7a2a..98a74157 100644 --- a/cmd/grapi-gen-command/main.go +++ b/cmd/grapi-gen-command/main.go @@ -3,8 +3,8 @@ package main import ( "github.com/spf13/cobra" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-command/template" - "github.com/izumin5210/grapi/pkg/gencmd" + _ "github.com/x-izumin/grapi/cmd/grapi-gen-command/template" + "github.com/x-izumin/grapi/pkg/gencmd" ) func main() { diff --git a/cmd/grapi-gen-command/main_test.go b/cmd/grapi-gen-command/main_test.go deleted file mode 100644 index c9884ce8..00000000 --- a/cmd/grapi-gen-command/main_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package main - -import ( - "testing" - - "github.com/bradleyjkemp/cupaloy/v2" - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - gencmdtesting "github.com/izumin5210/grapi/pkg/gencmd/testing" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/spf13/afero" -) - -func TestCommand(t *testing.T) { - cases := []struct { - test string - args []string - files []string - }{ - { - test: "simple", - args: []string{"foo"}, - files: []string{"cmd/foo/run.go"}, - }, - } - - rootDir := cli.RootDir{clib.Path("/home/src/testapp")} - - createGenApp := func(cmd *gencmd.Command) (*gencmd.App, error) { - return gencmdtesting.NewTestApp(cmd, cli.NopUI) - } - createCmd := func(t *testing.T, fs afero.Fs) gencmd.Executor { - ctx := &grapicmd.Ctx{ - FS: fs, - RootDir: rootDir, - } - return buildCommand(gencmd.WithGrapiCtx(ctx), gencmd.WithCreateAppFunc(createGenApp)) - } - - for _, tc := range cases { - t.Run(tc.test, func(t *testing.T) { - fs := afero.NewMemMapFs() - afero.WriteFile(fs, rootDir.Join("grapi.toml").String(), []byte{}, 0755) - - t.Run("generate", func(t *testing.T) { - cmd := createCmd(t, fs) - cmd.Command().SetArgs(append([]string{"generate"}, tc.args...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.files { - t.Run(file, func(t *testing.T) { - data, err := afero.ReadFile(fs, rootDir.Join(file).String()) - - if err != nil { - t.Errorf("returned an error: %v", err) - } - - cupaloy.SnapshotT(t, string(data)) - }) - } - }) - - t.Run("destroy", func(t *testing.T) { - cmd := createCmd(t, fs) - cmd.Command().SetArgs(append([]string{"destroy"}, tc.args...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.files { - t.Run(file, func(t *testing.T) { - ok, err := afero.Exists(fs, rootDir.Join(file).String()) - - if err != nil { - t.Errorf("Exists(fs, %q) returned an error: %v", file, err) - } - - if ok { - t.Errorf("%q should not exist", file) - } - }) - } - }) - }) - } -} diff --git a/cmd/grapi-gen-command/template/.gitignore b/cmd/grapi-gen-command/template/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/cmd/grapi-gen-command/template/_data/cmd/{{ .name }}/run.go.tmpl b/cmd/grapi-gen-command/template/_data/cmd/{{ .name }}/run.go.tmpl deleted file mode 100644 index 251be34d..00000000 --- a/cmd/grapi-gen-command/template/_data/cmd/{{ .name }}/run.go.tmpl +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "fmt" - "os" -) - -func main() { - os.Exit(run()) -} - -func run() int { - fmt.Println("It works!") - return 0 -} diff --git a/cmd/grapi-gen-command/template/gen.go b/cmd/grapi-gen-command/template/gen.go deleted file mode 100644 index ba18632b..00000000 --- a/cmd/grapi-gen-command/template/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate statik -src ./_data -dest .. -p template -f -m - -package template diff --git a/cmd/grapi-gen-command/template/statik.go b/cmd/grapi-gen-command/template/statik.go deleted file mode 100644 index 68e3dd19..00000000 --- a/cmd/grapi-gen-command/template/statik.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by statik. DO NOT EDIT. - -// Package statik contains static assets. -package template - -import ( - "github.com/rakyll/statik/fs" -) - -func init() { - data := "PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1b\x00 \x00cmd/{{ .name }}/run.go.tmplUT\x05\x00\x01\x80Cm8,\xcaA\n\xc20\x10\x05\xd0u\xfe)\xc6Y%\x9b\xe2%\\\xb8\xf3\n\xa142\xd4L\xcad\x82\x82\xf4\xeeb\xe9\xf2\xc1\xdb\xf2\xbc\xe6\xe7B5\x8b\x02R\xb7fN\x11\x81KuF\xe0\xd6\x19 (C\xe7\xe3\xc4D_\x84\xd6\xa7\xdbG<\xda\xd0\x98\x12\xf63\x1c$Q\xff\x9fR}z\x98\xa8\xbf4\xf2\xdd\xe9\xddl\xed\x17N\x08\xb6\xf80\xa5+v\xfc\x02\x00\x00\xff\xffPK\x07\x08\xe5<\xbb\x9ao\x00\x00\x00\x7f\x00\x00\x00PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\xe5<\xbb\x9ao\x00\x00\x00\x7f\x00\x00\x00\x1b\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00cmd/{{ .name }}/run.go.tmplUT\x05\x00\x01\x80Cm8PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00R\x00\x00\x00\xc1\x00\x00\x00\x00\x00" - fs.Register(data) -} diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 2590d59c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarBazService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fa385d3b..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto deleted file mode 100644 index 230cdcd3..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go deleted file mode 100644 index 68b67795..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarServiceServer is a composite interface of foo_pb.BarServiceServer and grapiserver.Server. -type BarServiceServer interface { - foo_pb.BarServiceServer - grapiserver.Server -} - -// NewBarServiceServer creates a new BarServiceServer instance. -func NewBarServiceServer() BarServiceServer { - return &barServiceServerImpl{} -} - -type barServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go deleted file mode 100644 index 27421437..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto deleted file mode 100644 index 2775531f..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testcompany.testapp.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go deleted file mode 100644 index 68b67795..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarServiceServer is a composite interface of foo_pb.BarServiceServer and grapiserver.Server. -type BarServiceServer interface { - foo_pb.BarServiceServer - grapiserver.Server -} - -// NewBarServiceServer creates a new BarServiceServer instance. -func NewBarServiceServer() BarServiceServer { - return &barServiceServerImpl{} -} - -type barServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go deleted file mode 100644 index 27421437..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-book.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-book.proto deleted file mode 100644 index 767d59bc..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-book.proto +++ /dev/null @@ -1,67 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service BookService { - rpc ListBooks (ListBooksRequest) returns (ListBooksResponse) { - option (google.api.http) = { - get: "/books" - }; - } - rpc GetBook (GetBookRequest) returns (Book) { - option (google.api.http) = { - get: "/books/{book_id}" - }; - } - rpc CreateBook (CreateBookRequest) returns (Book) { - option (google.api.http) = { - post: "/books" - body: "book" - }; - } - rpc UpdateBook (UpdateBookRequest) returns (Book) { - option (google.api.http) = { - patch: "/books/{book.book_id}" - body: "book" - }; - } - rpc DeleteBook (DeleteBookRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/books/{book_id}" - }; - } -} - -message Book { - string book_id = 1; -} - -message ListBooksRequest { -} - -message ListBooksResponse { - repeated Book books = 1; -} - -message GetBookRequest { - string book_id = 1; -} - -message CreateBookRequest { - Book book = 1; -} - -message UpdateBookRequest { - Book book = 1; -} - -message DeleteBookRequest { - string book_id = 1; -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto deleted file mode 100644 index e94131cc..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service FooService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server.go deleted file mode 100644 index 09152b99..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server.go +++ /dev/null @@ -1,52 +0,0 @@ -package server - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// BookServiceServer is a composite interface of api_pb.BookServiceServer and grapiserver.Server. -type BookServiceServer interface { - api_pb.BookServiceServer - grapiserver.Server -} - -// NewBookServiceServer creates a new BookServiceServer instance. -func NewBookServiceServer() BookServiceServer { - return &bookServiceServerImpl{} -} - -type bookServiceServerImpl struct { -} - -func (s *bookServiceServerImpl) ListBooks(ctx context.Context, req *api_pb.ListBooksRequest) (*api_pb.ListBooksResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *bookServiceServerImpl) GetBook(ctx context.Context, req *api_pb.GetBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *bookServiceServerImpl) CreateBook(ctx context.Context, req *api_pb.CreateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *bookServiceServerImpl) UpdateBook(ctx context.Context, req *api_pb.UpdateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *bookServiceServerImpl) DeleteBook(ctx context.Context, req *api_pb.DeleteBookRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_register_funcs.go deleted file mode 100644 index 0c8e7832..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *bookServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterBookServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *bookServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterBookServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_test.go deleted file mode 100644 index 2423f050..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-book_server_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package server - -import ( - "context" - "testing" - - api_pb "testapp/api" -) - -func Test_BookServiceServer_ListBooks(t *testing.T) { - svr := NewBookServiceServer() - - ctx := context.Background() - req := &api_pb.ListBooksRequest{} - - resp, err := svr.ListBooks(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BookServiceServer_GetBook(t *testing.T) { - svr := NewBookServiceServer() - - ctx := context.Background() - req := &api_pb.GetBookRequest{} - - resp, err := svr.GetBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BookServiceServer_CreateBook(t *testing.T) { - svr := NewBookServiceServer() - - ctx := context.Background() - req := &api_pb.CreateBookRequest{} - - resp, err := svr.CreateBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BookServiceServer_UpdateBook(t *testing.T) { - svr := NewBookServiceServer() - - ctx := context.Background() - req := &api_pb.UpdateBookRequest{} - - resp, err := svr.UpdateBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BookServiceServer_DeleteBook(t *testing.T) { - svr := NewBookServiceServer() - - ctx := context.Background() - req := &api_pb.DeleteBookRequest{} - - resp, err := svr.DeleteBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go deleted file mode 100644 index 04d3cf0b..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// FooServiceServer is a composite interface of api_pb.FooServiceServer and grapiserver.Server. -type FooServiceServer interface { - api_pb.FooServiceServer - grapiserver.Server -} - -// NewFooServiceServer creates a new FooServiceServer instance. -func NewFooServiceServer() FooServiceServer { - return &fooServiceServerImpl{} -} - -type fooServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go deleted file mode 100644 index 7b576996..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *fooServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterFooServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *fooServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterFooServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto deleted file mode 100644 index 5fe20ee3..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service BookService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go deleted file mode 100644 index 9c739963..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// BookServiceServer is a composite interface of api_pb.BookServiceServer and grapiserver.Server. -type BookServiceServer interface { - api_pb.BookServiceServer - grapiserver.Server -} - -// NewBookServiceServer creates a new BookServiceServer instance. -func NewBookServiceServer() BookServiceServer { - return &bookServiceServerImpl{} -} - -type bookServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go deleted file mode 100644 index 0c8e7832..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *bookServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterBookServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *bookServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterBookServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 2590d59c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarBazService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fa385d3b..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto deleted file mode 100644 index 447b4721..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testcompany.testapp; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service FooService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go deleted file mode 100644 index 04d3cf0b..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// FooServiceServer is a composite interface of api_pb.FooServiceServer and grapiserver.Server. -type FooServiceServer interface { - api_pb.FooServiceServer - grapiserver.Server -} - -// NewFooServiceServer creates a new FooServiceServer instance. -func NewFooServiceServer() FooServiceServer { - return &fooServiceServerImpl{} -} - -type fooServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go deleted file mode 100644 index 7b576996..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *fooServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterFooServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *fooServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterFooServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go deleted file mode 100644 index e0d87ee0..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// QuxServiceServer is a composite interface of api_pb.QuxServiceServer and grapiserver.Server. -type QuxServiceServer interface { - api_pb.QuxServiceServer - grapiserver.Server -} - -// NewQuxServiceServer creates a new QuxServiceServer instance. -func NewQuxServiceServer() QuxServiceServer { - return &quxServiceServerImpl{} -} - -type quxServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go deleted file mode 100644 index a23d82ec..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *quxServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterQuxServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *quxServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterQuxServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto deleted file mode 100644 index 3ea614e4..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service QuxService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto deleted file mode 100644 index e97ef74d..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.out; - -option go_package = "testapp/api/out;out_pb"; - - -import "google/api/annotations.proto"; - -service QuuxService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go deleted file mode 100644 index 2aa3e521..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - out_pb "testapp/api/out" -) - -// QuuxServiceServer is a composite interface of out_pb.QuuxServiceServer and grapiserver.Server. -type QuuxServiceServer interface { - out_pb.QuuxServiceServer - grapiserver.Server -} - -// NewQuuxServiceServer creates a new QuuxServiceServer instance. -func NewQuuxServiceServer() QuuxServiceServer { - return &quuxServiceServerImpl{} -} - -type quuxServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go deleted file mode 100644 index 26cfa4ea..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - out_pb "testapp/api/out" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *quuxServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - out_pb.RegisterQuuxServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *quuxServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return out_pb.RegisterQuuxServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto deleted file mode 100644 index 3b82cfe6..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto +++ /dev/null @@ -1,67 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service LibraryService { - rpc ListBooks (ListBooksRequest) returns (ListBooksResponse) { - option (google.api.http) = { - get: "/books" - }; - } - rpc GetBook (GetBookRequest) returns (Book) { - option (google.api.http) = { - get: "/books/{book_id}" - }; - } - rpc CreateBook (CreateBookRequest) returns (Book) { - option (google.api.http) = { - post: "/books" - body: "book" - }; - } - rpc UpdateBook (UpdateBookRequest) returns (Book) { - option (google.api.http) = { - patch: "/books/{book.book_id}" - body: "book" - }; - } - rpc DeleteBook (DeleteBookRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/books/{book_id}" - }; - } -} - -message Book { - string book_id = 1; -} - -message ListBooksRequest { -} - -message ListBooksResponse { - repeated Book books = 1; -} - -message GetBookRequest { - string book_id = 1; -} - -message CreateBookRequest { - Book book = 1; -} - -message UpdateBookRequest { - Book book = 1; -} - -message DeleteBookRequest { - string book_id = 1; -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go deleted file mode 100644 index ff6de0c2..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go +++ /dev/null @@ -1,52 +0,0 @@ -package server - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// LibraryServiceServer is a composite interface of api_pb.LibraryServiceServer and grapiserver.Server. -type LibraryServiceServer interface { - api_pb.LibraryServiceServer - grapiserver.Server -} - -// NewLibraryServiceServer creates a new LibraryServiceServer instance. -func NewLibraryServiceServer() LibraryServiceServer { - return &libraryServiceServerImpl{} -} - -type libraryServiceServerImpl struct { -} - -func (s *libraryServiceServerImpl) ListBooks(ctx context.Context, req *api_pb.ListBooksRequest) (*api_pb.ListBooksResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) GetBook(ctx context.Context, req *api_pb.GetBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) CreateBook(ctx context.Context, req *api_pb.CreateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) UpdateBook(ctx context.Context, req *api_pb.UpdateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) DeleteBook(ctx context.Context, req *api_pb.DeleteBookRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go deleted file mode 100644 index 71a96737..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *libraryServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterLibraryServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *libraryServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterLibraryServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go deleted file mode 100644 index 1cd46a69..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package server - -import ( - "context" - "testing" - - api_pb "testapp/api" -) - -func Test_LibraryServiceServer_ListBooks(t *testing.T) { - svr := NewLibraryServiceServer() - - ctx := context.Background() - req := &api_pb.ListBooksRequest{} - - resp, err := svr.ListBooks(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_LibraryServiceServer_GetBook(t *testing.T) { - svr := NewLibraryServiceServer() - - ctx := context.Background() - req := &api_pb.GetBookRequest{} - - resp, err := svr.GetBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_LibraryServiceServer_CreateBook(t *testing.T) { - svr := NewLibraryServiceServer() - - ctx := context.Background() - req := &api_pb.CreateBookRequest{} - - resp, err := svr.CreateBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_LibraryServiceServer_UpdateBook(t *testing.T) { - svr := NewLibraryServiceServer() - - ctx := context.Background() - req := &api_pb.UpdateBookRequest{} - - resp, err := svr.UpdateBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_LibraryServiceServer_DeleteBook(t *testing.T) { - svr := NewLibraryServiceServer() - - ctx := context.Background() - req := &api_pb.DeleteBookRequest{} - - resp, err := svr.DeleteBook(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto deleted file mode 100644 index ee9ce2a1..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service CorgeService { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go deleted file mode 100644 index 13334764..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// CorgeServiceServer is a composite interface of api_pb.CorgeServiceServer and grapiserver.Server. -type CorgeServiceServer interface { - api_pb.CorgeServiceServer - grapiserver.Server -} - -// NewCorgeServiceServer creates a new CorgeServiceServer instance. -func NewCorgeServiceServer() CorgeServiceServer { - return &corgeServiceServerImpl{} -} - -type corgeServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go deleted file mode 100644 index 93d5b5b8..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *corgeServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterCorgeServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *corgeServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterCorgeServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 5ea823df..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,70 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service BarBazService { - rpc ListBarBazs (ListBarBazsRequest) returns (ListBarBazsResponse) { - option (google.api.http) = { - get: "/bar_bazs" - }; - } - rpc CreateBarBaz (CreateBarBazRequest) returns (BarBaz) { - option (google.api.http) = { - post: "/bar_bazs" - body: "bar_baz" - }; - } - rpc DeleteBarBaz (DeleteBarBazRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/bar_bazs/{bar_baz_id}" - }; - } - rpc Rename (RenameRequest) returns (RenameResponse) { - option (google.api.http) = { - get: "/bar_bazs/rename" - }; - } - rpc MoveMove (MoveMoveRequest) returns (MoveMoveResponse) { - option (google.api.http) = { - get: "/bar_bazs/move_move" - }; - } -} - -message BarBaz { - string bar_baz_id = 1; -} - -message ListBarBazsRequest { -} - -message ListBarBazsResponse { - repeated BarBaz bar_bazs = 1; -} - -message CreateBarBazRequest { - BarBaz bar_baz = 1; -} - -message DeleteBarBazRequest { - string bar_baz_id = 1; -} - -message RenameRequest { -} - -message RenameResponse { -} - -message MoveMoveRequest { -} - -message MoveMoveResponse { -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index 0fb60647..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,52 +0,0 @@ -package foo - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - -func (s *barBazServiceServerImpl) ListBarBazs(ctx context.Context, req *foo_pb.ListBarBazsRequest) (*foo_pb.ListBarBazsResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) CreateBarBaz(ctx context.Context, req *foo_pb.CreateBarBazRequest) (*foo_pb.BarBaz, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) DeleteBarBaz(ctx context.Context, req *foo_pb.DeleteBarBazRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) Rename(ctx context.Context, req *foo_pb.RenameRequest) (*foo_pb.RenameResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) MoveMove(ctx context.Context, req *foo_pb.MoveMoveRequest) (*foo_pb.MoveMoveResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index e2b35ed5..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package foo - -import ( - "context" - "testing" - - "github.com/golang/protobuf/ptypes/empty" - - foo_pb "testapp/api/foo" -) - -func Test_BarBazServiceServer_ListBarBazs(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.ListBarBazsRequest{} - - resp, err := svr.ListBarBazs(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_CreateBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.CreateBarBazRequest{} - - resp, err := svr.CreateBarBaz(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_DeleteBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.DeleteBarBazRequest{} - - resp, err := svr.DeleteBarBaz(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_Rename(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.RenameRequest{} - - resp, err := svr.Rename(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_MoveMove(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.MoveMoveRequest{} - - resp, err := svr.MoveMove(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 44b449c3..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,48 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service BarBazService { - rpc ListBarBazs (ListBarBazsRequest) returns (ListBarBazsResponse) { - option (google.api.http) = { - get: "/bar_bazs" - }; - } - rpc CreateBarBaz (CreateBarBazRequest) returns (BarBaz) { - option (google.api.http) = { - post: "/bar_bazs" - body: "bar_baz" - }; - } - rpc DeleteBarBaz (DeleteBarBazRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/bar_bazs/{bar_baz_id}" - }; - } -} - -message BarBaz { - string bar_baz_id = 1; -} - -message ListBarBazsRequest { -} - -message ListBarBazsResponse { - repeated BarBaz bar_bazs = 1; -} - -message CreateBarBazRequest { - BarBaz bar_baz = 1; -} - -message DeleteBarBazRequest { - string bar_baz_id = 1; -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fc85ca3d..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,42 +0,0 @@ -package foo - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - -func (s *barBazServiceServerImpl) ListBarBazs(ctx context.Context, req *foo_pb.ListBarBazsRequest) (*foo_pb.ListBarBazsResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) CreateBarBaz(ctx context.Context, req *foo_pb.CreateBarBazRequest) (*foo_pb.BarBaz, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) DeleteBarBaz(ctx context.Context, req *foo_pb.DeleteBarBazRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index f64f9fac..00000000 --- a/cmd/grapi-gen-scaffold-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package foo - -import ( - "context" - "testing" - - "github.com/golang/protobuf/ptypes/empty" - - foo_pb "testapp/api/foo" -) - -func Test_BarBazServiceServer_ListBarBazs(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.ListBarBazsRequest{} - - resp, err := svr.ListBarBazs(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_CreateBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.CreateBarBazRequest{} - - resp, err := svr.CreateBarBaz(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_DeleteBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.DeleteBarBazRequest{} - - resp, err := svr.DeleteBarBaz(ctx, req) - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-scaffold-service/main.go b/cmd/grapi-gen-scaffold-service/main.go index e99776b1..25d7f91e 100644 --- a/cmd/grapi-gen-scaffold-service/main.go +++ b/cmd/grapi-gen-scaffold-service/main.go @@ -6,8 +6,8 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/svcgen" + "github.com/x-izumin/grapi/pkg/gencmd" + "github.com/x-izumin/grapi/pkg/svcgen" ) func main() { diff --git a/cmd/grapi-gen-scaffold-service/main_test.go b/cmd/grapi-gen-scaffold-service/main_test.go deleted file mode 100644 index 257629bd..00000000 --- a/cmd/grapi-gen-scaffold-service/main_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package main - -import ( - "context" - "testing" - - "github.com/spf13/afero" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - gencmdtesting "github.com/izumin5210/grapi/pkg/gencmd/testing" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen" - svcgentesting "github.com/izumin5210/grapi/pkg/svcgen/testing" -) - -func TestRun(t *testing.T) { - cases := []svcgentesting.Case{ - { - Test: "simple", - GArgs: []string{"book"}, - DArgs: []string{"book"}, - Files: []string{ - "api/protos/book.proto", - "app/server/book_server.go", - "app/server/book_server_register_funcs.go", - "app/server/book_server_test.go", - }, - }, - { - Test: "specify resource name", - GArgs: []string{"library", "--resource-name=book"}, - DArgs: []string{"library"}, - Files: []string{ - "api/protos/library.proto", - "app/server/library_server.go", - "app/server/library_server_register_funcs.go", - "app/server/library_server_test.go", - }, - }, - } - - rootDir := cli.RootDir{clib.Path("/home/src/testapp")} - - createSvcApp := func(cmd *gencmd.Command) (*svcgen.App, error) { - return svcgentesting.NewTestApp(cmd, &fakeProtocWrapper{}, cli.NopUI) - } - createGenApp := func(cmd *gencmd.Command) (*gencmd.App, error) { - return gencmdtesting.NewTestApp(cmd, cli.NopUI) - } - createCmd := func(t *testing.T, fs afero.Fs, tc svcgentesting.Case) gencmd.Executor { - ctx := &grapicmd.Ctx{ - FS: fs, - RootDir: rootDir, - Config: grapicmd.Config{ - Package: tc.PkgName, - }, - ProtocConfig: protoc.Config{ - ProtosDir: tc.ProtoDir, - OutDir: tc.ProtoOutDir, - }, - } - ctx.Config.Grapi.ServerDir = tc.ServerDir - return buildCommand(createSvcApp, gencmd.WithGrapiCtx(ctx), gencmd.WithCreateAppFunc(createGenApp)) - } - - ctx := &svcgentesting.Ctx{ - GOPATH: "/home", - RootDir: rootDir, - CreateCmd: createCmd, - Cases: cases, - } - - svcgentesting.Run(t, ctx) -} - -type fakeProtocWrapper struct{} - -func (*fakeProtocWrapper) Exec(context.Context) error { return nil } diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 2590d59c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarBazService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fa385d3b..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-kebab-case_name-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto b/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto deleted file mode 100644 index 230cdcd3..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-api-protos-foo-bar.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go deleted file mode 100644 index 68b67795..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarServiceServer is a composite interface of foo_pb.BarServiceServer and grapiserver.Server. -type BarServiceServer interface { - foo_pb.BarServiceServer - grapiserver.Server -} - -// NewBarServiceServer creates a new BarServiceServer instance. -func NewBarServiceServer() BarServiceServer { - return &barServiceServerImpl{} -} - -type barServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go deleted file mode 100644 index 27421437..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested-generate-app-server-foo-bar_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto b/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto deleted file mode 100644 index 2775531f..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-api-protos-foo-bar.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testcompany.testapp.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go deleted file mode 100644 index 68b67795..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarServiceServer is a composite interface of foo_pb.BarServiceServer and grapiserver.Server. -type BarServiceServer interface { - foo_pb.BarServiceServer - grapiserver.Server -} - -// NewBarServiceServer creates a new BarServiceServer instance. -func NewBarServiceServer() BarServiceServer { - return &barServiceServerImpl{} -} - -type barServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go deleted file mode 100644 index 27421437..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-nested_with_specify_pacakge-generate-app-server-foo-bar_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto b/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto deleted file mode 100644 index e94131cc..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-api-protos-foo.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service FooService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go deleted file mode 100644 index 04d3cf0b..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// FooServiceServer is a composite interface of api_pb.FooServiceServer and grapiserver.Server. -type FooServiceServer interface { - api_pb.FooServiceServer - grapiserver.Server -} - -// NewFooServiceServer creates a new FooServiceServer instance. -func NewFooServiceServer() FooServiceServer { - return &fooServiceServerImpl{} -} - -type fooServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go deleted file mode 100644 index 7b576996..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *fooServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterFooServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *fooServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterFooServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-simple-generate-app-server-foo_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto b/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto deleted file mode 100644 index 5fe20ee3..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-api-protos-book.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service BookService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go deleted file mode 100644 index 9c739963..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// BookServiceServer is a composite interface of api_pb.BookServiceServer and grapiserver.Server. -type BookServiceServer interface { - api_pb.BookServiceServer - grapiserver.Server -} - -// NewBookServiceServer creates a new BookServiceServer instance. -func NewBookServiceServer() BookServiceServer { - return &bookServiceServerImpl{} -} - -type bookServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go deleted file mode 100644 index 0c8e7832..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-skip_tests-generate-app-server-book_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *bookServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterBookServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *bookServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterBookServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 2590d59c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; - -service BarBazService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fa385d3b..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package foo - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index d1b1429c..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-snake_case_name-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package foo - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto b/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto deleted file mode 100644 index 447b4721..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-api-protos-foo.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testcompany.testapp; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service FooService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go deleted file mode 100644 index 04d3cf0b..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// FooServiceServer is a composite interface of api_pb.FooServiceServer and grapiserver.Server. -type FooServiceServer interface { - api_pb.FooServiceServer - grapiserver.Server -} - -// NewFooServiceServer creates a new FooServiceServer instance. -func NewFooServiceServer() FooServiceServer { - return &fooServiceServerImpl{} -} - -type fooServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go deleted file mode 100644 index 7b576996..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *fooServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterFooServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *fooServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterFooServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_package-generate-app-server-foo_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go deleted file mode 100644 index e0d87ee0..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// QuxServiceServer is a composite interface of api_pb.QuxServiceServer and grapiserver.Server. -type QuxServiceServer interface { - api_pb.QuxServiceServer - grapiserver.Server -} - -// NewQuxServiceServer creates a new QuxServiceServer instance. -func NewQuxServiceServer() QuxServiceServer { - return &quxServiceServerImpl{} -} - -type quxServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go deleted file mode 100644 index a23d82ec..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *quxServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterQuxServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *quxServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterQuxServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-app-server-qux_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto deleted file mode 100644 index 3ea614e4..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_dir-generate-pkg-foo-protos-qux.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service QuxService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto deleted file mode 100644 index e97ef74d..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-api-protos-quux.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api.out; - -option go_package = "testapp/api/out;out_pb"; - - -import "google/api/annotations.proto"; - -service QuuxService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go deleted file mode 100644 index 2aa3e521..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - out_pb "testapp/api/out" -) - -// QuuxServiceServer is a composite interface of out_pb.QuuxServiceServer and grapiserver.Server. -type QuuxServiceServer interface { - out_pb.QuuxServiceServer - grapiserver.Server -} - -// NewQuuxServiceServer creates a new QuuxServiceServer instance. -func NewQuuxServiceServer() QuuxServiceServer { - return &quuxServiceServerImpl{} -} - -type quuxServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go deleted file mode 100644 index 26cfa4ea..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - out_pb "testapp/api/out" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *quuxServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - out_pb.RegisterQuuxServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *quuxServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return out_pb.RegisterQuuxServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_proto_out_dir-generate-app-server-quux_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto b/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto deleted file mode 100644 index 5310394b..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-api-protos-library.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service LibraryService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go deleted file mode 100644 index 445f9247..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// LibraryServiceServer is a composite interface of api_pb.LibraryServiceServer and grapiserver.Server. -type LibraryServiceServer interface { - api_pb.LibraryServiceServer - grapiserver.Server -} - -// NewLibraryServiceServer creates a new LibraryServiceServer instance. -func NewLibraryServiceServer() LibraryServiceServer { - return &libraryServiceServerImpl{} -} - -type libraryServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go deleted file mode 100644 index 71a96737..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *libraryServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterLibraryServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *libraryServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterLibraryServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_resource_name-generate-app-server-library_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto b/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto deleted file mode 100644 index ee9ce2a1..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-api-protos-corge.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package testapp.api; - -option go_package = "testapp/api;api_pb"; - - -import "google/api/annotations.proto"; - -service CorgeService { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go deleted file mode 100644 index 13334764..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server.go +++ /dev/null @@ -1,26 +0,0 @@ -package server - -import ( - "context" - - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "testapp/api" -) - -// CorgeServiceServer is a composite interface of api_pb.CorgeServiceServer and grapiserver.Server. -type CorgeServiceServer interface { - api_pb.CorgeServiceServer - grapiserver.Server -} - -// NewCorgeServiceServer creates a new CorgeServiceServer instance. -func NewCorgeServiceServer() CorgeServiceServer { - return &corgeServiceServerImpl{} -} - -type corgeServiceServerImpl struct { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go deleted file mode 100644 index 93d5b5b8..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "testapp/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *corgeServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterCorgeServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *corgeServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterCorgeServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go deleted file mode 100644 index a86bc127..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-specify_server_dir-generate-pkg-foo-server-corge_server_test.go +++ /dev/null @@ -1,2 +0,0 @@ -package server - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 5ea823df..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,70 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service BarBazService { - rpc ListBarBazs (ListBarBazsRequest) returns (ListBarBazsResponse) { - option (google.api.http) = { - get: "/bar_bazs" - }; - } - rpc CreateBarBaz (CreateBarBazRequest) returns (BarBaz) { - option (google.api.http) = { - post: "/bar_bazs" - body: "bar_baz" - }; - } - rpc DeleteBarBaz (DeleteBarBazRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/bar_bazs/{bar_baz_id}" - }; - } - rpc Rename (RenameRequest) returns (RenameResponse) { - option (google.api.http) = { - get: "/bar_bazs/rename" - }; - } - rpc MoveMove (MoveMoveRequest) returns (MoveMoveResponse) { - option (google.api.http) = { - get: "/bar_bazs/move_move" - }; - } -} - -message BarBaz { - string bar_baz_id = 1; -} - -message ListBarBazsRequest { -} - -message ListBarBazsResponse { - repeated BarBaz bar_bazs = 1; -} - -message CreateBarBazRequest { - BarBaz bar_baz = 1; -} - -message DeleteBarBazRequest { - string bar_baz_id = 1; -} - -message RenameRequest { -} - -message RenameResponse { -} - -message MoveMoveRequest { -} - -message MoveMoveResponse { -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index 0fb60647..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,52 +0,0 @@ -package foo - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - -func (s *barBazServiceServerImpl) ListBarBazs(ctx context.Context, req *foo_pb.ListBarBazsRequest) (*foo_pb.ListBarBazsResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) CreateBarBaz(ctx context.Context, req *foo_pb.CreateBarBazRequest) (*foo_pb.BarBaz, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) DeleteBarBaz(ctx context.Context, req *foo_pb.DeleteBarBazRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) Rename(ctx context.Context, req *foo_pb.RenameRequest) (*foo_pb.RenameResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) MoveMove(ctx context.Context, req *foo_pb.MoveMoveRequest) (*foo_pb.MoveMoveResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index f1edda88..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_non-standard_methods-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package foo - -import ( - "context" - "testing" - - foo_pb "testapp/api/foo" -) - -func Test_BarBazServiceServer_ListBarBazs(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.ListBarBazsRequest{} - - resp, err := svr.ListBarBazs(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_CreateBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.CreateBarBazRequest{} - - resp, err := svr.CreateBarBaz(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_DeleteBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.DeleteBarBazRequest{} - - resp, err := svr.DeleteBarBaz(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_Rename(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.RenameRequest{} - - resp, err := svr.Rename(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_MoveMove(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.MoveMoveRequest{} - - resp, err := svr.MoveMove(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto b/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto deleted file mode 100644 index 44b449c3..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-api-protos-foo-bar_baz.proto +++ /dev/null @@ -1,48 +0,0 @@ -syntax = "proto3"; - -package testapp.api.foo; - -option go_package = "testapp/api/foo;foo_pb"; - - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service BarBazService { - rpc ListBarBazs (ListBarBazsRequest) returns (ListBarBazsResponse) { - option (google.api.http) = { - get: "/bar_bazs" - }; - } - rpc CreateBarBaz (CreateBarBazRequest) returns (BarBaz) { - option (google.api.http) = { - post: "/bar_bazs" - body: "bar_baz" - }; - } - rpc DeleteBarBaz (DeleteBarBazRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/bar_bazs/{bar_baz_id}" - }; - } -} - -message BarBaz { - string bar_baz_id = 1; -} - -message ListBarBazsRequest { -} - -message ListBarBazsResponse { - repeated BarBaz bar_bazs = 1; -} - -message CreateBarBazRequest { - BarBaz bar_baz = 1; -} - -message DeleteBarBazRequest { - string bar_baz_id = 1; -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go deleted file mode 100644 index fc85ca3d..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server.go +++ /dev/null @@ -1,42 +0,0 @@ -package foo - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - foo_pb "testapp/api/foo" -) - -// BarBazServiceServer is a composite interface of foo_pb.BarBazServiceServer and grapiserver.Server. -type BarBazServiceServer interface { - foo_pb.BarBazServiceServer - grapiserver.Server -} - -// NewBarBazServiceServer creates a new BarBazServiceServer instance. -func NewBarBazServiceServer() BarBazServiceServer { - return &barBazServiceServerImpl{} -} - -type barBazServiceServerImpl struct { -} - -func (s *barBazServiceServerImpl) ListBarBazs(ctx context.Context, req *foo_pb.ListBarBazsRequest) (*foo_pb.ListBarBazsResponse, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) CreateBarBaz(ctx context.Context, req *foo_pb.CreateBarBazRequest) (*foo_pb.BarBaz, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *barBazServiceServerImpl) DeleteBarBaz(ctx context.Context, req *foo_pb.DeleteBarBazRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go deleted file mode 100644 index 1c820532..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_register_funcs.go +++ /dev/null @@ -1,23 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package foo - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - foo_pb "testapp/api/foo" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *barBazServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - foo_pb.RegisterBarBazServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *barBazServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return foo_pb.RegisterBarBazServiceHandler(ctx, mux, conn) -} - diff --git a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go b/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go deleted file mode 100644 index f2414a33..00000000 --- a/cmd/grapi-gen-service/.snapshots/TestRun-with_some_standard_methods-generate-app-server-foo-bar_baz_server_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package foo - -import ( - "context" - "testing" - - foo_pb "testapp/api/foo" -) - -func Test_BarBazServiceServer_ListBarBazs(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.ListBarBazsRequest{} - - resp, err := svr.ListBarBazs(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_CreateBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.CreateBarBazRequest{} - - resp, err := svr.CreateBarBaz(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - -func Test_BarBazServiceServer_DeleteBarBaz(t *testing.T) { - svr := NewBarBazServiceServer() - - ctx := context.Background() - req := &foo_pb.DeleteBarBazRequest{} - - resp, err := svr.DeleteBarBaz(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} - diff --git a/cmd/grapi-gen-service/main.go b/cmd/grapi-gen-service/main.go index 704d2299..fcd80644 100644 --- a/cmd/grapi-gen-service/main.go +++ b/cmd/grapi-gen-service/main.go @@ -6,8 +6,8 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/svcgen" + "github.com/x-izumin/grapi/pkg/gencmd" + "github.com/x-izumin/grapi/pkg/svcgen" ) func main() { diff --git a/cmd/grapi-gen-service/main_test.go b/cmd/grapi-gen-service/main_test.go deleted file mode 100644 index 666e92c3..00000000 --- a/cmd/grapi-gen-service/main_test.go +++ /dev/null @@ -1,209 +0,0 @@ -package main - -import ( - "context" - "testing" - - "github.com/spf13/afero" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - gencmdtesting "github.com/izumin5210/grapi/pkg/gencmd/testing" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen" - svcgentesting "github.com/izumin5210/grapi/pkg/svcgen/testing" -) - -func TestRun(t *testing.T) { - cases := []svcgentesting.Case{ - { - Test: "simple", - GArgs: []string{"foo"}, - DArgs: []string{"foo"}, - Files: []string{ - "api/protos/foo.proto", - "app/server/foo_server.go", - "app/server/foo_server_register_funcs.go", - "app/server/foo_server_test.go", - }, - }, - { - Test: "specify package", - GArgs: []string{"foo"}, - DArgs: []string{"foo"}, - Files: []string{ - "api/protos/foo.proto", - "app/server/foo_server.go", - "app/server/foo_server_register_funcs.go", - "app/server/foo_server_test.go", - }, - PkgName: "testcompany.testapp", - }, - { - Test: "nested", - GArgs: []string{"foo/bar"}, - DArgs: []string{"foo/bar"}, - Files: []string{ - "api/protos/foo/bar.proto", - "app/server/foo/bar_server.go", - "app/server/foo/bar_server_register_funcs.go", - "app/server/foo/bar_server_test.go", - }, - }, - { - Test: "nested with specify pacakge", - GArgs: []string{"foo/bar"}, - DArgs: []string{"foo/bar"}, - Files: []string{ - "api/protos/foo/bar.proto", - "app/server/foo/bar_server.go", - "app/server/foo/bar_server_register_funcs.go", - "app/server/foo/bar_server_test.go", - }, - PkgName: "testcompany.testapp", - }, - { - Test: "snake_case name", - GArgs: []string{"foo/bar_baz"}, - DArgs: []string{"foo/bar_baz"}, - Files: []string{ - "api/protos/foo/bar_baz.proto", - "app/server/foo/bar_baz_server.go", - "app/server/foo/bar_baz_server_register_funcs.go", - "app/server/foo/bar_baz_server_test.go", - }, - }, - { - Test: "kebab-case name", - GArgs: []string{"foo/bar-baz"}, - DArgs: []string{"foo/bar-baz"}, - Files: []string{ - "api/protos/foo/bar_baz.proto", - "app/server/foo/bar_baz_server.go", - "app/server/foo/bar_baz_server_register_funcs.go", - "app/server/foo/bar_baz_server_test.go", - }, - }, - { - Test: "with some standard methods", - GArgs: []string{"foo/bar-baz", "list", "create", "delete"}, - DArgs: []string{"foo/bar-baz"}, - Files: []string{ - "api/protos/foo/bar_baz.proto", - "app/server/foo/bar_baz_server.go", - "app/server/foo/bar_baz_server_register_funcs.go", - "app/server/foo/bar_baz_server_test.go", - }, - }, - { - Test: "with non-standard methods", - GArgs: []string{"foo/bar-baz", "list", "create", "rename", "delete", "move_move"}, - DArgs: []string{"foo/bar-baz"}, - Files: []string{ - "api/protos/foo/bar_baz.proto", - "app/server/foo/bar_baz_server.go", - "app/server/foo/bar_baz_server_register_funcs.go", - "app/server/foo/bar_baz_server_test.go", - }, - }, - { - Test: "specify proto dir", - GArgs: []string{"qux"}, - DArgs: []string{"qux"}, - Files: []string{ - "pkg/foo/protos/qux.proto", - "app/server/qux_server.go", - "app/server/qux_server_register_funcs.go", - "app/server/qux_server_test.go", - }, - ProtoDir: "pkg/foo/protos", - }, - { - Test: "specify proto out dir", - GArgs: []string{"quux"}, - DArgs: []string{"quux"}, - Files: []string{ - "api/protos/quux.proto", - "app/server/quux_server.go", - "app/server/quux_server_register_funcs.go", - "app/server/quux_server_test.go", - }, - ProtoOutDir: "api/out", - }, - { - Test: "specify server dir", - GArgs: []string{"corge"}, - DArgs: []string{"corge"}, - Files: []string{ - "api/protos/corge.proto", - "pkg/foo/server/corge_server.go", - "pkg/foo/server/corge_server_register_funcs.go", - "pkg/foo/server/corge_server_test.go", - }, - ServerDir: "pkg/foo/server", - }, - { - Test: "skip tests", - GArgs: []string{"--skip-test", "book"}, - DArgs: []string{"book"}, - Files: []string{ - "api/protos/book.proto", - "app/server/book_server.go", - "app/server/book_server_register_funcs.go", - }, - SkippedFiles: map[string]struct{}{ - "app/server/book_server_test.go": {}, - }, - }, - { - Test: "specify resource name", - GArgs: []string{"library", "--resource-name=book"}, - DArgs: []string{"library"}, - Files: []string{ - "api/protos/library.proto", - "app/server/library_server.go", - "app/server/library_server_register_funcs.go", - "app/server/library_server_test.go", - }, - }, - } - - rootDir := cli.RootDir{clib.Path("/home/src/testapp")} - - createSvcApp := func(cmd *gencmd.Command) (*svcgen.App, error) { - return svcgentesting.NewTestApp(cmd, &fakeProtocWrapper{}, cli.NopUI) - } - createGenApp := func(cmd *gencmd.Command) (*gencmd.App, error) { - return gencmdtesting.NewTestApp(cmd, cli.NopUI) - } - createCmd := func(t *testing.T, fs afero.Fs, tc svcgentesting.Case) gencmd.Executor { - ctx := &grapicmd.Ctx{ - FS: fs, - RootDir: rootDir, - Config: grapicmd.Config{ - Package: tc.PkgName, - }, - ProtocConfig: protoc.Config{ - ProtosDir: tc.ProtoDir, - OutDir: tc.ProtoOutDir, - }, - } - ctx.Config.Grapi.ServerDir = tc.ServerDir - return buildCommand(createSvcApp, gencmd.WithGrapiCtx(ctx), gencmd.WithCreateAppFunc(createGenApp)) - } - - ctx := &svcgentesting.Ctx{ - GOPATH: "/home", - RootDir: rootDir, - CreateCmd: createCmd, - Cases: cases, - } - - svcgentesting.Run(t, ctx) -} - -type fakeProtocWrapper struct{} - -func (*fakeProtocWrapper) Exec(context.Context) error { return nil } diff --git a/cmd/grapi-gen-type/.snapshots/TestType-camel-generate-api-protos-type-foo-bar_user.proto b/cmd/grapi-gen-type/.snapshots/TestType-camel-generate-api-protos-type-foo-bar_user.proto deleted file mode 100644 index 9590f46e..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-camel-generate-api-protos-type-foo-bar_user.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type.foo; - -option go_package = "testapp/api/type/foo;foo_pb"; - -message BarUser { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-kebab-generate-api-protos-type-foo-bar_user.proto b/cmd/grapi-gen-type/.snapshots/TestType-kebab-generate-api-protos-type-foo-bar_user.proto deleted file mode 100644 index 9590f46e..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-kebab-generate-api-protos-type-foo-bar_user.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type.foo; - -option go_package = "testapp/api/type/foo;foo_pb"; - -message BarUser { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-nested-generate-api-protos-type-foo-user.proto b/cmd/grapi-gen-type/.snapshots/TestType-nested-generate-api-protos-type-foo-user.proto deleted file mode 100644 index 260291f9..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-nested-generate-api-protos-type-foo-user.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type.foo; - -option go_package = "testapp/api/type/foo;foo_pb"; - -message User { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-nested_with_specified_package-generate-api-protos-type-foo-user.proto b/cmd/grapi-gen-type/.snapshots/TestType-nested_with_specified_package-generate-api-protos-type-foo-user.proto deleted file mode 100644 index 260291f9..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-nested_with_specified_package-generate-api-protos-type-foo-user.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type.foo; - -option go_package = "testapp/api/type/foo;foo_pb"; - -message User { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-simple-generate-api-protos-type-book.proto b/cmd/grapi-gen-type/.snapshots/TestType-simple-generate-api-protos-type-book.proto deleted file mode 100644 index ec954fee..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-simple-generate-api-protos-type-book.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type; - -option go_package = "testapp/api/type;type_pb"; - -message Book { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-simple_with_specified_package-generate-api-protos-type-book.proto b/cmd/grapi-gen-type/.snapshots/TestType-simple_with_specified_package-generate-api-protos-type-book.proto deleted file mode 100644 index ec954fee..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-simple_with_specified_package-generate-api-protos-type-book.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type; - -option go_package = "testapp/api/type;type_pb"; - -message Book { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/.snapshots/TestType-snake-generate-api-protos-type-foo-bar_user.proto b/cmd/grapi-gen-type/.snapshots/TestType-snake-generate-api-protos-type-foo-bar_user.proto deleted file mode 100644 index 9590f46e..00000000 --- a/cmd/grapi-gen-type/.snapshots/TestType-snake-generate-api-protos-type-foo-bar_user.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package testapp.api.type.foo; - -option go_package = "testapp/api/type/foo;foo_pb"; - -message BarUser { - string id = 1; -} - diff --git a/cmd/grapi-gen-type/di/app.go b/cmd/grapi-gen-type/di/app.go deleted file mode 100644 index f61c910d..00000000 --- a/cmd/grapi-gen-type/di/app.go +++ /dev/null @@ -1,12 +0,0 @@ -package di - -import ( - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/protoc" -) - -type CreateAppFunc func(*gencmd.Command) (*App, error) - -type App struct { - Protoc protoc.Wrapper -} diff --git a/cmd/grapi-gen-type/di/wire.go b/cmd/grapi-gen-type/di/wire.go deleted file mode 100644 index 038985b6..00000000 --- a/cmd/grapi-gen-type/di/wire.go +++ /dev/null @@ -1,21 +0,0 @@ -//+build wireinject - -package di - -import ( - "github.com/google/wire" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/protoc" -) - -func NewApp(*gencmd.Command) (*App, error) { - wire.Build( - App{}, - gencmd.Set, - cli.UIInstance, - protoc.WrapperSet, - ) - return nil, nil -} diff --git a/cmd/grapi-gen-type/di/wire_gen.go b/cmd/grapi-gen-type/di/wire_gen.go deleted file mode 100644 index d0f33a49..00000000 --- a/cmd/grapi-gen-type/di/wire_gen.go +++ /dev/null @@ -1,36 +0,0 @@ -// Code generated by Wire. DO NOT EDIT. - -//go:generate wire -//+build !wireinject - -package di - -import ( - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" -) - -// Injectors from wire.go: - -func NewApp(command *gencmd.Command) (*App, error) { - ctx := gencmd.ProvideCtx(command) - grapicmdCtx := gencmd.ProvideGrapiCtx(ctx) - config := grapicmd.ProvideProtocConfig(grapicmdCtx) - fs := grapicmd.ProvideFS(grapicmdCtx) - executor := grapicmd.ProvideExec(grapicmdCtx) - io := grapicmd.ProvideIO(grapicmdCtx) - ui := cli.UIInstance(io) - rootDir := grapicmd.ProvideRootDir(grapicmdCtx) - gexConfig := protoc.ProvideGexConfig(fs, executor, io, rootDir) - repository, err := protoc.ProvideToolRepository(gexConfig) - if err != nil { - return nil, err - } - wrapper := protoc.NewWrapper(config, fs, executor, ui, repository, rootDir) - app := &App{ - Protoc: wrapper, - } - return app, nil -} diff --git a/cmd/grapi-gen-type/main.go b/cmd/grapi-gen-type/main.go index a0c4ab64..73b501f3 100644 --- a/cmd/grapi-gen-type/main.go +++ b/cmd/grapi-gen-type/main.go @@ -8,11 +8,11 @@ import ( "github.com/serenize/snaker" "github.com/spf13/cobra" - "github.com/izumin5210/grapi/cmd/grapi-gen-type/di" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-type/template" - "github.com/izumin5210/grapi/pkg/gencmd" - gencmdutil "github.com/izumin5210/grapi/pkg/gencmd/util" - "github.com/izumin5210/grapi/pkg/grapicmd" + "github.com/x-izumin/grapi/cmd/grapi-gen-type/di" + _ "github.com/x-izumin/grapi/cmd/grapi-gen-type/template" + "github.com/x-izumin/grapi/pkg/gencmd" + gencmdutil "github.com/x-izumin/grapi/pkg/gencmd/util" + "github.com/x-izumin/grapi/pkg/grapicmd" ) func main() { diff --git a/cmd/grapi-gen-type/main_test.go b/cmd/grapi-gen-type/main_test.go deleted file mode 100644 index 3de1a416..00000000 --- a/cmd/grapi-gen-type/main_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package main - -import ( - "context" - "go/build" - "testing" - - "github.com/bradleyjkemp/cupaloy/v2" - "github.com/spf13/afero" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/cmd/grapi-gen-type/di" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - gencmdtesting "github.com/izumin5210/grapi/pkg/gencmd/testing" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" -) - -func TestType(t *testing.T) { - cases := []struct { - test string - args []string - files []string - config string - }{ - { - test: "simple", - args: []string{"book"}, - files: []string{"api/protos/type/book.proto"}, - }, - { - test: "nested", - args: []string{"foo/user"}, - files: []string{"api/protos/type/foo/user.proto"}, - }, - { - test: "camel", - args: []string{"foo/barUser"}, - files: []string{"api/protos/type/foo/bar_user.proto"}, - }, - { - test: "snake", - args: []string{"foo/bar_user"}, - files: []string{"api/protos/type/foo/bar_user.proto"}, - }, - { - test: "kebab", - args: []string{"foo/bar-user"}, - files: []string{"api/protos/type/foo/bar_user.proto"}, - }, - { - test: "simple with specified package", - args: []string{"book"}, - files: []string{"api/protos/type/book.proto"}, - config: `package = "yourcompany.yourapp"`, - }, - { - test: "nested with specified package", - args: []string{"foo/user"}, - files: []string{"api/protos/type/foo/user.proto"}, - config: `package = "yourcompany.yourapp"`, - }, - } - - defer func(c build.Context) { fs.BuildContext = c }(fs.BuildContext) - fs.BuildContext = build.Context{GOPATH: "/go"} - rootDir := cli.RootDir{clib.Path("/go/src/testapp")} - - createApp := func(cmd *gencmd.Command) (*di.App, error) { - return &di.App{Protoc: &fakeProtocWrapper{}}, nil - } - createGenApp := func(cmd *gencmd.Command) (*gencmd.App, error) { - return gencmdtesting.NewTestApp(cmd, cli.NopUI) - } - createCmd := func(t *testing.T, fs afero.Fs) gencmd.Executor { - ctx := &grapicmd.Ctx{ - FS: fs, - RootDir: rootDir, - } - return buildCommand(createApp, gencmd.WithGrapiCtx(ctx), gencmd.WithCreateAppFunc(createGenApp)) - } - - for _, tc := range cases { - t.Run(tc.test, func(t *testing.T) { - fs := afero.NewMemMapFs() - afero.WriteFile(fs, rootDir.Join("grapi.toml").String(), []byte{}, 0755) - - t.Run("generate", func(t *testing.T) { - cmd := createCmd(t, fs) - cmd.Command().SetArgs(append([]string{"generate"}, tc.args...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.files { - t.Run(file, func(t *testing.T) { - data, err := afero.ReadFile(fs, rootDir.Join(file).String()) - - if err != nil { - t.Errorf("returned an error: %v", err) - } - - cupaloy.SnapshotT(t, string(data)) - }) - } - }) - - t.Run("destroy", func(t *testing.T) { - cmd := createCmd(t, fs) - cmd.Command().SetArgs(append([]string{"destroy"}, tc.args...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.files { - t.Run(file, func(t *testing.T) { - ok, err := afero.Exists(fs, rootDir.Join(file).String()) - - if err != nil { - t.Errorf("Exists(fs, %q) returned an error: %v", file, err) - } - - if ok { - t.Errorf("%q should not exist", file) - } - }) - } - }) - }) - } -} - -type fakeProtocWrapper struct{} - -func (*fakeProtocWrapper) Exec(context.Context) error { return nil } diff --git a/cmd/grapi-gen-type/template/_data/api/protos/{{.Path}}.proto.tmpl b/cmd/grapi-gen-type/template/_data/api/protos/{{.Path}}.proto.tmpl deleted file mode 100644 index a9bb09bd..00000000 --- a/cmd/grapi-gen-type/template/_data/api/protos/{{.Path}}.proto.tmpl +++ /dev/null @@ -1,9 +0,0 @@ -syntax = "proto3"; - -package {{ .Proto.Package }}; - -option go_package = "{{ .PbGo.PackagePath }};{{ .PbGo.PackageName }}"; - -message {{.Name}} { - string id = 1; -} diff --git a/cmd/grapi-gen-type/template/gen.go b/cmd/grapi-gen-type/template/gen.go deleted file mode 100644 index ba18632b..00000000 --- a/cmd/grapi-gen-type/template/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate statik -src ./_data -dest .. -p template -f -m - -package template diff --git a/cmd/grapi-gen-type/template/statik.go b/cmd/grapi-gen-type/template/statik.go deleted file mode 100644 index 02b3003a..00000000 --- a/cmd/grapi-gen-type/template/statik.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by statik. DO NOT EDIT. - -// Package statik contains static assets. -package template - -import ( - "github.com/rakyll/statik/fs" -) - -func init() { - data := "PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00 \x00api/protos/{{.Path}}.proto.tmplUT\x05\x00\x01\x80Cm8\\\xcd=\xaaB1\x10\xc5\xf1~Vq\xc8\x02\x02\x8fW\x86\xd4v\x92\x1dH\xd4K\x0cr3\xe1f\n%\xcc\xdee\xfc*l\xff\xfc8g\xdc\x9b\xe4\x1b\"\\\xdfX\xf8\xdf\x05\xa2\x9eO\xd7\\\x16\xcc \x9f\xac\xfa\xf4.\xaa\x81\x88\xbbTn(|\xf8\xc0\x08\xf7\xb4\xc7\xdd\x97\xa6,\x17\xe3\xbf}\x9fW\x9b\xb1\x9bu\x19\xe3u\xe3\xad\xaab\x120d\xab\xad\xa0\x9e\x11\xf1\x17H\xe9\x11\x00\x00\xff\xffPK\x07\x08O\x08A4v\x00\x00\x00\xa2\x00\x00\x00PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(O\x08A4v\x00\x00\x00\xa2\x00\x00\x00\x1f\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00api/protos/{{.Path}}.proto.tmplUT\x05\x00\x01\x80Cm8PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00V\x00\x00\x00\xcc\x00\x00\x00\x00\x00" - fs.Register(data) -} diff --git a/cmd/grapi/main.go b/cmd/grapi/main.go index 6315dbdd..2bc48d52 100644 --- a/cmd/grapi/main.go +++ b/cmd/grapi/main.go @@ -6,9 +6,9 @@ import ( "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/cmd" + "github.com/x-izumin/grapi/pkg/cli" + "github.com/x-izumin/grapi/pkg/grapicmd" + "github.com/x-izumin/grapi/pkg/grapicmd/cmd" ) func main() { diff --git a/go.mod b/go.mod index 2db7d1ab..d3cde784 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,4 @@ +// Deprecated: use github.com/x-izumin/grapi instead. module github.com/izumin5210/grapi go 1.12 @@ -26,6 +27,7 @@ require ( github.com/spf13/viper v1.4.0 github.com/srvc/appctx v0.1.0 github.com/tcnksm/go-input v0.0.0-20180404061846-548a7d7a8ee8 + github.com/x-izumin/grapi v0.8.0 // indirect go.uber.org/zap v1.10.0 golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586 // indirect golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 diff --git a/go.sum b/go.sum index f804d195..77f214d4 100644 --- a/go.sum +++ b/go.sum @@ -194,6 +194,10 @@ github.com/tcnksm/go-input v0.0.0-20180404061846-548a7d7a8ee8/go.mod h1:IlWNj9v/ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/x-izumin/gex v0.7.0 h1:e1CpoOqTWGRG71KhOOHsXYmXG33RT0ddc6QzedFFMgQ= +github.com/x-izumin/gex v0.7.0/go.mod h1:NPllnnJqH5urK0Ikodk3dKjDfCE34atOTV/oRZ3VbU0= +github.com/x-izumin/grapi v0.8.0 h1:zuTyc9wVg6ADKEYNsKGo5Oed7yZYi1aL8+XORFK3ubk= +github.com/x-izumin/grapi v0.8.0/go.mod h1:PxVKVmvunAcH+p3DFxLWC3I4uvLKb0kXEoRFPTjHWhU= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= diff --git a/pkg/cli/nop_ui.go b/pkg/cli/nop_ui.go index cc90c51a..d82c1305 100644 --- a/pkg/cli/nop_ui.go +++ b/pkg/cli/nop_ui.go @@ -1,12 +1,7 @@ package cli -var NopUI = &nopUIImpl{} +import ( + newCli "github.com/x-izumin/grapi/pkg/cli" +) -type nopUIImpl struct{} - -func (*nopUIImpl) Section(msg string) {} -func (*nopUIImpl) Subsection(msg string) {} -func (*nopUIImpl) ItemSuccess(msg string) {} -func (*nopUIImpl) ItemSkipped(msg string) {} -func (*nopUIImpl) ItemFailure(msg string, errs ...error) {} -func (*nopUIImpl) Confirm(msg string) (bool, error) { return true, nil } +var NopUI = newCli.NopUI diff --git a/pkg/cli/types.go b/pkg/cli/types.go index ab4fe66d..4406f4ed 100644 --- a/pkg/cli/types.go +++ b/pkg/cli/types.go @@ -1,15 +1,8 @@ package cli import ( - "github.com/izumin5210/clig/pkg/clib" + newCli "github.com/x-izumin/grapi/pkg/cli" ) // RootDir represents a project root directory. -type RootDir struct { - clib.Path -} - -// BinDir returns the directory path contains executable binaries. -func (d *RootDir) BinDir() clib.Path { - return d.Join("bin") -} +type RootDir = newCli.RootDir diff --git a/pkg/cli/ui.go b/pkg/cli/ui.go index e7210b51..ffe03d60 100644 --- a/pkg/cli/ui.go +++ b/pkg/cli/ui.go @@ -1,194 +1,14 @@ package cli import ( - "fmt" - "io" - "strconv" - "strings" - "sync" - - "github.com/fatih/color" - "github.com/izumin5210/clig/pkg/clib" - "github.com/pkg/errors" - "github.com/tcnksm/go-input" - "go.uber.org/zap" + newCli "github.com/x-izumin/grapi/pkg/cli" ) // UI is an interface for intaracting with the terminal. -type UI interface { - Section(msg string) - Subsection(msg string) - ItemSuccess(msg string) - ItemSkipped(msg string) - ItemFailure(msg string, errs ...error) - Confirm(msg string) (bool, error) -} - -var ( - ui UI - uiMu sync.Mutex -) +type UI = newCli.UI // UIInstance retuens a singleton UI instance. -func UIInstance(io *clib.IO) UI { - uiMu.Lock() - defer uiMu.Unlock() - if ui == nil { - ui = NewUI(io) - } - return ui -} +var UIInstance = newCli.UIInstance // NewUI creates a new UI instance. -func NewUI(io *clib.IO) UI { - return &uiImpl{ - out: io.Out, - inputUI: &input.UI{ - Reader: io.In, - Writer: io.Out, - }, - } -} - -type uiImpl struct { - out io.Writer - inSection bool - inputUI *input.UI -} - -func (u *uiImpl) Section(msg string) { - if u.inSection { - fmt.Fprintln(u.out) - u.inSection = false - } - printTypeSection.Fprintln(u.out, msg) -} - -func (u *uiImpl) Subsection(msg string) { - if u.inSection { - fmt.Fprintln(u.out) - u.inSection = false - } - printTypeSubsection.Fprintln(u.out, msg) -} - -func (u *uiImpl) ItemSuccess(msg string) { - u.inSection = true - printTypeItemSuccess.Fprintln(u.out, msg) -} - -func (u *uiImpl) ItemSkipped(msg string) { - u.inSection = true - printTypeItemSkipped.Fprintln(u.out, msg) -} - -func (u *uiImpl) ItemFailure(msg string, errs ...error) { - u.inSection = true - printTypeItemFailure.Fprintln(u.out, msg) - cfg := configByPrintType[printTypeItemFailure] - pad := strings.Repeat(" ", cfg.indent+4) - fprintln := color.New(color.FgRed).FprintlnFunc() - for _, err := range errs { - for _, s := range strings.Split(err.Error(), "\n") { - fprintln(u.out, pad+s) - } - } -} - -func (u *uiImpl) Confirm(msg string) (bool, error) { - ans, err := u.inputUI.Ask(fmt.Sprintf("%s [Y/n]", msg), &input.Options{ - HideOrder: true, - Loop: true, - ValidateFunc: func(ans string) error { - zap.L().Debug("receive user input", zap.String("query", msg), zap.String("input", ans)) - if ans != "Y" && ans != "n" { - return fmt.Errorf("input must be Y or n") - } - return nil - }, - }) - if err != nil { - return false, errors.WithStack(err) - } - return ans == "Y", nil -} - -type fprintFunc func(w io.Writer, msg string) - -type printConfig struct { - prefix string - colorAttrs []color.Attribute - indent int - allColor bool -} - -type printType int - -const ( - printTypeUnknown printType = iota - printTypeSection - printTypeSubsection - printTypeItemSuccess - printTypeItemSkipped - printTypeItemFailure -) - -const ( - indentSizeItem = 4 -) - -var ( - configByPrintType = map[printType]printConfig{ - printTypeSection: { - prefix: "➜", - colorAttrs: []color.Attribute{color.FgYellow}, - allColor: true, - }, - printTypeSubsection: { - prefix: "▸", - colorAttrs: []color.Attribute{color.FgBlue}, - allColor: true, - }, - printTypeItemSuccess: { - prefix: "✔", - colorAttrs: []color.Attribute{color.Bold, color.FgGreen}, - indent: indentSizeItem, - }, - printTypeItemSkipped: { - prefix: "╌", - colorAttrs: []color.Attribute{color.Bold, color.FgBlue}, - indent: indentSizeItem, - }, - printTypeItemFailure: { - prefix: "✗", - colorAttrs: []color.Attribute{color.Bold, color.FgRed}, - indent: indentSizeItem, - }, - } - fprintlnFuncByPrintType = map[printType]fprintFunc{} -) - -func init() { - for pt, cfg := range configByPrintType { - cfg := cfg - fmtStr := "%s" - if cfg.indent > 0 { - fmtStr = "%" + strconv.FormatInt(int64(cfg.indent), 10) + "s" - } - if cfg.allColor { - colored := color.New(cfg.colorAttrs...).FprintfFunc() - fprintlnFuncByPrintType[pt] = func(w io.Writer, msg string) { - colored(w, " "+fmtStr+" %s\n", cfg.prefix, msg) - } - } else { - prefix := color.New(cfg.colorAttrs...).Sprintf(fmtStr, cfg.prefix) - fprintlnFuncByPrintType[pt] = func(w io.Writer, msg string) { - fmt.Fprintf(w, " %s %s\n", prefix, msg) - } - } - } -} - -func (pt printType) Fprintln(w io.Writer, msg string) { - fprintlnFuncByPrintType[pt](w, msg) -} +var NewUI = newCli.NewUI diff --git a/pkg/cli/ui_test.go b/pkg/cli/ui_test.go deleted file mode 100644 index cb6b3970..00000000 --- a/pkg/cli/ui_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package cli_test - -import ( - "bytes" - "errors" - "strings" - "testing" - - "github.com/fatih/color" - "github.com/izumin5210/clig/pkg/clib" - - "github.com/izumin5210/grapi/pkg/cli" -) - -func TestUI(t *testing.T) { - defer func(b bool) { color.NoColor = b }(color.NoColor) - color.NoColor = true - - want := ` ➜ section 1 - ▸ subsection 1.1 - ✔ created - ╌ skipped - ✔ ok - - ▸ subsection 1.2 - ✗ failure - foobar - baz - - ➜ section 2 - ✗ fail!!! -` - - io := clib.NewBufferedIO() - ui := cli.NewUI(io) - - ui.Section("section 1") - ui.Subsection("subsection 1.1") - ui.ItemSuccess("created") - ui.ItemSkipped("skipped") - ui.ItemSuccess("ok") - ui.Subsection("subsection 1.2") - ui.ItemFailure("failure", errors.New("foobar"), errors.New("baz")) - ui.Section("section 2") - ui.ItemFailure("fail!!!") - - if got := io.Out.(*bytes.Buffer).String(); got != want { - t.Errorf("got:\n%s\nwant:\n%s", got, want) - } -} - -type errReader struct { -} - -func (r *errReader) Read(p []byte) (n int, err error) { - return 0, errors.New("failed to read") -} - -func TestUI_Confirm(t *testing.T) { - type TestContext struct { - io *clib.IO - ui cli.UI - } - - createTestContext := func() *TestContext { - io := clib.NewBufferedIO() - return &TestContext{ - io: io, - ui: cli.NewUI(io), - } - } - - cases := []struct { - test string - errMsgCnt int - input string - output bool - }{ - { - test: "with inputs 'n'", - errMsgCnt: 0, - input: "n\n", - output: false, - }, - { - test: "with inputs 'Y'", - errMsgCnt: 0, - input: "Y\n", - output: true, - }, - { - test: "with inputs 2 invalid chars and Y", - errMsgCnt: 2, - input: "y\nN\nY\n", - output: true, - }, - { - test: "with inputs 1 invalid chars and n", - errMsgCnt: 2, - input: "N\ny\nn\n", - output: false, - }, - } - - for _, c := range cases { - t.Run(c.test, func(t *testing.T) { - ctx := createTestContext() - ctx.io.In.(*bytes.Buffer).WriteString(c.input) - - ok, err := ctx.ui.Confirm(c.test) - - if got, want := ctx.io.Out.(*bytes.Buffer).String(), c.test; !strings.HasPrefix(got, want) { - t.Errorf("Confirm() wrote %q, want %q", got, want) - } - - wantErrMsg := "input must be Y or n\n" - if got, want := strings.Count(ctx.io.Out.(*bytes.Buffer).String(), wantErrMsg), c.errMsgCnt; got != want { - t.Errorf("Confirm() wrote %q as error %d times, want %d times", wantErrMsg, got, want) - } - - if err != nil { - t.Errorf("Confirm() should not return errors, but returned %v", err) - } - - if got, want := ok, c.output; got != want { - t.Errorf("Confirm() returned %t, want %t", got, want) - } - }) - } - - t.Run("when failed to read", func(t *testing.T) { - ui := cli.NewUI(clib.NewIO(&errReader{}, new(bytes.Buffer), new(bytes.Buffer))) - - ok, err := ui.Confirm("test") - - if err == nil { - t.Error("Confirm() should return an error") - } - - if ok { - t.Error("Confirm() should return false") - } - }) -} diff --git a/pkg/gencmd/app.go b/pkg/gencmd/app.go index e403a12c..6d093608 100644 --- a/pkg/gencmd/app.go +++ b/pkg/gencmd/app.go @@ -1,12 +1,11 @@ package gencmd -import "github.com/izumin5210/grapi/pkg/cli" +import ( + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" +) // CreateAppFunc initializes dependencies. -type CreateAppFunc func(*Command) (*App, error) +type CreateAppFunc = newGencmd.CreateAppFunc // App contains dependencies to execute a generator. -type App struct { - Generator Generator - UI cli.UI -} +type App = newGencmd.App diff --git a/pkg/gencmd/command.go b/pkg/gencmd/command.go index 15309ae5..56b2c803 100644 --- a/pkg/gencmd/command.go +++ b/pkg/gencmd/command.go @@ -1,89 +1,16 @@ package gencmd import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/pflag" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) // Command represents a subcommand of a generator plugin. It will be converted to a *cobra.Command object internally. -type Command struct { - // Use, Short, Long, Example and Args are pass-through into *cobra.Command object. - Use string - Short string - Long string - Example string - Args cobra.PositionalArgs - - // BuildParams returns parameters to generate/destroy files(required). - BuildParams func(c *Command, args []string) (interface{}, error) - - // PreRun is executed in *cobra.Command.PreRunE. - PreRun func(c *Command, args []string) error - - // PostRun is executed in *cobra.Command.PostRunE. - PostRun func(c *Command, args []string) error - - // ShouldRun is executed for each generated files. When it returns false, the file will be skipped. - ShouldRun ShouldRunFunc - - // ShouldInsideApp will disable the command when a current working directory is not inside of a grapi project. - ShouldInsideApp bool - - flags *pflag.FlagSet - ctx *Ctx -} - -// Flags returns a FlagSet that applies to this commmand. -func (c *Command) Flags() *pflag.FlagSet { - if c.flags == nil { - c.flags = new(pflag.FlagSet) - } - return c.flags -} - -// Ctx returns the context object. -func (c *Command) Ctx() *Ctx { - return c.ctx -} - -func (c *Command) newCobraCommand() *cobra.Command { - cc := &cobra.Command{ - Use: c.Use, - Short: c.Short, - Long: c.Long, - Example: c.Example, - Args: c.Args, - PreRunE: func(_ *cobra.Command, args []string) error { - if c.ShouldInsideApp && !c.Ctx().IsInsideApp() { - return errors.New("should execute inside grapi project") - } - if c.PreRun != nil { - err := c.PreRun(c, args) - if err != nil { - return errors.WithStack(err) - } - } - return nil - }, - } - if c.PostRun != nil { - cc.PostRunE = func(_ *cobra.Command, args []string) error { return c.PostRun(c, args) } - } - cc.PersistentFlags().AddFlagSet(c.Flags()) - return cc -} +type Command = newGencmd.Command // File represents a file content. -type File struct { - Path string - Body string -} +type File = newGencmd.File // Entry represents a file that will be generated. -type Entry struct { - File - Template File -} +type Entry = newGencmd.Entry -type ShouldRunFunc func(e *Entry) bool +type ShouldRunFunc = newGencmd.ShouldRunFunc diff --git a/pkg/gencmd/context.go b/pkg/gencmd/context.go index 272701af..5f4f853b 100644 --- a/pkg/gencmd/context.go +++ b/pkg/gencmd/context.go @@ -1,38 +1,8 @@ package gencmd import ( - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/pkg/errors" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) -func defaultCtx() *Ctx { - return &Ctx{ - Ctx: &grapicmd.Ctx{}, - } -} - // Ctx defines a context of a generator. -type Ctx struct { - *grapicmd.Ctx - - CreateAppFunc CreateAppFunc -} - -func (c *Ctx) apply(opts []Option) { - for _, f := range opts { - f(c) - } -} - -// CreateApp initializes dependencies. -func (c *Ctx) CreateApp(cmd *Command) (*App, error) { - f := c.CreateAppFunc - if c.CreateAppFunc == nil { - f = newApp - } - app, err := f(cmd) - if err != nil { - return nil, errors.WithStack(err) - } - return app, nil -} +type Ctx = newGencmd.Ctx diff --git a/pkg/gencmd/executor.go b/pkg/gencmd/executor.go index 5d10017f..7e06b630 100644 --- a/pkg/gencmd/executor.go +++ b/pkg/gencmd/executor.go @@ -1,48 +1,7 @@ package gencmd import ( - "fmt" - "os" - - "github.com/pkg/errors" - "github.com/spf13/cobra" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) -type Executor interface { - Command() *cobra.Command - Execute() error - MustExecute() -} - -func newExecutor(ctx *Ctx, cmd *cobra.Command) Executor { - return &executorImpl{ctx: ctx, cmd: cmd} -} - -type executorImpl struct { - ctx *Ctx - cmd *cobra.Command -} - -func (c *executorImpl) Command() *cobra.Command { - return c.cmd -} - -func (c *executorImpl) Execute() error { - err := c.ctx.Init() - if err != nil { - return errors.Wrap(err, "failed to initialize context") - } - - return errors.WithStack(c.cmd.Execute()) -} - -func (c *executorImpl) MustExecute() { - var code int - - if err := c.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - code = 1 - } - - os.Exit(code) -} +type Executor = newGencmd.Executor diff --git a/pkg/gencmd/generator.go b/pkg/gencmd/generator.go index fcab9f29..9ecdd983 100644 --- a/pkg/gencmd/generator.go +++ b/pkg/gencmd/generator.go @@ -1,208 +1,9 @@ package gencmd import ( - "net/http" - "os" - "path/filepath" - "strings" - - "github.com/pkg/errors" - "github.com/rakyll/statik/fs" - "github.com/spf13/afero" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) -type Generator interface { - Generate(params interface{}) error - Destroy(params interface{}) error -} - -func NewGenerator( - fs afero.Fs, - ui cli.UI, - outDir clib.Path, - templateFS http.FileSystem, - shouldRunFunc ShouldRunFunc, -) Generator { - return &generatorImpl{ - fs: fs, - ui: ui, - outDir: outDir, - templateFS: templateFS, - shouldRunFunc: shouldRunFunc, - } -} - -type generatorImpl struct { - fs afero.Fs - ui cli.UI - - outDir clib.Path - - templateFS http.FileSystem - shouldRunFunc ShouldRunFunc -} - -func (g *generatorImpl) Generate(params interface{}) error { - entries, err := g.listEntries(params) - if err != nil { - return errors.WithStack(err) - } - - for _, e := range entries { - if ok, err := g.shouldRun(e); err != nil { - g.ui.ItemFailure(e.Path[1:]) - return errors.WithStack(err) - } else if !ok { - g.ui.ItemSkipped(e.Path[1:]) - continue - } - - err := g.writeFile(e) - if err != nil { - g.ui.ItemFailure(e.Path[1:]) - return errors.WithStack(err) - } - g.ui.ItemSuccess(e.Path[1:]) - } - - return nil -} - -func (g *generatorImpl) Destroy(params interface{}) error { - tmplPaths, err := g.listPathTemplates() - if err != nil { - return errors.WithStack(err) - } - - for _, tmplPath := range tmplPaths { - path, err := TemplateString(strings.TrimSuffix(tmplPath, ".tmpl")).Compile(params) - if err != nil { - return errors.Wrapf(err, "failed to parse path: %s", tmplPath) - } - - absPath := g.outDir.Join(path).String() - if ok, err := afero.Exists(g.fs, absPath); err != nil { - g.ui.ItemFailure(path) - return errors.WithStack(err) - } else if !ok { - g.ui.ItemSkipped(path) - continue - } - - err = g.fs.Remove(absPath) - if err != nil { - g.ui.ItemFailure(path) - return errors.WithStack(err) - } - g.ui.ItemSuccess(path) - } - - return nil -} - -func (g *generatorImpl) listEntries(params interface{}) ([]*Entry, error) { - tmplPaths, err := g.listPathTemplates() - if err != nil { - return nil, errors.WithStack(err) - } - - entries := make([]*Entry, 0, len(tmplPaths)) - - for _, tmplPath := range tmplPaths { - path, err := TemplateString(strings.TrimSuffix(tmplPath, ".tmpl")).Compile(params) - if err != nil { - return nil, errors.Wrapf(err, "failed to parse path: %s", tmplPath) - } - - data, err := fs.ReadFile(g.templateFS, tmplPath) - if err != nil { - return nil, errors.Wrapf(err, "failed to read template: %s", tmplPath) - } - - body, err := TemplateString(string(data)).Compile(params) - if err != nil { - return nil, errors.Wrapf(err, "failed to compile temlpate: %s, %v", tmplPath, params) - } - - entries = append(entries, &Entry{File: File{Path: filepath.Clean(path), Body: body}, Template: File{Path: tmplPath, Body: string(data)}}) - } - return entries, nil -} - -func (g *generatorImpl) listPathTemplates() (tmplPaths []string, err error) { - err = fs.Walk(g.templateFS, "/", func(path string, info os.FileInfo, err error) error { - if err != nil { - return errors.WithStack(err) - } - - if info.IsDir() { - return nil - } - - tmplPaths = append(tmplPaths, path) - - return nil - }) - - err = errors.WithStack(err) - - return -} - -func (g *generatorImpl) shouldRun(e *Entry) (bool, error) { - if g.shouldRunFunc != nil && !g.shouldRunFunc(e) { - return false, nil - } - - absPath := g.outDir.Join(e.Path).String() - - if ok, err := afero.Exists(g.fs, absPath); err != nil { - return false, errors.WithStack(err) - } else if !ok { - return true, nil - } - - existed, err := afero.ReadFile(g.fs, absPath) - if err != nil { - return false, errors.WithStack(err) - } - - if string(existed) == e.Body { - return false, nil - } - - g.ui.ItemFailure(e.Path[1:] + " is conflicted.") - if ok, err := g.ui.Confirm("Overwite it?"); err != nil { - zap.L().Error("failed to confirm to apply", zap.Error(err)) - return false, errors.WithStack(err) - } else if ok { - return true, nil - } - - return false, nil -} - -func (g *generatorImpl) writeFile(e *Entry) error { - path := g.outDir.Join(e.Path).String() - dir := filepath.Dir(path) - - if ok, err := afero.DirExists(g.fs, dir); err != nil { - return errors.WithStack(err) - } else if !ok { - err := g.fs.MkdirAll(dir, 0755) - if err != nil { - return errors.Wrapf(err, "failed to create directory") - } - } - - err := afero.WriteFile(g.fs, path, []byte(e.Body), 0644) - if err != nil { - return errors.Wrapf(err, "failed to write %s", e.Path) - } +type Generator = newGencmd.Generator - return nil -} +var NewGenerator = newGencmd.NewGenerator diff --git a/pkg/gencmd/main.go b/pkg/gencmd/main.go index 4f5d4a5b..4f7876cf 100644 --- a/pkg/gencmd/main.go +++ b/pkg/gencmd/main.go @@ -1,96 +1,8 @@ package gencmd import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) // New creates an Executor instnace. -func New( - name string, - generateCmd *Command, - destroyCmd *Command, - opts ...Option, -) Executor { - ctx := defaultCtx() - ctx.apply(opts) - - rootCmd := &cobra.Command{ - Use: "grapi-gen-" + name, - } - - setGenerateCommand(name, rootCmd, generateCmd, ctx) - setDestroyCommand(name, rootCmd, destroyCmd, ctx) - - return newExecutor(ctx, rootCmd) -} - -func setGenerateCommand(name string, rootCmd *cobra.Command, cmd *Command, ctx *Ctx) { - if cmd == nil { - return - } - - ccmd := cmd.newCobraCommand() - - ccmd.RunE = func(_ *cobra.Command, args []string) error { - app, err := ctx.CreateApp(cmd) - if err != nil { - return errors.WithStack(err) - } - - app.UI.Section("Generate " + name) - params, err := cmd.BuildParams(cmd, args) - if err != nil { - return errors.WithStack(err) - } - - err = app.Generator.Generate(params) - if err != nil { - return errors.WithStack(err) - } - - return nil - } - - if ccmd.Use == "" { - ccmd.Use = "generate" - } - - cmd.ctx = ctx - rootCmd.AddCommand(ccmd) -} - -func setDestroyCommand(name string, rootCmd *cobra.Command, cmd *Command, ctx *Ctx) { - if cmd == nil { - return - } - - ccmd := cmd.newCobraCommand() - - ccmd.RunE = func(_ *cobra.Command, args []string) error { - app, err := ctx.CreateApp(cmd) - if err != nil { - return errors.WithStack(err) - } - - app.UI.Section("Destroy " + name) - params, err := cmd.BuildParams(cmd, args) - if err != nil { - return errors.WithStack(err) - } - - err = app.Generator.Destroy(params) - if err != nil { - return errors.WithStack(err) - } - - return nil - } - - if ccmd.Use == "" { - ccmd.Use = "destroy" - } - - cmd.ctx = ctx - rootCmd.AddCommand(ccmd) -} +var New = newGencmd.New diff --git a/pkg/gencmd/options.go b/pkg/gencmd/options.go index fefdbd6d..1073ce5b 100644 --- a/pkg/gencmd/options.go +++ b/pkg/gencmd/options.go @@ -1,22 +1,14 @@ package gencmd import ( - "github.com/izumin5210/grapi/pkg/grapicmd" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) // Option configures a command context. -type Option func(*Ctx) +type Option = newGencmd.Option // WithGrapiCtx specifies a grapi command context. -func WithGrapiCtx(gctx *grapicmd.Ctx) Option { - return func(ctx *Ctx) { - ctx.Ctx = gctx - } -} +var WithGrapiCtx = newGencmd.WithGrapiCtx // WithCreateAppFunc specifies a dependencies initializer. -func WithCreateAppFunc(f CreateAppFunc) Option { - return func(ctx *Ctx) { - ctx.CreateAppFunc = f - } -} +var WithCreateAppFunc = newGencmd.WithCreateAppFunc diff --git a/pkg/gencmd/providers.go b/pkg/gencmd/providers.go index 9d08b4bb..2f28dbdf 100644 --- a/pkg/gencmd/providers.go +++ b/pkg/gencmd/providers.go @@ -2,26 +2,13 @@ package gencmd import ( "github.com/google/wire" - "github.com/rakyll/statik/fs" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) -func ProvideGrapiCtx(ctx *Ctx) *grapicmd.Ctx { return ctx.Ctx } -func ProvideCtx(cmd *Command) *Ctx { return cmd.Ctx() } -func ProvideShouldRun(cmd *Command) ShouldRunFunc { return cmd.ShouldRun } -func ProvidePath(root cli.RootDir) clib.Path { return root.Path } +var ProvideGrapiCtx = newGencmd.ProvideGrapiCtx +var ProvideCtx = newGencmd.ProvideCtx +var ProvideShouldRun = newGencmd.ProvideShouldRun +var ProvidePath = newGencmd.ProvidePath // Set contains providers for DI. -var Set = wire.NewSet( - grapicmd.CtxSet, - fs.New, - ProvideGrapiCtx, - ProvideCtx, - ProvideShouldRun, - ProvidePath, - NewGenerator, - App{}, -) +var Set = wire.NewSet(newGencmd.Set) diff --git a/pkg/gencmd/template_string.go b/pkg/gencmd/template_string.go index 1fc0eddf..f4660d8c 100644 --- a/pkg/gencmd/template_string.go +++ b/pkg/gencmd/template_string.go @@ -1,25 +1,8 @@ package gencmd import ( - "bytes" - "text/template" - - "github.com/pkg/errors" + newGencmd "github.com/x-izumin/grapi/pkg/gencmd" ) // TemplateString is a compilable string with text/template package -type TemplateString string - -// Compile generates textual output applied a parsed template to the specified values -func (s TemplateString) Compile(v interface{}) (string, error) { - tmpl, err := template.New("").Parse(string(s)) - if err != nil { - return string(s), errors.Wrapf(err, "failed to parse a template: %q", string(s)) - } - buf := &bytes.Buffer{} - err = tmpl.Execute(buf, v) - if err != nil { - return string(s), errors.Wrapf(err, "failed to execute a template: %q", string(s)) - } - return string(buf.Bytes()), nil -} +type TemplateString = newGencmd.TemplateString diff --git a/pkg/gencmd/testing/wire.go b/pkg/gencmd/testing/wire.go deleted file mode 100644 index ab6bbab5..00000000 --- a/pkg/gencmd/testing/wire.go +++ /dev/null @@ -1,17 +0,0 @@ -//+build wireinject - -package testing - -import ( - "github.com/google/wire" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" -) - -func NewTestApp(*gencmd.Command, cli.UI) (*gencmd.App, error) { - wire.Build( - gencmd.Set, - ) - return nil, nil -} diff --git a/pkg/gencmd/testing/wire_gen.go b/pkg/gencmd/testing/wire_gen.go deleted file mode 100644 index a803ecc7..00000000 --- a/pkg/gencmd/testing/wire_gen.go +++ /dev/null @@ -1,34 +0,0 @@ -// Code generated by Wire. DO NOT EDIT. - -//go:generate wire -//+build !wireinject - -package testing - -import ( - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/rakyll/statik/fs" -) - -// Injectors from wire.go: - -func NewTestApp(command *gencmd.Command, ui cli.UI) (*gencmd.App, error) { - ctx := gencmd.ProvideCtx(command) - grapicmdCtx := gencmd.ProvideGrapiCtx(ctx) - aferoFs := grapicmd.ProvideFS(grapicmdCtx) - rootDir := grapicmd.ProvideRootDir(grapicmdCtx) - path := gencmd.ProvidePath(rootDir) - fileSystem, err := fs.New() - if err != nil { - return nil, err - } - shouldRunFunc := gencmd.ProvideShouldRun(command) - generator := gencmd.NewGenerator(aferoFs, ui, path, fileSystem, shouldRunFunc) - app := &gencmd.App{ - Generator: generator, - UI: ui, - } - return app, nil -} diff --git a/pkg/gencmd/util/package.go b/pkg/gencmd/util/package.go index 7bedf551..e2e19fc4 100644 --- a/pkg/gencmd/util/package.go +++ b/pkg/gencmd/util/package.go @@ -1,76 +1,9 @@ package util import ( - "path/filepath" - "strings" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" - "github.com/pkg/errors" - "github.com/serenize/snaker" + newUtil "github.com/x-izumin/grapi/pkg/gencmd/util" ) -type ProtoParams struct { - Proto struct { - Path string - Package string - } - PbGo struct { - Package string - ImportName string - } -} - -func BuildProtoParams(path string, rootDir cli.RootDir, protoOutDir string, pkg string) (out ProtoParams, err error) { - if protoOutDir == "" { - err = errors.New("protoOutDir is required") - return - } - - // github.com/foo/bar - importPath, err := fs.GetImportPath(rootDir.String()) - if err != nil { - err = errors.WithStack(err) - return - } - - // path => baz/qux/quux - path = strings.Replace(snaker.CamelToSnake(path), "-", "_", -1) - - // baz/qux - packagePath := filepath.Dir(path) - - // api/baz/qux - pbgoPackagePath := filepath.Join(protoOutDir, packagePath) - // qux_pb - pbgoPackageName := filepath.Base(pbgoPackagePath) + "_pb" - - if packagePath == "." { - pbgoPackagePath = protoOutDir - pbgoPackageName = filepath.Base(pbgoPackagePath) + "_pb" - } - - protoPackage := pkg - if protoPackage == "" { - protoPackageChunks := []string{} - for _, pkg := range strings.Split(filepath.ToSlash(filepath.Join(importPath, protoOutDir)), "/") { - chunks := strings.Split(pkg, ".") - for i := len(chunks) - 1; i >= 0; i-- { - protoPackageChunks = append(protoPackageChunks, chunks[i]) - } - } - // com.github.foo.bar.baz.qux - protoPackage = strings.Join(protoPackageChunks, ".") - } - if dir := filepath.Dir(path); dir != "." { - protoPackage = protoPackage + "." + strings.Replace(dir, string(filepath.Separator), ".", -1) - } - protoPackage = strings.Replace(protoPackage, "-", "_", -1) - - out.Proto.Path = path - out.Proto.Package = strings.Replace(protoPackage, "-", "_", -1) - out.PbGo.Package = filepath.ToSlash(filepath.Join(importPath, pbgoPackagePath)) - out.PbGo.ImportName = pbgoPackageName +type ProtoParams = newUtil.ProtoParams - return -} +var BuildProtoParams = newUtil.BuildProtoParams diff --git a/pkg/gencmd/util/string.go b/pkg/gencmd/util/string.go index 97623b2a..47bfadf4 100644 --- a/pkg/gencmd/util/string.go +++ b/pkg/gencmd/util/string.go @@ -1,33 +1,9 @@ package util import ( - "strings" - - "github.com/jinzhu/inflection" - "github.com/serenize/snaker" + newUtil "github.com/x-izumin/grapi/pkg/gencmd/util" ) -type String struct { - Camel struct { - Plural string - Singular string - } - CamelLower struct { - Plural string - Singular string - } - Snake struct { - Plural string - Singular string - } -} +type String = newUtil.String -func Inflect(in string) (out String) { - out.Camel.Singular = inflection.Singular(snaker.SnakeToCamel(in)) - out.Camel.Plural = inflection.Plural(out.Camel.Singular) - out.CamelLower.Singular = strings.ToLower(string(out.Camel.Singular[0])) + out.Camel.Singular[1:] - out.CamelLower.Plural = strings.ToLower(string(out.Camel.Plural[0])) + out.Camel.Plural[1:] - out.Snake.Singular = snaker.CamelToSnake(out.Camel.Singular) - out.Snake.Plural = snaker.CamelToSnake(out.Camel.Plural) - return -} +var Inflect = newUtil.Inflect diff --git a/pkg/gencmd/wire.go b/pkg/gencmd/wire.go deleted file mode 100644 index 612b0384..00000000 --- a/pkg/gencmd/wire.go +++ /dev/null @@ -1,16 +0,0 @@ -//+build wireinject - -package gencmd - -import ( - "github.com/google/wire" - "github.com/izumin5210/grapi/pkg/cli" -) - -func newApp(*Command) (*App, error) { - wire.Build( - Set, - cli.UIInstance, - ) - return nil, nil -} diff --git a/pkg/gencmd/wire_gen.go b/pkg/gencmd/wire_gen.go deleted file mode 100644 index bbd8dcb5..00000000 --- a/pkg/gencmd/wire_gen.go +++ /dev/null @@ -1,35 +0,0 @@ -// Code generated by Wire. DO NOT EDIT. - -//go:generate wire -//+build !wireinject - -package gencmd - -import ( - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/rakyll/statik/fs" -) - -// Injectors from wire.go: - -func newApp(command *Command) (*App, error) { - ctx := ProvideCtx(command) - grapicmdCtx := ProvideGrapiCtx(ctx) - aferoFs := grapicmd.ProvideFS(grapicmdCtx) - io := grapicmd.ProvideIO(grapicmdCtx) - ui := cli.UIInstance(io) - rootDir := grapicmd.ProvideRootDir(grapicmdCtx) - path := ProvidePath(rootDir) - fileSystem, err := fs.New() - if err != nil { - return nil, err - } - shouldRunFunc := ProvideShouldRun(command) - generator := NewGenerator(aferoFs, ui, path, fileSystem, shouldRunFunc) - app := &App{ - Generator: generator, - UI: ui, - } - return app, nil -} diff --git a/pkg/grapicmd/cmd/build.go b/pkg/grapicmd/cmd/build.go deleted file mode 100644 index 619a7aed..00000000 --- a/pkg/grapicmd/cmd/build.go +++ /dev/null @@ -1,75 +0,0 @@ -package cmd - -import ( - "strings" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/srvc/appctx" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/di" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" -) - -func splitOptions(args []string) ([]string, []string) { - pos := len(args) - for i, arg := range args { - if strings.HasPrefix(arg, "-") { - pos = i - - break - } - } - - return args[:pos], args[pos:] -} - -func newBuildCommand(ctx *grapicmd.Ctx) *cobra.Command { - scriptLoader := di.NewScriptLoader(ctx) - ui := di.NewUI(ctx) - - return newBuildCommandMocked(ctx.IsInsideApp(), ctx, scriptLoader, ui) -} - -func newBuildCommandMocked(isInsideApp bool, ctx *grapicmd.Ctx, scriptLoader module.ScriptLoader, ui cli.UI) *cobra.Command { - return &cobra.Command{ - Use: "build [flags] [TARGET]... [-- BUILD_OPTIONS]", - Short: "Build commands", - SilenceErrors: true, - SilenceUsage: true, - RunE: func(c *cobra.Command, args []string) error { - if !isInsideApp { - return errors.New("protoc command should be execute inside a grapi application directory") - } - - names, opt := splitOptions(args) - nameSet := make(map[string]bool, len(names)) - for _, n := range names { - nameSet[n] = true - } - isAll := len(names) == 0 - - err := scriptLoader.Load(ctx.RootDir.Join("cmd").String()) - if err != nil { - return errors.WithStack(err) - } - - ctx := appctx.Global() - - for _, name := range scriptLoader.Names() { - script, ok := scriptLoader.Get(name) - if ok && (isAll || nameSet[script.Name()]) { - ui.Subsection("Building " + script.Name()) - err := script.Build(ctx, opt...) - if err != nil { - return errors.WithStack(err) - } - } - } - - return nil - }, - } -} diff --git a/pkg/grapicmd/cmd/build_internal_test.go b/pkg/grapicmd/cmd/build_internal_test.go deleted file mode 100644 index e0d54742..00000000 --- a/pkg/grapicmd/cmd/build_internal_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package cmd - -import ( - "errors" - "reflect" - "testing" - - "github.com/golang/mock/gomock" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - moduletesting "github.com/izumin5210/grapi/pkg/grapicmd/internal/module/testing" -) - -func TestSplitOptions(t *testing.T) { - tests := []struct { - input []string - outputArg []string - outputOpt []string - }{ - { - []string{"foo", "bar"}, - []string{"foo", "bar"}, - []string{}, - }, - { - []string{"foo", "-b"}, - []string{"foo"}, - []string{"-b"}, - }, - { - []string{"foo", "-b", "-h"}, - []string{"foo"}, - []string{"-b", "-h"}, - }, - { - []string{"foo", "-b", "-h"}, - []string{"foo"}, - []string{"-b", "-h"}, - }, - { - []string{"-b", "-h"}, - []string{}, - []string{"-b", "-h"}, - }, - { - []string{"foo", "-b", "-h", "ooo"}, - []string{"foo"}, - []string{"-b", "-h", "ooo"}, - }, - { - []string{}, - []string{}, - []string{}, - }, - } - - for i, test := range tests { - gotArg, gotOpt := splitOptions(test.input) - if !reflect.DeepEqual(test.outputArg, gotArg) { - t.Errorf("(%v) Expected: %v gotArg: %v", i, test.outputArg, gotArg) - } - if !reflect.DeepEqual(test.outputOpt, gotOpt) { - t.Errorf("(%v) Expected: %v gotOpt: %v", i, test.outputOpt, gotOpt) - } - } -} - -var errBuildFailed = errors.New("error occur") - -func Test_newBuildCommandMocked(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - type errBuild struct { - err error - } - - testCases := []struct { - args []string - optExpect []string - // 単体のbuildの結果 - buildResult map[string]errBuild - // 全体のbuildの結果 - wantErr bool - }{ - { - // "aaa"だけ指定した場合,buildには成功する - // "bbb"と"ccc"は呼ばれない - args: []string{"aaa"}, - optExpect: []string{}, - buildResult: map[string]errBuild{ - "aaa": {}, - }, - }, - { - // なんらかの理由で"bbb"のbuildができずに失敗(args指定なし) - // "ccc"はbuildされない - args: []string{}, - optExpect: []string{}, - buildResult: map[string]errBuild{ - "aaa": {}, - "bbb": { - err: errBuildFailed, - }, - }, - wantErr: true, - }, - { - // なんらかの理由で"bbb"でエラーが発生した場合(args指定あり) - // "ccc"は実行されない - args: []string{"aaa", "bbb", "ccc"}, - optExpect: []string{}, - buildResult: map[string]errBuild{ - "aaa": {}, - "bbb": { - err: errBuildFailed, - }, - }, - wantErr: true, - }, - { - // 与えたオプションによってエラーが発生する場合 - // "bbb"以降は実行されない - args: []string{"--", "-b", "-c"}, - optExpect: []string{"-b", "-c"}, - buildResult: map[string]errBuild{ - "aaa": { - err: errBuildFailed, - }, - }, - wantErr: true, - }, - { - // build対象は与えず与えたオプションが正当でありすべて成功する場合 - args: []string{"--", "-a"}, - optExpect: []string{"-a"}, - buildResult: map[string]errBuild{ - "aaa": {}, - "bbb": {}, - "ccc": {}, - }, - }, - { - // build対象とオプションの両者を与えず,すべて成功する場合 - args: []string{}, - optExpect: []string{}, - buildResult: map[string]errBuild{ - "aaa": {}, - "bbb": {}, - "ccc": {}, - }, - }, - } - - ctx := &grapicmd.Ctx{} - err := ctx.Init() - if err != nil { - t.Fatal(err) - } - - commandNames := []string{"aaa", "bbb", "ccc"} - for _, c := range testCases { - loader := moduletesting.NewMockScriptLoader(ctrl) - - loader.EXPECT().Load(gomock.Any()).Return(nil) - loader.EXPECT().Names().Return(commandNames) - for _, arg := range commandNames { - script := moduletesting.NewMockScript(ctrl) - loader.EXPECT().Get(arg).Return(script, true).AnyTimes() - script.EXPECT().Name().Return(arg).AnyTimes() - if buildResult, ok := c.buildResult[arg]; ok { - script.EXPECT().Build(gomock.Any(), c.optExpect).Return(buildResult.err) - } - } - - cmd := newBuildCommandMocked(true, ctx, loader, cli.NopUI) - cmd.SetArgs(c.args) - err := cmd.Execute() - - if c.wantErr != (err != nil) { - t.Errorf("wantErr: %v, gotErr: %v", c.wantErr, err != nil) - } - } -} diff --git a/pkg/grapicmd/cmd/cmd.go b/pkg/grapicmd/cmd/cmd.go index 9edc0d15..6b8bbe82 100644 --- a/pkg/grapicmd/cmd/cmd.go +++ b/pkg/grapicmd/cmd/cmd.go @@ -1,42 +1,8 @@ package cmd import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/grapicmd" + newCmd "github.com/x-izumin/grapi/pkg/grapicmd/cmd" ) // NewGrapiCommand creates a new command object. -func NewGrapiCommand(ctx *grapicmd.Ctx) *cobra.Command { - initErr := ctx.Init() - - cmd := &cobra.Command{ - Use: ctx.Build.AppName, - Short: "JSON API framework implemented with gRPC and Gateway", - Long: "", - SilenceErrors: true, - SilenceUsage: true, - PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - return errors.WithStack(initErr) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - clib.Close() - }, - } - - clib.AddLoggingFlags(cmd) - clib.SetIO(cmd, ctx.IO) - - cmd.AddCommand( - newInitCommand(ctx), - newProtocCommand(ctx), - newBuildCommand(ctx), - clib.NewVersionCommand(ctx.Build), - ) - cmd.AddCommand(newGenerateCommands(ctx)...) - cmd.AddCommand(newUserDefinedCommands(ctx)...) - - return cmd -} +var NewGrapiCommand = newCmd.NewGrapiCommand diff --git a/pkg/grapicmd/cmd/generators.go b/pkg/grapicmd/cmd/generators.go deleted file mode 100644 index 324baad4..00000000 --- a/pkg/grapicmd/cmd/generators.go +++ /dev/null @@ -1,122 +0,0 @@ -package cmd - -import ( - "context" - "strings" - "sync" - - "github.com/spf13/cobra" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/gex/pkg/tool" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/di" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" -) - -func newGenerateCommands(ctx *grapicmd.Ctx) (cmds []*cobra.Command) { - gCmd := &cobra.Command{ - Use: "generate GENERATOR", - Short: "Generate a new code", - Aliases: []string{"g", "gen"}, - } - dCmd := &cobra.Command{ - Use: "destroy GENERATOR", - Short: "Destroy an existing new code", - Aliases: []string{"d"}, - } - - var ( - execs []string - wg sync.WaitGroup - ) - - wg.Add(2) - cmdNames := make(map[string]struct{}, 100) - - go func() { - defer wg.Done() - execs = fs.ListExecutableWithPrefix(ctx.FS, "grapi-gen-") - }() - - go func() { - defer wg.Done() - - toolRepo, err := di.NewToolRepository(ctx) - if err != nil { - zap.L().Debug("failed to initialize tools repository", zap.Error(err)) - return - } - - tools, err := toolRepo.List(context.TODO()) - if err != nil { - zap.L().Debug("failed to retrieve tools", zap.Error(err)) - return - } - - for _, t := range tools { - if !strings.HasPrefix(t.Name(), "grapi-gen-") { - continue - } - if _, ok := cmdNames[t.Name()]; ok { - continue - } - cmdNames[t.Name()] = struct{}{} - gCmd.AddCommand(newGenerateCommandByTool(toolRepo, t, "generate")) - dCmd.AddCommand(newGenerateCommandByTool(toolRepo, t, "destroy")) - } - }() - - wg.Wait() - - for _, exec := range execs { - if _, ok := cmdNames[exec]; ok { - continue - } - cmdNames[exec] = struct{}{} - gCmd.AddCommand(newGenerateCommandByExec(ctx.IO, ctx.Exec, exec, "generate")) - dCmd.AddCommand(newGenerateCommandByExec(ctx.IO, ctx.Exec, exec, "destroy")) - } - - cmds = append(cmds, gCmd, dCmd) - - return -} - -func newGenerateCommandByTool(repo tool.Repository, t tool.Tool, subCmd string) *cobra.Command { - cmd := &cobra.Command{ - Use: strings.TrimPrefix(t.Name(), "grapi-gen-"), - Args: cobra.ArbitraryArgs, - RunE: func(_ *cobra.Command, args []string) error { - return repo.Run(context.TODO(), t.Name(), append([]string{subCmd}, args...)...) - }, - } - cmd.SetUsageFunc(func(*cobra.Command) error { - return repo.Run(context.TODO(), t.Name(), subCmd, "--help") - }) - return cmd -} - -func newGenerateCommandByExec(io *clib.IO, exec *execx.Executor, path, subCmd string) *cobra.Command { - cmd := &cobra.Command{ - Use: strings.TrimPrefix(path, "grapi-gen-"), - Args: cobra.ArbitraryArgs, - RunE: func(_ *cobra.Command, args []string) error { - cmd := exec.CommandContext(context.TODO(), path, append([]string{subCmd}, args...)...) - cmd.Stdout = io.Out - cmd.Stderr = io.Err - cmd.Stdin = io.In - return cmd.Run() - }, - } - cmd.SetUsageFunc(func(*cobra.Command) error { - cmd := exec.CommandContext(context.TODO(), path, subCmd, "--help") - cmd.Stdout = io.Out - cmd.Stderr = io.Err - cmd.Stdin = io.In - return cmd.Run() - }) - return cmd -} diff --git a/pkg/grapicmd/cmd/init.go b/pkg/grapicmd/cmd/init.go deleted file mode 100644 index 19822271..00000000 --- a/pkg/grapicmd/cmd/init.go +++ /dev/null @@ -1,69 +0,0 @@ -package cmd - -import ( - "path/filepath" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/di" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/usecase" -) - -func newInitCommand(ctx *grapicmd.Ctx) *cobra.Command { - var cfg usecase.InitConfig - - cmd := &cobra.Command{ - Use: "init [name]", - Short: "Initialize a grapi application", - SilenceErrors: true, - SilenceUsage: true, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - root, err := parseInitArgs(ctx, args) - if err != nil { - return errors.WithStack(err) - } - zap.L().Debug("parseInitArgs", zap.String("root", root)) - - u, err := di.NewInitializeProjectUsecase(ctx, clib.Path(root)) - if err != nil { - return errors.WithStack(err) - } - - return errors.WithStack(u.Perform(root, cfg)) - }, - } - - cmd.PersistentFlags().StringVar(&cfg.Revision, "revision", "", "Specify grapi revision") - cmd.PersistentFlags().StringVar(&cfg.Branch, "branch", "", "Specify grapi branch") - cmd.PersistentFlags().StringVar(&cfg.Version, "version", "", "Specify grapi version") - cmd.PersistentFlags().BoolVar(&cfg.HEAD, "HEAD", false, "Use HEAD grapi") - cmd.PersistentFlags().StringVar(&cfg.GrapiReplacementURL, "replace-grapi", "", "Specify grapi replacement url") - cmd.PersistentFlags().StringVarP(&cfg.Package, "package", "p", "", `Package name of the application(default: ".")`) - cmd.PersistentFlags().BoolVar(&cfg.Dep, "use-dep", false, "Use dep instead of Modules") - - return cmd -} - -func parseInitArgs(ctx *grapicmd.Ctx, args []string) (root string, err error) { - if argCnt := len(args); argCnt != 1 { - err = errors.Errorf("invalid argument count: want 1, got %d", argCnt) - return - } - - arg := args[0] - root = ctx.RootDir.String() - - if arg == "." { - return - } - root = arg - if !filepath.IsAbs(arg) { - root = ctx.RootDir.Join(arg).String() - } - return -} diff --git a/pkg/grapicmd/cmd/protoc.go b/pkg/grapicmd/cmd/protoc.go deleted file mode 100644 index ddbf5770..00000000 --- a/pkg/grapicmd/cmd/protoc.go +++ /dev/null @@ -1,30 +0,0 @@ -package cmd - -import ( - "context" - - "github.com/pkg/errors" - "github.com/spf13/cobra" - - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/di" -) - -func newProtocCommand(ctx *grapicmd.Ctx) *cobra.Command { - return &cobra.Command{ - Use: "protoc", - Short: "Run protoc", - SilenceErrors: true, - SilenceUsage: true, - RunE: func(cmd *cobra.Command, args []string) error { - if !ctx.IsInsideApp() { - return errors.New("protoc command should be execute inside a grapi application directory") - } - protocw, err := di.NewProtocWrapper(ctx) - if err != nil { - return errors.WithStack(err) - } - return errors.WithStack(protocw.Exec(context.TODO())) - }, - } -} diff --git a/pkg/grapicmd/cmd/user_defined.go b/pkg/grapicmd/cmd/user_defined.go deleted file mode 100644 index e60fe52b..00000000 --- a/pkg/grapicmd/cmd/user_defined.go +++ /dev/null @@ -1,76 +0,0 @@ -package cmd - -import ( - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/srvc/appctx" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/di" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" -) - -func newUserDefinedCommands(ctx *grapicmd.Ctx) (cmds []*cobra.Command) { - if !ctx.IsInsideApp() { - return - } - - scriptLoader := di.NewScriptLoader(ctx) - - err := scriptLoader.Load(ctx.RootDir.Join("cmd").String()) - if err != nil { - // TODO: log - return - } - - ui := di.NewUI(ctx) - - for _, name := range scriptLoader.Names() { - cmds = append(cmds, newUserDefinedCommand(ui, scriptLoader, name)) - } - - return -} - -func newUserDefinedCommand(ui cli.UI, scriptLoader module.ScriptLoader, name string) *cobra.Command { - return &cobra.Command{ - Use: name + " [-- BUILD_OPTIONS] [-- RUN_ARGS]", - SilenceErrors: true, - SilenceUsage: true, - RunE: func(c *cobra.Command, args []string) (err error) { - script, ok := scriptLoader.Get(name) - if !ok { - err = errors.Wrapf(err, "faild to find subcommand %s", name) - return - } - - pos := len(args) - for i, arg := range args { - if arg == "--" { - pos = i - break - } - } - var buildArgs, runArgs []string - if pos == len(args) { - buildArgs = args - } else { - buildArgs = args[:pos] - runArgs = args[pos+1:] - } - - ctx := appctx.Global() - - ui.Section(script.Name()) - ui.Subsection("Building...") - err = errors.WithStack(script.Build(ctx, buildArgs...)) - if err != nil { - return - } - - ui.Subsection("Starting...") - return errors.WithStack(script.Run(ctx, runArgs...)) - }, - } -} diff --git a/pkg/grapicmd/cmd/user_defined_test.go b/pkg/grapicmd/cmd/user_defined_test.go deleted file mode 100644 index 29f4ef82..00000000 --- a/pkg/grapicmd/cmd/user_defined_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module/testing" -) - -func Test_userDefinedCommand(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - cases := []struct { - args []string - buildArgs []interface{} - runArgs []interface{} - verbose bool - }{ - { - args: []string{}, - buildArgs: []interface{}{}, - runArgs: []interface{}{}, - verbose: false, - }, - { - args: []string{"-v"}, - buildArgs: []interface{}{}, - runArgs: []interface{}{}, - verbose: true, - }, - { - args: []string{"--", "-v"}, - buildArgs: []interface{}{"-v"}, - runArgs: []interface{}{}, - verbose: false, - }, - { - args: []string{"-v", "--", "-v"}, - buildArgs: []interface{}{"-v"}, - runArgs: []interface{}{}, - verbose: true, - }, - { - args: []string{"--", "--", "-v"}, - buildArgs: []interface{}{}, - runArgs: []interface{}{"-v"}, - verbose: false, - }, - { - args: []string{"-v", "--", "--", "-v"}, - buildArgs: []interface{}{}, - runArgs: []interface{}{"-v"}, - verbose: true, - }, - { - args: []string{"-v", "--", "-a", "--", "-b"}, - buildArgs: []interface{}{"-a"}, - runArgs: []interface{}{"-b"}, - verbose: true, - }, - { - args: []string{"-v", "--", "-foo", "bar", "-baz", "--", "qux", "quux"}, - buildArgs: []interface{}{"-foo", "bar", "-baz"}, - runArgs: []interface{}{"qux", "quux"}, - verbose: true, - }, - } - - name := "testcommand" - - for _, c := range cases { - loader := moduletesting.NewMockScriptLoader(ctrl) - script := moduletesting.NewMockScript(ctrl) - - var verbose bool - cmd := newUserDefinedCommand(cli.NopUI, loader, name) - cmd.SetArgs(c.args) - cmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "") - - loader.EXPECT().Get(name).Return(script, true) - - script.EXPECT().Build(gomock.Any(), c.buildArgs...) - script.EXPECT().Run(gomock.Any(), c.runArgs...) - script.EXPECT().Name().Return(name) - - err := cmd.Execute() - - if err != nil { - t.Errorf("Execute() returned an error %v", err) - } - - if got, want := verbose, c.verbose; got != want { - t.Errorf("verbose option is %t, want %t", got, want) - } - } -} diff --git a/pkg/grapicmd/context.go b/pkg/grapicmd/context.go index eceab49e..1e2df951 100644 --- a/pkg/grapicmd/context.go +++ b/pkg/grapicmd/context.go @@ -1,128 +1,24 @@ package grapicmd import ( - "os" - "path/filepath" - "github.com/google/wire" - "github.com/pkg/errors" - "github.com/spf13/afero" - "github.com/spf13/viper" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/protoc" + newGrapicmd "github.com/x-izumin/grapi/pkg/grapicmd" ) // Ctx contains the runtime context of grpai. -type Ctx struct { - FS afero.Fs - Viper *viper.Viper - Exec *execx.Executor - IO *clib.IO - - RootDir cli.RootDir - insideApp bool - - Config Config - Build clib.Build - ProtocConfig protoc.Config -} +type Ctx = newGrapicmd.Ctx // Config stores general setting params and provides accessors for them. -type Config struct { - Package string - Grapi struct { - ServerDir string - } -} - -// Init initializes the runtime context. -func (c *Ctx) Init() error { - if c.RootDir.String() == "" { - dir, _ := os.Getwd() - c.RootDir = cli.RootDir{clib.Path(dir)} - } - - if c.IO == nil { - c.IO = clib.Stdio() - } - - if c.FS == nil { - c.FS = afero.NewOsFs() - } - - if c.Viper == nil { - c.Viper = viper.New() - } - - c.Viper.SetFs(c.FS) - - if c.Exec == nil { - c.Exec = execx.New() - } - - if c.Build.AppName == "" { - c.Build.AppName = "grapi" - } - - return errors.WithStack(c.loadConfig()) -} - -func (c *Ctx) loadConfig() error { - c.Viper.SetConfigName(c.Build.AppName) - for dir := c.RootDir.String(); dir != "/"; dir = filepath.Dir(dir) { - c.Viper.AddConfigPath(dir) - } - - err := c.Viper.ReadInConfig() - if err != nil { - zap.L().Info("failed to find config file", zap.Error(err)) - return nil - } - - c.insideApp = true - c.RootDir = cli.RootDir{clib.Path(filepath.Dir(c.Viper.ConfigFileUsed()))} - - err = c.Viper.Unmarshal(&c.Config) - if err != nil { - zap.L().Warn("failed to parse config", zap.Error(err)) - return errors.WithStack(err) - } - - err = c.Viper.UnmarshalKey("protoc", &c.ProtocConfig) - if err != nil { - zap.L().Warn("failed to parse protoc config", zap.Error(err)) - return errors.WithStack(err) - } - - return nil -} - -// IsInsideApp returns true if the current working directory is inside a grapi project. -func (c *Ctx) IsInsideApp() bool { - return c.insideApp -} +type Config = newGrapicmd.Config // CtxSet is a provider set that includes modules contained in Ctx. -var CtxSet = wire.NewSet( - ProvideFS, - ProvideViper, - ProvideExec, - ProvideIO, - ProvideRootDir, - ProvideConfig, - ProvideBuildConfig, - ProvideProtocConfig, -) - -func ProvideFS(c *Ctx) afero.Fs { return c.FS } -func ProvideViper(c *Ctx) *viper.Viper { return c.Viper } -func ProvideExec(c *Ctx) *execx.Executor { return c.Exec } -func ProvideIO(c *Ctx) *clib.IO { return c.IO } -func ProvideRootDir(c *Ctx) cli.RootDir { return c.RootDir } -func ProvideConfig(c *Ctx) *Config { return &c.Config } -func ProvideBuildConfig(c *Ctx) *clib.Build { return &c.Build } -func ProvideProtocConfig(c *Ctx) *protoc.Config { return &c.ProtocConfig } +var CtxSet = wire.NewSet(newGrapicmd.CtxSet) + +var ProvideFS = newGrapicmd.ProvideFS +var ProvideViper = newGrapicmd.ProvideViper +var ProvideExec = newGrapicmd.ProvideExec +var ProvideIO = newGrapicmd.ProvideIO +var ProvideRootDir = newGrapicmd.ProvideRootDir +var ProvideConfig = newGrapicmd.ProvideConfig +var ProvideBuildConfig = newGrapicmd.ProvideBuildConfig +var ProvideProtocConfig = newGrapicmd.ProvideProtocConfig diff --git a/pkg/grapicmd/context_test.go b/pkg/grapicmd/context_test.go deleted file mode 100644 index 774c1caa..00000000 --- a/pkg/grapicmd/context_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package grapicmd_test - -import ( - "testing" - - "github.com/spf13/afero" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" -) - -func TestCtx(t *testing.T) { - root := cli.RootDir{clib.Path("/go/src/awesomeapp")} - cwd := root.Join("api").String() - - orDie := func(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatalf("unexpected error %v", err) - } - } - - fs := afero.NewMemMapFs() - orDie(t, fs.MkdirAll(cwd, 0755)) - orDie(t, afero.WriteFile(fs, root.Join("grapi.toml").String(), []byte(` -package = "awesomeapp" - -[grapi] -server_dir = "./app/server" - -[protoc] -protos_dir = "./api/protos" -out_dir = "./api" -import_dirs = [ - "./api/protos", - "./vendor/github.com/grpc-ecosystem/grpc-gateway", - "./vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis", -] - - [[protoc.plugins]] - name = "go" - args = { plugins = "grpc", paths = "source_relative" } - - [[protoc.plugins]] - name = "grpc-gateway" - args = { logtostderr = true, paths = "source_relative" } - - [[protoc.plugins]] - name = "swagger" - args = { logtostderr = true } -`), 0644)) - - ctx := &grapicmd.Ctx{FS: fs, RootDir: cli.RootDir{clib.Path(cwd)}} - - err := ctx.Init() - - if err != nil { - t.Errorf("Init() returned %v", err) - } - - if got, want := ctx.RootDir, root; got != want { - t.Errorf("RootDir is %q, want %q", got, want) - } - - if got, want := ctx.IsInsideApp(), true; got != want { - t.Errorf("IsInsideApp() returned %t, want %t", got, want) - } - - if got, want := ctx.Config.Package, "awesomeapp"; got != want { - t.Errorf("Config.Package is %q, want %q", got, want) - } - - if got, want := ctx.ProtocConfig.ProtosDir, "./api/protos"; got != want { - t.Errorf("ProtocConfig.ProtosDir is %q, want %q", got, want) - } - - if got, want := len(ctx.ProtocConfig.Plugins), 3; got != want { - t.Errorf("ProtocConfig has %d plugins, want %d", got, want) - } -} - -func TestCtx_outsideApp(t *testing.T) { - root := cli.RootDir{clib.Path("/go/src/awesomeapp")} - cwd := root.Join("api").String() - - orDie := func(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatalf("unexpected error %v", err) - } - } - - fs := afero.NewMemMapFs() - orDie(t, fs.MkdirAll(cwd, 0755)) - - ctx := &grapicmd.Ctx{FS: fs, RootDir: cli.RootDir{clib.Path(cwd)}} - - err := ctx.Init() - - if err != nil { - t.Errorf("Init() returned %v", err) - } - - if got, want := ctx.RootDir.String(), cwd; got != want { - t.Errorf("RootDir is %q, want %q", got, want) - } - - if got, want := ctx.IsInsideApp(), false; got != want { - t.Errorf("IsInsideApp() returned %t, want %t", got, want) - } - - if got, want := ctx.Config.Package, ""; got != want { - t.Errorf("Config.Package is %q, want %q", got, want) - } - - if got, want := ctx.ProtocConfig.ProtosDir, ""; got != want { - t.Errorf("ProtocConfig.ProtosDir is %q, want %q", got, want) - } - - if got, want := len(ctx.ProtocConfig.Plugins), 0; got != want { - t.Errorf("ProtocConfig has %d plugins, want %d", got, want) - } -} diff --git a/pkg/grapicmd/di/providers.go b/pkg/grapicmd/di/providers.go index 2848f913..6a2169d2 100644 --- a/pkg/grapicmd/di/providers.go +++ b/pkg/grapicmd/di/providers.go @@ -1,43 +1,12 @@ package di import ( - "net/http" - "github.com/google/wire" - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/rakyll/statik/fs" - "github.com/spf13/afero" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module/script" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/usecase" - "github.com/izumin5210/grapi/pkg/protoc" + newDi "github.com/x-izumin/grapi/pkg/grapicmd/di" ) -func ProvideScriptLoader(ctx *grapicmd.Ctx, io *clib.IO, exec *execx.Executor) module.ScriptLoader { - return script.NewLoader(ctx.FS, io, exec, ctx.RootDir.String()) -} +var ProvideScriptLoader = newDi.ProvideScriptLoader -func ProvideGenerator(ctx *grapicmd.Ctx, ui cli.UI, fs afero.Fs, tmplFs http.FileSystem, outDir clib.Path) gencmd.Generator { - return gencmd.NewGenerator( - fs, - ui, - outDir, - tmplFs, - nil, - ) -} +var ProvideGenerator = newDi.ProvideGenerator -var Set = wire.NewSet( - grapicmd.CtxSet, - protoc.WrapperSet, - cli.UIInstance, - ProvideScriptLoader, - ProvideGenerator, - fs.New, - usecase.NewInitializeProjectUsecase, -) +var Set = wire.NewSet(newDi.Set) diff --git a/pkg/grapicmd/di/wire.go b/pkg/grapicmd/di/wire.go index 456a55c7..f3f96321 100644 --- a/pkg/grapicmd/di/wire.go +++ b/pkg/grapicmd/di/wire.go @@ -1,40 +1,14 @@ -//+build wireinject +//go:build wireinject +// +build wireinject package di -import ( - "github.com/google/wire" - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/gex/pkg/tool" +var NewUI = newDi.NewUI - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/usecase" - "github.com/izumin5210/grapi/pkg/protoc" -) +var NewScriptLoader = newDi.NewScriptLoader -func NewUI(*grapicmd.Ctx) cli.UI { - wire.Build(Set) - return nil -} +var NewToolRepository = newDi.NewToolRepository -func NewScriptLoader(*grapicmd.Ctx) module.ScriptLoader { - wire.Build(Set) - return nil -} +var NewProtocWrapper = newDi.NewProtocWrapper -func NewToolRepository(*grapicmd.Ctx) (tool.Repository, error) { - wire.Build(Set) - return nil, nil -} - -func NewProtocWrapper(*grapicmd.Ctx) (protoc.Wrapper, error) { - wire.Build(Set) - return nil, nil -} - -func NewInitializeProjectUsecase(*grapicmd.Ctx, clib.Path) (usecase.InitializeProjectUsecase, error) { - wire.Build(Set) - return nil, nil -} +var NewInitializeProjectUsecase = newDi.NewInitializeProjectUsecase diff --git a/pkg/grapicmd/di/wire_gen.go b/pkg/grapicmd/di/wire_gen.go index d411510b..2e635e03 100644 --- a/pkg/grapicmd/di/wire_gen.go +++ b/pkg/grapicmd/di/wire_gen.go @@ -1,77 +1,18 @@ -// Code generated by Wire. DO NOT EDIT. - -//go:generate wire -//+build !wireinject +//go:build !wireinject +// +build !wireinject package di import ( - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/gex/pkg/tool" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/usecase" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/rakyll/statik/fs" + newDi "github.com/x-izumin/grapi/pkg/grapicmd/di" ) -// Injectors from wire.go: - -func NewUI(ctx *grapicmd.Ctx) cli.UI { - io := grapicmd.ProvideIO(ctx) - ui := cli.UIInstance(io) - return ui -} +var NewUI = newDi.NewUI -func NewScriptLoader(ctx *grapicmd.Ctx) module.ScriptLoader { - io := grapicmd.ProvideIO(ctx) - executor := grapicmd.ProvideExec(ctx) - scriptLoader := ProvideScriptLoader(ctx, io, executor) - return scriptLoader -} +var NewScriptLoader = newDi.NewScriptLoader -func NewToolRepository(ctx *grapicmd.Ctx) (tool.Repository, error) { - fs := grapicmd.ProvideFS(ctx) - executor := grapicmd.ProvideExec(ctx) - io := grapicmd.ProvideIO(ctx) - rootDir := grapicmd.ProvideRootDir(ctx) - config := protoc.ProvideGexConfig(fs, executor, io, rootDir) - repository, err := protoc.ProvideToolRepository(config) - if err != nil { - return nil, err - } - return repository, nil -} +var NewToolRepository = newDi.NewToolRepository -func NewProtocWrapper(ctx *grapicmd.Ctx) (protoc.Wrapper, error) { - config := grapicmd.ProvideProtocConfig(ctx) - fs := grapicmd.ProvideFS(ctx) - executor := grapicmd.ProvideExec(ctx) - io := grapicmd.ProvideIO(ctx) - ui := cli.UIInstance(io) - rootDir := grapicmd.ProvideRootDir(ctx) - gexConfig := protoc.ProvideGexConfig(fs, executor, io, rootDir) - repository, err := protoc.ProvideToolRepository(gexConfig) - if err != nil { - return nil, err - } - wrapper := protoc.NewWrapper(config, fs, executor, ui, repository, rootDir) - return wrapper, nil -} +var NewProtocWrapper = newDi.NewProtocWrapper -func NewInitializeProjectUsecase(ctx *grapicmd.Ctx, path clib.Path) (usecase.InitializeProjectUsecase, error) { - io := grapicmd.ProvideIO(ctx) - ui := cli.UIInstance(io) - aferoFs := grapicmd.ProvideFS(ctx) - fileSystem, err := fs.New() - if err != nil { - return nil, err - } - generator := ProvideGenerator(ctx, ui, aferoFs, fileSystem, path) - executor := grapicmd.ProvideExec(ctx) - rootDir := grapicmd.ProvideRootDir(ctx) - config := protoc.ProvideGexConfig(aferoFs, executor, io, rootDir) - initializeProjectUsecase := usecase.NewInitializeProjectUsecase(ui, aferoFs, generator, io, executor, config) - return initializeProjectUsecase, nil -} +var NewInitializeProjectUsecase = newDi.NewInitializeProjectUsecase diff --git a/pkg/grapicmd/internal/module/gen.go b/pkg/grapicmd/internal/module/gen.go deleted file mode 100644 index 8767ef9a..00000000 --- a/pkg/grapicmd/internal/module/gen.go +++ /dev/null @@ -1,4 +0,0 @@ -//go:generate mockgen -package=moduletesting -source=generator.go -destination=testing/generator_mock.go -//go:generate mockgen -package=moduletesting -source=script.go -destination=testing/script_mock.go - -package module diff --git a/pkg/grapicmd/internal/module/generator.go b/pkg/grapicmd/internal/module/generator.go deleted file mode 100644 index 3e4ff554..00000000 --- a/pkg/grapicmd/internal/module/generator.go +++ /dev/null @@ -1,11 +0,0 @@ -package module - -// Generator creates files from templates and given params. -type Generator interface { - ProjectGenerator -} - -// ProjectGenerator is an interface to build a new project. -type ProjectGenerator interface { - GenerateProject(rootDir, pkgName string) error -} diff --git a/pkg/grapicmd/internal/module/script.go b/pkg/grapicmd/internal/module/script.go deleted file mode 100644 index 77d6c3f3..00000000 --- a/pkg/grapicmd/internal/module/script.go +++ /dev/null @@ -1,17 +0,0 @@ -package module - -import "context" - -// Script represents an user-defined command. -type Script interface { - Name() string - Build(ctx context.Context, args ...string) error - Run(ctx context.Context, args ...string) error -} - -// ScriptLoader is a factory object for creating Script objects. -type ScriptLoader interface { - Load(dir string) error - Get(name string) (script Script, ok bool) - Names() []string -} diff --git a/pkg/grapicmd/internal/module/script/loader.go b/pkg/grapicmd/internal/module/script/loader.go deleted file mode 100644 index 4c7e15f5..00000000 --- a/pkg/grapicmd/internal/module/script/loader.go +++ /dev/null @@ -1,78 +0,0 @@ -package script - -import ( - "path/filepath" - "runtime" - "sort" - - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" -) - -// NewLoader creates a new ScriptLoader instance. -func NewLoader(fs afero.Fs, io *clib.IO, exec *execx.Executor, rootDir string) module.ScriptLoader { - return &scriptLoader{ - fs: fs, - io: io, - exec: exec, - rootDir: rootDir, - binDir: filepath.Join(rootDir, "bin"), - scripts: make(map[string]module.Script), - } -} - -type scriptLoader struct { - fs afero.Fs - io *clib.IO - exec *execx.Executor - rootDir string - binDir string - scripts map[string]module.Script - names []string -} - -func (f *scriptLoader) Load(dir string) error { - srcsByDir, err := fs.FindMainPackagesAndSources(f.fs, dir) - zap.L().Debug("found main packages", zap.Any("srcs_by_dir", srcsByDir)) - if err != nil { - return errors.Wrap(err, "failed to find commands") - } - for dir, srcs := range srcsByDir { - srcPaths := make([]string, 0, len(srcs)) - for _, name := range srcs { - srcPaths = append(srcPaths, filepath.Join(dir, name)) - } - name := filepath.Base(dir) - ext := "" - if runtime.GOOS == "windows" { - ext = ".exe" - } - f.scripts[name] = &script{ - fs: f.fs, - io: f.io, - exec: f.exec, - srcPaths: srcPaths, - name: name, - binPath: filepath.Join(f.binDir, name+ext), - rootDir: f.rootDir, - } - f.names = append(f.names, name) - } - sort.Strings(f.names) - return nil -} - -func (f *scriptLoader) Get(name string) (script module.Script, ok bool) { - script, ok = f.scripts[name] - return -} - -func (f *scriptLoader) Names() []string { - return f.names -} diff --git a/pkg/grapicmd/internal/module/script/script.go b/pkg/grapicmd/internal/module/script/script.go deleted file mode 100644 index ce8302b6..00000000 --- a/pkg/grapicmd/internal/module/script/script.go +++ /dev/null @@ -1,70 +0,0 @@ -package script - -import ( - "context" - "fmt" - "path/filepath" - - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" -) - -type script struct { - fs afero.Fs - io *clib.IO - exec *execx.Executor - rootDir string - name, binPath string - srcPaths []string -} - -func (s *script) Name() string { - return s.name -} - -func (s *script) Build(ctx context.Context, args ...string) error { - zap.L().Debug("build script", zap.String("name", s.name), zap.String("bin", s.binPath), zap.Strings("srcs", s.srcPaths)) - err := fs.CreateDirIfNotExists(s.fs, filepath.Dir(s.binPath)) - if err != nil { - return errors.WithStack(err) - } - - cmd := s.exec.CommandContext(ctx, "go", s.buildArgs(args)...) - cmd.Dir = s.rootDir - cmd.Stdout = s.io.Out - cmd.Stderr = s.io.Err - cmd.Stdin = s.io.In - err = cmd.Run() - if err != nil { - return errors.Wrapf(err, "failed to build %v", s.srcPaths) - } - - return nil -} - -func (s *script) Run(ctx context.Context, args ...string) error { - cmd := s.exec.CommandContext(ctx, s.binPath, args...) - cmd.Dir = s.rootDir - cmd.Stdout = s.io.Out - cmd.Stderr = s.io.Err - cmd.Stdin = s.io.In - err := cmd.Run() - fmt.Println(err) - if err == context.Canceled { - return nil - } - return errors.WithStack(err) -} - -func (s *script) buildArgs(args []string) []string { - built := make([]string, 0, 3+len(args)+len(s.srcPaths)) - built = append(built, "build", "-o="+s.binPath) - built = append(built, args...) - built = append(built, s.srcPaths...) - return built -} diff --git a/pkg/grapicmd/internal/module/script/script_test.go b/pkg/grapicmd/internal/module/script/script_test.go deleted file mode 100644 index 74242991..00000000 --- a/pkg/grapicmd/internal/module/script/script_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package script - -import ( - "context" - "os/exec" - "path/filepath" - "reflect" - "testing" - - "github.com/spf13/afero" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" -) - -type testContext struct { - fs afero.Fs - loader module.ScriptLoader - binName string - rootDir string - cmdDir string - srcsByBinName map[string][]string - cmds []*exec.Cmd -} - -func createTestContext(t *testing.T) *testContext { - fs := afero.NewMemMapFs() - rootDir := "/home/app" - binName := "bar" - ctx := &testContext{ - fs: fs, - binName: binName, - rootDir: rootDir, - cmdDir: filepath.Join(rootDir, "cmd"), - srcsByBinName: map[string][]string{}, - } - exec := execx.New(execx.WithFakeProcess( - func(_ context.Context, c *exec.Cmd) error { ctx.cmds = append(ctx.cmds, c); return nil }, - )) - - srcsByBinName := map[string][]string{ - binName: {"bar.go", "foo.go", "main.go"}, - } - - for binName, srcs := range srcsByBinName { - dir := filepath.Join(ctx.cmdDir, binName) - err := fs.MkdirAll(dir, 0755) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - srcPaths := make([]string, 0, len(srcs)) - for _, src := range srcs { - path := filepath.Join(dir, src) - err = afero.WriteFile(fs, path, []byte("package main"), 0644) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - srcPaths = append(srcPaths, path) - } - ctx.srcsByBinName[binName] = srcPaths - } - - ctx.loader = NewLoader(fs, &clib.IO{}, exec, rootDir) - - return ctx -} - -func Test_Script(t *testing.T) { - ctx := createTestContext(t) - - err := ctx.loader.Load(ctx.cmdDir) - if err != nil { - t.Errorf("loader.Load() returned an error %v", err) - } - - s, ok := ctx.loader.Get(ctx.binName) - if got, want := ok, true; got != want { - t.Errorf("loader.Get() returned %t, want %t", got, want) - } - - if got, want := s.Name(), ctx.binName; got != want { - t.Errorf("script.Name() returned %v, want %v", got, want) - } - - if err != nil { - t.Errorf("script.Build() returned an error %v", err) - } - - err = s.Build(context.Background(), "-v") - binPath := filepath.Join(ctx.rootDir, "bin", ctx.binName) - cmd := ctx.cmds[0] - - srcs := ctx.srcsByBinName[ctx.binName] - if got, want := cmd.Args, append([]string{"go", "build", "-o=" + binPath, "-v"}, srcs...); !reflect.DeepEqual(got, want) { - t.Errorf("Build() executed %v, want %v", got, want) - } - - if got, want := cmd.Dir, "/home/app"; got != want { - t.Errorf("Build() executed a command in %v, want %v", got, want) - } - - if err != nil { - t.Errorf("Build() returned an error %v", err) - } - - err = s.Run(context.Background(), "-v") - cmd = ctx.cmds[1] - - if got, want := cmd.Path, binPath; got != want { - t.Errorf("Run() executed %v, want %v", got, want) - } - - if got, want := cmd.Dir, "/home/app"; got != want { - t.Errorf("Run() executed a command in %v, want %v", got, want) - } - - if err != nil { - t.Errorf("Run() returned an error %v", err) - } -} diff --git a/pkg/grapicmd/internal/module/testing/generator_mock.go b/pkg/grapicmd/internal/module/testing/generator_mock.go deleted file mode 100644 index 2a491442..00000000 --- a/pkg/grapicmd/internal/module/testing/generator_mock.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: generator.go - -// Package moduletesting is a generated GoMock package. -package moduletesting - -import ( - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockGenerator is a mock of Generator interface -type MockGenerator struct { - ctrl *gomock.Controller - recorder *MockGeneratorMockRecorder -} - -// MockGeneratorMockRecorder is the mock recorder for MockGenerator -type MockGeneratorMockRecorder struct { - mock *MockGenerator -} - -// NewMockGenerator creates a new mock instance -func NewMockGenerator(ctrl *gomock.Controller) *MockGenerator { - mock := &MockGenerator{ctrl: ctrl} - mock.recorder = &MockGeneratorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockGenerator) EXPECT() *MockGeneratorMockRecorder { - return m.recorder -} - -// GenerateProject mocks base method -func (m *MockGenerator) GenerateProject(rootDir, pkgName string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenerateProject", rootDir, pkgName) - ret0, _ := ret[0].(error) - return ret0 -} - -// GenerateProject indicates an expected call of GenerateProject -func (mr *MockGeneratorMockRecorder) GenerateProject(rootDir, pkgName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateProject", reflect.TypeOf((*MockGenerator)(nil).GenerateProject), rootDir, pkgName) -} - -// MockProjectGenerator is a mock of ProjectGenerator interface -type MockProjectGenerator struct { - ctrl *gomock.Controller - recorder *MockProjectGeneratorMockRecorder -} - -// MockProjectGeneratorMockRecorder is the mock recorder for MockProjectGenerator -type MockProjectGeneratorMockRecorder struct { - mock *MockProjectGenerator -} - -// NewMockProjectGenerator creates a new mock instance -func NewMockProjectGenerator(ctrl *gomock.Controller) *MockProjectGenerator { - mock := &MockProjectGenerator{ctrl: ctrl} - mock.recorder = &MockProjectGeneratorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockProjectGenerator) EXPECT() *MockProjectGeneratorMockRecorder { - return m.recorder -} - -// GenerateProject mocks base method -func (m *MockProjectGenerator) GenerateProject(rootDir, pkgName string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenerateProject", rootDir, pkgName) - ret0, _ := ret[0].(error) - return ret0 -} - -// GenerateProject indicates an expected call of GenerateProject -func (mr *MockProjectGeneratorMockRecorder) GenerateProject(rootDir, pkgName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateProject", reflect.TypeOf((*MockProjectGenerator)(nil).GenerateProject), rootDir, pkgName) -} diff --git a/pkg/grapicmd/internal/module/testing/script_mock.go b/pkg/grapicmd/internal/module/testing/script_mock.go deleted file mode 100644 index c70cde2b..00000000 --- a/pkg/grapicmd/internal/module/testing/script_mock.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: script.go - -// Package moduletesting is a generated GoMock package. -package moduletesting - -import ( - context "context" - gomock "github.com/golang/mock/gomock" - module "github.com/izumin5210/grapi/pkg/grapicmd/internal/module" - reflect "reflect" -) - -// MockScript is a mock of Script interface -type MockScript struct { - ctrl *gomock.Controller - recorder *MockScriptMockRecorder -} - -// MockScriptMockRecorder is the mock recorder for MockScript -type MockScriptMockRecorder struct { - mock *MockScript -} - -// NewMockScript creates a new mock instance -func NewMockScript(ctrl *gomock.Controller) *MockScript { - mock := &MockScript{ctrl: ctrl} - mock.recorder = &MockScriptMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockScript) EXPECT() *MockScriptMockRecorder { - return m.recorder -} - -// Name mocks base method -func (m *MockScript) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name -func (mr *MockScriptMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockScript)(nil).Name)) -} - -// Build mocks base method -func (m *MockScript) Build(ctx context.Context, args ...string) error { - m.ctrl.T.Helper() - varargs := []interface{}{ctx} - for _, a := range args { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Build", varargs...) - ret0, _ := ret[0].(error) - return ret0 -} - -// Build indicates an expected call of Build -func (mr *MockScriptMockRecorder) Build(ctx interface{}, args ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx}, args...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Build", reflect.TypeOf((*MockScript)(nil).Build), varargs...) -} - -// Run mocks base method -func (m *MockScript) Run(ctx context.Context, args ...string) error { - m.ctrl.T.Helper() - varargs := []interface{}{ctx} - for _, a := range args { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Run", varargs...) - ret0, _ := ret[0].(error) - return ret0 -} - -// Run indicates an expected call of Run -func (mr *MockScriptMockRecorder) Run(ctx interface{}, args ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx}, args...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockScript)(nil).Run), varargs...) -} - -// MockScriptLoader is a mock of ScriptLoader interface -type MockScriptLoader struct { - ctrl *gomock.Controller - recorder *MockScriptLoaderMockRecorder -} - -// MockScriptLoaderMockRecorder is the mock recorder for MockScriptLoader -type MockScriptLoaderMockRecorder struct { - mock *MockScriptLoader -} - -// NewMockScriptLoader creates a new mock instance -func NewMockScriptLoader(ctrl *gomock.Controller) *MockScriptLoader { - mock := &MockScriptLoader{ctrl: ctrl} - mock.recorder = &MockScriptLoaderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockScriptLoader) EXPECT() *MockScriptLoaderMockRecorder { - return m.recorder -} - -// Load mocks base method -func (m *MockScriptLoader) Load(dir string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Load", dir) - ret0, _ := ret[0].(error) - return ret0 -} - -// Load indicates an expected call of Load -func (mr *MockScriptLoaderMockRecorder) Load(dir interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Load", reflect.TypeOf((*MockScriptLoader)(nil).Load), dir) -} - -// Get mocks base method -func (m *MockScriptLoader) Get(name string) (module.Script, bool) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", name) - ret0, _ := ret[0].(module.Script) - ret1, _ := ret[1].(bool) - return ret0, ret1 -} - -// Get indicates an expected call of Get -func (mr *MockScriptLoaderMockRecorder) Get(name interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockScriptLoader)(nil).Get), name) -} - -// Names mocks base method -func (m *MockScriptLoader) Names() []string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Names") - ret0, _ := ret[0].([]string) - return ret0 -} - -// Names indicates an expected call of Names -func (mr *MockScriptLoaderMockRecorder) Names() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Names", reflect.TypeOf((*MockScriptLoader)(nil).Names)) -} diff --git a/pkg/grapicmd/internal/usecase/init_config.go b/pkg/grapicmd/internal/usecase/init_config.go deleted file mode 100644 index 3520df4e..00000000 --- a/pkg/grapicmd/internal/usecase/init_config.go +++ /dev/null @@ -1,32 +0,0 @@ -package usecase - -import "bytes" - -type InitConfig struct { - Revision string - Branch string - Version string - HEAD bool - GrapiReplacementURL string - Package string - Dep bool -} - -func (c *InitConfig) BuildSpec() string { - buf := bytes.NewBufferString("") - var constraint string - switch { - case c.Revision != "": - constraint = c.Revision - case c.Branch != "": - constraint = c.Branch - case c.HEAD: - constraint = "master" - case c.Version != "": - constraint = c.Version - } - if constraint != "" { - buf.WriteString("@" + constraint) - } - return buf.String() -} diff --git a/pkg/grapicmd/internal/usecase/init_config_test.go b/pkg/grapicmd/internal/usecase/init_config_test.go deleted file mode 100644 index e8d45c7d..00000000 --- a/pkg/grapicmd/internal/usecase/init_config_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package usecase - -import "testing" - -func TestInitConfig_BuildSpec(t *testing.T) { - cases := []struct { - test string - cfg InitConfig - out string - }{ - { - test: "empty", - }, - { - test: "HEAD", - cfg: InitConfig{HEAD: true}, - out: "@master", - }, - { - test: "branch", - cfg: InitConfig{Branch: "foo/bar"}, - out: "@foo/bar", - }, - { - test: "version", - cfg: InitConfig{Version: "^0.3.0"}, - out: "@^0.3.0", - }, - { - test: "revision", - cfg: InitConfig{Revision: "a2489d2"}, - out: "@a2489d2", - }, - } - - for _, tc := range cases { - t.Run(tc.test, func(t *testing.T) { - if got, want := tc.cfg.BuildSpec(), tc.out; got != want { - t.Errorf("BuildSpec() returned %q, want %q", got, want) - } - }) - } -} diff --git a/pkg/grapicmd/internal/usecase/initialize_project_usecase.go b/pkg/grapicmd/internal/usecase/initialize_project_usecase.go deleted file mode 100644 index cdb3d3c8..00000000 --- a/pkg/grapicmd/internal/usecase/initialize_project_usecase.go +++ /dev/null @@ -1,174 +0,0 @@ -package usecase - -import ( - "context" - "os" - "path/filepath" - - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/gex" - "github.com/izumin5210/gex/pkg/tool" - "github.com/pkg/errors" - "github.com/spf13/afero" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - _ "github.com/izumin5210/grapi/pkg/grapicmd/internal/usecase/template" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" -) - -// InitializeProjectUsecase is an interface to create a new grapi project. -type InitializeProjectUsecase interface { - Perform(rootDir string, cfg InitConfig) error - GenerateProject(rootDir, pkgName string) error - InstallDeps(rootDir string, cfg InitConfig) error -} - -// NewInitializeProjectUsecase creates a new InitializeProjectUsecase instance. -func NewInitializeProjectUsecase(ui cli.UI, fs afero.Fs, generator gencmd.Generator, io *clib.IO, exec *execx.Executor, gexCfg *gex.Config) InitializeProjectUsecase { - return &initializeProjectUsecase{ - ui: ui, - fs: fs, - generator: generator, - io: io, - exec: exec, - gexCfg: gexCfg, - } -} - -type initializeProjectUsecase struct { - ui cli.UI - fs afero.Fs - generator gencmd.Generator - io *clib.IO - exec *execx.Executor - gexCfg *gex.Config -} - -func (u *initializeProjectUsecase) Perform(rootDir string, cfg InitConfig) error { - u.ui.Section("Initialize project") - - var err error - err = u.GenerateProject(rootDir, cfg.Package) - if err != nil { - return errors.Wrap(err, "failed to initialize project") - } - - u.ui.Subsection("Install dependencies") - err = u.InstallDeps(rootDir, cfg) - if err != nil { - return errors.Wrap(err, "failed to install dependencies") - } - - return nil -} - -func (u *initializeProjectUsecase) GenerateProject(rootDir, pkgName string) error { - importPath, err := fs.GetImportPath(rootDir) - if err != nil { - return errors.WithStack(err) - } - - if pkgName == "" { - pkgName, err = fs.GetPackageName(rootDir) - if err != nil { - return errors.Wrap(err, "failed to decide a package name") - } - } - - data := map[string]interface{}{ - "packageName": pkgName, - "importPath": importPath, - } - return errors.WithStack(u.generator.Generate(data)) -} - -func (u *initializeProjectUsecase) InstallDeps(rootDir string, cfg InitConfig) error { - invoke := func(name string, args ...string) error { - cmd := u.exec.CommandContext(context.TODO(), name, args...) - cmd.Stdout = u.io.Out - cmd.Stderr = u.io.Err - cmd.Stdin = u.io.In - cmd.Dir = rootDir - if !cfg.Dep { - cmd.Env = append(os.Environ(), "GO111MODULE=on") - } - - return errors.WithStack(cmd.Run()) - } - - if cfg.Dep { - err := invoke("dep", "init") - if err != nil { - return errors.WithStack(err) - } - } else if ok, _ := afero.Exists(u.fs, filepath.Join(rootDir, "go.mod")); ok { - err := invoke("go", "mod", "tidy") - if err != nil { - return errors.WithStack(err) - } - } else { - err := invoke("go", "mod", "init", filepath.Base(rootDir)) - if err != nil { - return errors.WithStack(err) - } - } - - if cfg.Dep { - if spec := cfg.BuildSpec(); spec != "" { - u.ui.ItemFailure("--version, --revision, --branch and --HEAD are not supported in dep mode") - } - } else { - if cfg.GrapiReplacementURL != "" { - err := invoke("go", "mod", "edit", "-replace", "github.com/izumin5210/grapi="+cfg.GrapiReplacementURL) - if err != nil { - return errors.WithStack(err) - } - } else if spec := cfg.BuildSpec(); spec != "" { - pkg := "github.com/izumin5210/grapi/pkg/grapiserver" - err := invoke("go", "get", pkg+spec) - if err != nil { - return errors.WithStack(err) - } - } - err := invoke("go", "get", "./...") - if err != nil { - return errors.WithStack(err) - } - } - - u.gexCfg.WorkingDir = rootDir - u.gexCfg.RootDir = rootDir - toolRepo, err := u.gexCfg.Create() - if err != nil { - return errors.WithStack(err) - } - - { - // regen manifest - path := filepath.Join(u.gexCfg.RootDir, u.gexCfg.ManifestName) - m, err := tool.NewParser(u.fs, u.gexCfg.ManagerType).Parse(path) - if err != nil { - return errors.Wrapf(err, "%s was not found", path) - } - err = tool.NewWriter(u.fs).Write(path, m) - if err != nil { - return errors.WithStack(err) - } - } - - err = toolRepo.BuildAll(context.Background()) - if err != nil { - return errors.WithStack(err) - } - - if !cfg.Dep { - err := invoke("go", "mod", "tidy") - if err != nil { - return errors.WithStack(err) - } - } - - return nil -} diff --git a/pkg/grapicmd/internal/usecase/template/gen.go b/pkg/grapicmd/internal/usecase/template/gen.go deleted file mode 100644 index 70a73172..00000000 --- a/pkg/grapicmd/internal/usecase/template/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate statik -src ./init -dest .. -p template -f -m - -package template diff --git a/pkg/grapicmd/internal/usecase/template/init/.gitignore.tmpl b/pkg/grapicmd/internal/usecase/template/init/.gitignore.tmpl deleted file mode 100644 index c1a21e90..00000000 --- a/pkg/grapicmd/internal/usecase/template/init/.gitignore.tmpl +++ /dev/null @@ -1,4 +0,0 @@ -*.so -/vendor -/bin -/tmp diff --git a/pkg/grapicmd/internal/usecase/template/init/api/protos/.keep.tmpl b/pkg/grapicmd/internal/usecase/template/init/api/protos/.keep.tmpl deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/grapicmd/internal/usecase/template/init/api/protos/type/.keep.tmpl b/pkg/grapicmd/internal/usecase/template/init/api/protos/type/.keep.tmpl deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/grapicmd/internal/usecase/template/init/app/server/.keep.tmpl b/pkg/grapicmd/internal/usecase/template/init/app/server/.keep.tmpl deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/grapicmd/internal/usecase/template/init/cmd/server/main.go.tmpl b/pkg/grapicmd/internal/usecase/template/init/cmd/server/main.go.tmpl deleted file mode 100644 index 41c9e51e..00000000 --- a/pkg/grapicmd/internal/usecase/template/init/cmd/server/main.go.tmpl +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "os" - - "google.golang.org/grpc/grpclog" -) - -func main() { - err := run() - if err != nil { - grpclog.Errorf("server was shutdown with errors: %v", err) - os.Exit(1) - } -} diff --git a/pkg/grapicmd/internal/usecase/template/init/cmd/server/run.go.tmpl b/pkg/grapicmd/internal/usecase/template/init/cmd/server/run.go.tmpl deleted file mode 100644 index ddd13198..00000000 --- a/pkg/grapicmd/internal/usecase/template/init/cmd/server/run.go.tmpl +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "github.com/srvc/appctx" - - "github.com/izumin5210/grapi/pkg/grapiserver" -) - -func run() error { - // Application context - ctx := appctx.Global() - - s := grapiserver.New( - grapiserver.WithDefaultLogger(), - grapiserver.WithServers( - // TODO - ), - ) - return s.Serve(ctx) -} diff --git a/pkg/grapicmd/internal/usecase/template/init/grapi.toml.tmpl b/pkg/grapicmd/internal/usecase/template/init/grapi.toml.tmpl deleted file mode 100644 index 215c06b5..00000000 --- a/pkg/grapicmd/internal/usecase/template/init/grapi.toml.tmpl +++ /dev/null @@ -1,25 +0,0 @@ -package = "{{.packageName}}" - -[grapi] -server_dir = "./app/server" - -[protoc] -protos_dir = "./api/protos" -out_dir = "./api" -import_dirs = [ - "./api/protos", - '{{`{{ module "github.com/grpc-ecosystem/grpc-gateway" }}`}}', - '{{`{{ module "github.com/grpc-ecosystem/grpc-gateway" }}`}}/third_party/googleapis', -] - - [[protoc.plugins]] - name = "go" - args = { plugins = "grpc", paths = "source_relative" } - - [[protoc.plugins]] - name = "grpc-gateway" - args = { logtostderr = true, paths = "source_relative" } - - [[protoc.plugins]] - name = "swagger" - args = { logtostderr = true } diff --git a/pkg/grapicmd/internal/usecase/template/init/tools.go b/pkg/grapicmd/internal/usecase/template/init/tools.go deleted file mode 100644 index 09481548..00000000 --- a/pkg/grapicmd/internal/usecase/template/init/tools.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build tools - -package tools - -// tool dependencies -import ( - _ "github.com/golang/protobuf/protoc-gen-go" - _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway" - _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger" - _ "github.com/izumin5210/gex/cmd/gex" - _ "github.com/izumin5210/grapi/cmd/grapi" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-command" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-scaffold-service" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-service" - _ "github.com/izumin5210/grapi/cmd/grapi-gen-type" -) diff --git a/pkg/grapicmd/internal/usecase/template/statik.go b/pkg/grapicmd/internal/usecase/template/statik.go deleted file mode 100644 index 0bafdf93..00000000 --- a/pkg/grapicmd/internal/usecase/template/statik.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by statik. DO NOT EDIT. - -// Package statik contains static assets. -package template - -import ( - "github.com/rakyll/statik/fs" -) - -func init() { - data := "PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00 \x00cmd/server/main.go.tmplUT\x05\x00\x01\x80Cm8,\xcb\xc1j\x860\x10\x04\xe0\xf3\xeeSl\x03\x85\x04JJ\xaf\x82G\x1f$\xd8\xb8\x86\xc6\xacl\xa2\x16\x8a\xef^\"\xffe`f\xf8\xf60\xff\x04\x8e\xb4\x85T\x10\xd3\xb6\x8b6\xb2\x08F\xaaA\x04\xc3\"\x9c\xa3g\xc9\xa1\xb0\x17\xe5O\xd6}~\"\x0b\x1bt\x88\xcbQ\xe6\xc7[G\x7f\x08Q\x95\x86\x91\xf4(\xd6!\xa4\x85\xfa\xf06RI\xb9\xdf\xf0\xa2~R\x15]\xac\xa9Q\xcf\xa8t\x85Ju=\xda\xb7\\\x85\xae\xd4\xd6\xeeD\xeb@\xef\xa7\xf9\xe8\xc5!\x80T?\xfd\xa6f\xbf\x1c\xc2\x8d7\xfe\x07\x00\x00\xff\xffPK\x07\x08\xb3\x90\xcfL\x99\x00\x00\x00\xbf\x00\x00\x00PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x00 \x00cmd/server/run.go.tmplUT\x05\x00\x01\x80Cm8l\x8dAK31\x10@\xcf\x99_1\xec)\x81\x8f\xcd\xa7\xe0E\xf0 \x14\xbc\x88=(xN\xc34\x1d\xba\x9b\x84\xc9\xa4.\x8a\xff]\xb6\xbdT\xf0\xf6x\xf3f\xa6\x86x\x0c\x89p\x0e\x9c\x01x\xaeE\x14-\x98!\xb1\x1e\xfan\x8ce\xf6MN\xd1\x87Z\xa3.\x03\xfc\x1e\xf1g\x9f9\xdf\xdd\xde\xfc\xf7IBe_\x8f\xe9B\x8d\xe4D2\x80\x03\xd8\xf7\x1cQz\xb6\x0eI\xa4\x08~\x81\xf1\x1e\x1fk\x9d8\x06\xe5\x921\x96\xac\xb4(\x98\xa8\x0b\xde?\xe0\xe5\xdb\xf84\x95]\x98\xac\x030m\xd5W\x97\xc7\x17\xfa\xb0`\xcc\xb5zg=lh\x1f\xfa\xa4\xcf%%\x12\xeb\xfe\xfd\x91\xbc\x9e\xb1\xad\xdb\xde\xe3\xdbv\xb3\x05c\xd6\xd2\x81\x11\xd2.\x19\xdbx\x8el\xd4\xc5\xc17\xfc\x04\x00\x00\xff\xffPK\x07\x08\xabp\xba4\xce\x00\x00\x00&\x01\x00\x00PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00 \x00grapi.toml.tmplUT\x05\x00\x01\x80Cm8\xa4\x91A\x8e\xf20\x0c\x85\xf7>\x85\x95\x0d\x1b\xfe\xf6\x04\\\xe1\xbf\x00\xaa\xc0\x93Z&\x9a\x16GN\x02BQ\xee>j\xe9\x82\x99\xc5\xcc\x82U\xf4\x9e\xbf\xf8\xc5N$\xffI\xc2x@Wk\xb7\xa9\xff4sk\x0e\xe0(F1\x0c\x90\xd8nl\xa71\xd8\x02v=\xc5\xd8?\xbd\x05\x8a\xa6Y\xfd\x00\xeb\x99^\xa9\xd0?=\x07Z\xf2\xb7\x82\x830G\xb5\xd5Lx\xc0#\xe0\x8f+{@\xdc\xd5z\xae\x15g\x1d\xcb\xc4\xe8$\xe4K\xf9\xe8\xbc\xce\xbdX\xf4\xff\xd8kz\xa4\xcc\x9b\x14\xca|\xa7\x87\xc3\xd6\xce\xad\xed\xdem\xd0\xe7K\xb0\xf1\x14\xc9\xf2\xa3\x17U\x99\x98bH\xbb=\x0c\x00\x88\xc7m\xee.NE\xc25\x0d\x03 ^i^w)\xea\x00\x91L\x96\xd9*n\xc8Z\xb1\xe8\xdd\x1e#\xe5\xcb\xaa\x93\x16\xf3|2\x9e(\x87\x1b;l\x7f7\x7f}\xebk\xcc\xa4\x925\xe5\x91mYt\xb6\xc2\xef\x05\xa5;\x89,\x7f\xfck\x066\xf8\n\x00\x00\xff\xffPK\x07\x08\xfaZgN\xfd\x00\x00\x00F\x02\x00\x00PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00 \x00tools.goUT\x05\x00\x01\x80Cm8\x9c\x8e\xddJ\xc4@\x0c\x85\xaf\x9d\xa7\x18z\xa5H\x8d\n>\x8f\xa4\x994\x06;\x93a~\\\xeb\xd3\xcb\xee*(\x0b\x0b\xedU\xce \xdf\x17\x02\xe0\xef\xa7\xaeK\xf0\xcdl\xa9\xcee\xa4w\x14\xfe\xad\x00\xa7\xe4\x03gN\x81\x13)W\xa71[i\xfe\xd6\xdd\xbc\xfaA\xb4\xbd\xf5\xe9\x81,\x82\xd8\x82I \x17k6\xf5\xf9\x1ch\x14N\xa3\xd8pA\x97L#\x93\xd5\xb56\xfe\xa9\x82\x8d\x0f\xb8\xfe3\xff\xec\xf7\xde\xa8\x07\x14\xe1r\xa1\xebW\x8f\x9a^\x9e\x9f\x1eA\xf8\x13(\x86\xe3\xbc\x8a\x15\xccz\x06\x8fi\x03zz\x84,FLa\xabV \xe7\xd9\x960V.\x1fJ\xbc\xd9\xdf\xa7\xb55\xf3\xe0\xee\xdcw\x00\x00\x00\xff\xffPK\x07\x083'=\x96\xb9\x00\x00\x00%\x02\x00\x00PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\xb3\x90\xcfL\x99\x00\x00\x00\xbf\x00\x00\x00\x17\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00cmd/server/main.go.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\xabp\xba4\xce\x00\x00\x00&\x01\x00\x00\x16\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\xe7\x00\x00\x00cmd/server/run.go.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\xfaZgN\xfd\x00\x00\x00F\x02\x00\x00\x0f\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x02\x02\x00\x00grapi.toml.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(3'=\x96\xb9\x00\x00\x00%\x02\x00\x00\x08\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81E\x03\x00\x00tools.goUT\x05\x00\x01\x80Cm8PK\x05\x06\x00\x00\x00\x00\x04\x00\x04\x00 \x01\x00\x00=\x04\x00\x00\x00\x00" - fs.Register(data) -} diff --git a/pkg/grapicmd/util/fs/dir.go b/pkg/grapicmd/util/fs/dir.go index 014142eb..9f656e58 100644 --- a/pkg/grapicmd/util/fs/dir.go +++ b/pkg/grapicmd/util/fs/dir.go @@ -1,14 +1,8 @@ package fs import ( - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" + newFs "github.com/x-izumin/grapi/pkg/grapicmd/util/fs" ) // CreateDirIfNotExists creates a directory if it does not exist. -func CreateDirIfNotExists(fs afero.Fs, path string) (err error) { - err = fs.MkdirAll(path, 0755) - zap.L().Debug("CreateDirIfNotExists", zap.String("path", path), zap.Error(err)) - return errors.Wrapf(err, "failed to create %q directory", path) -} +var CreateDirIfNotExists = newFs.CreateDirIfNotExists diff --git a/pkg/grapicmd/util/fs/exec.go b/pkg/grapicmd/util/fs/exec.go index 7a9256fd..0e3f772d 100644 --- a/pkg/grapicmd/util/fs/exec.go +++ b/pkg/grapicmd/util/fs/exec.go @@ -1,47 +1,7 @@ package fs import ( - "os" - "path/filepath" - "sort" - "strings" - "sync" - - "github.com/spf13/afero" + newFs "github.com/x-izumin/grapi/pkg/grapicmd/util/fs" ) -func ListExecutableWithPrefix(fs afero.Fs, prefix string) []string { - var wg sync.WaitGroup - ch := make(chan string) - - for _, path := range filepath.SplitList(os.Getenv("PATH")) { - wg.Add(1) - go func(path string) { - defer wg.Done() - - files, err := afero.ReadDir(fs, path) - if err != nil { - return - } - - for _, f := range files { - if m := f.Mode(); !f.IsDir() && m&0111 != 0 && strings.HasPrefix(f.Name(), prefix) { - ch <- f.Name() - } - } - }(path) - } - - go func() { - wg.Wait() - close(ch) - }() - - execs := make([]string, 0, 100) - for exec := range ch { - execs = append(execs, exec) - } - sort.Strings(execs) - - return execs -} +var ListExecutableWithPrefix = newFs.ListExecutableWithPrefix diff --git a/pkg/grapicmd/util/fs/path.go b/pkg/grapicmd/util/fs/path.go index e63c65d9..46ce4b97 100644 --- a/pkg/grapicmd/util/fs/path.go +++ b/pkg/grapicmd/util/fs/path.go @@ -1,109 +1,19 @@ package fs import ( - "go/build" - "go/parser" - "go/token" - "os" - "os/user" - "path/filepath" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" + newFs "github.com/x-izumin/grapi/pkg/grapicmd/util/fs" ) -type getOSUserFunc func() (*user.User, error) - const ( // PackageSeparator is a package separator string on protobuf. - PackageSeparator = "." + PackageSeparator = newFs.PackageSeparator ) -// Make visible for testing -var ( - BuildContext build.Context - GetOSUser getOSUserFunc -) - -func init() { - BuildContext = build.Default - GetOSUser = user.Current -} - // GetImportPath creates the golang package path from the given path. -func GetImportPath(rootPath string) (importPath string, err error) { - for _, gopath := range filepath.SplitList(BuildContext.GOPATH) { - prefix := filepath.Join(gopath, "src") + string(filepath.Separator) - // FIXME: should not use strings.HasPrefix - if strings.HasPrefix(rootPath, prefix) { - importPath = filepath.ToSlash(strings.Replace(rootPath, prefix, "", 1)) - break - } - } - if importPath == "" { - importPath = filepath.Base(rootPath) - } - return -} +var GetImportPath = newFs.GetImportPath // GetPackageName generates the package name of this application from the given path and envs. -func GetPackageName(rootPath string) (string, error) { - importPath, err := GetImportPath(rootPath) - if err != nil { - return "", errors.WithStack(err) - } - entries := strings.Split(importPath, string(filepath.Separator)) - if len(entries) < 2 { - u, err := GetOSUser() - if err != nil { - return "", errors.WithStack(err) - } - entries = []string{u.Username, entries[0]} - } - entries = entries[len(entries)-2:] - if strings.Contains(entries[0], PackageSeparator) { - s := strings.Split(entries[0], PackageSeparator) - for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] - } - entries[0] = strings.Join(s, PackageSeparator) - } - pkgName := strings.Join(entries[len(entries)-2:], PackageSeparator) - pkgName = strings.Replace(pkgName, "-", "_", -1) - return pkgName, nil -} +var GetPackageName = newFs.GetPackageName // FindMainPackagesAndSources returns go source file names by main package directories. -func FindMainPackagesAndSources(fs afero.Fs, dir string) (map[string][]string, error) { - out := make(map[string][]string) - fset := token.NewFileSet() - err := afero.Walk(fs, dir, func(path string, info os.FileInfo, err error) error { - if err != nil { - return errors.WithStack(err) - } - if info.IsDir() || filepath.Ext(info.Name()) != ".go" || strings.HasSuffix(info.Name(), "_test.go") { - return nil - } - data, err := afero.ReadFile(fs, path) - if err != nil { - zap.L().Warn("failed to read a file", zap.Error(err), zap.String("path", path)) - return nil - } - f, err := parser.ParseFile(fset, "", data, parser.PackageClauseOnly) - if err != nil { - zap.L().Warn("failed to parse a file", zap.Error(err), zap.String("path", path), zap.String("body", string(data))) - return nil - } - if f.Package.IsValid() && f.Name.Name == "main" { - dir := filepath.Dir(path) - out[dir] = append(out[dir], info.Name()) - } - return nil - }) - if err != nil { - return nil, errors.WithStack(err) - } - return out, nil -} +var FindMainPackagesAndSources = newFs.FindMainPackagesAndSources diff --git a/pkg/grapicmd/util/fs/path_test.go b/pkg/grapicmd/util/fs/path_test.go deleted file mode 100644 index f476371c..00000000 --- a/pkg/grapicmd/util/fs/path_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package fs - -import ( - "os/user" - "path/filepath" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/spf13/afero" -) - -func Test_GetImportPath(t *testing.T) { - defer func(tmp string) { BuildContext.GOPATH = tmp }(BuildContext.GOPATH) - BuildContext.GOPATH = "/home/go" - - cases := []struct { - test string - in string - out string - isErr bool - }{ - { - test: "inside of GOPATH", - in: "/home/go/src/github.com/izumin5210/testapp", - out: "github.com/izumin5210/testapp", - }, - { - test: "directly under GOPATH", - in: "/home/go/src/testapp", - out: "testapp", - }, - { - test: "outside of GOPATH", - in: "/home/go/testapp", - out: "testapp", - }, - } - - for _, c := range cases { - t.Run(c.test, func(t *testing.T) { - out, err := GetImportPath(c.in) - - if got, want := err != nil, c.isErr; got != want { - t.Errorf("Returned error is %t, want %t (%v)", got, want, err) - } - - if got, want := out, c.out; got != want { - t.Errorf("Returned %s, want %s", got, want) - } - }) - } -} - -func Test_GetPackageName(t *testing.T) { - defer func(tmp getOSUserFunc) { GetOSUser = tmp }(GetOSUser) - GetOSUser = func() (*user.User, error) { return &user.User{Username: "testuser"}, nil } - defer func(tmp string) { BuildContext.GOPATH = tmp }(BuildContext.GOPATH) - BuildContext.GOPATH = "/home/go" - - cases := []struct { - test string - in string - out string - isErr bool - }{ - { - test: "inside of GOPATH", - in: "/home/go/src/github.com/izumin5210/testapp", - out: "izumin5210.testapp", - }, - { - test: "directly under GOPATH", - in: "/home/go/src/testapp", - out: "testuser.testapp", - }, - { - test: "company name includes separators", - in: "/home/go/src/go.example.com/testapp", - out: "com.example.go.testapp", - }, - { - test: "package name includes hyphens", - in: "/home/go/src/go.example.com/test-app", - out: "com.example.go.test_app", - }, - { - test: "outside of GOPATH", - in: "/home/go/testapp", - out: "testuser.testapp", - }, - } - - for _, c := range cases { - t.Run(c.test, func(t *testing.T) { - out, err := GetPackageName(c.in) - - if got, want := err != nil, c.isErr; got != want { - t.Errorf("Returned error is %t, want %t (%v)", got, want, err) - } - - if got, want := out, c.out; got != want { - t.Errorf("Returned %s, want %s", got, want) - } - }) - } -} - -func Test_FindUserDefinedCommandPaths(t *testing.T) { - fs := afero.NewMemMapFs() - rootPath := "/home/app" - cmdPath := filepath.Join(rootPath, "cmd") - - fs.MkdirAll(filepath.Join(rootPath, "app", "server"), 0755) - fs.MkdirAll(filepath.Join(rootPath, "api", "proto"), 0755) - afero.WriteFile(fs, filepath.Join(rootPath, "grapi.toml"), []byte(""), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "server"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "server", "run.go"), []byte("package main"), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "foo", "bar"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "foo", "bar", "run.go"), []byte("package main"), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "baz"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "baz", "qux"), []byte(""), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "quux", "corge"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "quux", "main.go"), []byte("package main"), 0644) - afero.WriteFile(fs, filepath.Join(cmdPath, "quux", "corge", "grault.go"), []byte("package corge"), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "garply"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "garply", "main.go"), []byte("package garply"), 0644) - fs.MkdirAll(filepath.Join(cmdPath, "waldo", "fred"), 0755) - afero.WriteFile(fs, filepath.Join(cmdPath, "waldo", "main.go"), []byte("package waldo"), 0644) - afero.WriteFile(fs, filepath.Join(cmdPath, "waldo", "fred", "main.go"), []byte("package main"), 0644) - afero.WriteFile(fs, filepath.Join(cmdPath, "waldo", "fred", "main_test.go"), []byte("package main"), 0644) - afero.WriteFile(fs, filepath.Join(cmdPath, "waldo", "fred", "plugh.go"), []byte("package main"), 0644) - - paths, err := FindMainPackagesAndSources(fs, cmdPath) - - if err != nil { - t.Errorf("FindUserDefinedCommandPaths returned an error %v", err) - } - - wantPaths := map[string][]string{ - filepath.Join(cmdPath, "foo", "bar"): {"run.go"}, - filepath.Join(cmdPath, "quux"): {"main.go"}, - filepath.Join(cmdPath, "waldo", "fred"): {"main.go", "plugh.go"}, - filepath.Join(cmdPath, "server"): {"run.go"}, - } - - if got, want := len(paths), len(wantPaths); got != want { - t.Errorf("FindUserDefinedCommandPaths returned %d paths, want %d paths", got, want) - } - - if diff := cmp.Diff(paths, wantPaths); diff != "" { - t.Errorf("Received path differs: (-got +want)\n%s", diff) - } -} diff --git a/pkg/grapiserver/cmux.go b/pkg/grapiserver/cmux.go deleted file mode 100644 index 98e446fd..00000000 --- a/pkg/grapiserver/cmux.go +++ /dev/null @@ -1,37 +0,0 @@ -package grapiserver - -import ( - "net" - - "github.com/soheilhy/cmux" - "google.golang.org/grpc/grpclog" -) - -type cmuxServer struct { - mux cmux.CMux - lis net.Listener -} - -func newCmuxServer(lis net.Listener) *cmuxServer { - return &cmuxServer{ - mux: cmux.New(lis), - lis: lis, - } -} - -// Serve implements Server.Serve -func (s *cmuxServer) Serve() { - grpclog.Info("mux is starting %s", s.lis.Addr()) - - err := s.mux.Serve() - - grpclog.Infof("mux is closed: %v", err) -} - -func (s *cmuxServer) GRPCListener() net.Listener { - return s.mux.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc")) -} - -func (s *cmuxServer) HTTPListener() net.Listener { - return s.mux.Match(cmux.HTTP2(), cmux.HTTP1Fast()) -} diff --git a/pkg/grapiserver/config.go b/pkg/grapiserver/config.go index ec66195a..2fcf548d 100644 --- a/pkg/grapiserver/config.go +++ b/pkg/grapiserver/config.go @@ -1,136 +1,13 @@ package grapiserver import ( - "crypto/tls" - "net" - "net/http" - "os" - "path/filepath" - pkg_runtime "runtime" - "time" - - "github.com/grpc-ecosystem/go-grpc-middleware" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/pkg/errors" - "google.golang.org/grpc" + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" ) -func createDefaultConfig() *Config { - config := &Config{ - GrpcInternalAddr: &Address{ - Network: "unix", - Addr: "tmp/server.sock", - }, - GatewayAddr: &Address{ - Network: "tcp", - Addr: ":3000", - }, - GatewayServerConfig: &HTTPServerConfig{ - ReadTimeout: 8 * time.Second, - WriteTimeout: 8 * time.Second, - IdleTimeout: 2 * time.Minute, - }, - MaxConcurrentStreams: 1000, - } - if pkg_runtime.GOOS == "windows" { - config.GrpcInternalAddr = &Address{ - Network: "tcp", - Addr: ":5050", - } - } - return config -} - // Address represents a network end point address. -type Address struct { - Network string - Addr string -} - -func (a *Address) createListener() (net.Listener, error) { - if a.Network == "unix" { - dir := filepath.Dir(a.Addr) - f, err := os.Stat(dir) - if err != nil { - if err = os.MkdirAll(dir, 0755); err != nil { - return nil, errors.Wrap(err, "failed to create the directory") - } - } else if !f.IsDir() { - return nil, errors.Errorf("file %q already exists", dir) - } - } - lis, err := net.Listen(a.Network, a.Addr) - if err != nil { - return nil, errors.Wrapf(err, "failed to listen %s %s", a.Network, a.Addr) - } - return lis, nil -} +type Address = newGrapiserver.Address -type HTTPServerConfig struct { - TLSConfig *tls.Config - ReadTimeout time.Duration - ReadHeaderTimeout time.Duration - WriteTimeout time.Duration - IdleTimeout time.Duration - MaxHeaderBytes int - TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler) - ConnState func(net.Conn, http.ConnState) -} - -func (c *HTTPServerConfig) applyTo(s *http.Server) { - s.TLSConfig = c.TLSConfig - s.ReadTimeout = c.ReadTimeout - s.ReadHeaderTimeout = c.ReadHeaderTimeout - s.WriteTimeout = c.WriteTimeout - s.IdleTimeout = c.IdleTimeout - s.MaxHeaderBytes = c.MaxHeaderBytes - s.TLSNextProto = c.TLSNextProto - s.ConnState = c.ConnState -} +type HTTPServerConfig = newGrapiserver.HTTPServerConfig // Config contains configurations of gRPC and Gateway server. -type Config struct { - GrpcAddr *Address - GrpcInternalAddr *Address - GatewayAddr *Address - Servers []Server - GrpcServerUnaryInterceptors []grpc.UnaryServerInterceptor - GrpcServerStreamInterceptors []grpc.StreamServerInterceptor - GatewayServerUnaryInterceptors []grpc.UnaryClientInterceptor - GatewayServerStreamInterceptors []grpc.StreamClientInterceptor - GrpcServerOption []grpc.ServerOption - GatewayDialOption []grpc.DialOption - GatewayMuxOptions []runtime.ServeMuxOption - GatewayServerConfig *HTTPServerConfig - MaxConcurrentStreams uint32 - GatewayServerMiddlewares []HTTPServerMiddleware -} - -func (c *Config) serverOptions() []grpc.ServerOption { - return append( - []grpc.ServerOption{ - grpc_middleware.WithUnaryServerChain(c.GrpcServerUnaryInterceptors...), - grpc_middleware.WithStreamServerChain(c.GrpcServerStreamInterceptors...), - grpc.MaxConcurrentStreams(c.MaxConcurrentStreams), - }, - c.GrpcServerOption..., - ) -} - -func (c *Config) clientOptions() []grpc.DialOption { - return append( - []grpc.DialOption{ - grpc.WithInsecure(), - grpc.WithDialer(func(a string, t time.Duration) (net.Conn, error) { - return net.Dial(c.GrpcInternalAddr.Network, a) - }), - grpc.WithUnaryInterceptor( - grpc_middleware.ChainUnaryClient(c.GatewayServerUnaryInterceptors...), - ), - grpc.WithStreamInterceptor( - grpc_middleware.ChainStreamClient(c.GatewayServerStreamInterceptors...), - ), - }, - c.GatewayDialOption..., - ) -} +type Config = newGrapiserver.Config diff --git a/pkg/grapiserver/engine.go b/pkg/grapiserver/engine.go index 5e47e059..c372a073 100644 --- a/pkg/grapiserver/engine.go +++ b/pkg/grapiserver/engine.go @@ -1,93 +1,11 @@ package grapiserver import ( - "context" - "net" - "reflect" - - "github.com/izumin5210/grapi/pkg/grapiserver/internal" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" ) // Engine is the framework instance. -type Engine struct { - *Config -} +type Engine = newGrapiserver.Engine // New creates a server intstance. -func New(opts ...Option) *Engine { - return &Engine{ - Config: createConfig(opts), - } -} - -// Serve starts gRPC and Gateway servers. -func (e *Engine) Serve(ctx context.Context) error { - var ( - grpcServer, gatewayServer internal.Server - grpcLis, gatewayLis, internalLis net.Listener - cmuxServer *cmuxServer - err error - ) - - if e.GrpcAddr != nil && e.GatewayAddr != nil && reflect.DeepEqual(e.GrpcAddr, e.GatewayAddr) { - lis, err := e.GrpcAddr.createListener() - if err != nil { - return errors.Wrap(err, "failed to listen network for servers") - } - defer lis.Close() - cmuxServer = newCmuxServer(lis) - grpcLis = cmuxServer.GRPCListener() - gatewayLis = cmuxServer.HTTPListener() - } - - // Setup servers - grpcServer = newGRPCServer(e.Config) - - // Setup listeners - if grpcLis == nil && e.GrpcAddr != nil { - grpcLis, err = e.GrpcAddr.createListener() - if err != nil { - return errors.Wrap(err, "failed to listen network for gRPC server") - } - defer grpcLis.Close() - } - - if e.GatewayAddr != nil { - gatewayServer = newGatewayServer(e.Config) - internalLis, err = e.GrpcInternalAddr.createListener() - if err != nil { - return errors.Wrap(err, "failed to listen network for gRPC server internal") - } - defer internalLis.Close() - } - - if gatewayLis == nil && e.GatewayAddr != nil { - gatewayLis, err = e.GatewayAddr.createListener() - if err != nil { - return errors.Wrap(err, "failed to listen network for gateway server") - } - defer gatewayLis.Close() - } - - // Start servers - ctx, cancel := context.WithCancel(ctx) - defer cancel() - eg, ctx := errgroup.WithContext(ctx) - - if internalLis != nil { - eg.Go(func() error { return grpcServer.Serve(ctx, internalLis) }) - } - if grpcLis != nil { - eg.Go(func() error { return grpcServer.Serve(ctx, grpcLis) }) - } - if gatewayLis != nil { - eg.Go(func() error { return gatewayServer.Serve(ctx, gatewayLis) }) - } - if cmuxServer != nil { - eg.Go(func() error { cmuxServer.Serve(); return nil }) - } - - return errors.WithStack(eg.Wait()) -} +var New = newGrapiserver.New diff --git a/pkg/grapiserver/gateway.go b/pkg/grapiserver/gateway.go deleted file mode 100644 index ea2170a5..00000000 --- a/pkg/grapiserver/gateway.go +++ /dev/null @@ -1,111 +0,0 @@ -package grapiserver - -import ( - "context" - "net" - "net/http" - "time" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/izumin5210/grapi/pkg/grapiserver/internal" - "github.com/pkg/errors" - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" -) - -func newGatewayServer(c *Config) internal.Server { - return &gatewayServer{ - Config: c, - } -} - -// gatewayServer wraps gRPC gateway server setup process. -type gatewayServer struct { - server *http.Server - *Config -} - -// Serve implements Server.Server -func (s *gatewayServer) Serve(ctx context.Context, l net.Listener) error { - conn, err := s.createConn() - if err != nil { - return errors.Wrap(err, "failed to create connection with grpc-gateway server") - } - defer conn.Close() - - s.server, err = s.createServer(conn) - if err != nil { - return errors.Wrap(err, "failed to create gRPC Gateway server: %v") - } - - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - go func() { - <-ctx.Done() - s.shutdown() - }() - - grpclog.Infof("grpc-gateway server is starting %s", l.Addr()) - - err = s.server.Serve(l) - - grpclog.Infof("stopped taking more http(s) requests: %v", err) - - if err != http.ErrServerClosed { - return errors.Wrap(err, "failed to serve grpc-gateway server") - } - - return nil -} - -func (s *gatewayServer) shutdown() { - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - err := s.server.Shutdown(ctx) - grpclog.Info("All http(s) requests finished") - if err != nil { - grpclog.Errorf("failed to shutdown grpc-gateway server: %v", err) - } -} - -func (s *gatewayServer) createConn() (conn *grpc.ClientConn, err error) { - conn, err = grpc.Dial(s.GrpcInternalAddr.Addr, s.clientOptions()...) - if err != nil { - err = errors.Wrap(err, "failed to connect to gRPC server") - } - return -} - -func (s *gatewayServer) createServer(conn *grpc.ClientConn) (*http.Server, error) { - mux := runtime.NewServeMux( - append( - []runtime.ServeMuxOption{runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler)}, - s.GatewayMuxOptions..., - )..., - ) - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) - defer cancel() - - for _, svr := range s.Servers { - err := svr.RegisterWithHandler(ctx, mux, conn) - if err != nil { - return nil, errors.Wrap(err, "failed to register handler") - } - } - - var handler http.Handler = mux - - for i := len(s.GatewayServerMiddlewares) - 1; i >= 0; i-- { - handler = (s.GatewayServerMiddlewares[i])(handler) - } - - svr := &http.Server{ - Handler: handler, - } - if cfg := s.GatewayServerConfig; cfg != nil { - cfg.applyTo(svr) - } - - return svr, nil -} diff --git a/pkg/grapiserver/grpc.go b/pkg/grapiserver/grpc.go deleted file mode 100644 index 1e7f4a12..00000000 --- a/pkg/grapiserver/grpc.go +++ /dev/null @@ -1,50 +0,0 @@ -package grapiserver - -import ( - "context" - "net" - - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/reflection" - - "github.com/izumin5210/grapi/pkg/grapiserver/internal" - "github.com/pkg/errors" -) - -// grpcServer wraps grpc.Server setup process. -type grpcServer struct { - server *grpc.Server - *Config -} - -func newGRPCServer(c *Config) internal.Server { - s := grpc.NewServer(c.serverOptions()...) - reflection.Register(s) - for _, svr := range c.Servers { - svr.RegisterWithServer(s) - } - return &grpcServer{ - server: s, - Config: c, - } -} - -// Serve implements Server.Server -func (s *grpcServer) Serve(ctx context.Context, l net.Listener) error { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - go func() { - <-ctx.Done() - s.server.GracefulStop() - }() - - grpclog.Infof("gRPC server is starting %s", l.Addr()) - - err := s.server.Serve(l) - - grpclog.Infof("gRPC server stopped: %v", err) - - return errors.Wrap(err, "failed to serve gRPC server") -} diff --git a/pkg/grapiserver/http_server_middleware.go b/pkg/grapiserver/http_server_middleware.go index 10a3765e..a5fb527f 100644 --- a/pkg/grapiserver/http_server_middleware.go +++ b/pkg/grapiserver/http_server_middleware.go @@ -1,6 +1,8 @@ package grapiserver -import "net/http" +import ( + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" +) // HTTPServerMiddleware is an interface of http server middleware -type HTTPServerMiddleware func(http.Handler) http.Handler +type HTTPServerMiddleware = newGrapiserver.HTTPServerMiddleware diff --git a/pkg/grapiserver/internal/server.go b/pkg/grapiserver/internal/server.go deleted file mode 100644 index 4cff156f..00000000 --- a/pkg/grapiserver/internal/server.go +++ /dev/null @@ -1,11 +0,0 @@ -package internal - -import ( - "context" - "net" -) - -// Server provides an interface for starting and stopping the server. -type Server interface { - Serve(context.Context, net.Listener) error -} diff --git a/pkg/grapiserver/main_test.go b/pkg/grapiserver/main_test.go deleted file mode 100644 index 505cad80..00000000 --- a/pkg/grapiserver/main_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package grapiserver_test - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "google.golang.org/grpc" - - "github.com/izumin5210/grapi/pkg/grapiserver" - api_pb "github.com/izumin5210/grapi/pkg/grapiserver/testing/api" - "github.com/izumin5210/grapi/pkg/grapiserver/testing/app/server" -) - -var ( - waitForServer = func() { time.Sleep(1 * time.Second) } -) - -func orDie(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func startServer(t *testing.T, s *grapiserver.Engine) func() { - var wg sync.WaitGroup - wg.Add(1) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - defer wg.Done() - if err := s.Serve(ctx); err != nil && - !strings.Contains(err.Error(), "use of closed network connection") && - !strings.Contains(err.Error(), "listener closed") { - t.Errorf("Engine.Serve returned an error: %v", err) - } - }() - waitForServer() - return func() { - cancel() - wg.Wait() - } -} - -func Test_server_onlyGateway(t *testing.T) { - var port int64 = 15261 - s := grapiserver.New( - grapiserver.WithGatewayAddr("tcp", ":"+strconv.FormatInt(port, 10)), - grapiserver.WithServers( - server.NewLibraryServiceServer(), - ), - ) - - defer startServer(t, s)() - - resp, err := http.Get(fmt.Sprintf("http://localhost:%d/books", port)) - orDie(t, err) - defer resp.Body.Close() - - if got, want := resp.StatusCode, 200; got != want { - t.Errorf("Response status is %d, want %d", got, want) - } - - data, err := ioutil.ReadAll(resp.Body) - orDie(t, err) - - got := map[string]interface{}{} - orDie(t, json.Unmarshal(data, &got)) - want := map[string]interface{}{ - "books": []interface{}{ - map[string]interface{}{"book_id": "The Go Programming Language"}, - map[string]interface{}{"book_id": "Programming Ruby"}, - }, - } - - if diff := cmp.Diff(got, want); diff != "" { - t.Errorf("Received body differs: (-got +want)\n%s", diff) - } -} - -func Test_server_samePort(t *testing.T) { - var port int64 = 15261 - addr := ":" + strconv.FormatInt(port, 10) - s := grapiserver.New( - grapiserver.WithAddr("tcp", addr), - grapiserver.WithServers( - server.NewLibraryServiceServer(), - ), - ) - - defer startServer(t, s)() - - t.Run("http", func(t *testing.T) { - resp, err := http.Get(fmt.Sprintf("http://localhost:%d/books", port)) - orDie(t, err) - defer resp.Body.Close() - - if got, want := resp.StatusCode, 200; got != want { - t.Errorf("Response status is %d, want %d", got, want) - } - - data, err := ioutil.ReadAll(resp.Body) - orDie(t, err) - - got := map[string]interface{}{} - orDie(t, json.Unmarshal(data, &got)) - want := map[string]interface{}{ - "books": []interface{}{ - map[string]interface{}{"book_id": "The Go Programming Language"}, - map[string]interface{}{"book_id": "Programming Ruby"}, - }, - } - - if diff := cmp.Diff(got, want); diff != "" { - t.Errorf("Received body differs: (-got +want)\n%s", diff) - } - }) - - t.Run("gRPC", func(t *testing.T) { - conn, err := grpc.Dial(addr, grpc.WithInsecure()) - orDie(t, err) - defer conn.Close() - - cli := api_pb.NewLibraryServiceClient(conn) - resp, err := cli.ListBooks(context.Background(), &api_pb.ListBooksRequest{}) - orDie(t, err) - - want := &api_pb.ListBooksResponse{ - Books: []*api_pb.Book{ - {BookId: "The Go Programming Language"}, - {BookId: "Programming Ruby"}, - }, - } - if diff := cmp.Diff(resp, want); diff != "" { - t.Errorf("Received body differs: (-got +want)\n%s", diff) - } - }) -} - -func Test_server_differentPort(t *testing.T) { - var ( - grpcPort int64 = 15261 - httpPort int64 = 15262 - ) - - grpcAddr := ":" + strconv.FormatInt(grpcPort, 10) - httpAddr := ":" + strconv.FormatInt(httpPort, 10) - - s := grapiserver.New( - grapiserver.WithGrpcAddr("tcp", grpcAddr), - grapiserver.WithGatewayAddr("tcp", httpAddr), - grapiserver.WithServers( - server.NewLibraryServiceServer(), - ), - ) - - defer startServer(t, s)() - - t.Run("http", func(t *testing.T) { - resp, err := http.Get(fmt.Sprintf("http://localhost:%d/books", httpPort)) - orDie(t, err) - defer resp.Body.Close() - - if got, want := resp.StatusCode, 200; got != want { - t.Errorf("Response status is %d, want %d", got, want) - } - - data, err := ioutil.ReadAll(resp.Body) - orDie(t, err) - - got := map[string]interface{}{} - orDie(t, json.Unmarshal(data, &got)) - want := map[string]interface{}{ - "books": []interface{}{ - map[string]interface{}{"book_id": "The Go Programming Language"}, - map[string]interface{}{"book_id": "Programming Ruby"}, - }, - } - - if diff := cmp.Diff(got, want); diff != "" { - t.Errorf("Received body differs: (-got +want)\n%s", diff) - } - }) - - t.Run("gRPC", func(t *testing.T) { - conn, err := grpc.Dial(grpcAddr, grpc.WithInsecure()) - orDie(t, err) - defer conn.Close() - - cli := api_pb.NewLibraryServiceClient(conn) - resp, err := cli.ListBooks(context.Background(), &api_pb.ListBooksRequest{}) - orDie(t, err) - - want := &api_pb.ListBooksResponse{ - Books: []*api_pb.Book{ - {BookId: "The Go Programming Language"}, - {BookId: "Programming Ruby"}, - }, - } - if diff := cmp.Diff(resp, want); diff != "" { - t.Errorf("Received body differs: (-got +want)\n%s", diff) - } - }) -} diff --git a/pkg/grapiserver/options.go b/pkg/grapiserver/options.go index 78b89f09..f1800957 100644 --- a/pkg/grapiserver/options.go +++ b/pkg/grapiserver/options.go @@ -1,140 +1,56 @@ package grapiserver import ( - "os" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" ) // Option configures a gRPC and a gateway server. -type Option func(*Config) - -func createConfig(opts []Option) *Config { - c := createDefaultConfig() - for _, f := range opts { - f(c) - } - return c -} +type Option = newGrapiserver.Option // WithServers returns an Option that sets gRPC service server implementation(s). -func WithServers(svrs ...Server) Option { - return func(c *Config) { - c.Servers = append(c.Servers, svrs...) - } -} +var WithServers = newGrapiserver.WithServers // WithAddr returns an Option that sets an network address for a gRPC and a gateway server. -func WithAddr(network, addr string) Option { - return func(c *Config) { - WithGrpcAddr(network, addr)(c) - WithGatewayAddr(network, addr)(c) - } -} +var WithAddr = newGrapiserver.WithAddr // WithGrpcAddr returns an Option that sets an network address for a gRPC server. -func WithGrpcAddr(network, addr string) Option { - return func(c *Config) { - c.GrpcAddr = &Address{ - Network: network, - Addr: addr, - } - } -} +var WithGrpcAddr = newGrapiserver.WithGrpcAddr // WithGrpcInternalAddr returns an Option that sets an network address connected by a gateway server. -func WithGrpcInternalAddr(network, addr string) Option { - return func(c *Config) { - c.GrpcInternalAddr = &Address{ - Network: network, - Addr: addr, - } - } -} +var WithGrpcInternalAddr = newGrapiserver.WithGrpcInternalAddr // WithGatewayAddr returns an Option that sets an network address for a gateway server. -func WithGatewayAddr(network, addr string) Option { - return func(c *Config) { - c.GatewayAddr = &Address{ - Network: network, - Addr: addr, - } - } -} +var WithGatewayAddr = newGrapiserver.WithGatewayAddr // WithGrpcServerUnaryInterceptors returns an Option that sets unary interceptor(s) for a gRPC server. -func WithGrpcServerUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option { - return func(c *Config) { - c.GrpcServerUnaryInterceptors = append(c.GrpcServerUnaryInterceptors, interceptors...) - } -} +var WithGrpcServerUnaryInterceptors = newGrapiserver.WithGrpcServerUnaryInterceptors // WithGrpcServerStreamInterceptors returns an Option that sets stream interceptor(s) for a gRPC server. -func WithGrpcServerStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option { - return func(c *Config) { - c.GrpcServerStreamInterceptors = append(c.GrpcServerStreamInterceptors, interceptors...) - } -} +var WithGrpcServerStreamInterceptors = newGrapiserver.WithGrpcServerStreamInterceptors // WithGatewayServerUnaryInterceptors returns an Option that sets unary interceptor(s) for a gRPC client used by a gateway server. -func WithGatewayServerUnaryInterceptors(interceptors ...grpc.UnaryClientInterceptor) Option { - return func(c *Config) { - c.GatewayServerUnaryInterceptors = append(c.GatewayServerUnaryInterceptors, interceptors...) - } -} +var WithGatewayServerUnaryInterceptors = newGrapiserver.WithGatewayServerUnaryInterceptors // WithGatewayServerStreamInterceptors returns an Option that sets stream interceptor(s) for a gRPC client used by a gateway server. -func WithGatewayServerStreamInterceptors(interceptors ...grpc.StreamClientInterceptor) Option { - return func(c *Config) { - c.GatewayServerStreamInterceptors = append(c.GatewayServerStreamInterceptors, interceptors...) - } -} +var WithGatewayServerStreamInterceptors = newGrapiserver.WithGatewayServerStreamInterceptors // WithGrpcServerOptions returns an Option that sets grpc.ServerOption(s) to a gRPC server. -func WithGrpcServerOptions(opts ...grpc.ServerOption) Option { - return func(c *Config) { - c.GrpcServerOption = append(c.GrpcServerOption, opts...) - } -} +var WithGrpcServerOptions = newGrapiserver.WithGrpcServerOptions // WithGatewayDialOptions returns an Option that sets grpc.DialOption(s) to a gRPC clinet used by a gateway server. -func WithGatewayDialOptions(opts ...grpc.DialOption) Option { - return func(c *Config) { - c.GatewayDialOption = append(c.GatewayDialOption, opts...) - } -} +var WithGatewayDialOptions = newGrapiserver.WithGatewayDialOptions // WithGatewayMuxOptions returns an Option that sets runtime.ServeMuxOption(s) to a gateway server. -func WithGatewayMuxOptions(opts ...runtime.ServeMuxOption) Option { - return func(c *Config) { - c.GatewayMuxOptions = append(c.GatewayMuxOptions, opts...) - } -} +var WithGatewayMuxOptions = newGrapiserver.WithGatewayMuxOptions // WithGatewayServerMiddlewares returns an Option that sets middleware(s) for http.Server to a gateway server. -func WithGatewayServerMiddlewares(middlewares ...HTTPServerMiddleware) Option { - return func(c *Config) { - c.GatewayServerMiddlewares = append(c.GatewayServerMiddlewares, middlewares...) - } -} +var WithGatewayServerMiddlewares = newGrapiserver.WithGatewayServerMiddlewares // WithGatewayServerConfig returns an Option that specifies http.Server configuration to a gateway server. -func WithGatewayServerConfig(cfg *HTTPServerConfig) Option { - return func(c *Config) { - c.GatewayServerConfig = cfg - } -} +var WithGatewayServerConfig = newGrapiserver.WithGatewayServerConfig // WithPassedHeader returns an Option that sets configurations about passed headers for a gateway server. -func WithPassedHeader(decider PassedHeaderDeciderFunc) Option { - return WithGatewayServerMiddlewares(createPassingHeaderMiddleware(decider)) -} +var WithPassedHeader = newGrapiserver.WithPassedHeader // WithDefaultLogger returns an Option that sets default grpclogger.LoggerV2 object. -func WithDefaultLogger() Option { - return func(c *Config) { - grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stdout, os.Stderr, os.Stderr)) - } -} +var WithDefaultLogger = newGrapiserver.WithDefaultLogger diff --git a/pkg/grapiserver/passing_header_middleware.go b/pkg/grapiserver/passing_header_middleware.go index bb41c7bc..c46bbbb7 100644 --- a/pkg/grapiserver/passing_header_middleware.go +++ b/pkg/grapiserver/passing_header_middleware.go @@ -1,36 +1,8 @@ package grapiserver import ( - "net/http" - "sync" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" ) // PassedHeaderDeciderFunc returns true if given header should be passed to gRPC server metadata. -type PassedHeaderDeciderFunc func(string) bool - -func createPassingHeaderMiddleware(decide PassedHeaderDeciderFunc) HTTPServerMiddleware { - return func(next http.Handler) http.Handler { - cache := new(sync.Map) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - newHeader := make(http.Header, 2*len(r.Header)) - - for k := range r.Header { - v := r.Header.Get(k) - if newKey, ok := cache.Load(k); ok { - newHeader.Set(newKey.(string), v) - } else if decide(k) { - newKey := runtime.MetadataHeaderPrefix + k - cache.Store(k, newKey) - newHeader.Set(newKey, v) - } - newHeader.Set(k, v) - } - - r.Header = newHeader - - next.ServeHTTP(w, r) - }) - } -} +type PassedHeaderDeciderFunc = newGrapiserver.PassedHeaderDeciderFunc diff --git a/pkg/grapiserver/passing_header_middleware_test.go b/pkg/grapiserver/passing_header_middleware_test.go deleted file mode 100644 index 94afcda5..00000000 --- a/pkg/grapiserver/passing_header_middleware_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package grapiserver - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/google/go-cmp/cmp" -) - -func Test_passingHeaderMiddleware(t *testing.T) { - type Case struct { - test string - decider PassedHeaderDeciderFunc - in http.Header - out http.Header - } - - cases := []Case{ - { - test: "passing 1 header", - decider: func(k string) bool { return strings.HasPrefix(k, "X-Debug-") }, - in: http.Header{ - "X-Debug-User-Id": []string{"100"}, - "X-User-Id": []string{"100"}, - }, - out: http.Header{ - "X-Debug-User-Id": []string{"100"}, - "Grpc-Metadata-X-Debug-User-Id": []string{"100"}, - "X-User-Id": []string{"100"}, - }, - }, - } - - getDefaultHeader := func() http.Header { - return http.Header{ - "Accept-Encoding": []string{"gzip"}, - "User-Agent": []string{"Go-http-client/1.1"}, - } - } - - for _, c := range cases { - t.Run(c.test, func(t *testing.T) { - var wantHeader, gotHeader http.Header - wantHeader = getDefaultHeader() - for k, v := range c.out { - wantHeader.Set(k, v[0]) - } - - wrap := createPassingHeaderMiddleware(c.decider) - s := httptest.NewServer(wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotHeader = r.Header - w.WriteHeader(200) - }))) - defer s.Close() - - req, _ := http.NewRequest("GET", s.URL, nil) - req.Header = c.in - - (&http.Client{}).Do(req) - if diff := cmp.Diff(gotHeader, wantHeader); diff != "" { - t.Errorf("Received header differs: (-got +want)\n%s", diff) - } - - (&http.Client{}).Do(req) - if diff := cmp.Diff(gotHeader, wantHeader); diff != "" { - t.Errorf("Received header differs: (-got +want)\n%s", diff) - } - }) - } -} diff --git a/pkg/grapiserver/server.go b/pkg/grapiserver/server.go index f0198f13..66d52f4b 100644 --- a/pkg/grapiserver/server.go +++ b/pkg/grapiserver/server.go @@ -1,14 +1,8 @@ package grapiserver import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" + newGrapiserver "github.com/x-izumin/grapi/pkg/grapiserver" ) // Server is an interface for representing gRPC server implementations. -type Server interface { - RegisterWithServer(*grpc.Server) - RegisterWithHandler(context.Context, *runtime.ServeMux, *grpc.ClientConn) error -} +type Server = newGrapiserver.Server diff --git a/pkg/grapiserver/testing/api/library.pb.go b/pkg/grapiserver/testing/api/library.pb.go deleted file mode 100644 index 9fba39e7..00000000 --- a/pkg/grapiserver/testing/api/library.pb.go +++ /dev/null @@ -1,393 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: library.proto - -/* -Package api_pb is a generated protocol buffer package. - -It is generated from these files: - library.proto - -It has these top-level messages: - Book - ListBooksRequest - ListBooksResponse - GetBookRequest - CreateBookRequest - UpdateBookRequest - DeleteBookRequest -*/ -package api_pb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "google.golang.org/genproto/googleapis/api/annotations" -import google_protobuf1 "github.com/golang/protobuf/ptypes/empty" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Book struct { - BookId string `protobuf:"bytes,1,opt,name=book_id,json=bookId" json:"book_id,omitempty"` -} - -func (m *Book) Reset() { *m = Book{} } -func (m *Book) String() string { return proto.CompactTextString(m) } -func (*Book) ProtoMessage() {} -func (*Book) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *Book) GetBookId() string { - if m != nil { - return m.BookId - } - return "" -} - -type ListBooksRequest struct { -} - -func (m *ListBooksRequest) Reset() { *m = ListBooksRequest{} } -func (m *ListBooksRequest) String() string { return proto.CompactTextString(m) } -func (*ListBooksRequest) ProtoMessage() {} -func (*ListBooksRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -type ListBooksResponse struct { - Books []*Book `protobuf:"bytes,1,rep,name=books" json:"books,omitempty"` -} - -func (m *ListBooksResponse) Reset() { *m = ListBooksResponse{} } -func (m *ListBooksResponse) String() string { return proto.CompactTextString(m) } -func (*ListBooksResponse) ProtoMessage() {} -func (*ListBooksResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *ListBooksResponse) GetBooks() []*Book { - if m != nil { - return m.Books - } - return nil -} - -type GetBookRequest struct { - BookId string `protobuf:"bytes,1,opt,name=book_id,json=bookId" json:"book_id,omitempty"` -} - -func (m *GetBookRequest) Reset() { *m = GetBookRequest{} } -func (m *GetBookRequest) String() string { return proto.CompactTextString(m) } -func (*GetBookRequest) ProtoMessage() {} -func (*GetBookRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *GetBookRequest) GetBookId() string { - if m != nil { - return m.BookId - } - return "" -} - -type CreateBookRequest struct { - Book *Book `protobuf:"bytes,1,opt,name=book" json:"book,omitempty"` -} - -func (m *CreateBookRequest) Reset() { *m = CreateBookRequest{} } -func (m *CreateBookRequest) String() string { return proto.CompactTextString(m) } -func (*CreateBookRequest) ProtoMessage() {} -func (*CreateBookRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *CreateBookRequest) GetBook() *Book { - if m != nil { - return m.Book - } - return nil -} - -type UpdateBookRequest struct { - Book *Book `protobuf:"bytes,1,opt,name=book" json:"book,omitempty"` -} - -func (m *UpdateBookRequest) Reset() { *m = UpdateBookRequest{} } -func (m *UpdateBookRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateBookRequest) ProtoMessage() {} -func (*UpdateBookRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -func (m *UpdateBookRequest) GetBook() *Book { - if m != nil { - return m.Book - } - return nil -} - -type DeleteBookRequest struct { - BookId string `protobuf:"bytes,1,opt,name=book_id,json=bookId" json:"book_id,omitempty"` -} - -func (m *DeleteBookRequest) Reset() { *m = DeleteBookRequest{} } -func (m *DeleteBookRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteBookRequest) ProtoMessage() {} -func (*DeleteBookRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *DeleteBookRequest) GetBookId() string { - if m != nil { - return m.BookId - } - return "" -} - -func init() { - proto.RegisterType((*Book)(nil), "com.github.izumin5210.grapi.testing.api.Book") - proto.RegisterType((*ListBooksRequest)(nil), "com.github.izumin5210.grapi.testing.api.ListBooksRequest") - proto.RegisterType((*ListBooksResponse)(nil), "com.github.izumin5210.grapi.testing.api.ListBooksResponse") - proto.RegisterType((*GetBookRequest)(nil), "com.github.izumin5210.grapi.testing.api.GetBookRequest") - proto.RegisterType((*CreateBookRequest)(nil), "com.github.izumin5210.grapi.testing.api.CreateBookRequest") - proto.RegisterType((*UpdateBookRequest)(nil), "com.github.izumin5210.grapi.testing.api.UpdateBookRequest") - proto.RegisterType((*DeleteBookRequest)(nil), "com.github.izumin5210.grapi.testing.api.DeleteBookRequest") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for LibraryService service - -type LibraryServiceClient interface { - ListBooks(ctx context.Context, in *ListBooksRequest, opts ...grpc.CallOption) (*ListBooksResponse, error) - GetBook(ctx context.Context, in *GetBookRequest, opts ...grpc.CallOption) (*Book, error) - CreateBook(ctx context.Context, in *CreateBookRequest, opts ...grpc.CallOption) (*Book, error) - UpdateBook(ctx context.Context, in *UpdateBookRequest, opts ...grpc.CallOption) (*Book, error) - DeleteBook(ctx context.Context, in *DeleteBookRequest, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) -} - -type libraryServiceClient struct { - cc *grpc.ClientConn -} - -func NewLibraryServiceClient(cc *grpc.ClientConn) LibraryServiceClient { - return &libraryServiceClient{cc} -} - -func (c *libraryServiceClient) ListBooks(ctx context.Context, in *ListBooksRequest, opts ...grpc.CallOption) (*ListBooksResponse, error) { - out := new(ListBooksResponse) - err := grpc.Invoke(ctx, "/com.github.izumin5210.grapi.testing.api.LibraryService/ListBooks", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *libraryServiceClient) GetBook(ctx context.Context, in *GetBookRequest, opts ...grpc.CallOption) (*Book, error) { - out := new(Book) - err := grpc.Invoke(ctx, "/com.github.izumin5210.grapi.testing.api.LibraryService/GetBook", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *libraryServiceClient) CreateBook(ctx context.Context, in *CreateBookRequest, opts ...grpc.CallOption) (*Book, error) { - out := new(Book) - err := grpc.Invoke(ctx, "/com.github.izumin5210.grapi.testing.api.LibraryService/CreateBook", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *libraryServiceClient) UpdateBook(ctx context.Context, in *UpdateBookRequest, opts ...grpc.CallOption) (*Book, error) { - out := new(Book) - err := grpc.Invoke(ctx, "/com.github.izumin5210.grapi.testing.api.LibraryService/UpdateBook", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *libraryServiceClient) DeleteBook(ctx context.Context, in *DeleteBookRequest, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) { - out := new(google_protobuf1.Empty) - err := grpc.Invoke(ctx, "/com.github.izumin5210.grapi.testing.api.LibraryService/DeleteBook", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for LibraryService service - -type LibraryServiceServer interface { - ListBooks(context.Context, *ListBooksRequest) (*ListBooksResponse, error) - GetBook(context.Context, *GetBookRequest) (*Book, error) - CreateBook(context.Context, *CreateBookRequest) (*Book, error) - UpdateBook(context.Context, *UpdateBookRequest) (*Book, error) - DeleteBook(context.Context, *DeleteBookRequest) (*google_protobuf1.Empty, error) -} - -func RegisterLibraryServiceServer(s *grpc.Server, srv LibraryServiceServer) { - s.RegisterService(&_LibraryService_serviceDesc, srv) -} - -func _LibraryService_ListBooks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListBooksRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LibraryServiceServer).ListBooks(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/com.github.izumin5210.grapi.testing.api.LibraryService/ListBooks", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LibraryServiceServer).ListBooks(ctx, req.(*ListBooksRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _LibraryService_GetBook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetBookRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LibraryServiceServer).GetBook(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/com.github.izumin5210.grapi.testing.api.LibraryService/GetBook", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LibraryServiceServer).GetBook(ctx, req.(*GetBookRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _LibraryService_CreateBook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateBookRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LibraryServiceServer).CreateBook(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/com.github.izumin5210.grapi.testing.api.LibraryService/CreateBook", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LibraryServiceServer).CreateBook(ctx, req.(*CreateBookRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _LibraryService_UpdateBook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateBookRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LibraryServiceServer).UpdateBook(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/com.github.izumin5210.grapi.testing.api.LibraryService/UpdateBook", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LibraryServiceServer).UpdateBook(ctx, req.(*UpdateBookRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _LibraryService_DeleteBook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteBookRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LibraryServiceServer).DeleteBook(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/com.github.izumin5210.grapi.testing.api.LibraryService/DeleteBook", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LibraryServiceServer).DeleteBook(ctx, req.(*DeleteBookRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _LibraryService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "com.github.izumin5210.grapi.testing.api.LibraryService", - HandlerType: (*LibraryServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ListBooks", - Handler: _LibraryService_ListBooks_Handler, - }, - { - MethodName: "GetBook", - Handler: _LibraryService_GetBook_Handler, - }, - { - MethodName: "CreateBook", - Handler: _LibraryService_CreateBook_Handler, - }, - { - MethodName: "UpdateBook", - Handler: _LibraryService_UpdateBook_Handler, - }, - { - MethodName: "DeleteBook", - Handler: _LibraryService_DeleteBook_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "library.proto", -} - -func init() { proto.RegisterFile("library.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 442 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x94, 0xcf, 0x8b, 0xd3, 0x40, - 0x1c, 0xc5, 0x89, 0xb6, 0x69, 0xfb, 0x15, 0x43, 0x3b, 0xf8, 0xa3, 0x44, 0xc5, 0x12, 0x0f, 0x56, - 0xd0, 0x89, 0x46, 0x44, 0xec, 0xcd, 0x56, 0x11, 0xa1, 0xa7, 0x8a, 0x22, 0x5e, 0xca, 0xa4, 0x1d, - 0xe3, 0xd0, 0x36, 0x33, 0x66, 0x26, 0x82, 0x15, 0x2f, 0x7b, 0x5d, 0xf6, 0xb2, 0x7b, 0xdd, 0xff, - 0x6a, 0xef, 0x7b, 0xda, 0x3f, 0x64, 0xc9, 0x24, 0xdd, 0xb6, 0x1b, 0x0a, 0xc9, 0xb2, 0xc7, 0x64, - 0xe6, 0xfb, 0xe6, 0x33, 0xef, 0x3d, 0x06, 0x6e, 0xcf, 0x99, 0x1f, 0x91, 0xe8, 0x2f, 0x16, 0x11, - 0x57, 0x1c, 0x3d, 0x9d, 0xf0, 0x05, 0x0e, 0x98, 0xfa, 0x15, 0xfb, 0x98, 0x2d, 0xe3, 0x05, 0x0b, - 0xdf, 0x78, 0xaf, 0x5e, 0xe2, 0x20, 0x22, 0x82, 0x61, 0x45, 0xa5, 0x62, 0x61, 0x80, 0x89, 0x60, - 0xf6, 0xc3, 0x80, 0xf3, 0x60, 0x4e, 0x5d, 0x22, 0x98, 0x4b, 0xc2, 0x90, 0x2b, 0xa2, 0x18, 0x0f, - 0x65, 0x2a, 0x63, 0x3f, 0xc8, 0x56, 0xf5, 0x97, 0x1f, 0xff, 0x74, 0xe9, 0x42, 0xa8, 0xec, 0x0c, - 0xe7, 0x31, 0x54, 0xfa, 0x9c, 0xcf, 0xd0, 0x7d, 0xa8, 0xf9, 0x9c, 0xcf, 0xc6, 0x6c, 0xda, 0x36, - 0x3a, 0x46, 0xb7, 0x31, 0x32, 0x93, 0xcf, 0xcf, 0x53, 0x07, 0x41, 0x73, 0xc8, 0xa4, 0x4a, 0x36, - 0xc9, 0x11, 0xfd, 0x1d, 0x53, 0xa9, 0x9c, 0xef, 0xd0, 0xda, 0xf8, 0x27, 0x05, 0x0f, 0x25, 0x45, - 0x03, 0xa8, 0x26, 0x23, 0xb2, 0x6d, 0x74, 0x6e, 0x76, 0x6f, 0x79, 0x2f, 0x70, 0x41, 0x7a, 0x9c, - 0xc8, 0x8c, 0xd2, 0x59, 0xe7, 0x19, 0x58, 0x9f, 0xa8, 0x16, 0xce, 0xce, 0xda, 0x0d, 0xf6, 0x0d, - 0x5a, 0x83, 0x88, 0x12, 0x45, 0x37, 0x77, 0xbf, 0x87, 0x4a, 0xb2, 0xac, 0xb7, 0x96, 0x66, 0xd0, - 0xa3, 0x89, 0xee, 0x57, 0x31, 0xbd, 0x7e, 0xdd, 0xe7, 0xd0, 0xfa, 0x40, 0xe7, 0x74, 0x5b, 0x77, - 0xd7, 0xed, 0xbc, 0xd3, 0x2a, 0x58, 0xc3, 0xb4, 0x0d, 0x5f, 0x68, 0xf4, 0x87, 0x4d, 0x28, 0x3a, - 0x34, 0xa0, 0x71, 0x61, 0x3b, 0x7a, 0x57, 0x98, 0xe1, 0x72, 0x7c, 0x76, 0xef, 0x2a, 0xa3, 0x69, - 0xca, 0x8e, 0xb5, 0x77, 0x72, 0x76, 0x74, 0xa3, 0x8e, 0x4c, 0x57, 0x07, 0x86, 0xf6, 0x0d, 0xa8, - 0x65, 0x89, 0xa1, 0xb7, 0x85, 0x75, 0xb7, 0x33, 0xb6, 0xcb, 0xf9, 0xe9, 0xb4, 0x35, 0x03, 0x42, - 0xcd, 0x94, 0xc1, 0xfd, 0x97, 0x59, 0xf8, 0x1f, 0x1d, 0x18, 0x00, 0xeb, 0x52, 0xa0, 0xe2, 0x17, - 0xcd, 0x35, 0xa9, 0x2c, 0xd3, 0x1d, 0xcd, 0x64, 0x39, 0x99, 0x2f, 0x3d, 0x9d, 0x39, 0x3a, 0x36, - 0x00, 0xd6, 0x65, 0x2a, 0xc1, 0x93, 0x6b, 0x60, 0x59, 0x9e, 0x27, 0x9a, 0xe7, 0x91, 0x77, 0x77, - 0xd3, 0x23, 0xbc, 0x32, 0x2a, 0xc3, 0x5b, 0x02, 0xac, 0x2b, 0x59, 0x82, 0x2e, 0xd7, 0x63, 0xfb, - 0x1e, 0x4e, 0x1f, 0x19, 0xbc, 0x7a, 0x64, 0xf0, 0xc7, 0xe4, 0x91, 0x59, 0x45, 0xe5, 0xe5, 0xa2, - 0xea, 0xd7, 0x7f, 0x98, 0x44, 0xb0, 0xb1, 0xf0, 0x7d, 0x53, 0xcf, 0xbc, 0x3e, 0x0f, 0x00, 0x00, - 0xff, 0xff, 0x5e, 0xe2, 0x36, 0x91, 0xfe, 0x04, 0x00, 0x00, -} diff --git a/pkg/grapiserver/testing/api/library.pb.gw.go b/pkg/grapiserver/testing/api/library.pb.gw.go deleted file mode 100644 index 7cd26254..00000000 --- a/pkg/grapiserver/testing/api/library.pb.gw.go +++ /dev/null @@ -1,346 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: library.proto - -/* -Package api_pb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package api_pb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -func request_LibraryService_ListBooks_0(ctx context.Context, marshaler runtime.Marshaler, client LibraryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ListBooksRequest - var metadata runtime.ServerMetadata - - msg, err := client.ListBooks(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_LibraryService_GetBook_0(ctx context.Context, marshaler runtime.Marshaler, client LibraryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq GetBookRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["book_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "book_id") - } - - protoReq.BookId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "book_id", err) - } - - msg, err := client.GetBook(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_LibraryService_CreateBook_0(ctx context.Context, marshaler runtime.Marshaler, client LibraryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq CreateBookRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.Book); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.CreateBook(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_LibraryService_UpdateBook_0(ctx context.Context, marshaler runtime.Marshaler, client LibraryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq UpdateBookRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.Book); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["book.book_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "book.book_id") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "book.book_id", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "book.book_id", err) - } - - msg, err := client.UpdateBook(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_LibraryService_DeleteBook_0(ctx context.Context, marshaler runtime.Marshaler, client LibraryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeleteBookRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["book_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "book_id") - } - - protoReq.BookId, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "book_id", err) - } - - msg, err := client.DeleteBook(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterLibraryServiceHandlerFromEndpoint is same as RegisterLibraryServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterLibraryServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterLibraryServiceHandler(ctx, mux, conn) -} - -// RegisterLibraryServiceHandler registers the http handlers for service LibraryService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterLibraryServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterLibraryServiceHandlerClient(ctx, mux, NewLibraryServiceClient(conn)) -} - -// RegisterLibraryServiceHandler registers the http handlers for service LibraryService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "LibraryServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "LibraryServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "LibraryServiceClient" to call the correct interceptors. -func RegisterLibraryServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client LibraryServiceClient) error { - - mux.Handle("GET", pattern_LibraryService_ListBooks_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_LibraryService_ListBooks_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_LibraryService_ListBooks_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_LibraryService_GetBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_LibraryService_GetBook_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_LibraryService_GetBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_LibraryService_CreateBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_LibraryService_CreateBook_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_LibraryService_CreateBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("PATCH", pattern_LibraryService_UpdateBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_LibraryService_UpdateBook_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_LibraryService_UpdateBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("PATCH", pattern_LibraryService_DeleteBook_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_LibraryService_DeleteBook_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_LibraryService_DeleteBook_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_LibraryService_ListBooks_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"books"}, "")) - - pattern_LibraryService_GetBook_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"books", "book_id"}, "")) - - pattern_LibraryService_CreateBook_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"books"}, "")) - - pattern_LibraryService_UpdateBook_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"books", "book.book_id"}, "")) - - pattern_LibraryService_DeleteBook_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"books", "book_id"}, "")) -) - -var ( - forward_LibraryService_ListBooks_0 = runtime.ForwardResponseMessage - - forward_LibraryService_GetBook_0 = runtime.ForwardResponseMessage - - forward_LibraryService_CreateBook_0 = runtime.ForwardResponseMessage - - forward_LibraryService_UpdateBook_0 = runtime.ForwardResponseMessage - - forward_LibraryService_DeleteBook_0 = runtime.ForwardResponseMessage -) diff --git a/pkg/grapiserver/testing/api/library.swagger.json b/pkg/grapiserver/testing/api/library.swagger.json deleted file mode 100644 index c32d39f0..00000000 --- a/pkg/grapiserver/testing/api/library.swagger.json +++ /dev/null @@ -1,163 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "library.proto", - "version": "version not set" - }, - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/books": { - "get": { - "operationId": "ListBooks", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/apiListBooksResponse" - } - } - }, - "tags": [ - "LibraryService" - ] - }, - "post": { - "operationId": "CreateBook", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/apiBook" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/apiBook" - } - } - ], - "tags": [ - "LibraryService" - ] - } - }, - "/books/{book.book_id}": { - "patch": { - "operationId": "UpdateBook", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/apiBook" - } - } - }, - "parameters": [ - { - "name": "book.book_id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/apiBook" - } - } - ], - "tags": [ - "LibraryService" - ] - } - }, - "/books/{book_id}": { - "get": { - "operationId": "GetBook", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/apiBook" - } - } - }, - "parameters": [ - { - "name": "book_id", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "LibraryService" - ] - }, - "patch": { - "operationId": "DeleteBook", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "book_id", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "LibraryService" - ] - } - } - }, - "definitions": { - "apiBook": { - "type": "object", - "properties": { - "book_id": { - "type": "string" - } - } - }, - "apiListBooksResponse": { - "type": "object", - "properties": { - "books": { - "type": "array", - "items": { - "$ref": "#/definitions/apiBook" - } - } - } - }, - "protobufEmpty": { - "type": "object", - "description": "service Foo {\n rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);\n }\n\nThe JSON representation for `Empty` is empty JSON object `{}`.", - "title": "A generic empty message that you can re-use to avoid defining duplicated\nempty messages in your APIs. A typical example is to use it as the request\nor the response type of an API method. For instance:" - } - } -} diff --git a/pkg/grapiserver/testing/api/protos/.keep b/pkg/grapiserver/testing/api/protos/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/grapiserver/testing/api/protos/library.proto b/pkg/grapiserver/testing/api/protos/library.proto deleted file mode 100644 index 8bfa5578..00000000 --- a/pkg/grapiserver/testing/api/protos/library.proto +++ /dev/null @@ -1,63 +0,0 @@ -syntax = "proto3"; -option go_package = "api_pb"; -package com.github.izumin5210.grapi.testing.api; - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; - -service LibraryService { - rpc ListBooks (ListBooksRequest) returns (ListBooksResponse) { - option (google.api.http) = { - get: "/books" - }; - } - rpc GetBook (GetBookRequest) returns (Book) { - option (google.api.http) = { - get: "/books/{book_id}" - }; - } - rpc CreateBook (CreateBookRequest) returns (Book) { - option (google.api.http) = { - post: "/books" - body: "book" - }; - } - rpc UpdateBook (UpdateBookRequest) returns (Book) { - option (google.api.http) = { - patch: "/books/{book.book_id}" - body: "book" - }; - } - rpc DeleteBook (DeleteBookRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - patch: "/books/{book_id}" - }; - } -} - -message Book { - string book_id = 1; -} - -message ListBooksRequest { -} - -message ListBooksResponse { - repeated Book books = 1; -} - -message GetBookRequest { - string book_id = 1; -} - -message CreateBookRequest { - Book book = 1; -} - -message UpdateBookRequest { - Book book = 1; -} - -message DeleteBookRequest { - string book_id = 1; -} diff --git a/pkg/grapiserver/testing/app/server/.keep b/pkg/grapiserver/testing/app/server/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/grapiserver/testing/app/server/library_server.go b/pkg/grapiserver/testing/app/server/library_server.go deleted file mode 100644 index e732f5ee..00000000 --- a/pkg/grapiserver/testing/app/server/library_server.go +++ /dev/null @@ -1,52 +0,0 @@ -package server - -import ( - "context" - - "github.com/golang/protobuf/ptypes/empty" - "github.com/izumin5210/grapi/pkg/grapiserver" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - api_pb "github.com/izumin5210/grapi/pkg/grapiserver/testing/api" -) - -// NewLibraryServiceServer creates a new LibraryServiceServer instance. -func NewLibraryServiceServer() interface { - api_pb.LibraryServiceServer - grapiserver.Server -} { - return &libraryServiceServerImpl{} -} - -type libraryServiceServerImpl struct { -} - -func (s *libraryServiceServerImpl) ListBooks(ctx context.Context, req *api_pb.ListBooksRequest) (*api_pb.ListBooksResponse, error) { - return &api_pb.ListBooksResponse{ - Books: []*api_pb.Book{ - {BookId: "The Go Programming Language"}, - {BookId: "Programming Ruby"}, - }, - }, nil -} - -func (s *libraryServiceServerImpl) GetBook(ctx context.Context, req *api_pb.GetBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) CreateBook(ctx context.Context, req *api_pb.CreateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) UpdateBook(ctx context.Context, req *api_pb.UpdateBookRequest) (*api_pb.Book, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} - -func (s *libraryServiceServerImpl) DeleteBook(ctx context.Context, req *api_pb.DeleteBookRequest) (*empty.Empty, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} diff --git a/pkg/grapiserver/testing/app/server/library_server_register_funcs.go b/pkg/grapiserver/testing/app/server/library_server_register_funcs.go deleted file mode 100644 index 637016fc..00000000 --- a/pkg/grapiserver/testing/app/server/library_server_register_funcs.go +++ /dev/null @@ -1,20 +0,0 @@ -package server - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - api_pb "github.com/izumin5210/grapi/pkg/grapiserver/testing/api" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *libraryServiceServerImpl) RegisterWithServer(grpcSvr *grpc.Server) { - api_pb.RegisterLibraryServiceServer(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *libraryServiceServerImpl) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return api_pb.RegisterLibraryServiceHandler(ctx, mux, conn) -} diff --git a/pkg/protoc/.snapshots/TestWrapper_Exec b/pkg/protoc/.snapshots/TestWrapper_Exec deleted file mode 100644 index 6b89d87a..00000000 --- a/pkg/protoc/.snapshots/TestWrapper_Exec +++ /dev/null @@ -1,80 +0,0 @@ -([][]string) (len=6) { - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=10) "api/protos", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=25) "--go_out=plugins=grpc:api", - (string) (len=21) "api/protos/book.proto" - }, - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=10) "api/protos", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=39) "--grpc-gateway_out=logtostderr=true:api", - (string) (len=21) "api/protos/book.proto" - }, - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=10) "api/protos", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=34) "--swagger_out=logtostderr=true:api", - (string) (len=21) "api/protos/book.proto" - }, - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=16) "api/protos/types", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=31) "--go_out=plugins=grpc:api/types", - (string) (len=28) "api/protos/types/users.proto" - }, - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=16) "api/protos/types", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=45) "--grpc-gateway_out=logtostderr=true:api/types", - (string) (len=28) "api/protos/types/users.proto" - }, - ([]string) (len=11) { - (string) (len=6) "protoc", - (string) (len=2) "-I", - (string) (len=16) "api/protos/types", - (string) (len=2) "-I", - (string) (len=57) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5", - (string) (len=2) "-I", - (string) (len=80) "/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5/third_party/googleapis", - (string) (len=2) "-I", - (string) (len=29) "/go/src/awesomeapp/api/protos", - (string) (len=40) "--swagger_out=logtostderr=true:api/types", - (string) (len=28) "api/protos/types/users.proto" - } -} diff --git a/pkg/protoc/config.go b/pkg/protoc/config.go index 3b18fc5b..d8627457 100644 --- a/pkg/protoc/config.go +++ b/pkg/protoc/config.go @@ -1,48 +1,8 @@ package protoc import ( - "os" - "path/filepath" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/afero" + newProtoc "github.com/x-izumin/grapi/pkg/protoc" ) // Config stores setting params related protoc. -type Config struct { - ImportDirs []string `mapstructure:"import_dirs"` - ProtosDir string `mapstructure:"protos_dir"` - OutDir string `mapstructure:"out_dir"` - Plugins []*Plugin -} - -// ProtoFiles returns .proto file paths. -func (c *Config) ProtoFiles(fs afero.Fs, rootDir string) ([]string, error) { - paths := []string{} - protosDir := filepath.Join(rootDir, c.ProtosDir) - err := afero.Walk(fs, protosDir, func(path string, info os.FileInfo, err error) error { - if err != nil { - return errors.WithStack(err) - } - if !info.IsDir() && filepath.Ext(path) == ".proto" { - paths = append(paths, path) - } - return nil - }) - return paths, errors.WithStack(err) -} - -// OutDirOf returns a directory path of protoc result output path for given proto file. -func (c *Config) OutDirOf(rootDir string, protoPath string) (string, error) { - protosDir := filepath.Join(rootDir, c.ProtosDir) - relProtoDir, err := filepath.Rel(protosDir, filepath.Dir(protoPath)) - if strings.Contains(relProtoDir, "..") { - return "", errors.Errorf(".proto files should be included in %s", c.ProtosDir) - } - if err != nil { - return "", errors.Wrapf(err, ".proto files should be included in %s", c.ProtosDir) - } - - return filepath.Join(c.OutDir, relProtoDir), nil -} +type Config = newProtoc.Config diff --git a/pkg/protoc/config_test.go b/pkg/protoc/config_test.go deleted file mode 100644 index c10159ba..00000000 --- a/pkg/protoc/config_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package protoc - -import ( - "path/filepath" - "testing" -) - -func createDefaultConfig() *Config { - return &Config{ - ImportDirs: []string{ - "./vendor/github.com/grpc-ecosystem/grpc-gateway", - "./vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis", - }, - ProtosDir: "./api/protos", - OutDir: "./api", - Plugins: []*Plugin{ - { - Name: "go", - Args: map[string]interface{}{"plugins": "grpc"}, - }, - { - Name: "grpc-gateway", - Args: map[string]interface{}{"logtostderr": true}, - }, - { - Name: "swagger", - Args: map[string]interface{}{"logtostderr": true}, - }, - }, - } -} - -func Test_Config_OutDirOf(t *testing.T) { - cfg := createDefaultConfig() - rootDir := "/home/example/app" - - t.Run("with no errors", func(t *testing.T) { - outDir, err := cfg.OutDirOf(rootDir, filepath.Join(rootDir, "api/protos/foo/bar.proto")) - - if err != nil { - t.Errorf("OutDirOf returns an error %v", err) - } - - if got, want := outDir, "api/foo"; got != want { - t.Errorf("OutDirOf returned %q, want %q", got, want) - } - }) - - t.Run("with an error", func(t *testing.T) { - outDir, err := cfg.OutDirOf(rootDir, filepath.Join(rootDir, "api/foo/bar.proto")) - - if err == nil { - t.Errorf("OutDirOf should return an error") - } - - if got, want := outDir, ""; got != want { - t.Errorf("OutDirOf returned %q, want %q", got, want) - } - }) -} diff --git a/pkg/protoc/plugin.go b/pkg/protoc/plugin.go index 753c3e63..fa2323b4 100644 --- a/pkg/protoc/plugin.go +++ b/pkg/protoc/plugin.go @@ -1,32 +1,8 @@ package protoc import ( - "bytes" - "fmt" - "strings" + newProtoc "github.com/x-izumin/grapi/pkg/protoc" ) // Plugin contains args and plugin name for using in protoc command. -type Plugin struct { - Name string - Args map[string]interface{} -} - -// BinName returns a executable binary name. -func (p *Plugin) BinName() string { - return "protoc-gen-" + p.Name -} - -func (p *Plugin) toProtocArg(outputPath string) string { - buf := new(bytes.Buffer) - buf.WriteString("--" + p.Name + "_out") - args := make([]string, 0, len(p.Args)) - for k, v := range p.Args { - args = append(args, k+"="+fmt.Sprint(v)) - } - if len(args) > 0 { - buf.WriteString("=" + strings.Join(args, ",")) - } - buf.WriteString(":" + outputPath) - return buf.String() -} +type Plugin = newProtoc.Plugin diff --git a/pkg/protoc/providers.go b/pkg/protoc/providers.go index 42442349..10bc8cd3 100644 --- a/pkg/protoc/providers.go +++ b/pkg/protoc/providers.go @@ -1,67 +1,13 @@ package protoc import ( - "sync" - "github.com/google/wire" - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/gex" - "github.com/izumin5210/gex/pkg/tool" - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" - - "github.com/izumin5210/grapi/pkg/cli" -) - -var ( - gexCfg *gex.Config - gexCfgMu sync.Mutex - - toolRepo tool.Repository - toolRepoMu sync.Mutex + newProtoc "github.com/x-izumin/grapi/pkg/protoc" ) -func ProvideGexConfig( - fs afero.Fs, - exec *execx.Executor, - io *clib.IO, - rootDir cli.RootDir, -) *gex.Config { - gexCfgMu.Lock() - defer gexCfgMu.Unlock() - if gexCfg == nil { - gexCfg = &gex.Config{ - OutWriter: io.Out, - ErrWriter: io.Err, - InReader: io.In, - FS: fs, - Exec: exec, - WorkingDir: rootDir.String(), - Verbose: clib.IsVerbose() || clib.IsDebug(), - Logger: zap.NewStdLog(zap.L()), - } - } - return gexCfg -} +var ProvideGexConfig = newProtoc.ProvideGexConfig -func ProvideToolRepository(gexCfg *gex.Config) (tool.Repository, error) { - toolRepoMu.Lock() - defer toolRepoMu.Unlock() - if toolRepo == nil { - var err error - toolRepo, err = gexCfg.Create() - if err != nil { - return nil, errors.WithStack(err) - } - } - return toolRepo, nil -} +var ProvideToolRepository = newProtoc.ProvideToolRepository // WrapperSet is a provider set that includes gex things and Wrapper instance. -var WrapperSet = wire.NewSet( - ProvideGexConfig, - ProvideToolRepository, - NewWrapper, -) +var WrapperSet = wire.NewSet(newProtoc.WrapperSet) diff --git a/pkg/protoc/wrapper.go b/pkg/protoc/wrapper.go index f0faf2cf..021e9ce6 100644 --- a/pkg/protoc/wrapper.go +++ b/pkg/protoc/wrapper.go @@ -1,195 +1,11 @@ package protoc import ( - "bytes" - "context" - "os" - "path/filepath" - "strings" - "sync" - "text/template" - - "github.com/izumin5210/execx" - "github.com/izumin5210/gex/pkg/tool" - "github.com/pkg/errors" - "github.com/spf13/afero" - "go.uber.org/zap" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" + newProtoc "github.com/x-izumin/grapi/pkg/protoc" ) // Wrapper can execute protoc commands for current project's proto files. -type Wrapper interface { - Exec(context.Context) error -} - -type wrapperImpl struct { - cfg *Config - fs afero.Fs - ui cli.UI - exec *execx.Executor - toolRepo tool.Repository - rootDir cli.RootDir - modCache *sync.Map -} +type Wrapper = newProtoc.Wrapper // NewWrapper creates a new Wrapper instance. -func NewWrapper(cfg *Config, fs afero.Fs, exec *execx.Executor, ui cli.UI, toolRepo tool.Repository, rootDir cli.RootDir) Wrapper { - return &wrapperImpl{ - cfg: cfg, - fs: fs, - ui: ui, - exec: exec, - toolRepo: toolRepo, - rootDir: rootDir, - modCache: new(sync.Map), - } -} - -func (e *wrapperImpl) Exec(ctx context.Context) (err error) { - e.ui.Section("Execute protoc") - - e.ui.Subsection("Install plugins") - err = errors.WithStack(e.installPlugins(ctx)) - if err != nil { - return - } - - e.ui.Subsection("Execute protoc") - err = errors.WithStack(e.execProtocAll(ctx)) - - return -} - -func (e *wrapperImpl) installPlugins(ctx context.Context) error { - return errors.WithStack(e.toolRepo.BuildAll(ctx)) -} - -func (e *wrapperImpl) execProtocAll(ctx context.Context) error { - protoFiles, err := e.cfg.ProtoFiles(e.fs, e.rootDir.String()) - if err != nil { - return errors.WithStack(err) - } - - var errs []error - for _, path := range protoFiles { - err = e.execProtoc(ctx, path) - relPath, _ := filepath.Rel(e.rootDir.String(), path) - if err == nil { - e.ui.ItemSuccess(relPath) - } else { - zap.L().Error("failed to execute protoc", zap.Error(err)) - errs = append(errs, err) - e.ui.ItemFailure(relPath, err) - } - } - - if len(errs) > 0 { - return errors.New("failed to execute protoc") - } - - return nil -} - -func (e *wrapperImpl) execProtoc(ctx context.Context, protoPath string) error { - outDir, err := e.cfg.OutDirOf(e.rootDir.String(), protoPath) - if err != nil { - return errors.WithStack(err) - } - - if err = fs.CreateDirIfNotExists(e.fs, outDir); err != nil { - return errors.WithStack(err) - } - - cmds, err := e.commands(ctx, protoPath) - if err != nil { - return errors.WithStack(err) - } - - path := e.rootDir.BinDir().String() + string(filepath.ListSeparator) + os.Getenv("PATH") - env := append(os.Environ(), "PATH="+path) - - for _, args := range cmds { - cmd := e.exec.CommandContext(ctx, args[0], args[1:]...) - cmd.Env = env - cmd.Dir = e.rootDir.String() - out, err := cmd.CombinedOutput() - if err != nil { - return errors.Wrapf(err, "failed to execute command: %v\n%s", args, string(out)) - } - } - - return nil -} - -func (e *wrapperImpl) commands(ctx context.Context, protoPath string) ([][]string, error) { - cmds := make([][]string, 0, len(e.cfg.Plugins)) - relProtoPath, _ := filepath.Rel(e.rootDir.String(), protoPath) - - outDir, err := e.cfg.OutDirOf(e.rootDir.String(), protoPath) - if err != nil { - return nil, errors.WithStack(err) - } - - isMod := e.modulesEnabled() - - funcMap := template.FuncMap{ - "module": func(in string) (string, error) { - if isMod { - return e.getModulePath(ctx, in) - } - return e.rootDir.Join("vendor", in).String(), nil - }, - } - - for _, p := range e.cfg.Plugins { - args := []string{} - args = append(args, "-I", filepath.Dir(relProtoPath)) - for _, dir := range e.cfg.ImportDirs { - tmpl, err := template.New(dir).Funcs(funcMap).Parse(dir) - if err != nil { - return nil, errors.WithStack(err) - } - buf := new(bytes.Buffer) - err = tmpl.Funcs(funcMap).Execute(buf, nil) - if err != nil { - return nil, errors.WithStack(err) - } - args = append(args, "-I", buf.String()) - } - args = append(args, p.toProtocArg(outDir)) - args = append(args, relProtoPath) - cmds = append(cmds, append([]string{"protoc"}, args...)) - } - - return cmds, nil -} - -func (e *wrapperImpl) getModulePath(ctx context.Context, pkg string) (string, error) { - if v, ok := e.modCache.Load(pkg); ok { - return v.(string), nil - } - buf := new(bytes.Buffer) - cmd := e.exec.CommandContext(ctx, "go", "list", "-f", "{{.Dir}}", "-m", pkg) - cmd.Env = append(os.Environ(), "GO111MODULE=on") - cmd.Dir = e.rootDir.String() - cmd.Stdout = buf - err := cmd.Run() - if err != nil { - return "", errors.WithStack(err) - } - out := strings.TrimSpace(buf.String()) - e.modCache.Store(pkg, out) - - return out, nil -} - -func (e *wrapperImpl) modulesEnabled() bool { - for _, f := range []string{"go.mod", "go.sum"} { - if ok, err := afero.Exists(e.fs, e.rootDir.Join(f).String()); err != nil || !ok { - return false - } - } - return true -} +var NewWrapper = newProtoc.NewWrapper diff --git a/pkg/protoc/wrapper_test.go b/pkg/protoc/wrapper_test.go deleted file mode 100644 index 417f0d5b..00000000 --- a/pkg/protoc/wrapper_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package protoc_test - -import ( - "context" - "os/exec" - "testing" - - "github.com/bradleyjkemp/cupaloy/v2" - "github.com/izumin5210/clig/pkg/clib" - "github.com/izumin5210/execx" - "github.com/izumin5210/gex/pkg/tool" - "github.com/spf13/afero" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/protoc" -) - -func TestWrapper_Exec(t *testing.T) { - dieIf := func(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - } - - calls := [][]string{} - - exec := execx.New(execx.WithFakeProcess( - func(ctx context.Context, cmd *exec.Cmd) error { - switch cmd.Args[0] { - case "go": - if out := cmd.Stdout; out != nil { - _, err := out.Write([]byte("/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.8.5\n")) - dieIf(t, err) - } - case "protoc": - calls = append(calls, cmd.Args) - default: - t.Errorf("unexpected command execution: %v", cmd.Args) - } - if out := cmd.Stdout; out != nil { - _, err := out.Write([]byte("\n")) - dieIf(t, err) - } - return nil - }, - )) - - rootDir := cli.RootDir{Path: clib.Path("/go/src/awesomeapp")} - protosDir := rootDir.Join("api", "protos") - - fs := afero.NewMemMapFs() - dieIf(t, fs.MkdirAll(rootDir.BinDir().String(), 0755)) - dieIf(t, fs.MkdirAll(protosDir.String(), 0755)) - dieIf(t, afero.WriteFile(fs, rootDir.Join("go.mod").String(), []byte("module example.com/awesomeapp"), 0644)) - dieIf(t, afero.WriteFile(fs, rootDir.Join("go.sum").String(), []byte(""), 0644)) - dieIf(t, afero.WriteFile(fs, rootDir.Join("api", "should_be_ignored.proto").String(), []byte{}, 0644)) - dieIf(t, afero.WriteFile(fs, rootDir.Join("api", "should_be_ignored_proto").String(), []byte{}, 0644)) - dieIf(t, afero.WriteFile(fs, protosDir.Join("book.proto").String(), []byte{}, 0644)) - dieIf(t, afero.WriteFile(fs, protosDir.Join("types", "users.proto").String(), []byte{}, 0644)) - - cfg := &protoc.Config{ - ImportDirs: []string{ - `{{ module "github.com/grpc-ecosystem/grpc-gateway" }}`, - `{{ module "github.com/grpc-ecosystem/grpc-gateway" }}/third_party/googleapis`, - protosDir.String(), - }, - ProtosDir: "./api/protos", - OutDir: "./api", - Plugins: []*protoc.Plugin{ - {Name: "go", Args: map[string]interface{}{"plugins": "grpc"}}, - {Name: "grpc-gateway", Args: map[string]interface{}{"logtostderr": true}}, - {Name: "swagger", Args: map[string]interface{}{"logtostderr": true}}, - }, - } - - wrapper := protoc.NewWrapper(cfg, fs, exec, cli.NopUI, &fakeToolRepository{}, rootDir) - - err := wrapper.Exec(context.TODO()) - if err != nil { - t.Fatalf("returned %v, want nil", err) - } - - cupaloy.SnapshotT(t, calls) -} - -type fakeToolRepository struct { - tool.Repository -} - -func (*fakeToolRepository) BuildAll(context.Context) error { return nil } diff --git a/pkg/svcgen/app.go b/pkg/svcgen/app.go index 072ece43..cec880c4 100644 --- a/pkg/svcgen/app.go +++ b/pkg/svcgen/app.go @@ -1,14 +1,9 @@ package svcgen import ( - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen/params" + newSvcgen "github.com/x-izumin/grapi/pkg/svcgen" ) -type CreateAppFunc func(*gencmd.Command) (*App, error) +type CreateAppFunc = newSvcgen.CreateAppFunc -type App struct { - ProtocWrapper protoc.Wrapper - ParamsBuilder params.Builder -} +type App = newSvcgen.App diff --git a/pkg/svcgen/params/builder.go b/pkg/svcgen/params/builder.go index 3950e6a5..46402263 100644 --- a/pkg/svcgen/params/builder.go +++ b/pkg/svcgen/params/builder.go @@ -1,247 +1,9 @@ package params import ( - "path/filepath" - "sort" - "strings" - - "github.com/pkg/errors" - "github.com/serenize/snaker" - - "github.com/izumin5210/grapi/pkg/cli" - gencmdutil "github.com/izumin5210/grapi/pkg/gencmd/util" + newParams "github.com/x-izumin/grapi/pkg/svcgen/params" ) -type Builder interface { - Build(path string, resName string, methodNames []string) (*Params, error) -} - -func NewBuilder(rootDir cli.RootDir, protoDir, protoOutDir, serverDir string, pkgName string) Builder { - if protoDir == "" { - protoDir = filepath.Join("api", "protos") - } - if protoOutDir == "" { - protoOutDir = filepath.Join("api") - } - if serverDir == "" { - serverDir = filepath.Join("app", "server") - } - return &builderImpl{ - rootDir: rootDir, - protoDir: protoDir, - protoOutDir: protoOutDir, - serverDir: serverDir, - pkgName: pkgName, - } -} - -type builderImpl struct { - rootDir cli.RootDir - protoDir string - protoOutDir string - serverDir string - pkgName string -} - -func (b *builderImpl) Build(path string, resName string, methodNames []string) (*Params, error) { - protoParams, err := gencmdutil.BuildProtoParams(path, b.rootDir, b.protoOutDir, b.pkgName) - if err != nil { - return nil, errors.WithStack(err) - } - - // path => baz/qux/quux - path = protoParams.Proto.Path - - // quux - name := filepath.Base(path) - - names := gencmdutil.Inflect(name) - - // Quux - serviceName := names.Camel.Singular - // quux - localServiceName := strings.ToLower(string(serviceName[0])) + serviceName[1:] - - // baz/qux - packagePath := filepath.Dir(path) - // qux - packageName := filepath.Base(packagePath) - - if packagePath == "." { - packagePath = filepath.Base(b.serverDir) - packageName = packagePath - } - - protoImports := []string{ - "google/api/annotations.proto", - } - goImports := []string{ - "github.com/izumin5210/grapi/pkg/grapiserver", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/status", - } - - resNames := names - if resName != "" { - resNames = gencmdutil.Inflect(resName) - } - methods := b.buildMethodParams(resNames, methodNames) - - protoImports = append(protoImports, methods.ProtoImports...) - sort.Strings(protoImports) - goImports = append(goImports, methods.GoImports...) - sort.Strings(goImports) - - params := &Params{ - ProtoDir: b.protoDir, - ProtoOutDir: b.protoOutDir, - ServerDir: b.serverDir, - Path: path, - ServiceName: serviceName, - Methods: methods.Methods, - Proto: ProtoParams{ - Package: protoParams.Proto.Package, - Imports: protoImports, - Messages: methods.Messages, - }, - PbGo: PbGoParams{ - PackagePath: protoParams.PbGo.Package, - PackageName: protoParams.PbGo.ImportName, - }, - Go: GoParams{ - Package: packageName, - Imports: goImports, - ServerName: serviceName + "Service" + "Server", - StructName: localServiceName + "Service" + "Server" + "Impl", - }, - } - - return params, nil -} - -func (b *builderImpl) buildMethodParams(name gencmdutil.String, methods []string) ( - params MethodsParams, -) { - id := name.Snake.Singular + "_id" - resource := &MethodMessage{ - Name: name.Camel.Singular, - Fields: []MethodMessageField{{Name: id, Type: "string", Tag: 1}}, - } - - basicMethods := [5]*MethodParams{} - customMethods := []MethodParams{} - basicMessages := [7]*MethodMessage{} - customMessages := []MethodMessage{} - - for _, meth := range methods { - switch strings.ToLower(meth) { - case "list": - methodName := "List" + name.Camel.Plural - reqName := methodName + "Request" - respName := methodName + "Response" - basicMethods[0] = &MethodParams{ - Method: methodName, - requestCommon: reqName, - responseCommon: respName, - HTTP: MethodHTTPParams{Method: "get", Path: name.Snake.Plural}, - } - basicMessages[0] = resource - basicMessages[1] = &MethodMessage{Name: reqName} - basicMessages[2] = &MethodMessage{ - Name: respName, - Fields: []MethodMessageField{{Name: name.Snake.Plural, Type: name.Camel.Singular, Repeated: true, Tag: 1}}, - } - case "get": - methodName := "Get" + name.Camel.Singular - reqName := methodName + "Request" - basicMethods[1] = &MethodParams{ - Method: methodName, - requestCommon: reqName, - responseCommon: resource.Name, - HTTP: MethodHTTPParams{Method: "get", Path: name.Snake.Plural + "/{" + id + "}"}, - } - basicMessages[0] = resource - basicMessages[3] = &MethodMessage{ - Name: reqName, - Fields: []MethodMessageField{{Name: id, Type: "string", Tag: 1}}, - } - case "create": - methodName := "Create" + name.Camel.Singular - reqName := methodName + "Request" - basicMethods[2] = &MethodParams{ - Method: methodName, - requestCommon: reqName, - responseCommon: resource.Name, - HTTP: MethodHTTPParams{Method: "post", Path: name.Snake.Plural, Body: name.Snake.Singular}, - } - basicMessages[0] = resource - basicMessages[4] = &MethodMessage{ - Name: reqName, - Fields: []MethodMessageField{{Name: name.Snake.Singular, Type: name.Camel.Singular, Tag: 1}}, - } - case "update": - methodName := "Update" + name.Camel.Singular - reqName := methodName + "Request" - basicMethods[3] = &MethodParams{ - Method: methodName, - requestCommon: reqName, - responseCommon: resource.Name, - HTTP: MethodHTTPParams{Method: "patch", Path: name.Snake.Plural + "/{" + name.Snake.Singular + "." + id + "}", Body: name.Snake.Singular}, - } - basicMessages[0] = resource - basicMessages[5] = &MethodMessage{ - Name: reqName, - Fields: []MethodMessageField{{Name: name.Snake.Singular, Type: name.Camel.Singular, Tag: 1}}, - } - case "delete": - methodName := "Delete" + name.Camel.Singular - reqName := methodName + "Request" - basicMethods[4] = &MethodParams{ - Method: methodName, - requestCommon: reqName, - responseProto: "google.protobuf.Empty", - responseGo: "empty.Empty", - HTTP: MethodHTTPParams{Method: "delete", Path: name.Snake.Plural + "/{" + id + "}"}, - } - basicMessages[6] = &MethodMessage{ - Name: reqName, - Fields: []MethodMessageField{{Name: id, Type: "string", Tag: 1}}, - } - params.ProtoImports = append(params.ProtoImports, "google/protobuf/empty.proto") - params.GoImports = append(params.GoImports, "github.com/golang/protobuf/ptypes/empty") - default: - methodName := snaker.SnakeToCamel(meth) - reqName := methodName + "Request" - respName := methodName + "Response" - customMethods = append(customMethods, MethodParams{ - Method: methodName, - requestCommon: reqName, - responseCommon: respName, - HTTP: MethodHTTPParams{Method: "get", Path: name.Snake.Plural + "/" + snaker.CamelToSnake(meth)}, - }) - customMessages = append( - customMessages, - MethodMessage{Name: reqName}, - MethodMessage{Name: respName}, - ) - } - } +type Builder = newParams.Builder - for _, meth := range basicMethods { - if meth != nil { - params.Methods = append(params.Methods, *meth) - } - } - for _, msg := range basicMessages { - if msg != nil { - params.Messages = append(params.Messages, *msg) - } - } - for _, meth := range customMethods { - params.Methods = append(params.Methods, meth) - } - for _, msg := range customMessages { - params.Messages = append(params.Messages, msg) - } - return -} +var NewBuilder = newParams.NewBuilder diff --git a/pkg/svcgen/params/params.go b/pkg/svcgen/params/params.go index aeabb026..15262b09 100644 --- a/pkg/svcgen/params/params.go +++ b/pkg/svcgen/params/params.go @@ -1,96 +1,21 @@ package params -type Params struct { - ProtoDir string - ProtoOutDir string - ServerDir string - Path string - ServiceName string - Methods []MethodParams - Proto ProtoParams - PbGo PbGoParams - Go GoParams -} +import newParams "github.com/x-izumin/grapi/pkg/svcgen/params" -type ProtoParams struct { - Package string - Imports []string - Messages []MethodMessage -} +type Params = newParams.Params -type PbGoParams struct { - PackageName string - PackagePath string -} +type ProtoParams = newParams.ProtoParams -type GoParams struct { - Package string - Imports []string - TestImports []string - ServerName string - StructName string -} +type PbGoParams = newParams.PbGoParams -type MethodsParams struct { - Methods []MethodParams - ProtoImports []string - GoImports []string - Messages []MethodMessage -} +type GoParams = newParams.GoParams -type MethodParams struct { - Method string - HTTP MethodHTTPParams - requestCommon string - requestGo string - requestProto string - responseCommon string - responseGo string - responseProto string -} +type MethodsParams = newParams.MethodsParams -func (p *MethodParams) RequestGo(pkg string) string { - if p.requestGo == "" { - return pkg + "." + p.requestCommon - } - return p.requestGo -} +type MethodParams = newParams.MethodParams -func (p *MethodParams) RequestProto() string { - if p.requestProto == "" { - return p.requestCommon - } - return p.requestProto -} +type MethodMessage = newParams.MethodMessage -func (p *MethodParams) ResponseGo(pkg string) string { - if p.responseGo == "" { - return pkg + "." + p.responseCommon - } - return p.responseGo -} +type MethodMessageField = newParams.MethodMessageField -func (p *MethodParams) ResponseProto() string { - if p.responseProto == "" { - return p.responseCommon - } - return p.responseProto -} - -type MethodMessage struct { - Name string - Fields []MethodMessageField -} - -type MethodMessageField struct { - Name string - Type string - Repeated bool - Tag uint -} - -type MethodHTTPParams struct { - Method string - Path string - Body string -} +type MethodHTTPParams = newParams.MethodHTTPParams diff --git a/pkg/svcgen/providers.go b/pkg/svcgen/providers.go index 0e3309fd..a20b7de0 100644 --- a/pkg/svcgen/providers.go +++ b/pkg/svcgen/providers.go @@ -2,25 +2,9 @@ package svcgen import ( "github.com/google/wire" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen/params" - _ "github.com/izumin5210/grapi/pkg/svcgen/template" + newSvcgen "github.com/x-izumin/grapi/pkg/svcgen" ) -func ProvideParamsBuilder(rootDir cli.RootDir, protocCfg *protoc.Config, grapiCfg *grapicmd.Config) params.Builder { - return params.NewBuilder( - rootDir, - protocCfg.ProtosDir, - protocCfg.OutDir, - grapiCfg.Grapi.ServerDir, - grapiCfg.Package, - ) -} +var ProvideParamsBuilder = newSvcgen.ProvideParamsBuilder -var Set = wire.NewSet( - ProvideParamsBuilder, - App{}, -) +var Set = wire.NewSet(newSvcgen.Set) diff --git a/pkg/svcgen/template/.gitignore b/pkg/svcgen/template/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/pkg/svcgen/template/_data/{{.ProtoDir}}/{{.Path}}.proto.tmpl b/pkg/svcgen/template/_data/{{.ProtoDir}}/{{.Path}}.proto.tmpl deleted file mode 100644 index 9cd6974e..00000000 --- a/pkg/svcgen/template/_data/{{.ProtoDir}}/{{.Path}}.proto.tmpl +++ /dev/null @@ -1,33 +0,0 @@ -syntax = "proto3"; - -package {{ .Proto.Package }}; - -option go_package = "{{ .PbGo.PackagePath }};{{ .PbGo.PackageName }}"; - -{{range .Proto.Imports}} -import "{{.}}"; -{{- end}} - -service {{ .ServiceName }}Service { -{{- range .Methods}} - rpc {{.Method}} ({{.RequestProto}}) returns ({{.ResponseProto}}) { - option (google.api.http) = { - {{.HTTP.Method}}: "/{{.HTTP.Path}}" - {{- if .HTTP.Body}} - body: "{{.HTTP.Body}}" - {{- end}} - }; - } -{{- end}} -} -{{range .Proto.Messages}} -message {{.Name}} { - {{- range .Fields}} - {{- if .Repeated}} - repeated {{.Type}} {{.Name}} = {{.Tag}}; - {{- else}} - {{.Type}} {{.Name}} = {{.Tag}}; - {{- end}} - {{- end}} -} -{{end -}} diff --git a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server.go.tmpl b/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server.go.tmpl deleted file mode 100644 index 8801f816..00000000 --- a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server.go.tmpl +++ /dev/null @@ -1,32 +0,0 @@ -package {{.Go.Package }} - -import ( - "context" -{{range .Go.Imports}} - "{{.}}" -{{- end}} - - {{.PbGo.PackageName}} "{{ .PbGo.PackagePath }}" -) - -// {{.Go.ServerName}} is a composite interface of {{.PbGo.PackageName }}.{{.Go.ServerName}} and grapiserver.Server. -type {{.Go.ServerName}} interface { - {{.PbGo.PackageName }}.{{.Go.ServerName}} - grapiserver.Server -} - -// New{{.Go.ServerName}} creates a new {{.Go.ServerName}} instance. -func New{{.Go.ServerName}}() {{.Go.ServerName}} { - return &{{.Go.StructName}}{} -} - -type {{.Go.StructName}} struct { -} -{{$go := .Go -}} -{{$pbGo := .PbGo -}} -{{- range .Methods}} -func (s *{{$go.StructName}}) {{.Method}}(ctx context.Context, req *{{.RequestGo $pbGo.PackageName}}) (*{{.ResponseGo $pbGo.PackageName}}, error) { - // TODO: Not yet implemented. - return nil, status.Error(codes.Unimplemented, "TODO: You should implement it!") -} -{{end -}} diff --git a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_register_funcs.go.tmpl b/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_register_funcs.go.tmpl deleted file mode 100644 index 1f820020..00000000 --- a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_register_funcs.go.tmpl +++ /dev/null @@ -1,22 +0,0 @@ -// Code generated by github.com/izumin5210/grapi. DO NOT EDIT. - -package {{.Go.Package }} - -import ( - "context" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - {{.PbGo.PackageName}} "{{ .PbGo.PackagePath }}" -) - -// RegisterWithServer implements grapiserver.Server.RegisterWithServer. -func (s *{{.Go.StructName}}) RegisterWithServer(grpcSvr *grpc.Server) { - {{.PbGo.PackageName}}.Register{{.Go.ServerName}}(grpcSvr, s) -} - -// RegisterWithHandler implements grapiserver.Server.RegisterWithHandler. -func (s *{{.Go.StructName}}) RegisterWithHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return {{.PbGo.PackageName}}.Register{{.ServiceName}}ServiceHandler(ctx, mux, conn) -} diff --git a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_test.go.tmpl b/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_test.go.tmpl deleted file mode 100644 index 14207074..00000000 --- a/pkg/svcgen/template/_data/{{.ServerDir}}/{{.Path}}_server_test.go.tmpl +++ /dev/null @@ -1,35 +0,0 @@ -package {{.Go.Package }} -{{if .Methods}} -import ( - "context" - "testing" - -{{- range .Go.TestImports}} - "{{.}}" -{{- end}} - - {{.PbGo.PackageName}} "{{ .PbGo.PackagePath }}" -) -{{$go := .Go -}} -{{$pbGo := .PbGo -}} -{{- range .Methods}} -func Test_{{$go.ServerName}}_{{.Method}}(t *testing.T) { - svr := New{{$go.ServerName}}() - - ctx := context.Background() - req := &{{.RequestGo $pbGo.PackageName}}{} - - resp, err := svr.{{.Method}}(ctx, req) - - t.SkipNow() - - if err != nil { - t.Errorf("returned an error %v", err) - } - - if resp == nil { - t.Error("response should not nil") - } -} -{{end -}} -{{end -}} diff --git a/pkg/svcgen/template/gen.go b/pkg/svcgen/template/gen.go deleted file mode 100644 index ba18632b..00000000 --- a/pkg/svcgen/template/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate statik -src ./_data -dest .. -p template -f -m - -package template diff --git a/pkg/svcgen/template/statik.go b/pkg/svcgen/template/statik.go deleted file mode 100644 index 57219db3..00000000 --- a/pkg/svcgen/template/statik.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by statik. DO NOT EDIT. - -// Package statik contains static assets. -package template - -import ( - "github.com/rakyll/statik/fs" -) - -func init() { - data := "PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\"\x00 \x00{{.ProtoDir}}/{{.Path}}.proto.tmplUT\x05\x00\x01\x80Cm8\x8cP\xbbn\xc30\x0c\x9c\xab\xaf <%C\xdc\xa1[\x02/\x1d\xfa\x18R\x18I\xf6B\x89Y\xc5h,\xa9\x92R\xd4\x10\xf8\xef\x05e\xd9p3\xd5\x13u<\xdf\x1d\xcf\xf7:\xc8\x1f\xa8\xa0\xb0\xce\x04\xf3Pl\x84\xb0\xf2\xf4)\x15B\x8cP\xd6\x8c\x96uF\x886B\x18\x1bZ\xa3A\x99\xf7\x91XA\x91\xb8\xc7\xe7\x89Z\xcbpf\xfa-\xfe&;\x96a\x9b\x18\x9d\xd4\nG\x8f\xd7\xce\x1a\x17<\x91h\xd3\xc4\x9aeb\xc6\xb8\x02\xd4\x0d\x91\x10\x1e\xddw{\x1a\xa2\xed\x879+\xee\xc7\xcd]\xe2g\xe9-\x86\xb3iX\x14\xc0\xd9\x13\xc4\x98!\"X\xc4X\xee\xf0\xeb\x8a>\xa4\x04DKp\x18\xaeN\xfb\xbc\xf3\xd6h\x8f\xd32\n\x00\x80|\xfeB\x19\xa3.XJ\xdb\x96\xe7\x10\xec\x12\xaaL\x00vy9\x1c\xea\xc9j\x0d\xc5\xfd\x88q1D\xc5\xc4\\A\xfb\x01\xc3\xea\xd14}J\xca\xdf\xd14\xfd:u0\xdb\xcd\x7f\x1b\x1a\xe1\x17m\x04\x00\xcdj\xa2\xdbn\xb7\xe8\xbdT\xc8=t\xc3\xc8\x19\xb99\xa2\x94zV\xd9S\x8b\x97\xdc\xd8\x98n\x87\x16e\xc0\xc1\xcf\xe5\x07+\x1cz\x9b\x14&\xad*\xa1RQ\xca\x94\x12],(\xbbI\xf3\x8c\x86\x98\xc6\xba^\xfe\n\x84\xcf\x0f\x04\x11E\x08\xef\x8f\x16w\x9f\xd2/\xc7:\xe6\xc2\xf8\xb0\x9dK)\x94\xa5\xb8\xc6r\x19\xdf\x89O\xb6Kg\x91\x07n<>f\x8d\x1b\x87<\xf0\xdc\x19c\xa3\xf9\x19\xcb\x89\xc9\xcf\xf3w\x05G\x8f\x89)\x7f\xd0\xe3D\x9e\xb7\x16\xd9\xf7\xf6\x9eZ4s\x8f\x1f\xad\xf1TnZ\x81\x9c\xb3\xaeM\x89l6\xf8u\xff\xe5\xfe\x0e;\xcbx!F?\x8cg\x1a\xc80u\xf250\xd3\x9fW\xf0\xacx\xf2\xf2k\xe26\xdav\xe4\xe5os\xd5\xbeB=K\xfd\xb1\x13\xfc\xc9N\xe7\xee\xa2\x86\x9e\xdf\xd5m\xce\x8fL\x973\xfa\x1f\x00\x00\xff\xffPK\x07\x08\x1an\x9c\xd3\x89\x01\x00\x00j\x03\x00\x00PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x006\x00 \x00{{.ServerDir}}/{{.Path}}_server_register_funcs.go.tmplUT\x05\x00\x01\x80Cm8\x94Q\xcd\xce\xd30\x10<\x7f~\x8aUNIU\x1c@\xe2 \xf2!\xe0@[\xd1J\x9c]wq-b;\xda\xacKJ\x94wGN\x0c\x14\x15\x84z\xb2\xf7gfvv\xeb\x1a\x9apB0\xe8\x91\x14\xe3 \x8eW0\x96\xcf\xf1(up\xb5\xfd\x1e\x9d\xf5o^\xbfzY\x1bR\x9d\x95\xf0\xbc\x85\xcd\xf6\x00o\x9f?\x1c\xa4\x10\x9d\xd2_\x95A\x18G\xf9.\xc8]\x8e\xa6I\x08\xeb\xba@\x0c\xa5x*t\xf0\x8c\x03\x17B<\x157\xdc\x86:\xfd\x02u\xe8\xaf=c\x0e\x8db\xfc\xa6\xae5E\xcf\xd6a\x91\x10!\x98\x16\xa5 \xad\xf2F\x062sg\"\x1bG\xb9;\xfe\x96\xdd(\x87\xd3\x04\xc58\xc2\x1f\xf9\x9d\xe23LS!*!\xea\x1a>\xa1\xb1=#}\xb6|\xde#]\x90\xc0\xba\xaeE\x87\x9e{\x98]\xf6sZ.Uy\x0f\x90\xe2K\xf4\x1a\xca\x1eV\x8b\xf1=S\xd4\xbc\x0cP\xfdE\xa1L#\xef/\x04\xab\xf4\xc9\xc4\x15\x8c\xff\xf0\xf0K2\xb3\xcf\xedK\xe9'\xd3\x1a\xfaJLw\x86\xde+\x7fj\x1fr\x94\x11\x0fX\xca\x88R\xf3\x00\xf9\xb4\xb2Y\xde5\xb88\xc0*_o\x91\xfb\x18\x87u\xea\xf3\xd9|\xd3Z\xf4\xdc\x04\xef+@\xa2@i\x0d\x84\x1c\xc9\xc3\x7f\xb7\x91\x18\xad\xce\x85\x1c\xdc\xcc3\xeb/ji;?\x02\x00\x00\xff\xffPK\x07\x084\x1fAoU\x01\x00\x00\xde\x02\x00\x00PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00,\x00 \x00{{.ServerDir}}/{{.Path}}_server_test.go.tmplUT\x05\x00\x01\x80Cm8d\x90Ao\xdb0\x0c\x85\xcf\xd2\xaf\xe0\x84n\xb0\x87V?`@.\x03\x86`\x87\x05\xc1\xda{\xe1\xda\xb4c\xa4\x95\x1c\x8av\x03\x10\xfa\xef\x03\x15o]\x90\x9bM\xbd\x8f\xef\xf1MM{l\x06\x04\x11\xbf\x8d~\xbf\xfe\xe5lE\xc6\x1e\xfc/\xe4C\xecR\xcev|\x9b\"1T\xd6\xb86\x06\xc63;k\x1cc\xe21\x0c\xceZ\x91\x07\xa0&\x0c\x08\xba\xe8 \x13\xff,\x84\xb2\xc6\x89\xf8\x9c]\x11a\xe8r\xb6\xd6\x88\xf8\xfd\xcb\x87\xe7\xaey\xc3\x9c\xc1\x89\xc0\xd5|\xdf\xf0\x01\x94\xad\xad\xc8\xdd\x10\xe1\xdbF\x1d\xe0\xa1d\xbc\x9b^\xb6\x97\x912\xeb\xf0_\x90\x8f\xf4\xfd\x1cZ\xd0P\xcfe\x89\x7fDZ\x90.\x9e\xcf\"\xab2\xe7\x8a\xe1\xebz\x93\x7f\xaaA\xacI\x0b\xe9\xfe\x1d\xbe\xdf\x92Um\xadi\xf9\xac\x82\xb5\x14\xff\xbdi\x8f\x03\xc59tUm\x0d\xe1I\x1f\xbf\x88\xf8\xdfx\x9a1\xf16B }}\xb7h#\x84i\xba\x07\xa4b\x98\x16\xf2\xff\x07k\xf9|\x0f\x84'\xb5d\xffx\x1c\xa7]|/\x01\xc6\xbe0\x9f6\x10\xc6W\x8dl\xd8\xff \x8a\xd4W\x8e\x90g\n\xd8A\x13T\x14 >/\xaex\xd4\xd6\xe4\x0b\xac\xb6\xb0\xb9\xa1\x15NS\x0c !\x1d\xe2\xfc\xdaA\x88\xac\"WP-\x1aC\xb7V\xfe\xf7\xebO\x00\x00\x00\xff\xffPK\x07\x08\xa73igR\x01\x00\x00O\x02\x00\x00PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(7\x19\x19\x13B\x01\x00\x00\xae\x02\x00\x00\"\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00{{.ProtoDir}}/{{.Path}}.proto.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\x1an\x9c\xd3\x89\x01\x00\x00j\x03\x00\x00'\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x9b\x01\x00\x00{{.ServerDir}}/{{.Path}}_server.go.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(4\x1fAoU\x01\x00\x00\xde\x02\x00\x006\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x82\x03\x00\x00{{.ServerDir}}/{{.Path}}_server_register_funcs.go.tmplUT\x05\x00\x01\x80Cm8PK\x01\x02\x14\x03\x14\x00\x08\x00\x08\x00\x00\x00!(\xa73igR\x01\x00\x00O\x02\x00\x00,\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81D\x05\x00\x00{{.ServerDir}}/{{.Path}}_server_test.go.tmplUT\x05\x00\x01\x80Cm8PK\x05\x06\x00\x00\x00\x00\x04\x00\x04\x00\x87\x01\x00\x00\xf9\x06\x00\x00\x00\x00" - fs.Register(data) -} diff --git a/pkg/svcgen/testing/run.go b/pkg/svcgen/testing/run.go deleted file mode 100644 index ec419288..00000000 --- a/pkg/svcgen/testing/run.go +++ /dev/null @@ -1,103 +0,0 @@ -package testing - -import ( - "go/build" - "testing" - - "github.com/bradleyjkemp/cupaloy/v2" - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd/util/fs" - "github.com/spf13/afero" -) - -type Ctx struct { - GOPATH string - RootDir cli.RootDir - CreateCmd func(*testing.T, afero.Fs, Case) gencmd.Executor - Cases []Case -} - -type Case struct { - Test string - GArgs []string - DArgs []string - Files []string - SkippedFiles map[string]struct{} - ProtoDir string - ProtoOutDir string - ServerDir string - PkgName string -} - -func Run(t *testing.T, ctx *Ctx) { - t.Helper() - - defer func(c build.Context) { fs.BuildContext = c }(fs.BuildContext) - fs.BuildContext = build.Context{GOPATH: ctx.GOPATH} - - for _, tc := range ctx.Cases { - t.Run(tc.Test, func(t *testing.T) { - fs := afero.NewMemMapFs() - afero.WriteFile(fs, ctx.RootDir.Join("grapi.toml").String(), []byte{}, 0755) - - t.Run("generate", func(t *testing.T) { - cmd := ctx.CreateCmd(t, fs, tc) - cmd.Command().SetArgs(append([]string{"generate"}, tc.GArgs...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.Files { - t.Run(file, func(t *testing.T) { - if _, ok := tc.SkippedFiles[file]; ok { - ok, err := afero.Exists(fs, file) - - if err != nil { - t.Errorf("returned an error: %v", err) - } - - if ok { - t.Error("should not exist") - } - } else { - data, err := afero.ReadFile(fs, ctx.RootDir.Join(file).String()) - - if err != nil { - t.Errorf("returned an error: %v", err) - } - - cupaloy.SnapshotT(t, string(data)) - } - }) - } - }) - - t.Run("destroy", func(t *testing.T) { - cmd := ctx.CreateCmd(t, fs, tc) - cmd.Command().SetArgs(append([]string{"destroy"}, tc.DArgs...)) - err := cmd.Execute() - - if err != nil { - t.Errorf("returned an error: %+v", err) - } - - for _, file := range tc.Files { - t.Run(file, func(t *testing.T) { - ok, err := afero.Exists(fs, ctx.RootDir.Join(file).String()) - - if err != nil { - t.Errorf("Exists(fs, %q) returned an error: %v", file, err) - } - - if ok { - t.Errorf("%q should not exist", file) - } - }) - } - }) - }) - } -} diff --git a/pkg/svcgen/testing/wire.go b/pkg/svcgen/testing/wire.go deleted file mode 100644 index 472ff6cd..00000000 --- a/pkg/svcgen/testing/wire.go +++ /dev/null @@ -1,21 +0,0 @@ -//+build wireinject - -package testing - -import ( - "github.com/google/wire" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen" -) - -func NewTestApp(*gencmd.Command, protoc.Wrapper, cli.UI) (*svcgen.App, error) { - wire.Build( - gencmd.Set, - svcgen.ProvideParamsBuilder, - svcgen.App{}, - ) - return nil, nil -} diff --git a/pkg/svcgen/testing/wire_gen.go b/pkg/svcgen/testing/wire_gen.go deleted file mode 100644 index 541ddff6..00000000 --- a/pkg/svcgen/testing/wire_gen.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by Wire. DO NOT EDIT. - -//go:generate wire -//+build !wireinject - -package testing - -import ( - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" - "github.com/izumin5210/grapi/pkg/svcgen" -) - -// Injectors from wire.go: - -func NewTestApp(command *gencmd.Command, wrapper protoc.Wrapper, ui cli.UI) (*svcgen.App, error) { - ctx := gencmd.ProvideCtx(command) - grapicmdCtx := gencmd.ProvideGrapiCtx(ctx) - rootDir := grapicmd.ProvideRootDir(grapicmdCtx) - config := grapicmd.ProvideProtocConfig(grapicmdCtx) - grapicmdConfig := grapicmd.ProvideConfig(grapicmdCtx) - builder := svcgen.ProvideParamsBuilder(rootDir, config, grapicmdConfig) - app := &svcgen.App{ - ProtocWrapper: wrapper, - ParamsBuilder: builder, - } - return app, nil -} diff --git a/pkg/svcgen/wire.go b/pkg/svcgen/wire.go index 6b9f94b7..d9a3ff34 100644 --- a/pkg/svcgen/wire.go +++ b/pkg/svcgen/wire.go @@ -1,21 +1,10 @@ -//+build wireinject +//go:build wireinject +// +build wireinject package svcgen import ( - "github.com/google/wire" - - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/protoc" + newSvcgen "github.com/x-izumin/grapi/pkg/svcgen" ) -func NewApp(*gencmd.Command) (*App, error) { - wire.Build( - Set, - gencmd.Set, - cli.UIInstance, - protoc.WrapperSet, - ) - return nil, nil -} +var NewApp = newSvcgen.NewApp diff --git a/pkg/svcgen/wire_gen.go b/pkg/svcgen/wire_gen.go index 43376044..16a7085e 100644 --- a/pkg/svcgen/wire_gen.go +++ b/pkg/svcgen/wire_gen.go @@ -1,43 +1,11 @@ -// Code generated by Wire. DO NOT EDIT. - //go:generate wire -//+build !wireinject +//go:build !wireinject +// +build !wireinject package svcgen import ( - "github.com/izumin5210/grapi/pkg/cli" - "github.com/izumin5210/grapi/pkg/gencmd" - "github.com/izumin5210/grapi/pkg/grapicmd" - "github.com/izumin5210/grapi/pkg/protoc" + newSvcgen "github.com/x-izumin/grapi/pkg/svcgen" ) -import ( - _ "github.com/izumin5210/grapi/pkg/svcgen/template" -) - -// Injectors from wire.go: - -func NewApp(command *gencmd.Command) (*App, error) { - ctx := gencmd.ProvideCtx(command) - grapicmdCtx := gencmd.ProvideGrapiCtx(ctx) - config := grapicmd.ProvideProtocConfig(grapicmdCtx) - fs := grapicmd.ProvideFS(grapicmdCtx) - executor := grapicmd.ProvideExec(grapicmdCtx) - io := grapicmd.ProvideIO(grapicmdCtx) - ui := cli.UIInstance(io) - rootDir := grapicmd.ProvideRootDir(grapicmdCtx) - gexConfig := protoc.ProvideGexConfig(fs, executor, io, rootDir) - repository, err := protoc.ProvideToolRepository(gexConfig) - if err != nil { - return nil, err - } - wrapper := protoc.NewWrapper(config, fs, executor, ui, repository, rootDir) - grapicmdConfig := grapicmd.ProvideConfig(grapicmdCtx) - builder := ProvideParamsBuilder(rootDir, config, grapicmdConfig) - app := &App{ - ProtocWrapper: wrapper, - ParamsBuilder: builder, - } - return app, nil -} +var NewApp = newSvcgen.NewApp