2018-10-13 13:45:53 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"unicode"
|
|
|
|
)
|
|
|
|
|
2019-04-15 14:43:01 +00:00
|
|
|
// SplitQuotedFields is like strings.Fields but ignores spaces inside areas surrounded
|
2018-10-13 13:45:53 +00:00
|
|
|
// by the specified quote character.
|
|
|
|
// To specify a single quote use backslash to escape it: '\''
|
|
|
|
func SplitQuotedFields(in string, quote rune) []string {
|
|
|
|
type stateEnum int
|
|
|
|
const (
|
|
|
|
inSpace stateEnum = iota
|
|
|
|
inField
|
|
|
|
inQuote
|
|
|
|
inQuoteEscaped
|
|
|
|
)
|
|
|
|
state := inSpace
|
|
|
|
r := []string{}
|
|
|
|
var buf bytes.Buffer
|
|
|
|
|
|
|
|
for _, ch := range in {
|
|
|
|
switch state {
|
|
|
|
case inSpace:
|
|
|
|
if ch == quote {
|
|
|
|
state = inQuote
|
|
|
|
} else if !unicode.IsSpace(ch) {
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
state = inField
|
|
|
|
}
|
|
|
|
|
|
|
|
case inField:
|
|
|
|
if ch == quote {
|
|
|
|
state = inQuote
|
|
|
|
} else if unicode.IsSpace(ch) {
|
|
|
|
r = append(r, buf.String())
|
|
|
|
buf.Reset()
|
|
|
|
} else {
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
case inQuote:
|
|
|
|
if ch == quote {
|
|
|
|
state = inField
|
|
|
|
} else if ch == '\\' {
|
|
|
|
state = inQuoteEscaped
|
|
|
|
} else {
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
case inQuoteEscaped:
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
state = inQuote
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if buf.Len() != 0 {
|
|
|
|
r = append(r, buf.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|