1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00
go-cqhttp/global/param.go
2020-12-19 02:09:36 +08:00

94 lines
1.9 KiB
Go

package global
import (
"math"
"regexp"
"strconv"
"strings"
"github.com/tidwall/gjson"
)
var trueSet = map[string]struct{}{
"true": {},
"yes": {},
"1": {},
}
var falseSet = map[string]struct{}{
"false": {},
"no": {},
"0": {},
}
func EnsureBool(p interface{}, defaultVal bool) bool {
var str string
if b, ok := p.(bool); ok {
return b
}
if j, ok := p.(gjson.Result); ok {
if !j.Exists() {
return defaultVal
}
if j.Type == gjson.True {
return true
}
if j.Type == gjson.False {
return false
}
if j.Type != gjson.String {
return defaultVal
}
str = j.Str
} else if s, ok := p.(string); ok {
str = s
}
str = strings.ToLower(str)
if _, ok := trueSet[str]; ok {
return true
}
if _, ok := falseSet[str]; ok {
return false
}
return defaultVal
}
// VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则
// 例: v0.9.29-fix2 == v0.9.29-fix2 -> false
// v0.9.29-fix1 < v0.9.29-fix2 -> true
// v0.9.29-fix2 > v0.9.29-fix1 -> false
// v0.9.29-fix2 < v0.9.30 -> true
func VersionNameCompare(current, remote string) bool {
sp := regexp.MustCompile(`[0-9]\d*`)
cur := sp.FindAllStringSubmatch(current, -1)
re := sp.FindAllStringSubmatch(remote, -1)
for i := 0; i < int(math.Min(float64(len(cur)), float64(len(re)))); i++ {
curSub, _ := strconv.Atoi(cur[i][0])
reSub, _ := strconv.Atoi(re[i][0])
if curSub < reSub {
return true
}
}
return len(cur) < len(re)
}
func SplitUrl(s string) []string {
reg := regexp.MustCompile(`[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?`)
idx := reg.FindAllStringIndex(s, -1)
if len(idx) == 0 {
return []string{s}
}
var result []string
last := 0
for i := 0; i < len(idx); i++ {
if len(idx[i]) != 2 {
continue
}
m := int(math.Abs(float64(idx[i][0]-idx[i][1]))/1.5) + idx[i][0]
result = append(result, s[last:m])
last = m
}
result = append(result, s[last:])
return result
}