| 1 |
// Copyright 2024 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 |
"encoding/json" |
| 18 |
|
| 19 |
"github.com/gohugoio/hugo/common/hashing" |
| 20 |
) |
| 21 |
|
| 22 |
func DecodeNamespace[S, C any](configSource any, buildConfig func(any) (C, any, error)) (*ConfigNamespace[S, C], error) { |
| 23 |
// Calculate the hash of the input (not including any defaults applied later). |
| 24 |
// This allows us to introduce new config options without breaking the hash. |
| 25 |
h := hashing.HashStringHex(configSource) |
| 26 |
|
| 27 |
// Build the config |
| 28 |
c, ext, err := buildConfig(configSource) |
| 29 |
if err != nil { |
| 30 |
return nil, err |
| 31 |
} |
| 32 |
|
| 33 |
if ext == nil { |
| 34 |
ext = configSource |
| 35 |
} |
| 36 |
|
| 37 |
if ext == nil { |
| 38 |
panic("ext is nil") |
| 39 |
} |
| 40 |
|
| 41 |
ns := &ConfigNamespace[S, C]{ |
| 42 |
SourceStructure: ext, |
| 43 |
SourceHash: h, |
| 44 |
Config: c, |
| 45 |
} |
| 46 |
|
| 47 |
return ns, nil |
| 48 |
} |
| 49 |
|
| 50 |
// ConfigNamespace holds a Hugo configuration namespace. |
| 51 |
// The construct looks a little odd, but it's built to make the configuration elements |
| 52 |
// both self-documenting and contained in a common structure. |
| 53 |
type ConfigNamespace[S, C any] struct { |
| 54 |
// SourceStructure represents the source configuration with any defaults applied. |
| 55 |
// This is used for documentation and printing of the configuration setup to the user. |
| 56 |
SourceStructure any |
| 57 |
|
| 58 |
// SourceHash is a hash of the source configuration before any defaults gets applied. |
| 59 |
SourceHash string |
| 60 |
|
| 61 |
// Config is the final configuration as used by Hugo. |
| 62 |
Config C |
| 63 |
} |
| 64 |
|
| 65 |
// MarshalJSON marshals the source structure. |
| 66 |
func (ns *ConfigNamespace[S, C]) MarshalJSON() ([]byte, error) { |
| 67 |
return json.Marshal(ns.SourceStructure) |
| 68 |
} |
| 69 |
|
| 70 |
// Signature returns the signature of the source structure. |
| 71 |
// Note that this is for documentation purposes only and SourceStructure may not always be cast to S (it's usually just a map). |
| 72 |
func (ns *ConfigNamespace[S, C]) Signature() S { |
| 73 |
var s S |
| 74 |
return s |
| 75 |
} |