github.com/reds/docker@v1.11.2-rc1/pkg/stringutils/stringutils.go (about)

     1  // Package stringutils provides helper functions for dealing with strings.
     2  package stringutils
     3  
     4  import (
     5  	"bytes"
     6  	"math/rand"
     7  	"strings"
     8  
     9  	"github.com/docker/docker/pkg/random"
    10  )
    11  
    12  // GenerateRandomAlphaOnlyString generates an alphabetical random string with length n.
    13  func GenerateRandomAlphaOnlyString(n int) string {
    14  	// make a really long string
    15  	letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    16  	b := make([]byte, n)
    17  	for i := range b {
    18  		b[i] = letters[random.Rand.Intn(len(letters))]
    19  	}
    20  	return string(b)
    21  }
    22  
    23  // GenerateRandomASCIIString generates an ASCII random stirng with length n.
    24  func GenerateRandomASCIIString(n int) string {
    25  	chars := "abcdefghijklmnopqrstuvwxyz" +
    26  		"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    27  		"~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
    28  	res := make([]byte, n)
    29  	for i := 0; i < n; i++ {
    30  		res[i] = chars[rand.Intn(len(chars))]
    31  	}
    32  	return string(res)
    33  }
    34  
    35  // Truncate truncates a string to maxlen.
    36  func Truncate(s string, maxlen int) string {
    37  	if len(s) <= maxlen {
    38  		return s
    39  	}
    40  	return s[:maxlen]
    41  }
    42  
    43  // InSlice tests whether a string is contained in a slice of strings or not.
    44  // Comparison is case insensitive
    45  func InSlice(slice []string, s string) bool {
    46  	for _, ss := range slice {
    47  		if strings.ToLower(s) == strings.ToLower(ss) {
    48  			return true
    49  		}
    50  	}
    51  	return false
    52  }
    53  
    54  func quote(word string, buf *bytes.Buffer) {
    55  	// Bail out early for "simple" strings
    56  	if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
    57  		buf.WriteString(word)
    58  		return
    59  	}
    60  
    61  	buf.WriteString("'")
    62  
    63  	for i := 0; i < len(word); i++ {
    64  		b := word[i]
    65  		if b == '\'' {
    66  			// Replace literal ' with a close ', a \', and a open '
    67  			buf.WriteString("'\\''")
    68  		} else {
    69  			buf.WriteByte(b)
    70  		}
    71  	}
    72  
    73  	buf.WriteString("'")
    74  }
    75  
    76  // ShellQuoteArguments takes a list of strings and escapes them so they will be
    77  // handled right when passed as arguments to an program via a shell
    78  func ShellQuoteArguments(args []string) string {
    79  	var buf bytes.Buffer
    80  	for i, arg := range args {
    81  		if i != 0 {
    82  			buf.WriteByte(' ')
    83  		}
    84  		quote(arg, &buf)
    85  	}
    86  	return buf.String()
    87  }