11package config
22
33import (
4+ "errors"
45 "fmt"
56 "strings"
67 "time"
@@ -64,6 +65,12 @@ var keySpecs = map[Key]KeySpec{
6465 },
6566}
6667
68+ var (
69+ errUnknownConfigKey = errors .New ("unknown config key" )
70+ errConfigKeyCannotSet = errors .New ("config key cannot be set" )
71+ errConfigKeyCannotUnset = errors .New ("config key cannot be unset" )
72+ )
73+
6774func (k Key ) String () string {
6875 return string (k )
6976}
@@ -72,27 +79,31 @@ func (k Key) Validate() error {
7279 if _ , ok := keySpecs [k ]; ok {
7380 return nil
7481 }
75- return fmt .Errorf ("unknown config key: %s (valid keys: %s)" , k , strings .Join (KeyNames (), ", " ))
82+
83+ return fmt .Errorf ("%w: %s (valid keys: %s)" , errUnknownConfigKey , k , strings .Join (KeyNames (), ", " ))
7684}
7785
7886func ParseKey (raw string ) (Key , error ) {
7987 key := Key (raw )
8088 if err := key .Validate (); err != nil {
8189 return "" , err
8290 }
91+
8392 return key , nil
8493}
8594
8695func KeySpecFor (key Key ) (KeySpec , error ) {
8796 if err := key .Validate (); err != nil {
8897 return KeySpec {}, err
8998 }
99+
90100 return keySpecs [key ], nil
91101}
92102
93103func KeyList () []Key {
94104 keys := make ([]Key , len (keyOrder ))
95105 copy (keys , keyOrder )
106+
96107 return keys
97108}
98109
@@ -101,6 +112,7 @@ func KeyNames() []string {
101112 for _ , key := range keyOrder {
102113 names = append (names , key .String ())
103114 }
115+
104116 return names
105117}
106118
@@ -109,26 +121,31 @@ func GetValue(cfg File, key Key) string {
109121 if ! ok || spec .Get == nil {
110122 return ""
111123 }
124+
112125 return spec .Get (cfg )
113126}
114127
115128func SetValue (cfg * File , key Key , value string ) error {
116129 if err := key .Validate (); err != nil {
117130 return err
118131 }
132+
119133 if spec := keySpecs [key ]; spec .Set != nil {
120134 return spec .Set (cfg , value )
121135 }
122- return fmt .Errorf ("config key %s cannot be set" , key )
136+
137+ return fmt .Errorf ("%w: %s" , errConfigKeyCannotSet , key )
123138}
124139
125140func UnsetValue (cfg * File , key Key ) error {
126141 if err := key .Validate (); err != nil {
127142 return err
128143 }
144+
129145 if spec := keySpecs [key ]; spec .Unset != nil {
130146 spec .Unset (cfg )
131147 return nil
132148 }
133- return fmt .Errorf ("config key %s cannot be unset" , key )
149+
150+ return fmt .Errorf ("%w: %s" , errConfigKeyCannotUnset , key )
134151}
0 commit comments