Refactor utils/utils, fixes #11923
Signed-off-by: Antonio Murdaca <me@runcom.ninja>
This commit is contained in:
parent
b15e56b3ef
commit
d7a5d5b94c
10 changed files with 328 additions and 10 deletions
|
@ -1,7 +1,9 @@
|
|||
package stringutils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
mathrand "math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
@ -28,3 +30,57 @@ func GenerateRandomAsciiString(n int) string {
|
|||
}
|
||||
return string(res)
|
||||
}
|
||||
|
||||
// Truncate a string to maxlen
|
||||
func Truncate(s string, maxlen int) string {
|
||||
if len(s) <= maxlen {
|
||||
return s
|
||||
}
|
||||
return s[:maxlen]
|
||||
}
|
||||
|
||||
// Test wheather a string is contained in a slice of strings or not.
|
||||
// Comparison is case insensitive
|
||||
func InSlice(slice []string, s string) bool {
|
||||
for _, ss := range slice {
|
||||
if strings.ToLower(s) == strings.ToLower(ss) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func quote(word string, buf *bytes.Buffer) {
|
||||
// Bail out early for "simple" strings
|
||||
if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
|
||||
buf.WriteString(word)
|
||||
return
|
||||
}
|
||||
|
||||
buf.WriteString("'")
|
||||
|
||||
for i := 0; i < len(word); i++ {
|
||||
b := word[i]
|
||||
if b == '\'' {
|
||||
// Replace literal ' with a close ', a \', and a open '
|
||||
buf.WriteString("'\\''")
|
||||
} else {
|
||||
buf.WriteByte(b)
|
||||
}
|
||||
}
|
||||
|
||||
buf.WriteString("'")
|
||||
}
|
||||
|
||||
// Take a list of strings and escape them so they will be handled right
|
||||
// when passed as arguments to an program via a shell
|
||||
func ShellQuoteArguments(args []string) string {
|
||||
var buf bytes.Buffer
|
||||
for i, arg := range args {
|
||||
if i != 0 {
|
||||
buf.WriteByte(' ')
|
||||
}
|
||||
quote(arg, &buf)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
|
|
@ -56,3 +56,32 @@ func TestGenerateRandomAsciiStringIsAscii(t *testing.T) {
|
|||
t.Fatalf("%s contained non-ascii characters", str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
str := "teststring"
|
||||
newstr := Truncate(str, 4)
|
||||
if newstr != "test" {
|
||||
t.Fatalf("Expected test, got %s", newstr)
|
||||
}
|
||||
newstr = Truncate(str, 20)
|
||||
if newstr != "teststring" {
|
||||
t.Fatalf("Expected teststring, got %s", newstr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInSlice(t *testing.T) {
|
||||
slice := []string{"test", "in", "slice"}
|
||||
|
||||
test := InSlice(slice, "test")
|
||||
if !test {
|
||||
t.Fatalf("Expected string test to be in slice")
|
||||
}
|
||||
test = InSlice(slice, "SLICE")
|
||||
if !test {
|
||||
t.Fatalf("Expected string SLICE to be in slice")
|
||||
}
|
||||
test = InSlice(slice, "notinslice")
|
||||
if test {
|
||||
t.Fatalf("Expected string notinslice not to be in slice")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue