Debian Codegraph @

resources/page/page_matcher.go

raw
1 // Copyright 2020 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 page
15
16 import (
17 "fmt"
18 "iter"
19 "path/filepath"
20 "slices"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/hashing"
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/hstrings"
26 "github.com/gohugoio/hugo/common/hugo"
27 "github.com/gohugoio/hugo/common/loggers"
28 "github.com/gohugoio/hugo/config"
29 "github.com/gohugoio/hugo/hugofs/hglob"
30 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
31 "github.com/gohugoio/hugo/resources/kinds"
32 "github.com/mitchellh/mapstructure"
33 )
34
35 // A PageMatcher can be used to match a Page with Glob patterns.
36 // Note that the pattern matching is case insensitive.
37 type PageMatcher struct {
38 // A Glob pattern matching the content path below /content.
39 // Expects Unix-styled slashes.
40 // Note that this is the virtual path, so it starts at the mount root
41 // with a leading "/".
42 Path string
43
44 // A Glob pattern matching the Page's Kind(s), e.g. "{home,section}"
45 Kind string
46
47 // A Glob pattern matching the Page's language, e.g. "{en,sv}".
48 // Deprecated: use Sites.Matrix instead.
49 Lang string
50
51 // The sites to apply this to.
52 // Note that we currently only use the Matrix field for cascade matching.
53 Sites sitesmatrix.Sites
54
55 // A Glob pattern matching the Page's Environment, e.g. "{production,development}".
56 Environment string
57
58 // Compiled values.
59 // The site vectors to apply this to.
60 SitesMatrixCompiled sitesmatrix.VectorProvider `mapstructure:"-"`
61 kindGlob hstrings.Matcher
62 pathGlob hstrings.Matcher
63 environmentGlob hstrings.Matcher
64 }
65
66 // Equal compares the configured fields; compiled state is ignored.
67 func (m PageMatcher) Equal(other PageMatcher) bool {
68 return m.Path == other.Path &&
69 m.Kind == other.Kind &&
70 m.Lang == other.Lang &&
71 m.Environment == other.Environment &&
72 m.Sites.Equal(other.Sites)
73 }
74
75 func (m PageMatcher) Matches(p Page) bool {
76 return m.Match(p.Kind(), p.Path(), p.Site().Hugo().Environment(), nil)
77 }
78
79 func (m PageMatcher) Match(kind, path, environment string, sitesMatrix sitesmatrix.VectorProvider) bool {
80 if sitesMatrix != nil {
81 if m.SitesMatrixCompiled != nil && !m.SitesMatrixCompiled.HasAnyVector(sitesMatrix) {
82 return false
83 }
84 }
85 if m.kindGlob != nil && !m.kindGlob.Match(kind) {
86 return false
87 }
88
89 if m.pathGlob != nil {
90 // TODO(bep) Path() vs filepath vs leading slash.
91 p := strings.ToLower(filepath.ToSlash(path))
92 if !strings.HasPrefix(p, "/") {
93 p = "/" + p
94 }
95 if !m.pathGlob.Match(p) {
96 return false
97 }
98 }
99
100 if m.environmentGlob != nil && !m.environmentGlob.Match(environment) {
101 return false
102 }
103
104 return true
105 }
106
107 var disallowedCascadeKeys = map[string]bool{
108 // These define the structure of the page tree and cannot
109 // currently be set in the cascade.
110 "kind": true,
111 "path": true,
112 "lang": true,
113 "cascade": true,
114 }
115
116 // See issue 11977.
117 func isGlobWithExtension(s string) bool {
118 pathParts := strings.Split(s, "/")
119 last := pathParts[len(pathParts)-1]
120 return strings.Count(last, ".") > 0
121 }
122
123 func checkCascadePattern(logger loggers.Logger, m PageMatcher) {
124 if m.Lang != "" {
125 hugo.DeprecateWithLogger("cascade.target.language", "cascade.target.sites.matrix instead, see https://gohugo.io/content-management/front-matter/#target", "v0.150.0", logger.Logger())
126 }
127 }
128
129 func AddLangToCascadeTargetMap(lang string, m hmaps.Params) {
130 hmaps.SetNestedParamIfNotSet("target.sites.matrix.languages", ".", lang, m)
131 }
132
133 func DecodeCascadeConfig(in any) (*PageMatcherParamsConfigs, error) {
134 buildConfig := func(in any) (CascadeConfig, any, error) {
135 dec := cascadeConfigDecoder{}
136
137 if in == nil {
138 return CascadeConfig{}, []map[string]any{}, nil
139 }
140
141 ms, err := hmaps.ToSliceStringMap(in)
142 if err != nil {
143 return CascadeConfig{}, nil, err
144 }
145
146 var cfgs []PageMatcherParamsConfig
147
148 for _, m := range ms {
149 m = hmaps.CleanConfigStringMap(m)
150 var (
151 c PageMatcherParamsConfig
152 err error
153 )
154 c, err = dec.mapToPageMatcherParamsConfig(m)
155 if err != nil {
156 return CascadeConfig{}, nil, err
157 }
158 for k := range m {
159 if disallowedCascadeKeys[k] {
160 return CascadeConfig{}, nil, fmt.Errorf("key %q not allowed in cascade config", k)
161 }
162 }
163 cfgs = append(cfgs, c)
164 }
165
166 if len(cfgs) == 0 {
167 return CascadeConfig{}, nil, nil
168 }
169
170 var n int
171 for _, cfg := range cfgs {
172 if len(cfg.Params) > 0 || len(cfg.Fields) > 0 {
173 cfgs[n] = cfg
174 n++
175 }
176 }
177
178 if n == 0 {
179 return CascadeConfig{}, nil, nil
180 }
181
182 cfgs = cfgs[:n]
183
184 return CascadeConfig{Cascades: cfgs}, cfgs, nil
185 }
186
187 c, err := config.DecodeNamespace[[]PageMatcherParamsConfig](in, buildConfig)
188 if err != nil || len(c.Config.Cascades) == 0 {
189 return nil, err
190 }
191
192 return &PageMatcherParamsConfigs{c: []*config.ConfigNamespace[[]PageMatcherParamsConfig, CascadeConfig]{c}}, nil
193 }
194
195 type cascadeConfigDecoder struct{}
196
197 func (d cascadeConfigDecoder) mapToPageMatcherParamsConfig(m map[string]any) (PageMatcherParamsConfig, error) {
198 var pcfg PageMatcherParamsConfig
199 if pcfg.Fields == nil {
200 pcfg.Fields = make(hmaps.Params)
201 }
202 if pcfg.Params == nil {
203 pcfg.Params = make(hmaps.Params)
204 }
205
206 for k, v := range m {
207 klc := strings.ToLower(k)
208 switch klc {
209 case "_target", "target":
210 if klc == "_target" {
211 hugo.Deprecate("cascade._target", "Use cascade.target instead, see https://gohugo.io/content-management/front-matter/#target", "v0.156.0")
212 }
213 var target PageMatcher
214 if err := d.decodePageMatcher(v, &target); err != nil {
215 return pcfg, err
216 }
217 pcfg.Target = target
218 case "params":
219 params := hmaps.ToStringMap(v)
220 for k, v := range params {
221 if _, found := pcfg.Params[k]; !found {
222 pcfg.Params[k] = v
223 }
224 }
225 default:
226 pcfg.Fields[k] = v
227 }
228 }
229 return pcfg, pcfg.init()
230 }
231
232 // decodePageMatcher decodes m into v.
233 func (d cascadeConfigDecoder) decodePageMatcher(m any, v *PageMatcher) error {
234 if err := mapstructure.WeakDecode(m, v); err != nil {
235 return err
236 }
237
238 v.Kind = strings.ToLower(v.Kind)
239 if v.Kind != "" {
240 g, _ := hglob.GetGlob(v.Kind)
241 found := slices.ContainsFunc(kinds.AllKindsInPages, g.Match)
242 if !found {
243 return fmt.Errorf("%q did not match a valid Page Kind", v.Kind)
244 }
245 }
246
247 v.Path = filepath.ToSlash(strings.ToLower(v.Path))
248
249 if v.Lang != "" {
250 v.Sites.Matrix.Languages = append(v.Sites.Matrix.Languages, v.Lang)
251 v.Sites.Matrix.Languages = hstrings.UniqueStringsReuse(v.Sites.Matrix.Languages)
252 }
253
254 return nil
255 }
256
257 func (v *PageMatcher) compileGlobs() error {
258 var err error
259 if v.Kind != "" {
260 v.kindGlob, err = hglob.GetGlob(v.Kind)
261 if err != nil {
262 return err
263 }
264 }
265 if v.Path != "" {
266 v.pathGlob, err = hglob.GetGlob(v.Path)
267 if err != nil {
268 return err
269 }
270 }
271 if v.Environment != "" {
272 v.environmentGlob, err = hglob.GetGlob(v.Environment)
273 if err != nil {
274 return err
275 }
276 }
277 return nil
278 }
279
280 // DecodeCascadeConfigOptions
281 func (v *PageMatcher) compileSitesMatrix(defaults sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error {
282 if err := v.compileGlobs(); err != nil {
283 return err
284 }
285
286 if v.Sites.Matrix.IsZero() && defaults == nil {
287 // Nothing to do.
288 v.SitesMatrixCompiled = nil
289 return nil
290 }
291 intSetsCfg := sitesmatrix.IntSetsConfig{
292 Globs: v.Sites.Matrix,
293 }
294
295 b := sitesmatrix.NewIntSetsBuilder(configuredDimensions).WithConfig(intSetsCfg)
296 if defaults != nil && v.Sites.Matrix.IsZero() {
297 b = b.WithDimensionsFromOtherIfNotSet(defaults)
298 }
299 b = b.WithAllIfNotSet()
300 v.SitesMatrixCompiled = b.Build()
301 return nil
302 }
303
304 type CascadeConfig struct {
305 Cascades []PageMatcherParamsConfig
306 }
307
308 type PageMatcherParamsConfig struct {
309 // Apply Params to all Pages matching Target.
310 Params hmaps.Params
311 // Fields holds all fields but Params.
312 Fields hmaps.Params
313 // Target is the PageMatcher that this config applies to.
314 Target PageMatcher
315 }
316
317 func (p *PageMatcherParamsConfig) init() error {
318 hmaps.PrepareParams(p.Params)
319 hmaps.PrepareParams(p.Fields)
320
321 return nil
322 }
323
324 func (p *PageMatcherParamsConfig) hasSitesMatrix() bool {
325 if m, ok := p.Fields["sites"]; ok {
326 mm := hmaps.ToStringMap(m)
327 if sm, found := mm["matrix"]; found {
328 mmm := hmaps.ToStringMap(sm)
329 return len(mmm) > 0
330 }
331 }
332 return false
333 }
334
335 type PageMatcherParamsConfigs struct {
336 c []*config.ConfigNamespace[[]PageMatcherParamsConfig, CascadeConfig]
337 }
338
339 func (c *PageMatcherParamsConfigs) Append(other *PageMatcherParamsConfigs) *PageMatcherParamsConfigs {
340 if c == nil || len(c.c) == 0 {
341 return other
342 }
343 if other == nil || len(other.c) == 0 {
344 return c
345 }
346 return &PageMatcherParamsConfigs{c: slices.Concat(c.c, other.c)}
347 }
348
349 func (c *PageMatcherParamsConfigs) Prepend(other *PageMatcherParamsConfigs) *PageMatcherParamsConfigs {
350 if c == nil || len(c.c) == 0 {
351 return other
352 }
353 if other == nil || len(other.c) == 0 {
354 return c
355 }
356 return &PageMatcherParamsConfigs{c: slices.Concat(other.c, c.c)}
357 }
358
359 func (c *PageMatcherParamsConfigs) All() iter.Seq[PageMatcherParamsConfig] {
360 if c == nil {
361 return func(func(PageMatcherParamsConfig) bool) {}
362 }
363 return func(yield func(PageMatcherParamsConfig) bool) {
364 if c == nil {
365 return
366 }
367 for _, v := range c.c {
368 for _, vv := range v.Config.Cascades {
369 if !yield(vv) {
370 return
371 }
372 }
373 }
374 }
375 }
376
377 func (c *PageMatcherParamsConfigs) Len() int {
378 if c == nil {
379 return 0
380 }
381 var n int
382 for _, v := range c.c {
383 n += len(v.Config.Cascades)
384 }
385 return n
386 }
387
388 func (c *PageMatcherParamsConfigs) SourceHash() uint64 {
389 if c == nil {
390 return 0
391 }
392 h := hashing.XxHasher()
393 defer h.Close()
394
395 for _, v := range c.c {
396 h.WriteString(v.SourceHash)
397 }
398 return h.Sum64()
399 }
400
401 func (c *PageMatcherParamsConfigs) InitConfig(logger loggers.Logger, defaultsIn sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error {
402 if c == nil {
403 return nil
404 }
405 for _, cc := range c.c {
406 for i := range cc.Config.Cascades {
407 ccc := cc.Config.Cascades[i]
408 checkCascadePattern(logger, ccc.Target)
409 defaults := defaultsIn
410 hasSitesMatrix := ccc.hasSitesMatrix()
411 if hasSitesMatrix {
412 defaults = nil
413 }
414 if err := ccc.Target.compileSitesMatrix(defaults, configuredDimensions); err != nil {
415 return fmt.Errorf("failed to compile cascade target %d: %w", i, err)
416 }
417 cc.Config.Cascades[i] = ccc
418 }
419 }
420 return nil
421 }