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