From 8c01b0f28967c6bce0b34fa5ad0d742730bed224 Mon Sep 17 00:00:00 2001 From: Carlos O'Ryan Date: Fri, 20 Nov 2026 20:33:18 +0000 Subject: [PATCH] fix(sidekick/swift): omit default enum values Update the Swift code generator to support Proto3 default value omission in _ProtoJSONEncoder while preserving explicit presence for optional and oneof fields. Non-optional singular enum fields are now guarded so default enum values are omitted during encoding. Oneof variants and optional singular Discovery URL-safe byte fields now use encodeIfPresent so explicit zero and empty values remain present in the serialized JSON. --- internal/sidekick/swift/annotate_field.go | 21 +++ .../sidekick/swift/annotate_field_test.go | 88 +++++++++++++ .../swift/generate_field_swift_test.go | 122 ++++++++++++++++++ .../sidekick/swift/generate_oneof_test.go | 10 +- .../templates/common/field_encode.gotmpl | 10 +- .../common/field_encode_url_safe.gotmpl | 2 +- .../swift/templates/common/message.gotmpl | 2 +- 7 files changed, 245 insertions(+), 10 deletions(-) diff --git a/internal/sidekick/swift/annotate_field.go b/internal/sidekick/swift/annotate_field.go index 0970376e5d..48d5318e80 100644 --- a/internal/sidekick/swift/annotate_field.go +++ b/internal/sidekick/swift/annotate_field.go @@ -131,6 +131,13 @@ const ( // EncodingSimple means that the field is encoded using a simple `.encode()` call. EncodingSimple EncodingStyle = iota + // EncodingOptional means that the field is encoded using an `.encodeIfPresent()` call. + EncodingOptional + + // EncodingSingularEnum means that the field is a non-optional singular enum + // encoded only when its value differs from the default value. + EncodingSingularEnum + // EncodingMapCustomKey means that the field is a map, with non-string keys // and requires mapping through a string-keyed temporary. EncodingMapCustomKey @@ -167,6 +174,16 @@ func (a *fieldAnnotations) IsEncodingSimple() bool { return a.Encoding == EncodingSimple } +// IsEncodingOptional is used in templates to check for optional encoding. +func (a *fieldAnnotations) IsEncodingOptional() bool { + return a.Encoding == EncodingOptional +} + +// IsEncodingSingularEnum is used in templates to check for non-optional singular enum encoding. +func (a *fieldAnnotations) IsEncodingSingularEnum() bool { + return a.Encoding == EncodingSingularEnum +} + // IsEncodingMapCustomKey is used in templates to check for custom-key map encoding. func (a *fieldAnnotations) IsEncodingMapCustomKey() bool { return a.Encoding == EncodingMapCustomKey @@ -213,6 +230,7 @@ func (c *codec) annotateField(field *api.Field, model *modelAnnotations) (*field annotations.BaseFieldType = fmt.Sprintf("%s.WKTRecursive<%s>", wellKnownSwiftPackage, parts.Base) annotations.FieldType = annotations.BaseFieldType + "?" annotations.Decoding = DecodingOptional + annotations.Encoding = EncodingOptional } if field.Typez() == api.TypezMap { if !annotations.IsStringKeyed() { @@ -236,6 +254,9 @@ func (c *codec) annotateField(field *api.Field, model *modelAnnotations) (*field } if field.Optional() { annotations.Decoding = DecodingOptional + annotations.Encoding = EncodingOptional + } else if field.Singular() && field.IsEnum() && !field.IsOneOf() { + annotations.Encoding = EncodingSingularEnum } if isExplicitNullField(field) { annotations.Decoding = DecodingExplicitNull diff --git a/internal/sidekick/swift/annotate_field_test.go b/internal/sidekick/swift/annotate_field_test.go index 965b4578bc..26b6fe7c65 100644 --- a/internal/sidekick/swift/annotate_field_test.go +++ b/internal/sidekick/swift/annotate_field_test.go @@ -51,6 +51,7 @@ func TestAnnotateField(t *testing.T) { FieldType: "Swift.String?", BaseFieldType: "Swift.String", Decoding: DecodingOptional, + Encoding: EncodingOptional, ProtoFieldName: "secretPayload", ProtoFieldNamePascal: "SecretPayload", PrimitiveFieldType: "Swift.String", @@ -135,6 +136,7 @@ func TestAnnotateField_Discovery(t *testing.T) { BaseFieldType: "Foundation.Data", UrlSafeValue: true, Decoding: DecodingOptional, + Encoding: EncodingOptional, ProtoFieldName: "name", ProtoFieldNamePascal: "Name", PrimitiveFieldType: "Foundation.Data", @@ -278,6 +280,7 @@ func TestAnnotateField_Recursive(t *testing.T) { BaseFieldType: "GoogleWKT.WKTRecursive", Recursive: true, Decoding: DecodingOptional, + Encoding: EncodingOptional, ProtoFieldName: "childNode", ProtoFieldNamePascal: "ChildNode", PrimitiveFieldType: "Node", @@ -293,6 +296,7 @@ func TestAnnotateField_Recursive(t *testing.T) { BaseFieldType: "GoogleWKT.WKTRecursive", Recursive: true, Decoding: DecodingOptional, + Encoding: EncodingOptional, ProtoFieldName: "childNode", ProtoFieldNamePascal: "ChildNode", PrimitiveFieldType: "Node", @@ -397,6 +401,7 @@ func TestAnnotateField_ExplicitNull(t *testing.T) { FieldType: "GoogleWKT.WKTValue?", BaseFieldType: "GoogleWKT.WKTValue", Decoding: DecodingExplicitNull, + Encoding: EncodingOptional, ProtoFieldName: "valueField", ProtoFieldNamePascal: "ValueField", PrimitiveFieldType: "GoogleWKT.WKTValue", @@ -468,6 +473,7 @@ func TestAnnotateField_ExplicitNull(t *testing.T) { FieldType: "GoogleWKT.WKTNullValue", BaseFieldType: "GoogleWKT.WKTNullValue", Decoding: DecodingExplicitNull, + Encoding: EncodingSingularEnum, ProtoFieldName: "nullField", ProtoFieldNamePascal: "NullField", PrimitiveFieldType: "GoogleWKT.WKTNullValue", @@ -485,6 +491,7 @@ func TestAnnotateField_ExplicitNull(t *testing.T) { FieldType: "GoogleWKT.WKTNullValue?", BaseFieldType: "GoogleWKT.WKTNullValue", Decoding: DecodingExplicitNull, + Encoding: EncodingOptional, ProtoFieldName: "nullField", ProtoFieldNamePascal: "NullField", PrimitiveFieldType: "GoogleWKT.WKTNullValue", @@ -557,6 +564,7 @@ func TestAnnotateField_ExplicitNull(t *testing.T) { FieldType: "GoogleWKT.WKTStruct?", BaseFieldType: "GoogleWKT.WKTStruct", Decoding: DecodingOptional, + Encoding: EncodingOptional, ProtoFieldName: "structField", ProtoFieldNamePascal: "StructField", PrimitiveFieldType: "GoogleWKT.WKTStruct", @@ -603,3 +611,83 @@ func TestAnnotateField_ExplicitNull(t *testing.T) { }) } } + +func TestAnnotateField_Encoding(t *testing.T) { + for _, test := range []struct { + name string + makeField func(statusEnum *api.Enum, intMap *api.Map) *api.Field + isOneOf bool + want EncodingStyle + }{ + { + name: "singular scalar", + makeField: func(_ *api.Enum, _ *api.Map) *api.Field { + return api.NewTestField("name").WithType(api.TypezString) + }, + want: EncodingSimple, + }, + { + name: "singular enum", + makeField: func(statusEnum *api.Enum, _ *api.Map) *api.Field { + return api.NewTestField("status").WithEnumType(statusEnum) + }, + want: EncodingSingularEnum, + }, + { + name: "optional enum", + makeField: func(statusEnum *api.Enum, _ *api.Map) *api.Field { + return api.NewTestField("status").WithEnumType(statusEnum).WithOptional() + }, + want: EncodingOptional, + }, + { + name: "repeated enum", + makeField: func(statusEnum *api.Enum, _ *api.Map) *api.Field { + return api.NewTestField("status").WithEnumType(statusEnum).WithRepeated() + }, + want: EncodingSimple, + }, + { + name: "oneof enum", + makeField: func(statusEnum *api.Enum, _ *api.Map) *api.Field { + return api.NewTestField("status").WithEnumType(statusEnum) + }, + isOneOf: true, + want: EncodingSimple, + }, + { + name: "custom key map", + makeField: func(_ *api.Enum, intMap *api.Map) *api.Field { + return api.NewTestField("labels").WithMapType(intMap) + }, + want: EncodingMapCustomKey, + }, + } { + t.Run(test.name, func(t *testing.T) { + statusEnum := api.NewTestEnum("Status").WithValues( + api.NewTestEnumValue("STATUS_UNSPECIFIED", 0), + api.NewTestEnumValue("STATUS_ACTIVE", 1), + ) + intMap := api.NewTestMap("map", api.TypezInt32, api.TypezString). + WithID("$map") + field := test.makeField(statusEnum, intMap) + msg := api.NewTestMessage("Message") + if test.isOneOf { + msg.WithOneOfs(api.NewTestOneOf("choice").WithFields(field)) + } else { + msg.WithFields(field) + } + model := api.NewTestAPI([]*api.Message{msg}, []*api.Enum{statusEnum}, nil). + WithMaps(intMap) + codec := newTestCodec(t, model, nil) + if err := codec.annotateModel(); err != nil { + t.Fatal(err) + } + + got := field.Codec().(*fieldAnnotations).Encoding + if diff := cmp.Diff(test.want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } + }) + } +} diff --git a/internal/sidekick/swift/generate_field_swift_test.go b/internal/sidekick/swift/generate_field_swift_test.go index 29941302b5..97449d72c3 100644 --- a/internal/sidekick/swift/generate_field_swift_test.go +++ b/internal/sidekick/swift/generate_field_swift_test.go @@ -221,3 +221,125 @@ func TestGenerateField_ExplicitNull(t *testing.T) { t.Errorf("mismatch (-want +got):\n%s", diff) } } + +func TestGenerateField_EncodeToEncoder(t *testing.T) { + outDir := t.TempDir() + + statusEnum := api.NewTestEnum("Status"). + WithPackage("google.cloud.test.v1"). + WithValues( + api.NewTestEnumValue("STATUS_UNSPECIFIED", 0), + api.NewTestEnumValue("STATUS_ACTIVE", 1), + ) + + msg := api.NewTestMessage("EncodeMessage"). + WithPackage("google.cloud.test.v1") + msg.WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("count").WithType(api.TypezInt32), + api.NewTestField("optional_count").WithType(api.TypezInt32).WithOptional(), + api.NewTestField("status").WithEnumType(statusEnum), + api.NewTestField("optional_status").WithEnumType(statusEnum).WithOptional(), + api.NewTestField("repeated_status").WithEnumType(statusEnum).WithRepeated(), + api.NewTestField("next").WithMessageType(msg).WithRecursive(), + ) + + model := api.NewTestAPI([]*api.Message{msg}, []*api.Enum{statusEnum}, nil) + library := &config.Library{ + Swift: swiftConfig(t, nil), + } + if err := Generate(t.Context(), model, outDir, library, nil); err != nil { + t.Fatal(err) + } + + filename := filepath.Join(outDir, "Sources", "GoogleCloudTestV1", "EncodeMessage.swift") + content, err := os.ReadFile(filename) + if err != nil { + t.Fatal(err) + } + + got := extractBlock(t, string(content), " public func encode(to encoder: any Encoder) throws {", "\n }") + want := ` public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.name, forKey: .name) + try container.encode(self.count, forKey: .count) + try container.encodeIfPresent(self.optionalCount, forKey: .optionalCount) + if self.status != Status() { + try container.encode(self.status, forKey: .status) + } + try container.encodeIfPresent(self.optionalStatus, forKey: .optionalStatus) + try container.encode(self.repeatedStatus, forKey: .repeatedStatus) + try container.encodeIfPresent(self.next, forKey: .next) + for (key, value) in self._unknownFields.json { + try container.encode(value, forKey: CodingKeys(stringValue: key)) + } + }` + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } +} + +func TestGenerateField_EncodeUrlSafe(t *testing.T) { + outDir := t.TempDir() + + mapBytes := api.NewTestMapWithFields( + "$map", + api.NewTestField("key").WithType(api.TypezString), + api.NewTestField("value").WithType(api.TypezBytes), + ) + + msg := api.NewTestMessage("UrlSafeMessage"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("singular").WithType(api.TypezBytes), + api.NewTestField("optional").WithType(api.TypezBytes).WithOptional(), + api.NewTestField("repeated").WithType(api.TypezBytes).WithRepeated(), + api.NewTestField("map").WithMapType(mapBytes), + ) + + model := api.NewTestAPI([]*api.Message{msg}, nil, nil). + WithMaps(mapBytes) + library := &config.Library{ + SpecificationFormat: config.SpecDiscovery, + Swift: swiftConfig(t, nil), + } + if err := Generate(t.Context(), model, outDir, library, nil); err != nil { + t.Fatal(err) + } + + filename := filepath.Join(outDir, "Sources", "GoogleCloudTestV1", "UrlSafeMessage.swift") + content, err := os.ReadFile(filename) + if err != nil { + t.Fatal(err) + } + + got := extractBlock(t, string(content), " public func encode(to encoder: any Encoder) throws {", "\n }") + want := ` public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode( + GoogleWKT._DiscoveryBase64.encode(singular), forKey: .singular + ) + if let v = ` + "`optional`" + ` { + try container.encodeIfPresent( + GoogleWKT._DiscoveryBase64.encode(v), forKey: .` + "`optional`" + ` + ) + } + try container.encode( + repeated.map { GoogleWKT._DiscoveryBase64.encode($0) }, forKey: .repeated + ) + do { + let transformed = self.map.mapValues { + GoogleWKT._DiscoveryBase64.encode($0) + } + try container.encode(transformed, forKey: .map) + } + for (key, value) in self._unknownFields.json { + try container.encode(value, forKey: CodingKeys(stringValue: key)) + } + }` + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } +} diff --git a/internal/sidekick/swift/generate_oneof_test.go b/internal/sidekick/swift/generate_oneof_test.go index 40bcc81478..e455300c87 100644 --- a/internal/sidekick/swift/generate_oneof_test.go +++ b/internal/sidekick/swift/generate_oneof_test.go @@ -178,9 +178,9 @@ func TestGenerateOneOf(t *testing.T) { if let choice = self.choice { switch choice { case .stringField(let value): - try container.encode(value, forKey: .stringField) + try container.encodeIfPresent(value, forKey: .stringField) case .messageField(let value): - try container.encode(value, forKey: .messageField) + try container.encodeIfPresent(value, forKey: .messageField) } } for (key, value) in self._unknownFields.json { @@ -344,11 +344,11 @@ func TestGenerateOneOfWithKeyword(t *testing.T) { if let choice = self.` + "`in`" + ` { switch choice { case .header(let value): - try container.encode(value, forKey: .header) + try container.encodeIfPresent(value, forKey: .header) case .query(let value): - try container.encode(value, forKey: .query) + try container.encodeIfPresent(value, forKey: .query) case .cookie(let value): - try container.encode(value, forKey: .cookie) + try container.encodeIfPresent(value, forKey: .cookie) } } for (key, value) in self._unknownFields.json { diff --git a/internal/sidekick/swift/templates/common/field_encode.gotmpl b/internal/sidekick/swift/templates/common/field_encode.gotmpl index 854e6b2188..bc058f6d14 100644 --- a/internal/sidekick/swift/templates/common/field_encode.gotmpl +++ b/internal/sidekick/swift/templates/common/field_encode.gotmpl @@ -14,11 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */}} {{- if .Codec.IsEncodingSimple }} -{{- if .Optional }} -try container.encodeIfPresent(self.{{ .Codec.Name }}, forKey: .{{ .Codec.Name }}) -{{- else }} try container.encode(self.{{ .Codec.Name }}, forKey: .{{ .Codec.Name }}) {{- end }} +{{- if .Codec.IsEncodingOptional }} +try container.encodeIfPresent(self.{{ .Codec.Name }}, forKey: .{{ .Codec.Name }}) +{{- end }} +{{- if .Codec.IsEncodingSingularEnum }} +if self.{{ .Codec.Name }} != {{ .Codec.FieldType }}() { + try container.encode(self.{{ .Codec.Name }}, forKey: .{{ .Codec.Name }}) +} {{- end }} {{- if .Codec.IsEncodingMapCustomKey }} do { diff --git a/internal/sidekick/swift/templates/common/field_encode_url_safe.gotmpl b/internal/sidekick/swift/templates/common/field_encode_url_safe.gotmpl index 70282a3ff1..50a7266ac6 100644 --- a/internal/sidekick/swift/templates/common/field_encode_url_safe.gotmpl +++ b/internal/sidekick/swift/templates/common/field_encode_url_safe.gotmpl @@ -16,7 +16,7 @@ limitations under the License. {{- if .Singular }} {{- if .Optional }} if let v = {{ .Codec.Name }} { - try container.encode( + try container.encodeIfPresent( {{ .Codec.Model.WktPackage }}._DiscoveryBase64.encode(v), forKey: .{{ .Codec.Name }} ) } diff --git a/internal/sidekick/swift/templates/common/message.gotmpl b/internal/sidekick/swift/templates/common/message.gotmpl index a4fd94a7da..8a486072e4 100644 --- a/internal/sidekick/swift/templates/common/message.gotmpl +++ b/internal/sidekick/swift/templates/common/message.gotmpl @@ -162,7 +162,7 @@ public struct {{ .Codec.Name }}: Codable, Equatable, {{ .Codec.Model.WktPackage switch choice { {{- range .Fields }} case .{{ .Codec.Name }}(let value): - try container.encode(value, forKey: .{{ .Codec.Name }}) + try container.encodeIfPresent(value, forKey: .{{ .Codec.Name }}) {{- end }} } }