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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
|
// Package shell supports splitting and joining of shell command strings.
//
// The Split function divides a string into whitespace-separated fields,
// respecting single and double quotation marks as defined by the Shell Command
// Language section of IEEE Std 1003.1 2013. The Quote function quotes
// characters that would otherwise be subject to shell evaluation, and the Join
// function concatenates quoted strings with spaces between them.
//
// The relationship between Split and Join is that given
//
// fields, ok := Split(Join(ss))
//
// the following relationship will hold:
//
// fields == ss && ok
package shell
import (
"bufio"
"bytes"
"io"
"strings"
)
// These characters must be quoted to escape special meaning. This list
// doesn't include the single quote.
const mustQuote = "|&;<>()$`\\\"\t\n"
// These characters should be quoted to escape special meaning, since in some
// contexts they are special (e.g., "x=y" in command position, "*" for globs).
const shouldQuote = `*?[#~=%`
// These are the separator characters in unquoted text.
const spaces = " \t\n"
const allQuote = mustQuote + shouldQuote + spaces
type state int
const (
stNone state = iota
stBreak
stBreakQ
stWord
stWordQ
stSingle
stDouble
stDoubleQ
)
type class int
const (
clOther class = iota
clBreak
clNewline
clQuote
clSingle
clDouble
)
type action int
const (
drop action = iota
push
xpush
emit
)
// N.B. Benchmarking shows that array lookup is substantially faster than map
// lookup here, but it requires caution when changing the state machine. In
// particular:
//
// 1. The state and action values must be small integers.
// 2. The update table must completely cover the state values.
// 3. Each action slice must completely cover the action values.
var update = [...][]struct {
state
action
}{
stNone: {},
stBreak: {
clBreak: {stBreak, drop},
clNewline: {stBreak, drop},
clQuote: {stBreakQ, drop},
clSingle: {stSingle, drop},
clDouble: {stDouble, drop},
clOther: {stWord, push},
},
stBreakQ: {
clBreak: {stWord, push},
clNewline: {stBreak, drop},
clQuote: {stWord, push},
clSingle: {stWord, push},
clDouble: {stWord, push},
clOther: {stWord, push},
},
stWord: {
clBreak: {stBreak, emit},
clNewline: {stBreak, emit},
clQuote: {stWordQ, drop},
clSingle: {stSingle, drop},
clDouble: {stDouble, drop},
clOther: {stWord, push},
},
stWordQ: {
clBreak: {stWord, push},
clNewline: {stWord, drop},
clQuote: {stWord, push},
clSingle: {stWord, push},
clDouble: {stWord, push},
clOther: {stWord, push},
},
stSingle: {
clBreak: {stSingle, push},
clNewline: {stSingle, push},
clQuote: {stSingle, push},
clSingle: {stWord, drop},
clDouble: {stSingle, push},
clOther: {stSingle, push},
},
stDouble: {
clBreak: {stDouble, push},
clNewline: {stDouble, push},
clQuote: {stDoubleQ, drop},
clSingle: {stDouble, push},
clDouble: {stWord, drop},
clOther: {stDouble, push},
},
stDoubleQ: {
clBreak: {stDouble, xpush},
clNewline: {stDouble, drop},
clQuote: {stDouble, push},
clSingle: {stDouble, xpush},
clDouble: {stDouble, push},
clOther: {stDouble, xpush},
},
}
var classOf = [256]class{
' ': clBreak,
'\t': clBreak,
'\n': clNewline,
'\\': clQuote,
'\'': clSingle,
'"': clDouble,
}
// A Scanner partitions input from a reader into tokens divided on space, tab,
// and newline characters. Single and double quotation marks are handled as
// described in http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02.
type Scanner struct {
buf *bufio.Reader
cur bytes.Buffer
st state
err error
}
// NewScanner returns a Scanner that reads input from r.
func NewScanner(r io.Reader) *Scanner {
return &Scanner{
buf: bufio.NewReader(r),
st: stBreak,
}
}
// Next advances the scanner and reports whether there are any further tokens
// to be consumed.
func (s *Scanner) Next() bool {
if s.err != nil {
return false
}
s.cur.Reset()
for {
c, err := s.buf.ReadByte()
s.err = err
if err == io.EOF {
break
} else if err != nil {
return false
}
next := update[s.st][classOf[c]]
s.st = next.state
switch next.action {
case push:
s.cur.WriteByte(c)
case xpush:
s.cur.Write([]byte{'\\', c})
case emit:
return true // s.cur has a complete token
case drop:
continue
default:
panic("unknown action")
}
}
return s.st != stBreak
}
// Text returns the text of the current token, or "" if there is none.
func (s *Scanner) Text() string { return s.cur.String() }
// Err returns the error, if any, that resulted from the most recent action.
func (s *Scanner) Err() error { return s.err }
// Complete reports whether the current token is complete, meaning that it is
// unquoted or its quotes were balanced.
func (s *Scanner) Complete() bool { return s.st == stBreak || s.st == stWord }
// Rest returns an io.Reader for the remainder of the unconsumed input in s.
// After calling this method, Next will always return false. The remainder
// does not include the text of the current token at the time Rest is called.
func (s *Scanner) Rest() io.Reader {
s.st = stNone
s.cur.Reset()
s.err = io.EOF
return s.buf
}
// Each calls f for each token in the scanner until the input is exhausted, f
// returns false, or an error occurs.
func (s *Scanner) Each(f func(tok string) bool) error {
for s.Next() {
if !f(s.Text()) {
return nil
}
}
if err := s.Err(); err != io.EOF {
return err
}
return nil
}
// Split returns the remaining tokens in s, not including the current token if
// there is one. Any tokens already consumed are still returned, even if there
// is an error.
func (s *Scanner) Split() []string {
var tokens []string
for s.Next() {
tokens = append(tokens, s.Text())
}
return tokens
}
// Split partitions s into tokens divided on space, tab, and newline characters
// using a *Scanner. Leading and trailing whitespace are ignored.
//
// The Boolean flag reports whether the final token is "valid", meaning there
// were no unclosed quotations in the string.
func Split(s string) ([]string, bool) {
sc := NewScanner(strings.NewReader(s))
ss := sc.Split()
return ss, sc.Complete()
}
func quotable(s string) (hasQ, hasOther bool) {
const (
quote = 1
other = 2
all = quote + other
)
var v uint
for i := 0; i < len(s) && v < all; i++ {
if s[i] == '\'' {
v |= quote
} else if strings.IndexByte(allQuote, s[i]) >= 0 {
v |= other
}
}
return v"e != 0, v&other != 0
}
// Quote returns a copy of s in which shell metacharacters are quoted to
// protect them from evaluation.
func Quote(s string) string {
var buf bytes.Buffer
return quote(s, &buf)
}
// quote implements quotation, using the provided buffer as scratch space. The
// existing contents of the buffer are clobbered.
func quote(s string, buf *bytes.Buffer) string {
if s == "" {
return "''"
}
hasQ, hasOther := quotable(s)
if !hasQ && !hasOther {
return s // fast path: nothing needs quotation
}
buf.Reset()
inq := false
for i := 0; i < len(s); i++ {
ch := s[i]
if ch == '\'' {
if inq {
buf.WriteByte('\'')
inq = false
}
buf.WriteByte('\\')
} else if !inq && hasOther {
buf.WriteByte('\'')
inq = true
}
buf.WriteByte(ch)
}
if inq {
buf.WriteByte('\'')
}
return buf.String()
}
// Join quotes each element of ss with Quote and concatenates the resulting
// strings separated by spaces.
func Join(ss []string) string {
quoted := make([]string, len(ss))
var buf bytes.Buffer
for i, s := range ss {
quoted[i] = quote(s, &buf)
}
return strings.Join(quoted, " ")
}
|