Debian Codegraph @

config/defaultConfigProvider.go

raw
1 // Copyright 2021 The Hugo Authors. All rights reserved.
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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package config
15
16 import (
17 "errors"
18 "fmt"
19 "sort"
20 "strings"
21 "sync"
22
23 "github.com/gohugoio/hugo/common/hmaps"
24 "github.com/spf13/cast"
25 )
26
27 // New creates a Provider backed by an empty hmaps.Params.
28 func New() Provider {
29 return &defaultConfigProvider{
30 root: make(hmaps.Params),
31 }
32 }
33
34 // NewFrom creates a Provider backed by params.
35 func NewFrom(params hmaps.Params) Provider {
36 hmaps.PrepareParams(params)
37 return &defaultConfigProvider{
38 root: params,
39 }
40 }
41
42 // defaultConfigProvider is a Provider backed by a map where all keys are lower case.
43 // All methods are thread safe.
44 type defaultConfigProvider struct {
45 mu sync.RWMutex
46 root hmaps.Params
47
48 keyCache sync.Map
49 }
50
51 func (c *defaultConfigProvider) Get(k string) any {
52 if k == "" {
53 return c.root
54 }
55 c.mu.RLock()
56 key, m := c.getNestedKeyAndMap(strings.ToLower(k), false)
57 if m == nil {
58 c.mu.RUnlock()
59 return nil
60 }
61 v := m[key]
62 c.mu.RUnlock()
63 return v
64 }
65
66 func (c *defaultConfigProvider) GetBool(k string) bool {
67 v := c.Get(k)
68 return cast.ToBool(v)
69 }
70
71 func (c *defaultConfigProvider) GetInt(k string) int {
72 v := c.Get(k)
73 return cast.ToInt(v)
74 }
75
76 func (c *defaultConfigProvider) IsSet(k string) bool {
77 var found bool
78 c.mu.RLock()
79 key, m := c.getNestedKeyAndMap(strings.ToLower(k), false)
80 if m != nil {
81 _, found = m[key]
82 }
83 c.mu.RUnlock()
84 return found
85 }
86
87 func (c *defaultConfigProvider) GetString(k string) string {
88 v := c.Get(k)
89 return cast.ToString(v)
90 }
91
92 func (c *defaultConfigProvider) GetParams(k string) hmaps.Params {
93 v := c.Get(k)
94 if v == nil {
95 return nil
96 }
97 return v.(hmaps.Params)
98 }
99
100 func (c *defaultConfigProvider) GetStringMap(k string) map[string]any {
101 v := c.Get(k)
102 return hmaps.ToStringMap(v)
103 }
104
105 func (c *defaultConfigProvider) GetStringMapString(k string) map[string]string {
106 v := c.Get(k)
107 return hmaps.ToStringMapString(v)
108 }
109
110 func (c *defaultConfigProvider) GetStringSlice(k string) []string {
111 v := c.Get(k)
112 return cast.ToStringSlice(v)
113 }
114
115 func (c *defaultConfigProvider) Set(k string, v any) {
116 c.mu.Lock()
117 defer c.mu.Unlock()
118
119 k = strings.ToLower(k)
120
121 if k == "" {
122 if p, err := hmaps.ToParamsAndPrepare(v); err == nil {
123 // Set the values directly in root.
124 hmaps.SetParams(c.root, p)
125 } else {
126 c.root[k] = v
127 }
128
129 return
130 }
131
132 switch vv := v.(type) {
133 case map[string]any, map[any]any, map[string]string:
134 p := hmaps.MustToParamsAndPrepare(vv)
135 v = p
136 }
137
138 key, m := c.getNestedKeyAndMap(k, true)
139 if m == nil {
140 return
141 }
142
143 if existing, found := m[key]; found {
144 if p1, ok := existing.(hmaps.Params); ok {
145 if p2, ok := v.(hmaps.Params); ok {
146 hmaps.SetParams(p1, p2)
147 return
148 }
149 }
150 }
151
152 m[key] = v
153 }
154
155 // SetDefaults will set values from params if not already set.
156 func (c *defaultConfigProvider) SetDefaults(params hmaps.Params) {
157 hmaps.PrepareParams(params)
158 for k, v := range params {
159 if _, found := c.root[k]; !found {
160 c.root[k] = v
161 }
162 }
163 }
164
165 func (c *defaultConfigProvider) Merge(k string, v any) {
166 c.mu.Lock()
167 defer c.mu.Unlock()
168 k = strings.ToLower(k)
169
170 if k == "" {
171 rs, f := c.root.GetMergeStrategy()
172 if f && rs == hmaps.ParamsMergeStrategyNone {
173 // The user has set a "no merge" strategy on this,
174 // nothing more to do.
175 return
176 }
177
178 if p, err := hmaps.ToParamsAndPrepare(v); err == nil {
179 // As there may be keys in p not in root, we need to handle
180 // those as a special case.
181 var keysToDelete []string
182 for kk, vv := range p {
183 if pp, ok := vv.(hmaps.Params); ok {
184 if pppi, ok := c.root[kk]; ok {
185 ppp := pppi.(hmaps.Params)
186 hmaps.MergeParamsWithStrategy("", ppp, pp)
187 } else {
188 // We need to use the default merge strategy for
189 // this key.
190 np := make(hmaps.Params)
191 strategy := c.determineMergeStrategy(hmaps.KeyParams{Key: "", Params: c.root}, hmaps.KeyParams{Key: kk, Params: np})
192 np.SetMergeStrategy(strategy)
193 hmaps.MergeParamsWithStrategy("", np, pp)
194 c.root[kk] = np
195 if np.IsZero() {
196 // Just keep it until merge is done.
197 keysToDelete = append(keysToDelete, kk)
198 }
199 }
200 }
201 }
202 // Merge the rest.
203 hmaps.MergeParams(c.root, p)
204 for _, k := range keysToDelete {
205 delete(c.root, k)
206 }
207 } else {
208 panic(fmt.Sprintf("unsupported type %T received in Merge", v))
209 }
210
211 return
212 }
213
214 switch vv := v.(type) {
215 case map[string]any, map[any]any, map[string]string:
216 p := hmaps.MustToParamsAndPrepare(vv)
217 v = p
218 }
219
220 key, m := c.getNestedKeyAndMap(k, true)
221 if m == nil {
222 return
223 }
224
225 if existing, found := m[key]; found {
226 if p1, ok := existing.(hmaps.Params); ok {
227 if p2, ok := v.(hmaps.Params); ok {
228 hmaps.MergeParamsWithStrategy("", p1, p2)
229 }
230 }
231 } else {
232 m[key] = v
233 }
234 }
235
236 func (c *defaultConfigProvider) Keys() []string {
237 c.mu.RLock()
238 defer c.mu.RUnlock()
239 var keys []string
240 for k := range c.root {
241 keys = append(keys, k)
242 }
243 sort.Strings(keys)
244 return keys
245 }
246
247 func (c *defaultConfigProvider) WalkParams(walkFn func(params ...hmaps.KeyParams) bool) {
248 maxDepth := 1000
249 var walk func(depth int, params ...hmaps.KeyParams)
250 walk = func(depth int, params ...hmaps.KeyParams) {
251 if depth > maxDepth {
252 panic(errors.New("max depth exceeded"))
253 }
254 if walkFn(params...) {
255 return
256 }
257 p1 := params[len(params)-1]
258 i := len(params)
259 for k, v := range p1.Params {
260 if p2, ok := v.(hmaps.Params); ok {
261 paramsplus1 := make([]hmaps.KeyParams, i+1)
262 copy(paramsplus1, params)
263 paramsplus1[i] = hmaps.KeyParams{Key: k, Params: p2}
264 walk(depth+1, paramsplus1...)
265 }
266 }
267 }
268 walk(0, hmaps.KeyParams{Key: "", Params: c.root})
269 }
270
271 func (c *defaultConfigProvider) determineMergeStrategy(params ...hmaps.KeyParams) hmaps.ParamsMergeStrategy {
272 if len(params) == 0 {
273 return hmaps.ParamsMergeStrategyNone
274 }
275
276 var (
277 strategy hmaps.ParamsMergeStrategy
278 prevIsRoot bool
279 curr = params[len(params)-1]
280 )
281
282 if len(params) > 1 {
283 prev := params[len(params)-2]
284 prevIsRoot = prev.Key == ""
285
286 // Inherit from parent (but not from the root unless it's set by user).
287 s, found := prev.Params.GetMergeStrategy()
288 if !prevIsRoot && !found {
289 panic("invalid state, merge strategy not set on parent")
290 }
291 if found || !prevIsRoot {
292 strategy = s
293 }
294 }
295
296 switch curr.Key {
297 case "":
298 // Don't set a merge strategy on the root unless set by user.
299 // This will be handled as a special case.
300 case "params":
301 strategy = hmaps.ParamsMergeStrategyDeep
302 case "outputformats", "mediatypes":
303 if prevIsRoot {
304 strategy = hmaps.ParamsMergeStrategyShallow
305 }
306 case "menus":
307 isMenuKey := prevIsRoot
308 if !isMenuKey {
309 // Can also be set below languages.
310 // root > languages > en > menus
311 if len(params) == 4 && params[1].Key == "languages" {
312 isMenuKey = true
313 }
314 }
315 if isMenuKey {
316 strategy = hmaps.ParamsMergeStrategyShallow
317 }
318 default:
319 if strategy == "" {
320 strategy = hmaps.ParamsMergeStrategyNone
321 }
322 }
323
324 return strategy
325 }
326
327 func (c *defaultConfigProvider) SetDefaultMergeStrategy() {
328 c.WalkParams(func(params ...hmaps.KeyParams) bool {
329 if len(params) == 0 {
330 return false
331 }
332 p := params[len(params)-1].Params
333 var found bool
334 if _, found = p.GetMergeStrategy(); found {
335 // Set by user.
336 return false
337 }
338 strategy := c.determineMergeStrategy(params...)
339 if strategy != "" {
340 p.SetMergeStrategy(strategy)
341 }
342 return false
343 })
344 }
345
346 func (c *defaultConfigProvider) getNestedKeyAndMap(key string, create bool) (string, hmaps.Params) {
347 var parts []string
348 v, ok := c.keyCache.Load(key)
349 if ok {
350 parts = v.([]string)
351 } else {
352 parts = strings.Split(key, ".")
353 c.keyCache.Store(key, parts)
354 }
355 current := c.root
356 for i := range len(parts) - 1 {
357 next, found := current[parts[i]]
358 if !found {
359 if create {
360 next = make(hmaps.Params)
361 current[parts[i]] = next
362 } else {
363 return "", nil
364 }
365 }
366 var ok bool
367 current, ok = next.(hmaps.Params)
368 if !ok {
369 // E.g. a string, not a map that we can store values in.
370 return "", nil
371 }
372 }
373 return parts[len(parts)-1], current
374 }