log: use strconv conversion instead of custom escape function

This commit is contained in:
Martin Holst Swende 2020-04-25 19:31:57 +02:00
parent 1591632e3f
commit b5abd6d127
No known key found for this signature in database
GPG key ID: 683B438C05A5DDF0
3 changed files with 12 additions and 43 deletions

View file

@ -325,7 +325,7 @@ func formatJSONValue(value interface{}) interface{} {
// formatValue formats a value for serialization
func formatLogfmtValue(value interface{}, term bool) string {
if value == nil {
if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
return "nil"
}
@ -358,49 +358,19 @@ func formatLogfmtValue(value interface{}, term bool) string {
}
}
var stringBufPool = sync.Pool{
New: func() interface{} { return new(bytes.Buffer) },
}
// escapeString checks if the provided string needs escaping/quoting, and
// calls strconv.Quote if needed
func escapeString(s string) string {
needsQuotes := false
needsEscape := false
needsQuoting := false
for _, r := range s {
if r <= ' ' || r == '=' || r == '"' {
needsQuotes = true
}
if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' {
needsEscape = true
// We quote everything below " (0x34) and above~ (0x7E), plus equal-sign
if r <= '"' || r > '~' || r == '=' {
needsQuoting = true
break
}
}
if !needsEscape && !needsQuotes {
if !needsQuoting {
return s
}
e := stringBufPool.Get().(*bytes.Buffer)
e.WriteByte('"')
for _, r := range s {
switch r {
case '\\', '"':
e.WriteByte('\\')
e.WriteByte(byte(r))
case '\n':
e.WriteString("\\n")
case '\r':
e.WriteString("\\r")
case '\t':
e.WriteString("\\t")
default:
e.WriteRune(r)
}
}
e.WriteByte('"')
var ret string
if needsQuotes {
ret = e.String()
} else {
ret = string(e.Bytes()[1 : e.Len()-1])
}
e.Reset()
stringBufPool.Put(e)
return ret
return strconv.Quote(s)
}

View file

@ -88,8 +88,7 @@ func (ui *CommandlineUI) confirm() bool {
// sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
// and ellipsis is added after the quoted string
func sanitize(txt string, limit int) string {
size := len(txt)
if size > limit {
if len(txt) > limit {
return fmt.Sprintf("%q...", txt[:limit])
}
return fmt.Sprintf("%q", txt)

View file

@ -98,7 +98,7 @@ func parseSelector(unescapedSelector string) ([]byte, error) {
// Validate the unescapedSelector and extract it's components
groups := selectorRegexp.FindStringSubmatch(unescapedSelector)
if len(groups) != 3 {
return nil, fmt.Errorf("invalid unescapedSelector %q (%v matches)", unescapedSelector, len(groups))
return nil, fmt.Errorf("invalid selector %q (%v matches)", unescapedSelector, len(groups))
}
name := groups[1]
args := groups[2]