Skip to content

Commit

Permalink
feat: support dup key conversion for prototext to kcl (#326)
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy authored Jun 11, 2024
1 parent cf3d8ab commit eb605aa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
3 changes: 1 addition & 2 deletions pkg/tools/gen/genkcl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,7 @@ func TestGenKclFromTextProto(t *testing.T) {
{Key: "int3", Value: []interface{}{1, 2}},
{Key: "string1", Value: []interface{}{"a", "b"}},
{Key: "float1", Value: []interface{}{100.0, 1.0, 0.0}},
{Key: "map", Value: []data{{Key: "foo", Value: 2}}},
{Key: "map", Value: []data{{Key: "bar", Value: 3}}},
{Key: "map", Value: []data{{Key: "foo", Value: 2}, {Key: "bar", Value: 3}}},
},
}
assert2.Equal(t, expected, got)
Expand Down
37 changes: 31 additions & 6 deletions pkg/tools/gen/genkcl_textproto.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ func (d *TextProtoGenerator) GenFromSchemaFile(filename string, src any, schemaF

func (d *TextProtoGenerator) genProperties(ty *kcl.KclType, nodes []*pbast.Node) (*config, error) {
var values []data
for _, n := range nodes {
var complexDataMapping map[string]int = make(map[string]int)
for i, n := range nodes {
var comments []*ast.Comment
if n.Values == nil && n.Children == nil {
if comments = addComments(n.PreComments...); comments != nil {
Expand All @@ -79,11 +80,35 @@ func (d *TextProtoGenerator) genProperties(ty *kcl.KclType, nodes []*pbast.Node)
if err != nil {
return nil, err
}
values = append(values, data{
Key: n.Name,
Value: value,
Comments: comments,
})
// Handling duplicate keys
if existingIndex, exists := complexDataMapping[n.Name]; exists {
v := values[existingIndex].Value
switch v := v.(type) {
// Schema
case config:
config := value.(config)
v.Data = append(v.Data, config.Data...)
values[existingIndex].Value = v
// Dict
case []data:
entries := value.([]data)
v = append(v, entries...)
values[existingIndex].Value = v
case []any:
data := value.([]any)
v = append(v, data...)
values[existingIndex].Value = v
default:
return nil, d.errorf(n, "duplicate key %s for value %v", n.Name, value)
}
} else {
complexDataMapping[n.Name] = i
values = append(values, data{
Key: n.Name,
Value: value,
Comments: comments,
})
}
}
return &config{
Name: ty.SchemaName,
Expand Down

0 comments on commit eb605aa

Please sign in to comment.