Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape single quotes in single-quoted string #256

Merged
merged 3 commits into from
Oct 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -793,11 +793,22 @@ 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
sb.Grow(2+strings.Count(s, "'")*2)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
sb.Grow(2+strings.Count(s, "'")*2)
growLen := len(s)+2+strings.Count(s, "'")*2
sb.Grow(growLen)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for spotting this!

As I'm reading the code again, the length should be sum of

  • len(s) for the original string (including ' characters)
  • 2 for the opening and closing '
  • strings.Count(s, "'") (without the *2) as each ' is already included in len(s) once

I've added a commit to fix the calculation.

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)
}
}