This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
executable file
·64 lines (57 loc) · 1.66 KB
/
utils.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
// Package util provides simple utility functions usable in all modules.
package util
import (
"regexp"
"strings"
"unicode"
)
// StringID sanitizes the string and makes it more suitable for the id attribute in HTML.
func StringID(s string) string {
var (
ret strings.Builder
usedUnderscore bool
)
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
ret.WriteRune(r)
usedUnderscore = false
} else if !usedUnderscore {
ret.WriteRune('_')
usedUnderscore = true
}
}
return strings.Trim(ret.String(), "_")
}
var badCharactersRe = regexp.MustCompile(`[?!:#@<>*|'"&%{}\\]`)
// SanitizedName is unsafeName with all unsafe characters removed.
func SanitizedName(unsafeName string) string {
return badCharactersRe.ReplaceAllString(unsafeName, "")
}
// BeautifulName makes the ugly name beautiful by replacing _ with spaces and using title case
func BeautifulName(uglyName string) string {
uglyName = SanitizedName(uglyName)
// What other transformations can we apply for a better beautifying process?
if uglyName == "" {
return uglyName
}
return strings.Title(strings.ReplaceAll(uglyName, "_", " "))
}
// CanonicalName returns the canonical form of the name. A name is canonical if it is lowercase, all left and right whitespace is trimmed and all spaces are replaced with underscores.
func CanonicalName(name string) string {
return strings.ToLower(
strings.ReplaceAll(
strings.TrimRight(
strings.TrimLeft(
SanitizedName(name),
"_",
),
"_",
), " ", "_"))
}
// DefaultString returns d if s is an empty string, s otherwise.
func DefaultString(s, d string) string {
if s == "" {
return d
}
return s
}