From 96207f342c311dbcc0c2bb384cfa6b2815be53f3 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Wed, 10 Mar 2021 11:58:23 +0000 Subject: [PATCH] configmap: add consistent String() method to configmap.Simple #4996 --- fs/config/configmap/configmap.go | 33 +++++++++++++++++++++++++++ fs/config/configmap/configmap_test.go | 24 +++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/fs/config/configmap/configmap.go b/fs/config/configmap/configmap.go index 2d1267a22..fa323e1c1 100644 --- a/fs/config/configmap/configmap.go +++ b/fs/config/configmap/configmap.go @@ -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() +} diff --git a/fs/config/configmap/configmap_test.go b/fs/config/configmap/configmap_test.go index 08ef4ec52..90b70a4bf 100644 --- a/fs/config/configmap/configmap_test.go +++ b/fs/config/configmap/configmap_test.go @@ -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()) +}