2015-03-24 11:25:26 +00:00
|
|
|
package stringutils
|
|
|
|
|
|
|
|
import (
|
2015-03-29 21:17:23 +00:00
|
|
|
"bytes"
|
2015-05-19 19:32:40 +00:00
|
|
|
"math/rand"
|
2015-03-29 21:17:23 +00:00
|
|
|
"strings"
|
2015-05-19 19:32:40 +00:00
|
|
|
|
|
|
|
"github.com/docker/docker/pkg/random"
|
2015-03-24 11:25:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Generate alpha only random stirng with length n
|
|
|
|
func GenerateRandomAlphaOnlyString(n int) string {
|
|
|
|
// make a really long string
|
|
|
|
letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
|
|
|
b := make([]byte, n)
|
2015-05-19 19:32:40 +00:00
|
|
|
r := rand.New(random.NewSource())
|
2015-03-24 11:25:26 +00:00
|
|
|
for i := range b {
|
|
|
|
b[i] = letters[r.Intn(len(letters))]
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate Ascii random stirng with length n
|
|
|
|
func GenerateRandomAsciiString(n int) string {
|
|
|
|
chars := "abcdefghijklmnopqrstuvwxyz" +
|
|
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
|
|
|
|
"~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
|
|
|
|
res := make([]byte, n)
|
|
|
|
for i := 0; i < n; i++ {
|
2015-05-19 19:32:40 +00:00
|
|
|
res[i] = chars[rand.Intn(len(chars))]
|
2015-03-24 11:25:26 +00:00
|
|
|
}
|
|
|
|
return string(res)
|
|
|
|
}
|
2015-03-29 21:17:23 +00:00
|
|
|
|
|
|
|
// 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()
|
|
|
|
}
|