shell.go 873 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7. var _ = fmt.Print
  8. // Quotes arbitrary strings for bash, dash and zsh
  9. func QuoteStringForSH(x string) string {
  10. parts := strings.Split(x, "'")
  11. for i, p := range parts {
  12. parts[i] = "'" + p + "'"
  13. }
  14. return strings.Join(parts, "\"'\"")
  15. }
  16. // Quotes arbitrary strings for fish
  17. func QuoteStringForFish(x string) string {
  18. x = strings.ReplaceAll(x, "\\", "\\\\")
  19. x = strings.ReplaceAll(x, "'", "\\'")
  20. return "'" + x + "'"
  21. }
  22. // Escapes common shell meta characters
  23. func EscapeSHMetaCharacters(x string) string {
  24. ans := strings.Builder{}
  25. ans.Grow(len(x) + 32)
  26. for _, ch := range x {
  27. switch ch {
  28. case '\\', '|', '&', ';', '<', '>', '(', ')', '$', '\'', '"', ' ', '\n', '\t':
  29. ans.WriteRune('\\')
  30. }
  31. ans.WriteRune(ch)
  32. }
  33. return ans.String()
  34. }