/
namer.go
66 lines (56 loc) · 1.89 KB
/
namer.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
package generator
import (
"regexp"
"strings"
)
const (
invalidTokensExpr = `[._\s]+`
)
// Namer is the interface defining a function for converting
// a name to a go-idiomatic public name.
type Namer interface {
// ToPublicName returns a go-idiomatic public name. The Avro spec
// specifies names must start with [A-Za-z_] and contain [A-Za-z0-9_].
// The golang spec says valid identifiers start with [A-Za-z_] and contain
// [A-Za-z0-9], but the first character must be [A-Z] for the field to be
// public.
ToPublicName(name string) string
}
// DefaultNamer implements the Namer interface with the
// backwards-compatible public name generator function.
type DefaultNamer struct {
}
// NamespaceNamer is like DefaultNamer but taking into account
// special tokens so namespaced names can be generated safely.
type NamespaceNamer struct {
shortNames bool
re *regexp.Regexp
}
var (
namer Namer = &DefaultNamer{}
)
// NewNamespaceNamer returns a namespace-aware namer.
func NewNamespaceNamer(shortNames bool) *NamespaceNamer {
return &NamespaceNamer{shortNames: shortNames, re: regexp.MustCompile(invalidTokensExpr)}
}
// SetNamer sets the generator's global namer
func SetNamer(n Namer) {
namer = n
}
// ToPublicName implements the backwards-compatible name converter in
// DefaultNamer.
func (d *DefaultNamer) ToPublicName(name string) string {
return ToPublicSimpleName(name)
}
// ToPublicName implements the go-idiomatic public name as in DefaultNamer's
// struct, but with additional treatment applied in order to remove possible
// invalid tokens from it. Final string is then converted to camel-case.
func (n *NamespaceNamer) ToPublicName(name string) string {
if n.shortNames {
if parts := strings.Split(name, "."); len(parts) > 2 {
name = strings.Join(parts[len(parts)-2:], ".")
}
}
name = n.re.ReplaceAllString(name, " ")
return strings.Replace(strings.Title(name), " ", "", -1)
}