diff --git a/.gitattributes b/.gitattributes index 68f90fe8..b489800e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,5 +7,6 @@ # for more info. *.pb.go linguist-generated *.mock.go linguist-generated +api_next/** linguist-generated=true internal/protojson/** linguist-vendored internal/strcase/** linguist-vendored diff --git a/.github/workflows/update-proto.yml b/.github/workflows/update-proto.yml index 16c4a5b1..c3aadfc3 100644 --- a/.github/workflows/update-proto.yml +++ b/.github/workflows/update-proto.yml @@ -47,9 +47,10 @@ jobs: go-version-file: 'go.mod' check-latest: true - - uses: arduino/setup-protoc@149f6c87b92550901b26acd1632e11c3662e381f # v1.3.0 + - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3.0.0 with: - version: "3.x" + version: '23.x' + repo-token: ${{ secrets.GITHUB_TOKEN }} # Needed for pnpm - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 diff --git a/Makefile b/Makefile index f732a9db..bce16929 100644 --- a/Makefile +++ b/Makefile @@ -73,6 +73,8 @@ HELPER_FILES = $(shell find ./cmd/protoc-gen-go-helpers) go-grpc: clean .go-helpers-installed $(PROTO_OUT) printf $(COLOR) "Compile for go-gRPC..." + # Post-processing walks every .pb.go under $(PROTO_OUT). Exclude the + # separately generated api_next module and the helper test fixtures. go run ./cmd/protogen \ --root=$(PROTO_ROOT)/temporal/api \ -I=$(PROTO_ROOT) \ @@ -80,6 +82,8 @@ go-grpc: clean .go-helpers-installed $(PROTO_OUT) --exclude=internal \ --exclude=proto/api/google \ --exclude=$(PROTO_ROOT)/temporal/api_next \ + --exclude=$(API_NEXT_OUT) \ + --exclude=cmd/protoc-gen-go-helpers/testprotos \ -p go-grpc_out=$(PROTO_PATHS) \ -p grpc-gateway_out=allow_patch_feature=false,$(PROTO_PATHS) \ -p go-helpers_out=$(PROTO_PATHS) @@ -233,6 +237,7 @@ helper-test-protos: # We need to ensure protos are up to date to test our UTF-8 post-processing test: copy-helpers go test -race -tags protolegacy ./... + go -C cmd/proxygenerator test ./... ##### Check ##### diff --git a/api_next/.gitattributes b/api_next/.gitattributes index 68f90fe8..b489800e 100644 --- a/api_next/.gitattributes +++ b/api_next/.gitattributes @@ -7,5 +7,6 @@ # for more info. *.pb.go linguist-generated *.mock.go linguist-generated +api_next/** linguist-generated=true internal/protojson/** linguist-vendored internal/strcase/** linguist-vendored diff --git a/api_next/.github/workflows/update-proto.yml b/api_next/.github/workflows/update-proto.yml index 16c4a5b1..c3aadfc3 100644 --- a/api_next/.github/workflows/update-proto.yml +++ b/api_next/.github/workflows/update-proto.yml @@ -47,9 +47,10 @@ jobs: go-version-file: 'go.mod' check-latest: true - - uses: arduino/setup-protoc@149f6c87b92550901b26acd1632e11c3662e381f # v1.3.0 + - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3.0.0 with: - version: "3.x" + version: '23.x' + repo-token: ${{ secrets.GITHUB_TOKEN }} # Needed for pnpm - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 diff --git a/api_next/Makefile b/api_next/Makefile index f732a9db..bce16929 100644 --- a/api_next/Makefile +++ b/api_next/Makefile @@ -73,6 +73,8 @@ HELPER_FILES = $(shell find ./cmd/protoc-gen-go-helpers) go-grpc: clean .go-helpers-installed $(PROTO_OUT) printf $(COLOR) "Compile for go-gRPC..." + # Post-processing walks every .pb.go under $(PROTO_OUT). Exclude the + # separately generated api_next module and the helper test fixtures. go run ./cmd/protogen \ --root=$(PROTO_ROOT)/temporal/api \ -I=$(PROTO_ROOT) \ @@ -80,6 +82,8 @@ go-grpc: clean .go-helpers-installed $(PROTO_OUT) --exclude=internal \ --exclude=proto/api/google \ --exclude=$(PROTO_ROOT)/temporal/api_next \ + --exclude=$(API_NEXT_OUT) \ + --exclude=cmd/protoc-gen-go-helpers/testprotos \ -p go-grpc_out=$(PROTO_PATHS) \ -p grpc-gateway_out=allow_patch_feature=false,$(PROTO_PATHS) \ -p go-helpers_out=$(PROTO_PATHS) @@ -233,6 +237,7 @@ helper-test-protos: # We need to ensure protos are up to date to test our UTF-8 post-processing test: copy-helpers go test -race -tags protolegacy ./... + go -C cmd/proxygenerator test ./... ##### Check ##### diff --git a/api_next/cmd/protogen/main.go b/api_next/cmd/protogen/main.go index 7098f2c4..77c0564d 100644 --- a/api_next/cmd/protogen/main.go +++ b/api_next/cmd/protogen/main.go @@ -94,19 +94,19 @@ func walkExtension(ctx context.Context, root string, extension string, exclusion }) } -// Walk the file tree and collect all enum definitions we find -// so we can post-process the go code we're generating -func findEnums(ctx context.Context, cfg genConfig) ([]string, []string, error) { +// Walk the file tree and collect proto files and their enum definitions +// so we can post-process the go code we're generating. +func findProtos(ctx context.Context, cfg genConfig) ([]string, []string, error) { seen := map[string]struct{}{} var enums []string - var dirs []string + var files []string walkFunc := func(path string) error { - // Emit unique directories containing proto files - dir := filepath.Dir(path) - if _, ok := seen[dir]; !ok { - seen[dir] = struct{}{} - dirs = append(dirs, dir) + // Emit each proto file once, even if the roots overlap. + if _, ok := seen[path]; ok { + return nil } + seen[path] = struct{}{} + files = append(files, path) // There isn't a good way to iteratively find matches using an io.Reader // so we need to pull the whole thing into memory. We could do it line by line @@ -126,12 +126,11 @@ func findEnums(ctx context.Context, cfg genConfig) ([]string, []string, error) { return nil, nil, err } } - return enums, dirs, nil + return enums, files, nil } -// Run protoc on all proto dirs we discover under the root directory -func runProtoc(ctx context.Context, cfg genConfig, protoDirs []string) error { - // Run protoc on each directory individually +// Run protoc on the proto files discovered under the roots. +func runProtoc(ctx context.Context, cfg genConfig, protoFiles []string) error { args := []string{ "--fatal_warnings", } @@ -154,14 +153,7 @@ func runProtoc(ctx context.Context, cfg genConfig, protoDirs []string) error { args = append(args, fmt.Sprintf("--%s", plugin)) } - for i := 0; i < len(protoDirs); i++ { - dir := protoDirs[i] - files, err := filepath.Glob(filepath.Join(dir, "*.proto")) - if err != nil { - return err - } - args = append(args, files...) - } + args = append(args, protoFiles...) var stderr bytes.Buffer protoc := exec.CommandContext(ctx, cfg.protocPath, args...) @@ -226,12 +218,12 @@ func postProcess(ctx context.Context, cfg genConfig) error { } func compileProtos(ctx context.Context, cfg genConfig) error { - enums, dirs, err := findEnums(ctx, cfg) + enums, files, err := findProtos(ctx, cfg) if err != nil { return err } - if err := runProtoc(ctx, cfg, dirs); err != nil { + if err := runProtoc(ctx, cfg, files); err != nil { return err } @@ -271,7 +263,7 @@ func main() { flag.Var(&protoIncludes, "I", "Directory to include when compiling protos") flag.Var(&descriptorSetIn, "descriptor_set_in", "Files containing binary FileDescriptorSet messages as inputs") flag.Var(&protoPlugins, "p", "Plugin=Options pairs of protobuf plugins, like grpc-gateway_out=allow_patch_feature=false") - flag.Var(&excludeDirs, "exclude", "Directory to exclude when compiling post-processing protos") + flag.Var(&excludeDirs, "exclude", "File or directory to exclude when compiling protos or post-processing generated Go code") flag.StringVar(&enumPrefixPairs, "rewrite-enum", "", "Comma-separated list of additional EnumType:CodePrefix pairs to remove when rewriting golang enums. Example: BuildId_State:BuildId") flag.IntVar(&concurrency, "concurrency", 0, "Maximum number of goroutines to run. Defaults to 0, meaning unlimited") diff --git a/cmd/protogen/main.go b/cmd/protogen/main.go index 7098f2c4..77c0564d 100644 --- a/cmd/protogen/main.go +++ b/cmd/protogen/main.go @@ -94,19 +94,19 @@ func walkExtension(ctx context.Context, root string, extension string, exclusion }) } -// Walk the file tree and collect all enum definitions we find -// so we can post-process the go code we're generating -func findEnums(ctx context.Context, cfg genConfig) ([]string, []string, error) { +// Walk the file tree and collect proto files and their enum definitions +// so we can post-process the go code we're generating. +func findProtos(ctx context.Context, cfg genConfig) ([]string, []string, error) { seen := map[string]struct{}{} var enums []string - var dirs []string + var files []string walkFunc := func(path string) error { - // Emit unique directories containing proto files - dir := filepath.Dir(path) - if _, ok := seen[dir]; !ok { - seen[dir] = struct{}{} - dirs = append(dirs, dir) + // Emit each proto file once, even if the roots overlap. + if _, ok := seen[path]; ok { + return nil } + seen[path] = struct{}{} + files = append(files, path) // There isn't a good way to iteratively find matches using an io.Reader // so we need to pull the whole thing into memory. We could do it line by line @@ -126,12 +126,11 @@ func findEnums(ctx context.Context, cfg genConfig) ([]string, []string, error) { return nil, nil, err } } - return enums, dirs, nil + return enums, files, nil } -// Run protoc on all proto dirs we discover under the root directory -func runProtoc(ctx context.Context, cfg genConfig, protoDirs []string) error { - // Run protoc on each directory individually +// Run protoc on the proto files discovered under the roots. +func runProtoc(ctx context.Context, cfg genConfig, protoFiles []string) error { args := []string{ "--fatal_warnings", } @@ -154,14 +153,7 @@ func runProtoc(ctx context.Context, cfg genConfig, protoDirs []string) error { args = append(args, fmt.Sprintf("--%s", plugin)) } - for i := 0; i < len(protoDirs); i++ { - dir := protoDirs[i] - files, err := filepath.Glob(filepath.Join(dir, "*.proto")) - if err != nil { - return err - } - args = append(args, files...) - } + args = append(args, protoFiles...) var stderr bytes.Buffer protoc := exec.CommandContext(ctx, cfg.protocPath, args...) @@ -226,12 +218,12 @@ func postProcess(ctx context.Context, cfg genConfig) error { } func compileProtos(ctx context.Context, cfg genConfig) error { - enums, dirs, err := findEnums(ctx, cfg) + enums, files, err := findProtos(ctx, cfg) if err != nil { return err } - if err := runProtoc(ctx, cfg, dirs); err != nil { + if err := runProtoc(ctx, cfg, files); err != nil { return err } @@ -271,7 +263,7 @@ func main() { flag.Var(&protoIncludes, "I", "Directory to include when compiling protos") flag.Var(&descriptorSetIn, "descriptor_set_in", "Files containing binary FileDescriptorSet messages as inputs") flag.Var(&protoPlugins, "p", "Plugin=Options pairs of protobuf plugins, like grpc-gateway_out=allow_patch_feature=false") - flag.Var(&excludeDirs, "exclude", "Directory to exclude when compiling post-processing protos") + flag.Var(&excludeDirs, "exclude", "File or directory to exclude when compiling protos or post-processing generated Go code") flag.StringVar(&enumPrefixPairs, "rewrite-enum", "", "Comma-separated list of additional EnumType:CodePrefix pairs to remove when rewriting golang enums. Example: BuildId_State:BuildId") flag.IntVar(&concurrency, "concurrency", 0, "Maximum number of goroutines to run. Defaults to 0, meaning unlimited") diff --git a/cmd/protogen/main_test.go b/cmd/protogen/main_test.go new file mode 100644 index 00000000..61b43282 --- /dev/null +++ b/cmd/protogen/main_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/descriptorpb" +) + +func TestWalkExtensionExclusions(t *testing.T) { + tests := []struct { + name string + exclusion string + files []string + want []string + }{ + { + name: "exact file match", + exclusion: "temporal/api_next/message.proto", + files: []string{"temporal/api_next/message.proto", "temporal/api_next/service.proto"}, + want: []string{"temporal/api_next/service.proto"}, + }, + { + name: "prefix within a component", + exclusion: "temporal/api_next", + files: []string{"temporal/api_next_other/message.proto"}, + want: []string{"temporal/api_next_other/message.proto"}, + }, + { + name: "nested exclusion", + exclusion: "temporal/api_next/internal", + files: []string{"temporal/api_next/internal/v1/message.proto", "temporal/api_next/public/v1/message.proto"}, + want: []string{"temporal/api_next/public/v1/message.proto"}, + }, + { + name: "excluded directory and sibling", + exclusion: "temporal/api_next", + files: []string{"temporal/api_next/message.proto", "temporal/api/message.proto"}, + want: []string{"temporal/api/message.proto"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + for _, file := range tt.files { + path := filepath.Join(root, filepath.FromSlash(file)) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0755)) + require.NoError(t, os.WriteFile(path, nil, 0644)) + } + + var got []string + err := walkExtension(t.Context(), root, ".proto", []string{filepath.FromSlash(tt.exclusion)}, func(path string) error { + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + got = append(got, filepath.ToSlash(rel)) + return nil + }) + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} + +func TestCompileProtosExcludesFileAlongsideSibling(t *testing.T) { + root := t.TempDir() + for _, name := range []string{"excluded.proto", "included.proto"} { + require.NoError(t, os.WriteFile(filepath.Join(root, name), []byte("syntax = \"proto3\";\n"), 0644)) + } + descriptorPath := filepath.Join(t.TempDir(), "descriptor.pb") + require.NoError(t, compileProtos(t.Context(), genConfig{ + protocPath: "protoc", + rootDirs: []string{root}, + excludeDirs: []string{"excluded.proto"}, + includes: []string{root}, + outputDescriptorPath: descriptorPath, + })) + data, err := os.ReadFile(descriptorPath) + require.NoError(t, err) + var descriptors descriptorpb.FileDescriptorSet + require.NoError(t, proto.Unmarshal(data, &descriptors)) + var names []string + for _, file := range descriptors.GetFile() { + names = append(names, file.GetName()) + } + require.Equal(t, []string{"included.proto"}, names) +} diff --git a/cmd/proxygenerator/api_next_test.go b/cmd/proxygenerator/api_next_test.go index 7df6198a..0adf464b 100644 --- a/cmd/proxygenerator/api_next_test.go +++ b/cmd/proxygenerator/api_next_test.go @@ -1,6 +1,7 @@ package main import ( + "errors" "os" "os/exec" "path/filepath" @@ -17,8 +18,16 @@ func TestAPINextProxy(t *testing.T) { if err != nil { t.Fatal(err) } + apiNext := filepath.Join(root, "api_next") + raw, err := os.ReadFile(filepath.Join(apiNext, "descriptor_set.pb")) + if errors.Is(err, os.ErrNotExist) { + t.Skip("api_next/descriptor_set.pb is missing. Run make api-next before this test.") + } + if err != nil { + t.Fatal(err) + } stage := t.TempDir() - if err := os.CopyFS(stage, os.DirFS(filepath.Join(root, "api_next"))); err != nil { + if err := os.CopyFS(stage, os.DirFS(apiNext)); err != nil { t.Fatal(err) } run := func(dir, name string, args ...string) { @@ -30,10 +39,6 @@ func TestAPINextProxy(t *testing.T) { } } descriptorPath := filepath.Join(stage, "descriptor_set.pb") - raw, err := os.ReadFile(descriptorPath) - if err != nil { - t.Fatalf("run make api-next before this test: %v", err) - } var set descriptorpb.FileDescriptorSet if err := proto.Unmarshal(raw, &set); err != nil { t.Fatal(err)