cmd/protoc-gen-go: generate package documentation for well-known types

Change-Id: Ia079805e24d3490301355e09693255b157cabaed
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/239167
Reviewed-by: Damien Neil <dneil@google.com>
This commit is contained in:
Joe Tsai 2020-06-12 11:12:50 -07:00
parent b0c4001c72
commit 5a96da2901
19 changed files with 650 additions and 2 deletions

View File

@ -75,7 +75,9 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated
genStandaloneComments(g, f, int32(genid.FileDescriptorProto_Syntax_field_number))
genGeneratedHeader(gen, g, f)
genStandaloneComments(g, f, int32(genid.FileDescriptorProto_Package_field_number))
g.P("package ", f.GoPackageName)
packageDoc := genPackageKnownComment(f)
g.P(packageDoc, "package ", f.GoPackageName)
g.P()
// Emit a static check that enforces a minimum version of the proto package.

View File

@ -16,6 +16,325 @@ import (
// in order to support specialized build systems like Bazel that always generate
// dynamically from the source .proto files.
func genPackageKnownComment(f *fileInfo) protogen.Comments {
switch f.Desc.Path() {
case genid.File_google_protobuf_any_proto:
return ` Package anypb contains generated types for ` + genid.File_google_protobuf_any_proto + `.
The Any message is a dynamic representation of any other message value.
It is functionally a tuple of the full name of the remote message type and
the serialized bytes of the remote message value.
Constructing an Any
An Any message containing another message value is constructed using New:
any, err := anypb.New(m)
if err != nil {
... // handle error
}
... // make use of any
Unmarshaling an Any
With a populated Any message, the underlying message can be serialized into
a remote concrete message value in a few ways.
If the exact concrete type is known, then a new (or pre-existing) instance
of that message can be passed to the UnmarshalTo method:
m := new(foopb.MyMessage)
if err := any.UnmarshalTo(m); err != nil {
... // handle error
}
... // make use of m
If the exact concrete type is not known, then the UnmarshalNew method can be
used to unmarshal the contents into a new instance of the remote message type:
m, err := any.UnmarshalNew()
if err != nil {
... // handle error
}
... // make use of m
UnmarshalNew uses the global type registry to resolve the message type and
construct a new instance of that message to unmarshal into. In order for a
message type to appear in the global registry, the Go type representing that
protobuf message type must be linked into the Go binary. For messages
generated by protoc-gen-go, this is achieved through an import of the
generated Go package representing a .proto file.
A common pattern with UnmarshalNew is to use a type switch with the resulting
proto.Message value:
switch m := m.(type) {
case *foopb.MyMessage:
... // make use of m as a *foopb.MyMessage
case *barpb.OtherMessage:
... // make use of m as a *barpb.OtherMessage
case *bazpb.SomeMessage:
... // make use of m as a *bazpb.SomeMessage
}
This pattern ensures that the generated packages containing the message types
listed in the case clauses are linked into the Go binary and therefore also
registered in the global registry.
Type checking an Any
In order to type check whether an Any message represents some other message,
then use the MessageIs method:
if any.MessageIs((*foopb.MyMessage)(nil)) {
... // make use of any, knowing that it contains a foopb.MyMessage
}
The MessageIs method can also be used with an allocated instance of the target
message type if the intention is to unmarshal into it if the type matches:
m := new(foopb.MyMessage)
if any.MessageIs(m) {
if err := any.UnmarshalTo(m); err != nil {
... // handle error
}
... // make use of m
}
`
case genid.File_google_protobuf_timestamp_proto:
return ` Package timestamppb contains generated types for ` + genid.File_google_protobuf_timestamp_proto + `.
The Timestamp message represents a timestamp,
an instant in time since the Unix epoch (January 1st, 1970).
Conversion to a Go Time
The AsTime method can be used to convert a Timestamp message to a
standard Go time.Time value in UTC:
t := ts.AsTime()
... // make use of t as a time.Time
Converting to a time.Time is a common operation so that the extensive
set of time-based operations provided by the time package can be leveraged.
See https://golang.org/pkg/time for more information.
The AsTime method performs the conversion on a best-effort basis. Timestamps
with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive)
are normalized during the conversion to a time.Time. To manually check for
invalid Timestamps per the documented limitations in timestamp.proto,
additionally call the CheckValid method:
if err := ts.CheckValid(); err != nil {
... // handle error
}
Conversion from a Go Time
The timestamppb.New function can be used to construct a Timestamp message
from a standard Go time.Time value:
ts := timestamppb.New(t)
... // make use of ts as a *timestamppb.Timestamp
In order to construct a Timestamp representing the current time, use Now:
ts := timestamppb.Now()
... // make use of ts as a *timestamppb.Timestamp
`
case genid.File_google_protobuf_duration_proto:
return ` Package durationpb contains generated types for ` + genid.File_google_protobuf_duration_proto + `.
The Duration message represents a signed span of time.
Conversion to a Go Duration
The AsDuration method can be used to convert a Duration message to a
standard Go time.Duration value:
d := dur.AsDuration()
... // make use of d as a time.Duration
Converting to a time.Duration is a common operation so that the extensive
set of time-based operations provided by the time package can be leveraged.
See https://golang.org/pkg/time for more information.
The AsDuration method performs the conversion on a best-effort basis.
Durations with denormal values (e.g., nanoseconds beyond -99999999 and
+99999999, inclusive; or seconds and nanoseconds with opposite signs)
are normalized during the conversion to a time.Duration. To manually check for
invalid Duration per the documented limitations in duration.proto,
additionally call the CheckValid method:
if err := dur.CheckValid(); err != nil {
... // handle error
}
Note that the documented limitations in duration.proto does not protect a
Duration from overflowing the representable range of a time.Duration in Go.
The AsDuration method uses saturation arithmetic such that an overflow clamps
the resulting value to the closest representable value (e.g., math.MaxInt64
for positive overflow and math.MinInt64 for negative overflow).
Conversion from a Go Duration
The durationpb.New function can be used to construct a Duration message
from a standard Go time.Duration value:
dur := durationpb.New(d)
... // make use of d as a *durationpb.Duration
`
case genid.File_google_protobuf_struct_proto:
return ` Package structpb contains generated types for ` + genid.File_google_protobuf_struct_proto + `.
The messages (i.e., Value, Struct, and ListValue) defined in struct.proto are
used to represent arbitrary JSON. The Value message represents a JSON value,
the Struct message represents a JSON object, and the ListValue message
represents a JSON array. See https://json.org for more information.
The Value, Struct, and ListValue types have generated MarshalJSON and
UnmarshalJSON methods such that they serialize JSON equivalent to what the
messages themselves represent. Use of these types with the
"google.golang.org/protobuf/encoding/protojson" package
ensures that they will be serialized as their JSON equivalent.
Conversion to and from a Go interface
The standard Go "encoding/json" package has functionality to serialize
arbitrary types to a large degree. The Value.AsInterface, Struct.AsMap, and
ListValue.AsSlice methods can convert the protobuf message representation into
a form represented by interface{}, map[string]interface{}, and []interface{}.
This form can be used with other packages that operate on such data structures
and also directly with the standard json package.
In order to convert the interface{}, map[string]interface{}, and []interface{}
forms back as Value, Struct, and ListValue messages, use the NewStruct,
NewList, and NewValue constructor functions.
Example usage
Consider the following example JSON object:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
To construct a Value message representing the above JSON object:
m, err := structpb.NewValue(map[string]interface{}{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": map[string]interface{}{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100",
},
"phoneNumbers": []interface{}{
map[string]interface{}{
"type": "home",
"number": "212 555-1234",
},
map[string]interface{}{
"type": "office",
"number": "646 555-4567",
},
},
"children": []interface{}{},
"spouse": nil,
})
if err != nil {
... // handle error
}
... // make use of m as a *structpb.Value
`
case genid.File_google_protobuf_field_mask_proto:
return ` Package fieldmaskpb contains generated types for ` + genid.File_google_protobuf_field_mask_proto + `.
The FieldMask message represents a set of symbolic field paths.
The paths are specific to some target message type,
which is not stored within the FieldMask message itself.
Constructing a FieldMask
The New function is used construct a FieldMask:
var messageType *descriptorpb.DescriptorProto
fm, err := fieldmaskpb.New(messageType, "field.name", "field.number")
if err != nil {
... // handle error
}
... // make use of fm
The "field.name" and "field.number" paths are valid paths according to the
google.protobuf.DescriptorProto message. Use of a path that does not correlate
to valid fields reachable from DescriptorProto would result in an error.
Once a FieldMask message has been constructed,
the Append method can be used to insert additional paths to the path set:
var messageType *descriptorpb.DescriptorProto
if err := fm.Append(messageType, "options"); err != nil {
... // handle error
}
Type checking a FieldMask
In order to verify that a FieldMask represents a set of fields that are
reachable from some target message type, use the IsValid method:
var messageType *descriptorpb.DescriptorProto
if fm.IsValid(messageType) {
... // make use of fm
}
IsValid needs to be passed the target message type as an input since the
FieldMask message itself does not store the message type that the set of paths
are for.
`
default:
return ""
}
}
func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) {
switch m.Desc.FullName() {
case genid.Any_message_fullname:

View File

@ -290,7 +290,10 @@ func generateIdentifiers(gen *protogen.Plugin, file *protogen.File) {
g.P(s)
}
g.P("package ", path.Base(importPath))
g.P("")
g.P()
g.P("const ", file.GoDescriptorIdent.GoName, " = ", strconv.Quote(file.Desc.Path()))
g.P()
var processEnums func([]*protogen.Enum)
var processMessages func([]*protogen.Message)

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_any_proto = "google/protobuf/any.proto"
// Names for google.protobuf.Any.
const (
Any_message_name protoreflect.Name = "Any"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_api_proto = "google/protobuf/api.proto"
// Names for google.protobuf.Api.
const (
Api_message_name protoreflect.Name = "Api"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_descriptor_proto = "google/protobuf/descriptor.proto"
// Names for google.protobuf.FileDescriptorSet.
const (
FileDescriptorSet_message_name protoreflect.Name = "FileDescriptorSet"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_duration_proto = "google/protobuf/duration.proto"
// Names for google.protobuf.Duration.
const (
Duration_message_name protoreflect.Name = "Duration"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_empty_proto = "google/protobuf/empty.proto"
// Names for google.protobuf.Empty.
const (
Empty_message_name protoreflect.Name = "Empty"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_field_mask_proto = "google/protobuf/field_mask.proto"
// Names for google.protobuf.FieldMask.
const (
FieldMask_message_name protoreflect.Name = "FieldMask"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_source_context_proto = "google/protobuf/source_context.proto"
// Names for google.protobuf.SourceContext.
const (
SourceContext_message_name protoreflect.Name = "SourceContext"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_struct_proto = "google/protobuf/struct.proto"
// Full and short names for google.protobuf.NullValue.
const (
NullValue_enum_fullname = "google.protobuf.NullValue"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_timestamp_proto = "google/protobuf/timestamp.proto"
// Names for google.protobuf.Timestamp.
const (
Timestamp_message_name protoreflect.Name = "Timestamp"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_type_proto = "google/protobuf/type.proto"
// Full and short names for google.protobuf.Syntax.
const (
Syntax_enum_fullname = "google.protobuf.Syntax"

View File

@ -10,6 +10,8 @@ import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
)
const File_google_protobuf_wrappers_proto = "google/protobuf/wrappers.proto"
// Names for google.protobuf.DoubleValue.
const (
DoubleValue_message_name protoreflect.Name = "DoubleValue"

View File

@ -31,6 +31,91 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/any.proto
// Package anypb contains generated types for google/protobuf/any.proto.
//
// The Any message is a dynamic representation of any other message value.
// It is functionally a tuple of the full name of the remote message type and
// the serialized bytes of the remote message value.
//
//
// Constructing an Any
//
// An Any message containing another message value is constructed using New:
//
// any, err := anypb.New(m)
// if err != nil {
// ... // handle error
// }
// ... // make use of any
//
//
// Unmarshaling an Any
//
// With a populated Any message, the underlying message can be serialized into
// a remote concrete message value in a few ways.
//
// If the exact concrete type is known, then a new (or pre-existing) instance
// of that message can be passed to the UnmarshalTo method:
//
// m := new(foopb.MyMessage)
// if err := any.UnmarshalTo(m); err != nil {
// ... // handle error
// }
// ... // make use of m
//
// If the exact concrete type is not known, then the UnmarshalNew method can be
// used to unmarshal the contents into a new instance of the remote message type:
//
// m, err := any.UnmarshalNew()
// if err != nil {
// ... // handle error
// }
// ... // make use of m
//
// UnmarshalNew uses the global type registry to resolve the message type and
// construct a new instance of that message to unmarshal into. In order for a
// message type to appear in the global registry, the Go type representing that
// protobuf message type must be linked into the Go binary. For messages
// generated by protoc-gen-go, this is achieved through an import of the
// generated Go package representing a .proto file.
//
// A common pattern with UnmarshalNew is to use a type switch with the resulting
// proto.Message value:
//
// switch m := m.(type) {
// case *foopb.MyMessage:
// ... // make use of m as a *foopb.MyMessage
// case *barpb.OtherMessage:
// ... // make use of m as a *barpb.OtherMessage
// case *bazpb.SomeMessage:
// ... // make use of m as a *bazpb.SomeMessage
// }
//
// This pattern ensures that the generated packages containing the message types
// listed in the case clauses are linked into the Go binary and therefore also
// registered in the global registry.
//
//
// Type checking an Any
//
// In order to type check whether an Any message represents some other message,
// then use the MessageIs method:
//
// if any.MessageIs((*foopb.MyMessage)(nil)) {
// ... // make use of any, knowing that it contains a foopb.MyMessage
// }
//
// The MessageIs method can also be used with an allocated instance of the target
// message type if the intention is to unmarshal into it if the type matches:
//
// m := new(foopb.MyMessage)
// if any.MessageIs(m) {
// if err := any.UnmarshalTo(m); err != nil {
// ... // handle error
// }
// ... // make use of m
// }
//
package anypb
import (

View File

@ -31,6 +31,49 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/duration.proto
// Package durationpb contains generated types for google/protobuf/duration.proto.
//
// The Duration message represents a signed span of time.
//
//
// Conversion to a Go Duration
//
// The AsDuration method can be used to convert a Duration message to a
// standard Go time.Duration value:
//
// d := dur.AsDuration()
// ... // make use of d as a time.Duration
//
// Converting to a time.Duration is a common operation so that the extensive
// set of time-based operations provided by the time package can be leveraged.
// See https://golang.org/pkg/time for more information.
//
// The AsDuration method performs the conversion on a best-effort basis.
// Durations with denormal values (e.g., nanoseconds beyond -99999999 and
// +99999999, inclusive; or seconds and nanoseconds with opposite signs)
// are normalized during the conversion to a time.Duration. To manually check for
// invalid Duration per the documented limitations in duration.proto,
// additionally call the CheckValid method:
//
// if err := dur.CheckValid(); err != nil {
// ... // handle error
// }
//
// Note that the documented limitations in duration.proto does not protect a
// Duration from overflowing the representable range of a time.Duration in Go.
// The AsDuration method uses saturation arithmetic such that an overflow clamps
// the resulting value to the closest representable value (e.g., math.MaxInt64
// for positive overflow and math.MinInt64 for negative overflow).
//
//
// Conversion from a Go Duration
//
// The durationpb.New function can be used to construct a Duration message
// from a standard Go time.Duration value:
//
// dur := durationpb.New(d)
// ... // make use of d as a *durationpb.Duration
//
package durationpb
import (

View File

@ -31,6 +31,50 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/field_mask.proto
// Package fieldmaskpb contains generated types for google/protobuf/field_mask.proto.
//
// The FieldMask message represents a set of symbolic field paths.
// The paths are specific to some target message type,
// which is not stored within the FieldMask message itself.
//
//
// Constructing a FieldMask
//
// The New function is used construct a FieldMask:
//
// var messageType *descriptorpb.DescriptorProto
// fm, err := fieldmaskpb.New(messageType, "field.name", "field.number")
// if err != nil {
// ... // handle error
// }
// ... // make use of fm
//
// The "field.name" and "field.number" paths are valid paths according to the
// google.protobuf.DescriptorProto message. Use of a path that does not correlate
// to valid fields reachable from DescriptorProto would result in an error.
//
// Once a FieldMask message has been constructed,
// the Append method can be used to insert additional paths to the path set:
//
// var messageType *descriptorpb.DescriptorProto
// if err := fm.Append(messageType, "options"); err != nil {
// ... // handle error
// }
//
//
// Type checking a FieldMask
//
// In order to verify that a FieldMask represents a set of fields that are
// reachable from some target message type, use the IsValid method:
//
// var messageType *descriptorpb.DescriptorProto
// if fm.IsValid(messageType) {
// ... // make use of fm
// }
//
// IsValid needs to be passed the target message type as an input since the
// FieldMask message itself does not store the message type that the set of paths
// are for.
package fieldmaskpb
import (

View File

@ -31,6 +31,94 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/struct.proto
// Package structpb contains generated types for google/protobuf/struct.proto.
//
// The messages (i.e., Value, Struct, and ListValue) defined in struct.proto are
// used to represent arbitrary JSON. The Value message represents a JSON value,
// the Struct message represents a JSON object, and the ListValue message
// represents a JSON array. See https://json.org for more information.
//
// The Value, Struct, and ListValue types have generated MarshalJSON and
// UnmarshalJSON methods such that they serialize JSON equivalent to what the
// messages themselves represent. Use of these types with the
// "google.golang.org/protobuf/encoding/protojson" package
// ensures that they will be serialized as their JSON equivalent.
//
//
// Conversion to and from a Go interface
//
// The standard Go "encoding/json" package has functionality to serialize
// arbitrary types to a large degree. The Value.AsInterface, Struct.AsMap, and
// ListValue.AsSlice methods can convert the protobuf message representation into
// a form represented by interface{}, map[string]interface{}, and []interface{}.
// This form can be used with other packages that operate on such data structures
// and also directly with the standard json package.
//
// In order to convert the interface{}, map[string]interface{}, and []interface{}
// forms back as Value, Struct, and ListValue messages, use the NewStruct,
// NewList, and NewValue constructor functions.
//
//
// Example usage
//
// Consider the following example JSON object:
//
// {
// "firstName": "John",
// "lastName": "Smith",
// "isAlive": true,
// "age": 27,
// "address": {
// "streetAddress": "21 2nd Street",
// "city": "New York",
// "state": "NY",
// "postalCode": "10021-3100"
// },
// "phoneNumbers": [
// {
// "type": "home",
// "number": "212 555-1234"
// },
// {
// "type": "office",
// "number": "646 555-4567"
// }
// ],
// "children": [],
// "spouse": null
// }
//
// To construct a Value message representing the above JSON object:
//
// m, err := structpb.NewValue(map[string]interface{}{
// "firstName": "John",
// "lastName": "Smith",
// "isAlive": true,
// "age": 27,
// "address": map[string]interface{}{
// "streetAddress": "21 2nd Street",
// "city": "New York",
// "state": "NY",
// "postalCode": "10021-3100",
// },
// "phoneNumbers": []interface{}{
// map[string]interface{}{
// "type": "home",
// "number": "212 555-1234",
// },
// map[string]interface{}{
// "type": "office",
// "number": "646 555-4567",
// },
// },
// "children": []interface{}{},
// "spouse": nil,
// })
// if err != nil {
// ... // handle error
// }
// ... // make use of m as a *structpb.Value
//
package structpb
import (

View File

@ -31,6 +31,48 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/timestamp.proto
// Package timestamppb contains generated types for google/protobuf/timestamp.proto.
//
// The Timestamp message represents a timestamp,
// an instant in time since the Unix epoch (January 1st, 1970).
//
//
// Conversion to a Go Time
//
// The AsTime method can be used to convert a Timestamp message to a
// standard Go time.Time value in UTC:
//
// t := ts.AsTime()
// ... // make use of t as a time.Time
//
// Converting to a time.Time is a common operation so that the extensive
// set of time-based operations provided by the time package can be leveraged.
// See https://golang.org/pkg/time for more information.
//
// The AsTime method performs the conversion on a best-effort basis. Timestamps
// with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive)
// are normalized during the conversion to a time.Time. To manually check for
// invalid Timestamps per the documented limitations in timestamp.proto,
// additionally call the CheckValid method:
//
// if err := ts.CheckValid(); err != nil {
// ... // handle error
// }
//
//
// Conversion from a Go Time
//
// The timestamppb.New function can be used to construct a Timestamp message
// from a standard Go time.Time value:
//
// ts := timestamppb.New(t)
// ... // make use of ts as a *timestamppb.Timestamp
//
// In order to construct a Timestamp representing the current time, use Now:
//
// ts := timestamppb.Now()
// ... // make use of ts as a *timestamppb.Timestamp
//
package timestamppb
import (