Skip to content

Commit

Permalink
Include original text in annotation location text attribute (#6808)
Browse files Browse the repository at this point in the history
Previously it would just say '# METADATA'

Fixes #6779

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert authored Jun 11, 2024
1 parent b2146ed commit 8f25aaf
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
15 changes: 15 additions & 0 deletions ast/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,21 @@ func (b *metadataParser) Parse() (*Annotations, error) {
}

result.Location = b.loc

// recreate original text of entire metadata block for location text attribute
sb := strings.Builder{}
sb.WriteString("# METADATA\n")

lines := bytes.Split(b.buf.Bytes(), []byte{'\n'})

for _, line := range lines[:len(lines)-1] {
sb.WriteString("# ")
sb.Write(line)
sb.WriteByte('\n')
}

result.Location.Text = []byte(strings.TrimSuffix(sb.String(), "\n"))

return &result, nil
}

Expand Down
26 changes: 26 additions & 0 deletions ast/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6190,6 +6190,32 @@ func TestRelatedResourceAnnotation(t *testing.T) {
}
}

func TestAnnotationsLocationText(t *testing.T) {
module := `# METADATA
# title: pkg
# description: a package
package pkg
import rego.v1
# METADATA
# title: rule
allow if {
true
}
`

m, err := ParseModuleWithOpts("test.rego", module, ParserOptions{ProcessAnnotation: true})
if err != nil {
t.Fatal(err)
}

assertLocationText(t, "# METADATA\n# title: pkg\n# description: a package", m.Annotations[0].Location)
assertLocationText(t, "# METADATA\n# title: rule", m.Annotations[1].Location)

assertLocationText(t, "# METADATA\n# title: rule", m.Rules[0].Annotations[0].Location)
}

func assertLocationText(t *testing.T, expected string, actual *Location) {
t.Helper()
if actual == nil || actual.Text == nil {
Expand Down

0 comments on commit 8f25aaf

Please sign in to comment.