stringutils.go 2.0 KB

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