kvdb: add loggableKeyName method

Safely logs the bucket key name as hex if it includes special
characters.

Co-authored-by: Oliver Gugger <gugger@gmail.com>
This commit is contained in:
Johan T. Halseth 2021-10-31 19:16:10 +01:00
parent 40ea494d2a
commit 10aaa35db5
No known key found for this signature in database
GPG key ID: 15BAADA29DA20D26

View file

@ -8,6 +8,7 @@
package kvdb package kvdb
import ( import (
"encoding/hex"
"fmt" "fmt"
"os" "os"
"path" "path"
@ -228,6 +229,30 @@ func (cmd *compacter) walk(db *bbolt.DB, walkFn walkFunc) error {
}) })
} }
// LoggableKeyName returns a printable name of the given key.
func LoggableKeyName(key []byte) string {
strKey := string(key)
if hasSpecialChars(strKey) {
return hex.EncodeToString(key)
}
return strKey
}
// hasSpecialChars returns true if any of the characters in the given string
// cannot be printed.
func hasSpecialChars(s string) bool {
for _, b := range s {
if !(b >= 'a' && b <= 'z') && !(b >= 'A' && b <= 'Z') &&
!(b >= '0' && b <= '9') && b != '-' && b != '_' {
return true
}
}
return false
}
// walkBucket recursively walks through a bucket. // walkBucket recursively walks through a bucket.
func (cmd *compacter) walkBucket(b *bbolt.Bucket, keyPath [][]byte, k, v []byte, func (cmd *compacter) walkBucket(b *bbolt.Bucket, keyPath [][]byte, k, v []byte,
seq uint64, fn walkFunc) error { seq uint64, fn walkFunc) error {