encoding/prototext: add MarshalOptions.EmitUnknown
This changes text marshaling to avoid unknown fields by default
and instead adds an option so that unknown fields be emitted.
This ensures that the default marshal/unknown can round-trip.
Change-Id: I85c84ba6ab7916d538ec6bfd4e9d399a8fcba14e
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/195778
Reviewed-by: Herbie Ong <herbie@google.com>
diff --git a/encoding/prototext/encode.go b/encoding/prototext/encode.go
index 8856dae..eef63d3 100644
--- a/encoding/prototext/encode.go
+++ b/encoding/prototext/encode.go
@@ -38,6 +38,11 @@
// Marshal will return error if there are any missing required fields.
AllowPartial bool
+ // EmitUnknown specifies whether to emit unknown fields in the output.
+ // If specified, the unmarshaler may be unable to parse the output.
+ // The default is to exclude unknown fields.
+ EmitUnknown bool
+
// If Indent is a non-empty string, it causes entries for a Message to be
// preceded by the indent and trailed by a newline. Indent can only be
// composed of space or tab characters.
@@ -123,8 +128,9 @@
}
// Handle unknown fields.
- // TODO: Provide option to exclude or include unknown fields.
- msgFields = appendUnknown(msgFields, m.GetUnknown())
+ if o.EmitUnknown {
+ msgFields = appendUnknown(msgFields, m.GetUnknown())
+ }
return text.ValueOf(msgFields), nil
}