Skip to content

Commit 1105f16

Browse files
committed
add marks.RemoveAll
RemoveAll filters marks from a set of cty.PathValueMarks, removing all instances of the remove parameter in all paths. If a path has no remaining marks, it is removed entirely.
1 parent 473e593 commit 1105f16

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

internal/lang/marks/paths.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,28 @@ func PathsWithMark(pvms []cty.PathValueMarks, wantMark any) (withWanted []cty.Pa
4141
return withWanted, withOthers
4242
}
4343

44+
// RemoveAll take a series of PathValueMarks and removes the unwanted mark from
45+
// all paths. Paths with no remaining marks will be removed entirely. The
46+
// PathValuesMarks passed in are not cloned, and RemoveAll will modify the
47+
// original values, so the prior set of marks should not be retained for use.
48+
func RemoveAll(pvms []cty.PathValueMarks, remove any) []cty.PathValueMarks {
49+
if len(pvms) == 0 {
50+
// No-allocations path for the common case where there are no marks at all.
51+
return nil
52+
}
53+
54+
var res []cty.PathValueMarks
55+
56+
for _, pvm := range pvms {
57+
delete(pvm.Marks, remove)
58+
if len(pvm.Marks) > 0 {
59+
res = append(res, pvm)
60+
}
61+
}
62+
63+
return res
64+
}
65+
4466
// MarkPaths transforms the given value by marking each of the given paths
4567
// with the given mark value.
4668
func MarkPaths(val cty.Value, mark any, paths []cty.Path) cty.Value {

internal/lang/marks/paths_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,40 @@ func TestPathsWithMark(t *testing.T) {
5858
}
5959
}
6060

61+
func TestRemoveAll(t *testing.T) {
62+
input := []cty.PathValueMarks{
63+
{
64+
Path: cty.GetAttrPath("sensitive"),
65+
Marks: cty.NewValueMarks("sensitive"),
66+
},
67+
{
68+
Path: cty.GetAttrPath("other"),
69+
Marks: cty.NewValueMarks("other"),
70+
},
71+
{
72+
Path: cty.GetAttrPath("both"),
73+
Marks: cty.NewValueMarks("sensitive", "other"),
74+
},
75+
}
76+
77+
want := []cty.PathValueMarks{
78+
{
79+
Path: cty.GetAttrPath("sensitive"),
80+
Marks: cty.NewValueMarks("sensitive"),
81+
},
82+
{
83+
Path: cty.GetAttrPath("both"),
84+
Marks: cty.NewValueMarks("sensitive"),
85+
},
86+
}
87+
88+
got := RemoveAll(input, "other")
89+
90+
if diff := cmp.Diff(want, got, ctydebug.CmpOptions); diff != "" {
91+
t.Errorf("wrong matched paths\n%s", diff)
92+
}
93+
}
94+
6195
func TestMarkPaths(t *testing.T) {
6296
value := cty.ObjectVal(map[string]cty.Value{
6397
"s": cty.StringVal(".s"),

0 commit comments

Comments
 (0)