-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgen_test.go
49 lines (41 loc) · 1.23 KB
/
gen_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package fauxrpc_test
import (
"fmt"
"strings"
"github.com/bufbuild/protocompile/parser"
"github.com/bufbuild/protocompile/reporter"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
func wrapProto(inner string) string {
return fmt.Sprintf(`syntax = "proto3";
package test.v1;
import "buf/validate/validate.proto";
%s`, inner)
}
func mustCompileField(fieldType, fieldName, fieldOptions string) protoreflect.FieldDescriptor {
optionsSection := ""
if len(fieldOptions) > 0 {
optionsSection = "[" + fieldOptions + "]"
}
protoText := wrapProto(fmt.Sprintf(`
message Test {
%s %s = 1 %s;
}
`, fieldType, fieldName, optionsSection))
handler := reporter.NewHandler(nil)
ast, err := parser.Parse("test.proto", strings.NewReader(protoText), handler)
if err != nil {
panic(err)
}
res, err := parser.ResultFromAST(ast, true, handler)
if err != nil {
panic(fmt.Errorf("convert from AST: %w", err))
}
fd, err := protodesc.NewFile(res.FileDescriptorProto(), protoregistry.GlobalFiles)
if err != nil {
panic(fmt.Errorf("protodesc.NewFile: %w", err))
}
return fd.Messages().ByName("Test").Fields().ByName(protoreflect.Name(fieldName))
}