Skip to content

Commit b8a0992

Browse files
authored
fix(locations): add arbitrary field option helper (#1213)
1 parent fd0dc6c commit b8a0992

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

locations/field_locations.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,17 @@ import (
1818
dpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
1919
"github.com/jhump/protoreflect/desc"
2020
apb "google.golang.org/genproto/googleapis/api/annotations"
21+
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
2122
)
2223

24+
// FieldOption returns the precise location for the given extension defintion on
25+
// the given field. This is useful for writing rules against custom extensions.
26+
//
27+
// Example: locations.FieldOption(field, fieldbehaviorpb.E_FieldBehavior)
28+
func FieldOption(f *desc.FieldDescriptor, e *protoimpl.ExtensionInfo) *dpb.SourceCodeInfo_Location {
29+
return pathLocation(f, 8, int(e.TypeDescriptor().Number())) // FieldDescriptor.options == 8
30+
}
31+
2332
// FieldResourceReference returns the precise location for a field's
2433
// resource reference annotation.
2534
func FieldResourceReference(f *desc.FieldDescriptor) *dpb.SourceCodeInfo_Location {

locations/field_locations_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919

2020
"github.com/google/go-cmp/cmp"
2121
"github.com/jhump/protoreflect/desc"
22+
apb "google.golang.org/genproto/googleapis/api/annotations"
2223
)
2324

2425
func TestFieldLocations(t *testing.T) {
@@ -81,6 +82,22 @@ func TestFieldResourceReference(t *testing.T) {
8182
}
8283
`)
8384
loc := FieldResourceReference(f.GetMessageTypes()[0].GetFields()[0])
85+
// resource_reference annotation location is roughly line 4, column 19.
86+
if diff := cmp.Diff(loc.GetSpan(), []int32{4, 19, 6, 3}); diff != "" {
87+
t.Errorf(diff)
88+
}
89+
}
90+
91+
func TestFieldOption(t *testing.T) {
92+
f := parse(t, `
93+
import "google/api/resource.proto";
94+
message GetBookRequest {
95+
string name = 1 [(google.api.resource_reference) = {
96+
type: "library.googleapis.com/Book"
97+
}];
98+
}
99+
`)
100+
loc := FieldOption(f.GetMessageTypes()[0].GetFields()[0], apb.E_ResourceReference)
84101
if diff := cmp.Diff(loc.GetSpan(), []int32{4, 19, 6, 3}); diff != "" {
85102
t.Errorf(diff)
86103
}

0 commit comments

Comments
 (0)