stringutils.go 1.9 KB

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