Documentation ¶
Index ¶
- Variables
- func Atoi64(s string) (int64, error)
- func Center(s string, length int) string
- func CollapseWhitespace(s string) string
- func Concat(s ...string) string
- func Contains(s string, substrs ...string) bool
- func ContainsOrEmpty(source, target string) bool
- func DedupAnySlice(s interface{}, uniq func(i int) interface{}) interface{}
- func DedupInt64Slice(ii []int64, omitZeroOpt ...bool) []int64
- func DedupSlice(ss []string, omitEmptyOpt ...bool) []string
- func DedupUint64Slice(ii []uint64, omitZeroOpt ...bool) []uint64
- func DistinctArray[T comparable](arr []T) []T
- func DistinctArrayFiledInStruct[T any, C comparable](arr []T, fn func(T) (target C, skip bool)) []C
- func DistinctArrayInStructByFiled[T any, C comparable](arr []T, getField func(T) (value C, skip bool)) []T
- func Equal[T ~string, S ~string](s S, t T, ignorecase ...bool) bool
- func Exist(slice []string, val string) bool
- func FirstCustomExpression(s, left, right string, f func(string) bool) (expr string, indexStart, indexEnd int, err error)
- func FirstCustomPlaceholder(s, left, right string) (expr string, indexStart, indexEnd int, err error)
- func FirstNoneEmpty(strs ...string) string
- func FlatErrors(errs []error, sep string) error
- func HandleQuotes(data []byte, quotes [2]byte, handler func([]byte))
- func HasPrefixes(s string, prefixes ...string) bool
- func HasSuffixes(s string, suffixes ...string) bool
- func InSlice[T comparable](item T, dst []T) bool
- func Interpolate(s string, values map[string]string, defaultPrecedence bool, left, right string) (string, error)
- func InterpolationDereference(values map[string]string, left, right string) error
- func IntersectionInt64Slice(s1, s2 []int64) []int64
- func IntersectionUin64Slice(s1, s2 []uint64) []uint64
- func IsValidPrjOrAppName(repo string) bool
- func Join(ss []string, sep string, omitEmptyOpt ...bool) string
- func JoinPath(ss ...string) string
- func Lines(s string, omitEmptyOpt ...bool) []string
- func Map(ss []string, fs ...func(s string) string) []string
- func MatchSemVer(s string) bool
- func NoCopyBytesToString(b []byte) string
- func NoCopyStringToBytes(s string) []byte
- func NormalizeNewlines(d []byte) []byte
- func ParseVersion(version string) string
- func PrefixWithSemVer(s string) bool
- func RandStr(size int) string
- func RemoveSlice(ss []string, removes ...string) []string
- func Repeat(s string, count int) string
- func Replace(s string, new string, indexStart, indexEnd int) string
- func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, s string, repl func([]string) string) string
- func ReverseSlice(s interface{})
- func ReverseString(s string) string
- func SnakeToUpCamel(name string) string
- func Split(s string, sep string, omitEmptyOpt ...bool) []string
- func SplitIfEmptyString(s, sep string) []string
- func Splits(s string, seps []string, omitEmptyOpt ...bool) []string
- func String(i interface{}) string
- func Title(s string) string
- func ToLower(s string) string
- func ToStrSlice[T uint64 | uint | int64 | int](input []T, withQuote ...bool) []string
- func ToTitle(s string) string
- func ToUpper(s string) string
- func Trim(s string, cutset ...string) string
- func TrimLeft(s string, cutset ...string) string
- func TrimPrefixes(s string, prefixes ...string) string
- func TrimRight(s string, cutset ...string) string
- func TrimSlice(ss []string, cutset ...string) []string
- func TrimSliceLeft(ss []string, cutset ...string) []string
- func TrimSlicePrefixes(ss []string, prefixes ...string) []string
- func TrimSliceRight(ss []string, cutset ...string) []string
- func TrimSliceSuffixes(ss []string, suffixes ...string) []string
- func TrimSuffixes(s string, suffixes ...string) string
- func Truncate(s string, length int) string
- func TryGetJsonStr(v any) string
- func TryGetYamlStr(v any) string
- func Validate(s string, validators ...Validator) error
- func YamlOrJsonToJson(data []byte) (json.RawMessage, error)
- type Validator
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var EnvValueLenValidator = MaxLenValidator(128 * 1024)
EnvValueLenValidator 校验 `s` 是否超过 linux env value 最大长度
var K8sNodeSelectorMatchValidator = AlphaNumericDashUnderscoreValidator
K8sNodeSelectorKeyValidator k8s 节点选择正则表达式校验
Functions ¶
func Center ¶
Center 居中 `s`
Center("a", 5) => " a "
Center("ab", 5) => " ab "
Center("abc", 1) => "abc"
func CollapseWhitespace ¶
CollapseWhitespace 转化连续的 space 为 _一个_ 空格
CollapseWhitespace("only one space") => "only one space"
CollapseWhitespace("collapse \n all \t sorts of \r \n \r\n whitespace") => "collapse all sorts of whitespace"
func Contains ¶
Contains 检查 `s` 中是否存在 `substrs` 中的某个字符串
Contains("test contains.", "t c", "iii") => true
Contains("test contains.", "t cc", "test ") => false
Contains("test contains.", "iii", "uuu", "ont") => true
func ContainsOrEmpty ¶ added in v1.3.0
func DedupAnySlice ¶
func DedupAnySlice(s interface{}, uniq func(i int) interface{}) interface{}
func DedupInt64Slice ¶
DedupInt64Slice ([]int64{3, 3, 1, 2, 1, 2, 3, 3, 2, 1, 0, 1, 2}, true) => []int64{3, 1, 2}
func DedupSlice ¶
DedupSlice 返回不含重复元素的 slice,各元素按第一次出现顺序排序。如果 omitEmptyOpt = true, 忽略空字符串
DedupSlice([]string{"c", "", "b", "a", "", "a", "b", "c", "", "d"}) => []string{"c", "", "b", "a", "d"}
DedupSlice([]string{"c", "", "b", "a", "", "a", "b", "c", "", "d"}, true) => []string{"c", "b", "a", "d"}
func DedupUint64Slice ¶
DedupUint64Slice 返回不含重复元素的 slice,各元素按第一次出现顺序排序。
DedupUint64Slice([]uint64{3, 3, 1, 2, 1, 2, 3, 3, 2, 1, 0, 1, 2}) => []uint64{3, 1, 2, 0}
DedupUint64Slice([]uint64{3, 3, 1, 2, 1, 2, 3, 3, 2, 1, 0, 1, 2}, true) => []uint64{3, 1, 2}
func DistinctArray ¶
func DistinctArray[T comparable](arr []T) []T
DistinctArray is used to get unique elements from a slice with comparable type \
func DistinctArrayFiledInStruct ¶
func DistinctArrayFiledInStruct[T any, C comparable](arr []T, fn func(T) (target C, skip bool)) []C
DistinctArrayFiledInStruct it is used to get unique elements from struct you should offer a function to get the field from the struct besides, the function you can set a skip condition, if skip is true, it will ignore the elem it returns the array of Type C(the field type)
For Example:
type TestIntStruct struct { Name string Field int } testInt := []TestIntStruct{ {Field: 1, Name: "1"}, {Field: 2, Name: "2"}, {Field: 1, Name: "3"}, } testIntResp := DistinctArrayFiledInStruct(testInt, func(t TestIntStruct) (int, bool) { return t.Field, false })
Result:
testIntWant = []int{1, 2}
Example ¶
package main import ( "fmt" "github.com/erda-project/erda/pkg/strutil" ) func main() { type TestIntStruct struct { Name string Field int } input := []TestIntStruct{ {Field: 1, Name: "1"}, {Field: 2, Name: "2"}, {Field: 1, Name: "3"}, } output := strutil.DistinctArrayFiledInStruct(input, func(t TestIntStruct) (int, bool) { return t.Field, false }) fmt.Println(output) }
Output: [1 2]
func DistinctArrayInStructByFiled ¶
func DistinctArrayInStructByFiled[T any, C comparable](arr []T, getField func(T) (value C, skip bool)) []T
DistinctArrayInStructByFiled it is used to get unique elements from struct array filter by filed you should offer a function to get the field from the struct besides, the function you can set a skip condition, if skip is true, it will ignore the elem it returns the array of Type T(the same as the array offered)
For Example:
1. use multiple fields for deduplication
type TestIntStruct struct { Name string Field int } testInt := []TestIntStruct{ {Field: 1, Name: "1"}, {Field: 2, Name: "2"}, {Field: 1, Name: "3"}, {Field: 1, Name: "3"}, } testIntResp := DistinctArrayInStructByFiled(testInt, func(t TestIntStruct) (string, bool) { hash := sha256.Sum256([]byte(fmt.Sprintf("%s%d", t.Name, t.Field))) return string(hash[:]), false })
Result:
testIntResp = []TestIntStruct{ {Field: 1, Name: "1"}, {Field: 2, Name: "2"}, {Field: 1, Name: "3"}, }
2. use only one fields for deduplication and skip the field equals xxx
type TestStringStruct struct { Name string Field string } testString := []TestStringStruct{ {Name: "1", Field: "123"}, {Name: "2", Field: "234"}, {Name: "#", Field: "#"}, {Name: "#2", Field: "#"}, {Name: "#3", Field: "#"}, {Name: "123", Field: "123"}, } testStringResp := DistinctArrayInStructByFiled(testString, func(t TestStringStruct) (string, bool) { if t.Field == "123" { return t.Field, true } return t.Field, false })
Result:
testStringResp := []TestStringStruct{ {Name: "2", Field: "234"}, {Name: "#", Field: "#"}, }
Example ¶
package main import ( "crypto/sha256" "fmt" "github.com/erda-project/erda/pkg/strutil" ) func main() { type TestIntStruct struct { Name string Field int } input := []TestIntStruct{ {Field: 1, Name: "1"}, {Field: 2, Name: "2"}, {Field: 3, Name: "3"}, {Field: 3, Name: "3"}, } output := strutil.DistinctArrayInStructByFiled(input, func(t TestIntStruct) (string, bool) { hash := sha256.Sum256([]byte(fmt.Sprintf("%s%d", t.Name, t.Field))) return string(hash[:]), false }) fmt.Println(output) }
Output: [{1 1} {2 2} {3 3}]
func Equal ¶
Equal 判断 `s` 和 `other` 是否相同,如果 ignorecase = true, 忽略大小写
Equal("aaa", "AAA") => false
Equal("aaa", "AaA", true) => true
func FirstCustomExpression ¶
func FirstCustomPlaceholder ¶
func FirstCustomPlaceholder(s, left, right string) (expr string, indexStart, indexEnd int, err error)
FirstCustomPlaceholder 找出字符串 s 中的占位符. left 是占位符标志的左部, right 是占位符标志的右部, 如 ${expression}, left 为 '${', right 为 '}', ${{ expression }}, left 为 '${{', right 为 '}}'. 注意占位符表达式中不能出现 '\n', '\r' 等字符. 返回值 expression 为占位符表达式, indexStart 为占位符起始位置索引, indexEnd 为占位符结束位置索引. 当 err==nil && indexStart==0 && indexEnd==0 时, 表示 s 中不存在任何给定的占位符.
func FirstNoneEmpty ¶
func HandleQuotes ¶
func HasPrefixes ¶
HasPrefixes `prefixes` 中是否存在 `s` 的前缀
HasPrefixes("asd", "ddd", "uuu") => false
HasPrefixes("asd", "sd", "as") => true
HasPrefixes("asd", "asd") => true
func HasSuffixes ¶
HasSuffixes `suffixes` 中是否存在 `s` 的后缀
HasSuffixes("asd", "ddd", "d") => true
HasSuffixes("asd", "sd") => true
HasSuffixes("asd", "iid", "as") => false
func InSlice ¶ added in v1.1.0
func InSlice[T comparable](item T, dst []T) bool
func Interpolate ¶
func Interpolate(s string, values map[string]string, defaultPrecedence bool, left, right string) (string, error)
Interpolate 对 s 中的 ${PLACEHOLDER} 或 ${PLACEHOLDER:DEFAULT} 占位符进行插值
func InterpolationDereference ¶
InterpolationDereference 渲染出 values 值之间的互相引用. 注意 key 中不能出现占位符; 不能出现循环引用.
func IntersectionInt64Slice ¶
IntersectionIn64Slice 返回两个 int64 slice 的交集,复杂度 O(m * log(m))
IntersectionIn64Slice([]int64{3, 1, 2, 0}, []int64{0, 3}) => []int64{3, 0}
IntersectionIn64Slice([]int64{3, 1, 2, 1, 0}, []int64{1, 2, 0}) => []int64{1, 2, 1, 0}
func IntersectionUin64Slice ¶
IntersectionUin64Slice 返回两个 uint64 slice 的交集,复杂度 O(m * n),待优化
IntersectionUin64Slice([]uint64{3, 1, 2, 0}, []uint64{0, 3}) => []uint64{3, 0}
IntersectionUin64Slice([]uint64{3, 1, 2, 1, 0}, []uint64{1, 2, 0}) => []uint64{1, 2, 1, 0}
func IsValidPrjOrAppName ¶
IsValidPrjOrAppName 是否是一个合法的项目或应用名 需要满足docker repository的规则,和ingress域名的规则
func Lines ¶
Lines 将 `s` 按 newline 切分成 string slice, omitEmptyOpt=true 时,忽略结果中的空字符串
Lines("abc\ndef\nghi") => []string{"abc", "def", "ghi"}
Lines("abc\rdef\rghi") => []string{"abc", "def", "ghi"}
Lines("abc\r\ndef\r\nghi\n") => []string{"abc", "def", "ghi", ""}
Lines("abc\r\ndef\r\nghi\n", true) => []string{"abc", "def", "ghi"}
func Map ¶
Map 对 `ss` 中的每个元素执行 `f`, 返回f返回的结果列表
Map([]string{"1", "2", "3"}, func(s string) string {return Concat("X", s)}) => []string{"X1", "X2", "X3"}
Map([]string{"Aa", "bB", "cc"}, ToLower, Title) => []string{"Aa", "Bb", "Cc"}
func NoCopyBytesToString ¶
func NoCopyStringToBytes ¶
func NormalizeNewlines ¶
NormalizeNewlines normalizes \r\n (windows) and \r (mac) into \n (unix).
There are 3 ways to represent a newline.
Unix: using single character LF, which is byte 10 (0x0a), represented as “” in Go string literal. Windows: using 2 characters: CR LF, which is bytes 13 10 (0x0d, 0x0a), represented as “” in Go string literal. Mac OS: using 1 character CR (byte 13 (0x0d)), represented as “” in Go string literal. This is the least popular.
func ParseVersion ¶
ParseVersion 序列化版本 "1.05.1" --> "1.5.1",
func RemoveSlice ¶
Remove 删除 slice 在 removes 中存在的元素。
RemoveSlice([]string{"a", "b", "c", "a"}, "a") => []string{"b", "c"})
RemoveSlice([]string{"a", "b", "c", "a"}, "b", "c") => []string{"a", "a"})
func ReverseSlice ¶
func ReverseSlice(s interface{})
ReverseSlice reverses the slice s in place with any type
func ReverseString ¶
func SnakeToUpCamel ¶ added in v1.1.0
SnakeToUpCamel make a snake style name to up-camel style
func Split ¶
Split 根据 `sep` 来切分 `s`, `omitEmptyOpt`=true 时,忽略结果中的空字符串
Split("a|bc|12||3", "|") => []string{"a", "bc", "12", "", "3"}
Split("a|bc|12||3", "|", true) => []string{"a", "bc", "12", "3"}
Split("a,b,c", ":") => []string{"a,b,c"}
func SplitIfEmptyString ¶
func Splits ¶
Splits 根据 `seps` 中的每个元素来切分 `s`, `omitEmptyOpt`=true 时,忽略结果中的空字符串
Splits("a,bc,,12,3", []string{",", ","}) => []string{"a", "bc", "12", "", "3"}
Splits("a,bc,,12,3", []string{",", ","}, true) => []string{"a", "bc", "12", "3"}
func ToStrSlice ¶
func Trim ¶
Trim 两边裁剪 `s`, 如果不指定 `cutset`, 默认cutset=space
Trim("trim ") => "trim"
Trim(" this ") => "this"
Trim("athisb", "abs") => "this"
func TrimLeft ¶
TrimLeft 裁剪 `s` 左边, 如果不指定 `cutset`, 默认cutset=space
TrimLeft("trim ") => "trim "
TrimLeft(" this") => "this"
TrimLeft("athisa", "a") => "thisa"
func TrimPrefixes ¶
TrimPrefixes 裁剪 `s` 的前缀
TrimPrefixes("/tmp/file", "/tmp") => "/file"
TrimPrefixes("/tmp/tmp/file", "/tmp", "/tmp/tmp") => "/tmp/file"
func TrimRight ¶
TrimRight 裁剪 `s` 右边,如果不指定 `cutset`, 默认cutset=space
TrimRight("trim ") => "trim"
TrimRight(" this") => " this"
TrimRight("athisa", "a") => "athis"
func TrimSlice ¶
TrimSlice Trim 的 Slice 版本
TrimSlice([]string{"trim ", " trim", " trim "}) => []string{"trim", "trim", "trim"}
func TrimSliceLeft ¶
TrimSliceLeft TrimLeft 的 Slice 版本
TrimSliceLeft([]string{"trim ", " trim", " trim "}) => []string{"trim ", "trim", "trim "}
func TrimSlicePrefixes ¶
TrimSlicePrefixes TrimPrefixes 的 Slice 版本
TrimSlicePrefixes([]string{"/tmp/file", "/tmp/tmp/file"}, "/tmp", "/tmp/tmp") => []string{"/file", "/tmp/file"}
func TrimSliceRight ¶
TrimSliceRight TrimRight 的 Slice 版本
TrimSliceRight([]string{"trim ", " trim", " trim "}) => []string{"trim", " trim", " trim"}
func TrimSliceSuffixes ¶
TrimSliceSuffixes TrimSuffixes 的 Slice 版本
TrimSliceSuffixes([]string{"test.go", "test.go.tmp"}, ".go", ".tmp") => []string{"test", "test.go"}
func TrimSuffixes ¶
TrimSuffixes 裁剪 `s` 的后缀
TrimSuffixes("test.go", ".go") => "test"
TrimSuffixes("test.go", ".md", ".go", ".sh") => "test"
TrimSuffixes("test.go.tmp", ".go", ".tmp") => "test.go"
func Truncate ¶
Truncate 截断 `s` 到 `length`-3 的长度,末尾增加 "..."
Truncate("it is too long", 6) => "it ..."
Truncate("it is too long", 13) => "it is too ..."
Truncate("but it is not", 16) => "but it is not"
func TryGetJsonStr ¶
func TryGetYamlStr ¶
func YamlOrJsonToJson ¶
func YamlOrJsonToJson(data []byte) (json.RawMessage, error)
Types ¶
type Validator ¶
Validator defines a validator function. User can extend validator in their own packages.
var AlphaNumericDashUnderscoreValidator Validator = func(s string) error { exp := `^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$` valid := regexp.MustCompile(exp).MatchString(s) if !valid { return fmt.Errorf("valid regexp: %s", exp) } return nil }
AlphaNumericDashUnderscoreValidator 正则表达式校验,只能以大小写字母或数字开头,支持大小写字母、数字、中划线、下划线、点
var EnvKeyValidator Validator = func(s string) error { valid := envKeyRegexp.MatchString(s) if !valid { return fmt.Errorf("illegal env key, validated by regexp: %s", envKeyRegexp.String()) } return nil }
EnvKeyValidator 检验 `s` 是否符合 linux env key 规范
var NoChineseValidator Validator = func(s string) error { var chineseCharacters []string for _, runeValue := range s { if unicode.Is(unicode.Han, runeValue) { chineseCharacters = append(chineseCharacters, string(runeValue)) } } if len(chineseCharacters) > 0 { return fmt.Errorf("found %d chinese characters: %s", len(chineseCharacters), Join(chineseCharacters, " ", true)) } return nil }
NoChineseValidator 校验 `s` 是否包含中文字符