-
Notifications
You must be signed in to change notification settings - Fork 191
/
textutil.go
64 lines (55 loc) · 1.63 KB
/
textutil.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 textutil provide some extensions text handle util functions.
package textutil
import (
"fmt"
"strings"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil"
)
// ReplaceVars by regex replace given tpl vars.
//
// If format is empty, will use {const defaultVarFormat}
func ReplaceVars(text string, vars map[string]any, format string) string {
return NewVarReplacer(format).Replace(text, vars)
}
// RenderSMap by regex replace given tpl vars.
//
// If format is empty, will use {const defaultVarFormat}
func RenderSMap(text string, vars map[string]string, format string) string {
return NewVarReplacer(format).RenderSimple(text, vars)
}
// IsMatchAll keywords in the give text string.
//
// TIP: can use ^ for exclude match.
func IsMatchAll(s string, keywords []string) bool {
return strutil.SimpleMatch(s, keywords)
}
// ParseInlineINI parse config string to string-map. it's like INI format contents.
//
// Examples:
//
// eg: "name=val0;shorts=i;required=true;desc=a message"
// =>
// {name: val0, shorts: i, required: true, desc: a message}
func ParseInlineINI(tagVal string, keys ...string) (mp maputil.SMap, err error) {
ss := strutil.Split(tagVal, ";")
ln := len(ss)
if ln == 0 {
return
}
mp = make(maputil.SMap, ln)
for _, s := range ss {
if !strings.ContainsRune(s, '=') {
err = fmt.Errorf("parse inline config error: must match `KEY=VAL`")
return
}
key, val := strutil.TrimCut(s, "=")
if len(keys) > 0 && !arrutil.StringsHas(keys, key) {
err = fmt.Errorf("parse inline config error: invalid key name %q", key)
return
}
mp[key] = val
}
return
}