Codebase list golang-github-go-openapi-swag / 49551d5
Make ToGoName prefix configurable when first char is not a letter This will allow go-swagger to plus in here its pascalize func and contribute fixing go-swagger/go-swagger#1937 (inconsistent naming rules) Signed-off-by: Frederic BIDON <fredbi@yahoo.com> Frederic BIDON 4 years ago
2 changed file(s) with 55 addition(s) and 2 deletion(s). Raw diff Collapse all Expand all
1515
1616 import (
1717 "reflect"
18 "regexp"
1819 "strings"
1920 "unicode"
2021 )
2627 var initialisms []string
2728
2829 var isInitialism func(string) bool
30
31 var (
32 splitRex1 *regexp.Regexp
33 splitRex2 *regexp.Regexp
34 splitReplacer *strings.Replacer
35 )
36
37 // GoNamePrefixFunc sets an optional rule to prefix go names
38 // which do not start with a letter.
39 //
40 // e.g. to help converting "123" into "{prefix}123"
41 //
42 // The default is to prefix with "X"
43 var GoNamePrefixFunc func(string) string
2944
3045 func init() {
3146 // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769
290305 // Only prefix with X when the first character isn't an ascii letter
291306 first := []rune(result)[0]
292307 if !unicode.IsLetter(first) || (first > unicode.MaxASCII && !unicode.IsUpper(first)) {
293 result = "X" + result
308 if GoNamePrefixFunc == nil {
309 return "X" + result
310 }
311 result = GoNamePrefixFunc(name) + result
294312 }
295313 first = []rune(result)[0]
296314 if unicode.IsLetter(first) && !unicode.IsUpper(first) {
1515
1616 import (
1717 "fmt"
18 "github.com/stretchr/testify/require"
1918 "log"
2019 "strings"
2120 "testing"
2221 "time"
2322 "unicode"
23
24 "github.com/stretchr/testify/require"
2425
2526 "github.com/stretchr/testify/assert"
2627 )
402403 {"ELB.HTTPLoadBalancer", "Elb.httploadbalancer"},
403404 {"elbHTTPLoadBalancer", "Elbhttploadbalancer"},
404405 {"ELBHTTPLoadBalancer", "Elbhttploadbalancer"},
406 {"12ab", "12ab"},
405407 }
406408
407409 for _, sample := range samples {
454456 assert.Equalf(t, sample.out, res, "expected ToVarName(%q)=%q, got %q", sample.str, sample.out, res)
455457 }
456458 }
459
460 func TestToGoNameUnicode(t *testing.T) {
461 defer func() { GoNamePrefixFunc = nil }()
462 GoNamePrefixFunc = func(name string) string {
463 // this is the pascalize func from go-swagger codegen
464 arg := []rune(name)
465 if len(arg) == 0 || arg[0] > '9' {
466 return ""
467 }
468 if arg[0] == '+' {
469 return "Plus"
470 }
471 if arg[0] == '-' {
472 return "Minus"
473 }
474
475 return "Nr"
476 }
477
478 samples := []translationSample{
479 {"123_a", "Nr123a"},
480 {"!123_a", "Bang123a"},
481 {"+123_a", "Plus123a"},
482 {"abc", "Abc"},
483 {"éabc", "Éabc"},
484 {":éabc", "Éabc"},
485 // TODO: non unicode char
486 }
487
488 for _, sample := range samples {
489 assert.Equal(t, sample.out, ToGoName(sample.str))
490 }
491 }