-
Notifications
You must be signed in to change notification settings - Fork 346
/
Copy pathtruncate.go
56 lines (45 loc) · 1.43 KB
/
truncate.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
package util
import (
"fmt"
"regexp"
)
var regexpEndReplace, regexpBeginReplace *regexp.Regexp
func init() {
regexpEndReplace, _ = regexp.Compile("[^A-Za-z0-9]+$")
regexpBeginReplace, _ = regexp.Compile("^[^A-Za-z0-9]+")
}
// Truncate will shorten the length of the instance name so that it contains at most max chars when combined with the fixed part
// If the fixed part is already bigger than the max, this function is noop.
func Truncate(format string, max int, values ...interface{}) string {
var truncated []interface{}
result := fmt.Sprintf(format, values...)
if excess := len(result) - max; excess > 0 {
// we try to reduce the first string we find
for _, value := range values {
if excess == 0 {
continue
}
if s, ok := value.(string); ok {
if len(s) > excess {
value = s[:len(s)-excess]
excess = 0
} else {
value = "" // skip this value entirely
excess = excess - len(s)
}
}
truncated = append(truncated, value)
}
result = fmt.Sprintf(format, truncated...)
}
// if at this point, the result is still bigger than max, apply a hard cap:
if len(result) > max {
return result[:max]
}
return trimNonAlphaNumeric(result)
}
// trimNonAlphaNumeric remove all non-alphanumeric values from start and end of the string
func trimNonAlphaNumeric(text string) string {
newText := regexpEndReplace.ReplaceAllString(text, "")
return regexpBeginReplace.ReplaceAllString(newText, "")
}