Skip to content

Commit 490bbb5

Browse files
committed
fix(golang): unescape double quotes in go tags
1 parent a6d8760 commit 490bbb5

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

docs/string-literals-in-the-IDL.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,8 @@ func NewS() *S {
5656
}
5757
```
5858

59-
Note that it is malformed to escape a single quote in a double quoted literal or vice versa.
59+
Note that it is unnecessary to escape a single quote in a double quoted literal or vice versa.
60+
But for compatibility with existing IDLs, escaped double quotes in a quoted literal is allowed in go generator by default. It can be disabled by specifying `unescape_double_quote=false`.
61+
62+
63+

generator/golang/option.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ type Features struct {
3939
CompatibleNames bool `compatible_names:"Add a '_' suffix if an name has a prefix 'New' or suffix 'Args' or 'Result'."`
4040
ReserveComments bool `reserve_comments:"Reserve comments of definitions in thrift file"`
4141
NilSafe bool `nil_safe:"Generate nil-safe getters."`
42-
FrugalTag bool `frugal_tag:"generate 'frugal' tag"`
42+
FrugalTag bool `frugal_tag:"Generate 'frugal' tags."`
43+
EscapeDoubleInTag bool `unescape_double_quote:"Unescape the double quotes in literals when generating go tags."`
4344
}
4445

4546
var defaultFeatures = Features{
@@ -59,6 +60,7 @@ var defaultFeatures = Features{
5960
ReserveComments: false,
6061
NilSafe: false,
6162
FrugalTag: false,
63+
EscapeDoubleInTag: true,
6264
}
6365

6466
type param struct {

generator/golang/util.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package golang
1717
import (
1818
"fmt"
1919
"path/filepath"
20+
"regexp"
2021
"strings"
2122
"text/template"
2223

@@ -34,6 +35,8 @@ const (
3435
DefaultUnknownLib = "github.com/cloudwego/thriftgo/generator/golang/extension/unknown"
3536
)
3637

38+
var escape = regexp.MustCompile(`\\.`)
39+
3740
// CodeUtils contains a set of utility functions.
3841
type CodeUtils struct {
3942
backend.LogFunc
@@ -196,7 +199,16 @@ func (cu *CodeUtils) GenTags(f *parser.Field, insertPoint string) (string, error
196199
}
197200

198201
if gotags := f.Annotations.Get("go.tag"); len(gotags) > 0 {
199-
tags = append(tags, gotags[0])
202+
tag := gotags[0]
203+
if cu.Features().EscapeDoubleInTag {
204+
tag = escape.ReplaceAllStringFunc(tag, func(m string) string {
205+
if m[1] == '"' {
206+
return m[1:]
207+
}
208+
return m
209+
})
210+
}
211+
tags = append(tags, tag)
200212
} else {
201213
if cu.Features().GenDatabaseTag {
202214
tags = append(tags, fmt.Sprintf(`db:"%s"`, f.Name))

0 commit comments

Comments
 (0)