Debian Codegraph @

media/config.go

raw
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 media
15
16 import (
17 "fmt"
18 "path/filepath"
19 "reflect"
20 "slices"
21 "sort"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/paths"
26 "github.com/gohugoio/hugo/config"
27
28 "github.com/mitchellh/mapstructure"
29 "github.com/spf13/cast"
30 )
31
32 // DefaultTypes is the default media types supported by Hugo.
33 var DefaultTypes Types
34
35 func init() {
36 // Apply delimiter to all.
37 for _, m := range defaultMediaTypesConfig {
38 m.(map[string]any)["delimiter"] = "."
39 }
40
41 ns, err := DecodeTypes(nil)
42 if err != nil {
43 panic(err)
44 }
45 DefaultTypes = ns.Config
46
47 // Initialize the Builtin types with values from DefaultTypes.
48 v := reflect.ValueOf(&Builtin).Elem()
49
50 for i := range v.NumField() {
51 f := v.Field(i)
52 fieldName := v.Type().Field(i).Name
53 builtinType := f.Interface().(Type)
54 if builtinType.Type == "" {
55 panic(fmt.Errorf("builtin type %q is empty", fieldName))
56 }
57 defaultType, found := DefaultTypes.GetByType(builtinType.Type)
58 if !found {
59 panic(fmt.Errorf("missing default type for field builtin type: %q", fieldName))
60 }
61 f.Set(reflect.ValueOf(defaultType))
62 }
63 }
64
65 func init() {
66 DefaultContentTypes = ContentTypes{
67 HTML: Builtin.HTMLType,
68 Markdown: Builtin.MarkdownType,
69 AsciiDoc: Builtin.AsciiDocType,
70 Pandoc: Builtin.PandocType,
71 ReStructuredText: Builtin.ReStructuredTextType,
72 EmacsOrgMode: Builtin.EmacsOrgModeType,
73 }
74
75 DefaultContentTypes.init(nil)
76 }
77
78 var DefaultContentTypes ContentTypes
79
80 type ContentTypeConfig struct {
81 // Empty for now.
82 }
83
84 // ContentTypes holds the media types that are considered content in Hugo.
85 type ContentTypes struct {
86 HTML Type
87 Markdown Type
88 AsciiDoc Type
89 Pandoc Type
90 ReStructuredText Type
91 EmacsOrgMode Type
92
93 types Types
94
95 // Created in init().
96 extensionSet map[string]bool
97 }
98
99 func (t *ContentTypes) init(types Types) {
100 sort.Slice(t.types, func(i, j int) bool {
101 return t.types[i].Type < t.types[j].Type
102 })
103
104 if tt, ok := types.GetByType(t.HTML.Type); ok {
105 t.HTML = tt
106 }
107 if tt, ok := types.GetByType(t.Markdown.Type); ok {
108 t.Markdown = tt
109 }
110 if tt, ok := types.GetByType(t.AsciiDoc.Type); ok {
111 t.AsciiDoc = tt
112 }
113 if tt, ok := types.GetByType(t.Pandoc.Type); ok {
114 t.Pandoc = tt
115 }
116 if tt, ok := types.GetByType(t.ReStructuredText.Type); ok {
117 t.ReStructuredText = tt
118 }
119 if tt, ok := types.GetByType(t.EmacsOrgMode.Type); ok {
120 t.EmacsOrgMode = tt
121 }
122
123 t.extensionSet = make(map[string]bool)
124 for _, mt := range t.types {
125 for _, suffix := range mt.Suffixes() {
126 t.extensionSet[suffix] = true
127 }
128 }
129 }
130
131 func (t ContentTypes) IsContentSuffix(suffix string) bool {
132 return t.extensionSet[suffix]
133 }
134
135 // IsContentFile returns whether the given filename is a content file.
136 func (t ContentTypes) IsContentFile(filename string) bool {
137 return t.IsContentSuffix(strings.TrimPrefix(filepath.Ext(filename), "."))
138 }
139
140 // IsIndexContentFile returns whether the given filename is an index content file.
141 func (t ContentTypes) IsIndexContentFile(filename string) bool {
142 if !t.IsContentFile(filename) {
143 return false
144 }
145
146 base := filepath.Base(filename)
147
148 return strings.HasPrefix(base, "index.") || strings.HasPrefix(base, "_index.")
149 }
150
151 // IsHTMLSuffix returns whether the given suffix is a HTML media type.
152 func (t ContentTypes) IsHTMLSuffix(suffix string) bool {
153 return slices.Contains(t.HTML.Suffixes(), suffix)
154 }
155
156 // Types is a slice of media types.
157 func (t ContentTypes) Types() Types {
158 return t.types
159 }
160
161 // Hold the configuration for a given media type.
162 type MediaTypeConfig struct {
163 // The file suffixes used for this media type.
164 Suffixes []string
165 // Delimiter used before suffix.
166 Delimiter string
167 }
168
169 var defaultContentTypesConfig = map[string]ContentTypeConfig{
170 Builtin.HTMLType.Type: {},
171 Builtin.MarkdownType.Type: {},
172 Builtin.AsciiDocType.Type: {},
173 Builtin.PandocType.Type: {},
174 Builtin.ReStructuredTextType.Type: {},
175 Builtin.EmacsOrgModeType.Type: {},
176 }
177
178 // DecodeContentTypes decodes the given map of content types.
179 func DecodeContentTypes(in map[string]any, types Types) (*config.ConfigNamespace[map[string]ContentTypeConfig, ContentTypes], error) {
180 buildConfig := func(v any) (ContentTypes, any, error) {
181 var s map[string]ContentTypeConfig
182 c := DefaultContentTypes
183 m, err := hmaps.ToStringMapE(v)
184 if err != nil {
185 return c, nil, err
186 }
187 if len(m) == 0 {
188 s = defaultContentTypesConfig
189 } else {
190 s = make(map[string]ContentTypeConfig)
191 m = hmaps.CleanConfigStringMap(m)
192 for k, v := range m {
193 var ctc ContentTypeConfig
194 if err := mapstructure.WeakDecode(v, &ctc); err != nil {
195 return c, nil, err
196 }
197 s[k] = ctc
198 }
199 }
200
201 for k := range s {
202 mediaType, found := types.GetByType(k)
203 if !found {
204 return c, nil, fmt.Errorf("unknown media type %q", k)
205 }
206 c.types = append(c.types, mediaType)
207 }
208
209 c.init(types)
210
211 return c, s, nil
212 }
213
214 ns, err := config.DecodeNamespace[map[string]ContentTypeConfig](in, buildConfig)
215 if err != nil {
216 return nil, fmt.Errorf("failed to decode media types: %w", err)
217 }
218 return ns, nil
219 }
220
221 // DecodeTypes decodes the given map of media types.
222 func DecodeTypes(in map[string]any) (*config.ConfigNamespace[map[string]MediaTypeConfig, Types], error) {
223 buildConfig := func(v any) (Types, any, error) {
224 m, err := hmaps.ToStringMapE(v)
225 if err != nil {
226 return nil, nil, err
227 }
228 if m == nil {
229 m = map[string]any{}
230 }
231 m = hmaps.CleanConfigStringMap(m)
232 // Merge with defaults.
233 hmaps.MergeShallow(m, defaultMediaTypesConfig)
234
235 var types Types
236
237 for k, v := range m {
238 mediaType, err := FromString(k)
239 if err != nil {
240 return nil, nil, err
241 }
242 if err := mapstructure.WeakDecode(v, &mediaType); err != nil {
243 return nil, nil, err
244 }
245 mm := hmaps.ToStringMap(v)
246 suffixes, _, found := hmaps.LookupEqualFold(mm, "suffixes")
247 if found {
248 mediaType.SuffixesCSV = strings.TrimSpace(strings.ToLower(strings.Join(cast.ToStringSlice(suffixes), ",")))
249 }
250 if mediaType.SuffixesCSV != "" && mediaType.Delimiter == "" {
251 mediaType.Delimiter = DefaultDelimiter
252 }
253 InitMediaType(&mediaType)
254 types = append(types, mediaType)
255 }
256
257 sort.Sort(types)
258
259 return types, m, nil
260 }
261
262 ns, err := config.DecodeNamespace[map[string]MediaTypeConfig](in, buildConfig)
263 if err != nil {
264 return nil, fmt.Errorf("failed to decode media types: %w", err)
265 }
266 return ns, nil
267 }
268
269 // TODO(bep) get rid of this.
270 var DefaultPathParser = &paths.PathParser{
271 IsContentExt: func(ext string) bool {
272 panic("not supported")
273 },
274 IsOutputFormat: func(name, ext string) bool {
275 panic("DefaultPathParser: not supported")
276 },
277 }