stringutil

package
v0.0.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2024 License: Apache-2.0 Imports: 45 Imported by: 0

Documentation

Overview

Copyright © 2020 Marvin

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	ASCIIArtWarning = `` /* 623-byte string literal not displayed */

)

pre-defined ascii art strings

View Source
const DefaultEditor = "vi"

DefaultEditor is vi because we're adults ;)

Variables

This section is empty.

Functions

func Abs

func Abs(user, path string) string

Abs returns the absolute path

func AnySliceSplit added in v0.0.9

func AnySliceSplit(value interface{}, batchSize int) []interface{}

AnySliceSplit used for the according to splitCounts, split slice

func BytesToString

func BytesToString(b []byte) string

BytesToString used for bytes to string, reduce memory https://segmentfault.com/a/1190000037679588

func CharsetConvert

func CharsetConvert(data []byte, fromCharset, toCharset string) ([]byte, error)

CharsetConvert used for string data charset convert

func Checksum

func Checksum(file string) (string, error)

Checksum returns the sha1 sum of target file

func CompareInter

func CompareInter(structA, structB interface{}) ([]interface{}, []interface{})

func CompareMapInter

func CompareMapInter(mapSA interface{}, mapTB interface{}) (map[string]interface{}, map[string]interface{}, map[string]interface{})

Key-Value

func Copy

func Copy(src, dst string) error

Copy copies a file or directory from src to dst

func CreateDir

func CreateDir(path string) error

CreateDir used to create dir

func CurrentTimeFormatString

func CurrentTimeFormatString() string

CurrentTimeFormatString used for format time string

func Decrypt

func Decrypt(ciphertext string, key []byte) (string, error)

func Encrypt

func Encrypt(text string, key []byte) (string, error)

func EscapeBinaryCSV

func EscapeBinaryCSV(s []byte, escapeBackslash bool, delimiterCsv, separatorCsv string) string

EscapeBinaryCSV used for bytes to string

func ExchangeStringDict

func ExchangeStringDict(highPriority, lowPriority map[string]string) map[string]string

ExchangeStringDict used for exchange string dict

func FlattenMap

func FlattenMap(ms map[string]any) map[string]any

FlattenMap convert mutil-layer map to single layer

func FoldMap

func FoldMap(ms map[string]any) map[string]any

FoldMap convert single layer map to multi-layer

func FormatJSONFields

func FormatJSONFields(data interface{}) interface{}

FormatJSONFields returns format json string

func GetDiskUsage

func GetDiskUsage(path string) (*syscall.Statfs_t, error)

GetDiskUsage used for get the current dir disk usage size

func GetJSONTagFieldValue

func GetJSONTagFieldValue(obj interface{}) map[string]string

GetJSONTagFieldValue used for get field value with json tag

func GetOutBoundIP added in v0.0.1

func GetOutBoundIP() (string, error)

GetOutBoundIP used for the host ipaddr

func GetRandomElem

func GetRandomElem(slice []string) (string, error)

GetRandomElem used for get random element

func GetTopologyUserSudoPrivileges added in v0.0.6

func GetTopologyUserSudoPrivileges(deployUser string) []string

func HostWhiteListForInitialCluster

func HostWhiteListForInitialCluster(s string) map[string]struct{}

HostWhiteListForInitialCluster remove duplicate addr, returns addr.

func IsContainedString

func IsContainedString(items []string, item string) bool

IsContainedString used for judge items whether is contained the item, and if it's contained, return true

func IsContainedStringIgnoreCase

func IsContainedStringIgnoreCase(items []string, item string) bool

IsContainedStringIgnoreCase used for judge items whether is contained the item, and if it's contained, return true

func IsDirExist

func IsDirExist(d string) bool

IsDirExist returns whether the directory is exists.

func IsPathExist

func IsPathExist(path string) bool

IsPathExist check whether a path is exist

func IsPathNotExist

func IsPathNotExist(path string) bool

IsPathNotExist check whether a path is not exist

func IsSubDir

func IsSubDir(parent, sub string) bool

IsSubDir returns if sub is a sub directory of parent

func IsValueNil

func IsValueNil(i interface{}) bool

func JoinHostPort

func JoinHostPort(host string, port int) string

JoinHostPort return host and port

func JoinInt

func JoinInt(nums []int, delim string) string

JoinInt joins a slice of int to string

func LogDigitWidth added in v0.0.9

func LogDigitWidth(number int) int

LogDigitWidth calculates the number of digits of a given positive integer

func MarshalIndentJSON

func MarshalIndentJSON(v any) (string, error)

MarshalIndentJSON returns marshal indent object json

func MarshalJSON

func MarshalJSON(v any) (string, error)

MarshalJSON returns marshal object json

func Max

func Max(x, y int64) int64

func Merge2TomlConfig

func Merge2TomlConfig(comp string, global, overwrite map[string]any) ([]byte, error)

Merge2TomlConfig merge the config of global.

func MergeConfig

func MergeConfig(orig map[string]any, overwrites ...map[string]any) map[string]any

