Quellcode durchsuchen

encoding/jsonpb: change MarshalOptions.Compact option to Indent

This makes it consistent with jsonpb.MarshalOptions. This does change
the default to be in compact form.

Change-Id: I1b07f06f282c019b30f3f1cbb43f6c8cba18f385
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/168405
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
Herbie Ong vor 6 Jahren
Ursprung
Commit
3a385917c0
4 geänderte Dateien mit 9 neuen und 11 gelöschten Zeilen
  1. 5 8
      encoding/textpb/encode.go
  2. 2 1
      encoding/textpb/encode_test.go
  3. 1 1
      internal/impl/export.go
  4. 1 1
      protogen/protogen.go

+ 5 - 8
encoding/textpb/encode.go

@@ -27,8 +27,10 @@ func Marshal(m proto.Message) ([]byte, error) {
 type MarshalOptions struct {
 	pragma.NoUnkeyedLiterals
 
-	// Set Compact to true to have output in a single line with no line breaks.
-	Compact 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.
+	Indent string
 
 	// Resolver is the registry used for type lookups when marshaling out
 	// google.protobuf.Any messages in expanded form. If Resolver is not set,
@@ -49,14 +51,9 @@ func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
 		return nil, err
 	}
 
-	indent := "  "
-	if o.Compact {
-		indent = ""
-	}
 	delims := [2]byte{'{', '}'}
-
 	const outputASCII = false
-	b, err := text.Marshal(v, indent, delims, outputASCII)
+	b, err := text.Marshal(v, o.Indent, delims, outputASCII)
 	if !nerr.Merge(err) {
 		return nil, err
 	}

+ 2 - 1
encoding/textpb/encode_test.go

@@ -1111,7 +1111,8 @@ value: "\x80"
 	for _, tt := range tests {
 		tt := tt
 		t.Run(tt.desc, func(t *testing.T) {
-			t.Parallel()
+			// Use 2-space indentation on all MarshalOptions.
+			tt.mo.Indent = "  "
 			b, err := tt.mo.Marshal(tt.input)
 			if err != nil && !tt.wantErr {
 				t.Errorf("Marshal() returned error: %v\n", err)

+ 1 - 1
internal/impl/export.go

@@ -91,6 +91,6 @@ func (Export) ExtensionTypeOf(d pref.ExtensionDescriptor, t interface{}) pref.Ex
 // MessageStringOf returns the message value as a string,
 // which is the message serialized in the protobuf text format.
 func (Export) MessageStringOf(m pref.ProtoMessage) string {
-	b, _ := textpb.MarshalOptions{Compact: true}.Marshal(m)
+	b, _ := textpb.Marshal(m)
 	return string(b)
 }

+ 1 - 1
protogen/protogen.go

@@ -1110,7 +1110,7 @@ func (g *GeneratedFile) metaFile(content []byte) (string, error) {
 		}
 	}
 
-	b, err := textpb.MarshalOptions{Compact: true}.Marshal(info)
+	b, err := textpb.Marshal(info)
 	if err != nil {
 		return "", err
 	}