Skip to content

Commit

Permalink
ast: Fix deep copy on Module to include comments
Browse files Browse the repository at this point in the history
Previously comments were not being deep copied which could lead to
data races from the transfomer and other places.

Fixes open-policy-agent#3793

Signed-off-by: Torin Sandall <[email protected]>
  • Loading branch information
tsandall committed Sep 16, 2021
1 parent 4747e22 commit 467fad3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ast/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,11 @@ func (mod *Module) Copy() *Module {
cpy.Annotations[i] = mod.Annotations[i].Copy(nodes[mod.Annotations[i].node])
}

cpy.Comments = make([]*Comment, len(mod.Comments))
for i := range mod.Comments {
cpy.Comments[i] = mod.Comments[i].Copy()
}

return &cpy
}

Expand Down
17 changes: 17 additions & 0 deletions ast/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package ast

import (
"bytes"
"encoding/json"
"fmt"
"reflect"
Expand Down Expand Up @@ -484,6 +485,22 @@ wildcard = true { bar[_] = 1 }`
}
}

func TestModuleCopy(t *testing.T) {

input := `package foo
# comment
p := 7`

mod := MustParseModule(input)
cpy := mod.Copy()
cpy.Comments[0].Text[0] = 'X'

if !bytes.Equal(mod.Comments[0].Text, []byte(" comment")) {
t.Fatal("expected comment text to be unchanged")
}
}

func TestWithString(t *testing.T) {

with1 := &With{
Expand Down

0 comments on commit 467fad3

Please sign in to comment.