1
mirror of https://github.com/rclone/rclone synced 2024-11-15 14:57:03 +01:00

configmap: add consistent String() method to configmap.Simple #4996

This commit is contained in:
Nick Craig-Wood 2021-03-10 11:58:23 +00:00
parent e25ac4dcf0
commit 96207f342c
2 changed files with 57 additions and 0 deletions

View File

@ -1,6 +1,11 @@
// Package configmap provides an abstraction for reading and writing config
package configmap
import (
"sort"
"strings"
)
// Getter provides an interface to get config items
type Getter interface {
// Get should get an item with the key passed in and return
@ -84,3 +89,31 @@ func (c Simple) Get(key string) (value string, ok bool) {
func (c Simple) Set(key, value string) {
c[key] = value
}
// String the map value the same way the config parser does, but with
// sorted keys for reproducability.
func (c Simple) String() string {
var ks = make([]string, 0, len(c))
for k := range c {
ks = append(ks, k)
}
sort.Strings(ks)
var out strings.Builder
for _, k := range ks {
if out.Len() > 0 {
out.WriteRune(',')
}
out.WriteString(k)
out.WriteRune('=')
out.WriteRune('\'')
for _, ch := range c[k] {
out.WriteRune(ch)
// Escape ' as ''
if ch == '\'' {
out.WriteRune(ch)
}
}
out.WriteRune('\'')
}
return out.String()
}

View File

@ -89,3 +89,27 @@ func TestConfigMapSet(t *testing.T) {
"config2": "potato",
}, m2)
}
func TestSimpleString(t *testing.T) {
// Basic
assert.Equal(t, "", Simple(nil).String())
assert.Equal(t, "", Simple{}.String())
assert.Equal(t, "config1='one'", Simple{
"config1": "one",
}.String())
// Check ordering
assert.Equal(t, "config1='one',config2='two',config3='three',config4='four',config5='five'", Simple{
"config5": "five",
"config4": "four",
"config3": "three",
"config2": "two",
"config1": "one",
}.String())
// Check escaping
assert.Equal(t, "apple='',config1='o''n''e'", Simple{
"config1": "o'n'e",
"apple": "",
}.String())
}