Skip to content

Commit 14c932c

Browse files
author
Evsyukov Denis
committed
refactor: implement deepCopy function to prevent input data mutations in apply.go
Signed-off-by: Evsyukov Denis <denis.evsyukov@flant.com>
1 parent 319cb26 commit 14c932c

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

pkg/filter/jq/apply.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package jq
22

33
import (
4+
"encoding/json"
45
"errors"
56
"maps"
67

@@ -25,8 +26,7 @@ func (f *Filter) ApplyFilter(jqFilter string, data map[string]any) (map[string]a
2526
}
2627

2728
// gojs will normalize numbers in the input data, we should create new map for prevent changes in input data
28-
workData := make(map[string]any)
29-
maps.Copy(workData, data)
29+
workData := deepCopy(data)
3030
iter := query.Run(workData)
3131
result := make(map[string]any)
3232
for {
@@ -52,3 +52,10 @@ func (f *Filter) ApplyFilter(jqFilter string, data map[string]any) (map[string]a
5252
func (f *Filter) FilterInfo() string {
5353
return "jqFilter implementation: using itchyny/gojq"
5454
}
55+
56+
func deepCopy(input map[string]any) map[string]any {
57+
data, _ := json.Marshal(input)
58+
var output map[string]any
59+
_ = json.Unmarshal(data, &output)
60+
return output
61+
}

pkg/filter/jq/apply_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,26 @@ func Test_ApplyFilter_InvalidJson(t *testing.T) {
7272
g.Expect(err).Should(BeNil())
7373
g.Expect(result).ShouldNot(BeNil())
7474
}
75+
76+
func Test_deepCopy(t *testing.T) {
77+
g := NewWithT(t)
78+
79+
original := map[string]any{
80+
"name": "John",
81+
"age": 30.0,
82+
"address": map[string]any{
83+
"city": "New York",
84+
"state": "NY",
85+
},
86+
}
87+
88+
cp := deepCopy(original)
89+
90+
g.Expect(cp).Should(Equal(original))
91+
92+
cp["name"] = "Jane"
93+
cp["address"].(map[string]any)["city"] = "Los Angeles"
94+
95+
g.Expect(original["name"]).Should(Equal("John"))
96+
g.Expect(original["address"].(map[string]any)["city"]).Should(Equal("New York"))
97+
}

0 commit comments

Comments
 (0)