Skip to content

Commit

Permalink
Merge pull request #256 from kiwicom/ms/issue-255
Browse files Browse the repository at this point in the history
Escape single quotes in single-quoted string
  • Loading branch information
goccy authored Oct 16, 2021
2 parents b478465 + e5c9c3d commit c4f7968
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ comment:
layout: "header,diff"
behavior: default
require_changes: no

ignore:
- ast
16 changes: 15 additions & 1 deletion ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -793,11 +793,25 @@ func (n *StringNode) GetValue() interface{} {
return n.Value
}

// escapeSingleQuote escapes s to a single quoted scalar.
// https://yaml.org/spec/1.2.2/#732-single-quoted-style
func escapeSingleQuote(s string) string {
var sb strings.Builder
growLen := len(s) + // s includes also one ' from the doubled pair
2 + // opening and closing '
strings.Count(s, "'") // ' added by ReplaceAll
sb.Grow(growLen)
sb.WriteString("'")
sb.WriteString(strings.ReplaceAll(s, "'", "''"))
sb.WriteString("'")
return sb.String()
}

// String string value to text with quote or literal header if required
func (n *StringNode) String() string {
switch n.Token.Type {
case token.SingleQuoteType:
quoted := fmt.Sprintf(`'%s'`, n.Value)
quoted := escapeSingleQuote(n.Value)
if n.Comment != nil {
return addCommentString(quoted, n.Comment)
}
Expand Down
11 changes: 11 additions & 0 deletions ast/ast_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ast

import "testing"

func TestEscapeSingleQuote(t *testing.T) {
expected := `'Victor''s victory'`
got := escapeSingleQuote("Victor's victory")
if got != expected {
t.Fatalf("expected:%s\ngot:%s", expected, got)
}
}

0 comments on commit c4f7968

Please sign in to comment.