github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/config/map_config.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package config 16 17 // MapConfig is a simple config for in memory or test configuration. Calls to SetStrings will are valid for the 18 // lifecycle of a program, but are not persisted anywhere and will return to their default values on the next run 19 // of a program. 20 type MapConfig struct { 21 properties map[string]string 22 } 23 24 var _ ReadableConfig = &MapConfig{} 25 var _ WritableConfig = &MapConfig{} 26 var _ ReadWriteConfig = &MapConfig{} 27 28 // NewMapConfig creates a config from a map. 29 func NewMapConfig(properties map[string]string) *MapConfig { 30 return &MapConfig{properties} 31 } 32 33 func NewEmptyMapConfig() *MapConfig { 34 return &MapConfig{make(map[string]string)} 35 } 36 37 // GetString retrieves a value for a given key. 38 func (mc *MapConfig) GetString(k string) (string, error) { 39 if val, ok := mc.properties[k]; ok { 40 return val, nil 41 } 42 43 return "", ErrConfigParamNotFound 44 } 45 46 func (mc *MapConfig) GetStringOrDefault(key, defStr string) string { 47 if val, err := mc.GetString(key); err == nil { 48 return val 49 } 50 return defStr 51 } 52 53 // SetStrings sets the values for a map of updates. 54 func (mc *MapConfig) SetStrings(updates map[string]string) error { 55 for k, v := range updates { 56 mc.properties[k] = v 57 } 58 59 return nil 60 } 61 62 // Iter will perform a callback for ech value in a config until all values have been exhausted or until the 63 // callback returns true indicating that it should stop. 64 func (mc *MapConfig) Iter(cb func(string, string) (stop bool)) { 65 for k, v := range mc.properties { 66 stop := cb(k, v) 67 68 if stop { 69 break 70 } 71 } 72 } 73 74 // Unset removes a configuration parameter from the config 75 func (mc *MapConfig) Unset(params []string) error { 76 for _, param := range params { 77 delete(mc.properties, param) 78 } 79 80 return nil 81 } 82 83 // Size returns the number of properties contained within the config 84 func (mc *MapConfig) Size() int { 85 return len(mc.properties) 86 }