Skip to content

Commit

Permalink
fix: use strconv.Quote to generate description
Browse files Browse the repository at this point in the history
Generated code cannot be built if the field's comment has an invalid
escape sequence (ex. `\.`). This commit fixes this issue by replacing
current description escape logic with `strconv.Quote` to properly
escape characters in string.

Signed-off-by: Sunghoon Kang <me@hoon.dev>
  • Loading branch information
devholic committed Apr 23, 2024
1 parent dc4e619 commit 23d5b2f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
14 changes: 5 additions & 9 deletions pkg/generators/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"reflect"
"regexp"
"sort"
"strconv"
"strings"

"k8s.io/gengo/v2"
Expand Down Expand Up @@ -844,15 +845,10 @@ func (g openAPITypeWriter) generateDescription(CommentLines []string) {
}
}

postDoc := strings.TrimLeft(buffer.String(), "\n")
postDoc = strings.TrimRight(postDoc, "\n")
postDoc = strings.Replace(postDoc, "\\\"", "\"", -1) // replace user's \" to "
postDoc = strings.Replace(postDoc, "\"", "\\\"", -1) // Escape "
postDoc = strings.Replace(postDoc, "\n", "\\n", -1)
postDoc = strings.Replace(postDoc, "\t", "\\t", -1)
postDoc = strings.Trim(postDoc, " ")
if postDoc != "" {
g.Do("Description: \"$.$\",\n", postDoc)
postDoc := strings.TrimSpace(buffer.String())
postDoc = strconv.Quote(postDoc)
if postDoc != `""` {
g.Do("Description: $.$,\n", postDoc)
}
}

Expand Down
13 changes: 12 additions & 1 deletion pkg/generators/openapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ func TestSimple(t *testing.T) {
// an int member with a default
// +default=1
OmittedInt int ` + "`" + `json:"omitted,omitempty"` + "`" + `
// a field with an invalid escape sequence in comment
// ex) regexp:^.*\.yaml$
InvalidEscapeSequenceInComment string
}`

packagestest.TestAll(t, func(t *testing.T, x packagestest.Exporter) {
Expand Down Expand Up @@ -384,8 +387,16 @@ Type: []string{"integer"},
Format: "int32",
},
},
"InvalidEscapeSequenceInComment": {
SchemaProps: spec.SchemaProps{
Description: "a field with an invalid escape sequence in comment ex) regexp:^.*\\.yaml$",
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"String","Int64","Int32","Int16","Int8","Uint","Uint64","Uint32","Uint16","Uint8","Byte","Bool","Float64","Float32","ByteArray","WithExtension","WithStructTagExtension","WithListType","Map","StringPointer"},
Required: []string{"String","Int64","Int32","Int16","Int8","Uint","Uint64","Uint32","Uint16","Uint8","Byte","Bool","Float64","Float32","ByteArray","WithExtension","WithStructTagExtension","WithListType","Map","StringPointer","InvalidEscapeSequenceInComment"},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
Expand Down

0 comments on commit 23d5b2f

Please sign in to comment.