MergeConfig merge two or more config into one and unflat them config1:

a.b.a: 1
a.b.b: 2

config2:

a.b.a: 3
a.b.c: 4

config3:

b.c = 5

After MergeConfig(config1, config2, config3):

a:
  b:
    a: 3
    b: 2
    c: 4
b:
  c: 5

func Min

func Min(x, y int64) int64

func MkdirAll

func MkdirAll(path string, minPerm os.FileMode) error

MkdirAll basically copied from os.MkdirAll, but use max(parent permission,minPerm)

func MultiDirAbs

func MultiDirAbs(user, paths string) []string

MultiDirAbs returns the absolute path for multi-dir separated by comma

func OpenFileInEditor

func OpenFileInEditor(filename string) error

OpenFileInEditor opens filename in a text editor.

func OsArch

func OsArch(os, arch string) string

OsArch builds an "os/arch" string from input, it converts some similar strings to different words to avoid misreading when displaying in terminal

func PKCS7Padding

func PKCS7Padding(ciphertext []byte, blockSize int) []byte

func PKCS7UnPadding

func PKCS7UnPadding(origData []byte) ([]byte, error)

func PackagePath

func PackagePath(mirrorDir, comp string, version string, os string, arch string) string

PackagePath return the tar bar path

func PaddingString

func PaddingString(padNums int, padStr string, lastPadStr string) string

func PathNotExistOrCreate

func PathNotExistOrCreate(path string) error

PathNotExistOrCreate used for the filepath is whether exist, if not exist, then create

func PrintTable

func PrintTable(rows [][]string, header bool)

PrintTable accepts a matrix of strings and print them as ASCII table to terminal

func Prompt

func Prompt(prompt string) string

Prompt accepts input from console by user

func PromptForAnswerOrAbortError

func PromptForAnswerOrAbortError(answer string, format string, a ...any) error

PromptForAnswerOrAbortError accepts string from console by user, generates AbortError if user does not input the pre-defined answer.

func PromptForConfirmAnswer

func PromptForConfirmAnswer(answer string, format string, a ...any) (bool, string)

PromptForConfirmAnswer accepts string from console by user, default to empty and only return true if the user input is exactly the same as pre-defined answer.

func PromptForConfirmNo

func PromptForConfirmNo(format string, a ...any) (bool, string)

PromptForConfirmNo accepts yes / no from console by user, default to Yes and only return true if the user input is No

func PromptForConfirmOrAbortError

func PromptForConfirmOrAbortError(format string, a ...any) error

PromptForConfirmOrAbortError accepts yes / no from console by user, generates AbortError if user does not input yes.

func PromptForConfirmYes

func PromptForConfirmYes(format string, a ...any) (bool, string)

PromptForConfirmYes accepts yes / no from console by user, default to No and only return true if the user input is Yes

func PromptForPassword

func PromptForPassword(format string, a ...any) string

PromptForPassword reads a password input from console

func RemoveAllDir added in v0.0.14

func RemoveAllDir(dir string) error

RemoveAllDir used to remove dir

func RemovePrefixOnce

func RemovePrefixOnce(s, prefix string) string

func RemovePrefixSuffixOnce

func RemovePrefixSuffixOnce(str string, prefix, suffix string) string

func RemoveSuffixOnce

func RemoveSuffixOnce(s, suffix string) string

func ReplaceQuestionPlacholders added in v0.0.15

func ReplaceQuestionPlacholders(qry string, replacePlacs, newPlacs byte) string

ReplaceQuestionPlacholders replaces ? marks with support placeholders.

func SaveFileWithBackup

func SaveFileWithBackup(path string, data []byte, backupDir string) error

SaveFileWithBackup will backup the file before save it. e.g., backup meta.yaml as meta-2006-01-02T15:04:05Z07:00.yaml backup the files in the same dir of path if backupDir is empty.

func ShowDiff

func ShowDiff(t1 string, t2 string, w io.Writer)

ShowDiff write diff result into the Writer. return false if there's no diff.

func SpecialLettersMySQLCompatibleDatabase

func SpecialLettersMySQLCompatibleDatabase(bs []byte) string

If there are special characters, add \ directly before the special characters. * Determine whether it is a letter: unicode.IsLetter(v) Determine whether it is a decimal number: unicode.IsDigit(v) Determine whether it is a number: unicode.IsNumber(v) Determine whether it is a white space symbol: unicode.IsSpace(v) Determine whether it is a special symbol: unicode.IsSymbol(v) Determine whether it is a Unicode punctuation character: unicode.IsPunct(v) Determine whether it is Chinese: unicode.Han(v)

func SpecialLettersOracleCompatibleDatabase

func SpecialLettersOracleCompatibleDatabase(bs []byte) string

func StrconvFloatBitSize

func StrconvFloatBitSize(s string, bitSize int) (float64, error)

func StrconvIntBitSize

func StrconvIntBitSize(s string, bitSize int) (int64, error)

func StrconvRune

func StrconvRune(s string) (int32, error)

func StrconvUintBitSize

