-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
converter.go
116 lines (96 loc) · 2.49 KB
/
converter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package tagliatelle
import (
"fmt"
"strings"
"github.com/ettle/strcase"
)
// https://github.com/dominikh/go-tools/blob/v0.5.1/config/config.go#L167-L175
//
//nolint:gochecknoglobals // For now I'll accept this, but I think will refactor to use a structure.
var staticcheckInitialisms = map[string]bool{
"AMQP": true,
"DB": true,
"GID": true,
"LHS": false,
"RHS": false,
"RTP": true,
"SIP": true,
"TS": true,
}
// Converter is the signature of a case converter.
type Converter func(s string) string
// ConverterCallback allows to abstract `getSimpleConverter` and `ruleToConverter`.
type ConverterCallback func() (Converter, error)
func getSimpleConverter(c string) (Converter, error) {
switch c {
case "camel":
return strcase.ToCamel, nil
case "pascal":
return strcase.ToPascal, nil
case "kebab":
return strcase.ToKebab, nil
case "snake":
return strcase.ToSnake, nil
case "goCamel":
return strcase.ToGoCamel, nil
case "goPascal":
return strcase.ToGoPascal, nil
case "goKebab":
return strcase.ToGoKebab, nil
case "goSnake":
return strcase.ToGoSnake, nil
case "upperSnake":
return strcase.ToSNAKE, nil
case "header":
return toHeader, nil
case "upper":
return strings.ToUpper, nil
case "lower":
return strings.ToLower, nil
default:
return nil, fmt.Errorf("unsupported case: %s", c)
}
}
func toHeader(s string) string {
return strcase.ToCase(s, strcase.TitleCase, '-')
}
func ruleToConverter(rule ExtendedRule) (Converter, error) {
if rule.ExtraInitialisms {
for k, v := range staticcheckInitialisms {
if _, found := rule.InitialismOverrides[k]; found {
continue
}
rule.InitialismOverrides[k] = v
}
}
caser := strcase.NewCaser(strings.HasPrefix(rule.Case, "go"), rule.InitialismOverrides, nil)
switch strings.ToLower(strings.TrimPrefix(rule.Case, "go")) {
case "camel":
return caser.ToCamel, nil
case "pascal":
return caser.ToPascal, nil
case "kebab":
return caser.ToKebab, nil
case "snake":
return caser.ToSnake, nil
case "uppersnake":
return caser.ToSNAKE, nil
case "header":
return toHeaderCase(caser), nil
case "upper":
return func(s string) string {
return caser.ToCase(s, strcase.UpperCase, 0)
}, nil
case "lower":
return func(s string) string {
return caser.ToCase(s, strcase.LowerCase, 0)
}, nil
default:
return nil, fmt.Errorf("unsupported case: %s", rule.Case)
}
}
func toHeaderCase(caser *strcase.Caser) Converter {
return func(s string) string {
return caser.ToCase(s, strcase.TitleCase, '-')
}
}