Avoid using regexp

This commit is contained in:
Giovanni Bajo 2014-12-18 15:09:01 +01:00
parent 98ee5434ef
commit 15b296befc
1 changed files with 14 additions and 3 deletions

View File

@ -26,7 +26,6 @@ var (
func init() { func init() {
baseTimestamp = time.Now() baseTimestamp = time.Now()
isTerminal = IsTerminal() isTerminal = IsTerminal()
noQuoteNeeded, _ = regexp.Compile("^[a-zA-Z0-9.-]*$")
} }
func miniTS() int { func miniTS() int {
@ -88,16 +87,28 @@ func printColored(b *bytes.Buffer, entry *Entry, keys []string) {
} }
} }
func needsQuoting(text string) bool {
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch < '9') ||
ch == '-' || ch == '.') {
return false
}
}
return true
}
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) {
switch value.(type) { switch value.(type) {
case string: case string:
if noQuoteNeeded.MatchString(value.(string)) { if needsQuoting(value.(string)) {
fmt.Fprintf(b, "%v=%s ", key, value) fmt.Fprintf(b, "%v=%s ", key, value)
} else { } else {
fmt.Fprintf(b, "%v=%q ", key, value) fmt.Fprintf(b, "%v=%q ", key, value)
} }
case error: case error:
if noQuoteNeeded.MatchString(value.(error).Error()) { if needsQuoting(value.(error).Error()) {
fmt.Fprintf(b, "%v=%s ", key, value) fmt.Fprintf(b, "%v=%s ", key, value)
} else { } else {
fmt.Fprintf(b, "%v=%q ", key, value) fmt.Fprintf(b, "%v=%q ", key, value)