func StrconvUintBitSize(s string, bitSize int) (uint64, error)

func StringBuilder

func StringBuilder(str ...string) string

StringBuilder used for string builder, and returns string

func StringExtractorWithinBrackets

func StringExtractorWithinBrackets(text string) []string

func StringExtractorWithinQuotationMarks

func StringExtractorWithinQuotationMarks(text string, patterns ...string) []string

func StringExtractorWithoutQuotationMarks

func StringExtractorWithoutQuotationMarks(text string, patterns ...string) []string

func StringItemsFilterDifference

func StringItemsFilterDifference(originItems, excludeItems []string) []string

StringItemsFilterDifference used for filter difference items, and returns new array string

func StringItemsFilterIntersection

func StringItemsFilterIntersection(originItems, newItems []string) []string

StringItemsFilterIntersection used for filter intersection items in the two items, and return new array string

func StringJoin

func StringJoin(strs []string, sep string) string

StringJoin used for string join, and returns array string

func StringLower

func StringLower(str string) string

StringLower used for string lower, and returns lower string

func StringLowerSlice

func StringLowerSlice(strs []string) []string

StringLowerSlice used for string slice lower, and returns lower string

func StringMatcher

func StringMatcher(str, toMatch string) bool

func StringPairKey

func StringPairKey(res map[string]string) string

func StringReplacer

func StringReplacer(str, toReplace, replaceWith string) string

func StringSliceAlignLen

func StringSliceAlignLen(slices [][]string) ([][]string, int)

func StringSliceRemoveElement added in v0.0.7

func StringSliceRemoveElement(slice []string, elem string) []string

StringSliceRemoveElement used for string slice remove element

func StringSliceSplit added in v0.0.6

func StringSliceSplit(items []string, splitCounts int) [][]string

StringSliceSplit used for the according to splitCounts, split slice

func StringSplit

func StringSplit(str string, sep string) []string

StringSplit used for string split, and returns array string

func StringTrim

func StringTrim(originStr string, trimStr string) string

func StringUpper

func StringUpper(str string) string

StringUpper used for string upper, and returns upper string

func StringUpperSlice

func StringUpperSlice(strs []string) []string

StringUpperSlice used for string slice upper, and returns upper string

func Ternary

func Ternary(condition bool, a, b any) any

Ternary operator

func TrimIfBothExist added in v0.0.15

func TrimIfBothExist(s string, ch rune) string

TrimIfBothExist Determine whether a specific character exists at the beginning and end of the string, and if so, remove these characters.

func UnmarshalJSON

func UnmarshalJSON(data []byte, v any) error

UnmarshalJSON returns marshal object json

func UnwrapScheme

func UnwrapScheme(s string) string

UnwrapScheme removes http or https scheme from input.

func UppercaseMap added in v0.0.9

func UppercaseMap(m interface{}) interface{}

UppercaseMap recursively converts all string keys and values within a map to uppercase. It also handles slices of structures by converting their fields to uppercase.

func ValidateSpecDiff

func ValidateSpecDiff(s1, s2 any) error

ValidateSpecDiff checks and validates the new spec to see if the modified keys are all marked as editable

func VersionCompare

func VersionCompare(curVersion, newVersion string) error

func VersionOrdinal

func VersionOrdinal(version string) string

VersionOrdinal used for the database version comparison

func WithHostPort

func WithHostPort(addr string) string

WithHostPort returns addr with host port

func WrapPrefixIPName

func WrapPrefixIPName(localHost string, prefix string, peerAddr string) string

WrapPrefixIPName returns the name with ip and prefix

func WrapScheme

func WrapScheme(s string, https bool) string

func WrapSchemes

func WrapSchemes(str string, https bool) []string

WrapSchemes adds http or https scheme to input if missing. input could be a comma-separated list.

func WrapSchemesForInitialCluster

func WrapSchemesForInitialCluster(s string, prefix string, https bool) string

WrapSchemesForInitialCluster acts like WrapSchemes, except input is "name=URL,...".

func WriteFile

func WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile call os.WriteFile, but use max(parent permission,minPerm)

Types

type StringSet

type StringSet map[string]struct{}

StringSet is a string set.

func NewStringSet

func NewStringSet(ss ...string) StringSet

NewStringSet builds a string set.

func (StringSet) Difference

func (s StringSet) Difference(rhs StringSet) StringSet

Difference returns the difference of two sets

func (StringSet) Exist

func (s StringSet) Exist(val string) bool

Exist checks whether `val` exists in `s`.

func (StringSet) Insert

func (s StringSet) Insert(val string)

Insert inserts `val` into `s`.

func (StringSet) Intersection

func (s StringSet) Intersection(rhs StringSet) StringSet

Intersection returns the intersection of two sets

func (StringSet) Join

func (s StringSet) Join(add StringSet) StringSet

Join add all elements of `add` to `s`.

func (StringSet) Remove

func (s StringSet) Remove(val string)

Remove removes `val` from `s`

func (StringSet) Slice

func (s StringSet) Slice() []string

Slice converts the set to a slice

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL