Use custom quote char and escape it

This commit is contained in:
Paul Seiffert 2017-07-10 14:09:37 +02:00
parent f78f8d07f6
commit 0383f49850
No known key found for this signature in database
GPG Key ID: C9F76DC911D6EA29
2 changed files with 50 additions and 2 deletions

View File

@ -174,14 +174,20 @@ func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
if !f.needsQuoting(value) { if !f.needsQuoting(value) {
b.WriteString(value) b.WriteString(value)
} else { } else {
fmt.Fprintf(b, "%q", value) escapedQuote := fmt.Sprintf("\\%s", f.QuoteCharacter)
escapedValue := strings.Replace(value, f.QuoteCharacter, escapedQuote, -1)
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, escapedValue, f.QuoteCharacter)
} }
case error: case error:
errmsg := value.Error() errmsg := value.Error()
if !f.needsQuoting(errmsg) { if !f.needsQuoting(errmsg) {
b.WriteString(errmsg) b.WriteString(errmsg)
} else { } else {
fmt.Fprintf(b, "%q", errmsg) escapedQuote := fmt.Sprintf("\\%s", f.QuoteCharacter)
escapedErrmsg := strings.Replace(errmsg, f.QuoteCharacter, escapedQuote, -1)
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, escapedErrmsg, f.QuoteCharacter)
} }
default: default:
fmt.Fprint(b, value) fmt.Fprint(b, value)

View File

@ -53,6 +53,48 @@ func TestQuoting(t *testing.T) {
checkQuoting(true, errors.New("invalid argument")) checkQuoting(true, errors.New("invalid argument"))
} }
func TestEscaping_DefaultQuoteCharacter(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
testCases := []struct {
value string
expected string
}{
{`ba"r`, `ba\"r`},
{`ba'r`, `ba'r`},
}
for _, tc := range testCases {
b, _ := tf.Format(WithField("test", tc.value))
if !bytes.Contains(b, []byte(tc.expected)) {
t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}
func TestEscaping_CustomQuoteCharacter(t *testing.T) {
tf := &TextFormatter{DisableColors: true}
testCases := []struct {
value string
expected string
quoteChar string
}{
{`ba"r`, `ba"r`, `'`},
{`ba'r`, `ba\'r`, `'`},
{`ba^r`, `ba\^r`, `^`},
{`ba'r`, `ba'r`, `^`},
}
for _, tc := range testCases {
tf.QuoteCharacter = tc.quoteChar
b, _ := tf.Format(WithField("test", tc.value))
if !bytes.Contains(b, []byte(tc.expected)) {
t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}
func TestTimestampFormat(t *testing.T) { func TestTimestampFormat(t *testing.T) {
checkTimeStr := func(format string) { checkTimeStr := func(format string) {
customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}