From a3b9f399e142ea750718633a68ad249e29dcd171 Mon Sep 17 00:00:00 2001 From: Leon Mika Date: Fri, 24 Jan 2025 13:25:28 +1100 Subject: [PATCH] Added list:add --- ucl/builtins/lists.go | 35 +++++++++++++++++++++++++++++++++++ ucl/builtins/lists_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 ucl/builtins/lists.go create mode 100644 ucl/builtins/lists_test.go diff --git a/ucl/builtins/lists.go b/ucl/builtins/lists.go new file mode 100644 index 0000000..be3259d --- /dev/null +++ b/ucl/builtins/lists.go @@ -0,0 +1,35 @@ +package builtins + +import ( + "context" + "ucl.lmika.dev/ucl" +) + +func Lists() ucl.Module { + return ucl.Module{ + Name: "lists", + Builtins: map[string]ucl.BuiltinHandler{ + "add": listAdd, + }, + } +} + +func listAdd(ctx context.Context, args ucl.CallArgs) (any, error) { + var target ucl.ModListable + + if err := args.Bind(&target); err != nil { + return nil, err + } + + for args.NArgs() > 0 { + var obj ucl.Object + if err := args.Bind(&obj); err != nil { + return nil, err + } + if err := target.Insert(-1, obj); err != nil { + return nil, err + } + } + + return target, nil +} diff --git a/ucl/builtins/lists_test.go b/ucl/builtins/lists_test.go new file mode 100644 index 0000000..8d8b909 --- /dev/null +++ b/ucl/builtins/lists_test.go @@ -0,0 +1,37 @@ +package builtins_test + +import ( + "context" + "github.com/stretchr/testify/assert" + "testing" + "ucl.lmika.dev/ucl" + "ucl.lmika.dev/ucl/builtins" +) + +func TestLists_Add(t *testing.T) { + tests := []struct { + desc string + eval string + want any + wantErr bool + }{ + {desc: "list add 1", eval: `lists:add [1 2 3] 4`, want: []any{1, 2, 3, 4}}, + {desc: "list add 2", eval: `lists:add [1 2 3] 4 5`, want: []any{1, 2, 3, 4, 5}}, + {desc: "list add 3", eval: `lists:add [1 2 3]`, want: []any{1, 2, 3}}, + } + + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + inst := ucl.New( + ucl.WithModule(builtins.Lists()), + ) + res, err := inst.Eval(context.Background(), tt.eval) + if tt.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.Equal(t, tt.want, res) + } + }) + } +}