stringutils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. func quote(word string, buf *bytes.Buffer) {
  40. // Bail out early for "simple" strings
  41. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  42. buf.WriteString(word)
  43. return
  44. }
  45. buf.WriteString("'")
  46. for i := 0; i < len(word); i++ {
  47. b := word[i]
  48. if b == '\'' {
  49. // Replace literal ' with a close ', a \', and an open '
  50. buf.WriteString("'\\''")
  51. } else {
  52. buf.WriteByte(b)
  53. }
  54. }
  55. buf.WriteString("'")
  56. }
  57. // ShellQuoteArguments takes a list of strings and escapes them so they will be
  58. // handled right when passed as arguments to a program via a shell
  59. func ShellQuoteArguments(args []string) string {
  60. var buf bytes.Buffer
  61. for i, arg := range args {
  62. if i != 0 {
  63. buf.WriteByte(' ')
  64. }
  65. quote(arg, &buf)
  66. }
  67. return buf.String()
  68. }