Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions internal/sidekick/swift/annotate_field.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand All @@ -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
Expand Down
88 changes: 88 additions & 0 deletions internal/sidekick/swift/annotate_field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -278,6 +280,7 @@ func TestAnnotateField_Recursive(t *testing.T) {
BaseFieldType: "GoogleWKT.WKTRecursive<Node>",
Recursive: true,
Decoding: DecodingOptional,
Encoding: EncodingOptional,
ProtoFieldName: "childNode",
ProtoFieldNamePascal: "ChildNode",
PrimitiveFieldType: "Node",
Expand All @@ -293,6 +296,7 @@ func TestAnnotateField_Recursive(t *testing.T) {
BaseFieldType: "GoogleWKT.WKTRecursive<Node>",
Recursive: true,
Decoding: DecodingOptional,
Encoding: EncodingOptional,
ProtoFieldName: "childNode",
ProtoFieldNamePascal: "ChildNode",
PrimitiveFieldType: "Node",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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<int32, string>", api.TypezInt32, api.TypezString).
WithID("$map<int32, string>")
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)
}
})
}
}
122 changes: 122 additions & 0 deletions internal/sidekick/swift/generate_field_swift_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, bytes>",
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)
}
}
10 changes: 5 additions & 5 deletions internal/sidekick/swift/generate_oneof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 7 additions & 3 deletions internal/sidekick/swift/templates/common/field_encode.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/sidekick/swift/templates/common/message.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
}
}
Expand Down
Loading