File: shell.go

package info (click to toggle)
go-dlib 5.6.0.9%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,212 kB
  • sloc: ansic: 4,664; xml: 1,456; makefile: 20; sh: 15
file content (33 lines) | stat: -rw-r--r-- 607 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package shell

import (
	"bytes"
	"strings"
)

const specialChars = "`~!#$&*()|\\;'\"<>? "

func isSpecialChar(c byte) bool {
	return strings.IndexByte(specialChars, c) >= 0
}

// Encode returns a sh string literal representing s
func Encode(s string) string {
	var buf bytes.Buffer
	for i := 0; i < len(s); i++ {
		c := s[i]
		if isSpecialChar(c) {
			buf.WriteByte('\\')
			buf.WriteByte(c)
		} else if c == '\t' {
			buf.WriteString(`'\t'`)
		} else if c == '\r' {
			buf.WriteString(`'\r'`)
		} else if c == '\n' {
			buf.WriteString(`'\n'`)
		} else {
			buf.WriteByte(c)
		}
	}
	return buf.String()
}