Skip to content

Commit

Permalink
fix: [TKC-3038] support brace escaping (#6106)
Browse files Browse the repository at this point in the history
* fix: support brace escaping

Signed-off-by: Vladislav Sukhin <[email protected]>

* fixL change escaping

Signed-off-by: Vladislav Sukhin <[email protected]>

* fix: escape braces and double braces

Signed-off-by: Vladislav Sukhin <[email protected]>

* fix: add comments

Signed-off-by: Vladislav Sukhin <[email protected]>

---------

Signed-off-by: Vladislav Sukhin <[email protected]>
  • Loading branch information
vsukhin authored Jan 8, 2025
1 parent 4e6f2cb commit a5a5555
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
4 changes: 4 additions & 0 deletions pkg/expressions/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ func TestCompileEscapeTemplate(t *testing.T) {
assert.Equal(t, `foo{{"{{"}}barbaz{{"{{"}}`, MustCompileTemplate(`foo{{"{{bar"}}baz{{"{{"}}`).Template())
}

func TestCompileEscapeBrace(t *testing.T) {
assert.Equal(t, `foo{{"{"}}barbaz{{"{"}}`, MustCompileTemplate(`foo{{"{bar"}}baz{{"{"}}`).Template())
}

func TestCompileStandardLib(t *testing.T) {
assert.Equal(t, `false`, MustCompile(`bool(0)`).String())
assert.Equal(t, `true`, MustCompile(`bool(500)`).String())
Expand Down
39 changes: 38 additions & 1 deletion pkg/expressions/static.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package expressions

import (
"bytes"
"encoding/json"
"strings"
)
Expand Down Expand Up @@ -69,7 +70,43 @@ func (s *static) Template() string {
return ""
}
v, _ := s.StringValue()
return strings.ReplaceAll(v, "{{", "{{\"{{\"}}")
// Escape double braces
oldValue := strings.ReplaceAll(v, "{{", "{{\"{{\"}}")

// Escape single brace
newValue := oldValue
replacement := "{{\"{\"}}"
offset := 0
extension := 0
for index := strings.Index(oldValue[offset:], "{"); index != -1; index = strings.Index(oldValue[offset:], "{") {
// make sure no other brace before
if offset+index > 0 && string(oldValue[offset+index-1:offset+index]) == "{" {
offset += index + 1
continue
}
// make sure no other brace after
if offset+index < len(oldValue)-1 && string(oldValue[offset+index+1:offset+index+2]) == "{" {
offset += index + 1
continue
}

var value bytes.Buffer
if index+offset+extension > 0 {
value.WriteString(newValue[:index+offset+extension])
}

value.WriteString(replacement)

if index+offset+extension < len(newValue)-1 {
value.WriteString(newValue[index+offset+extension+1:])
}

newValue = value.String()
extension += len(replacement) - 1
offset += index + 1
}

return newValue
}

func (s *static) SafeResolve(_ ...Machine) (Expression, bool, error) {
Expand Down

0 comments on commit a5a5555

Please sign in to comment.