Debian Codegraph @

resources/page/permalinks.go

raw
1 // Copyright 2019 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 "errors"
18 "fmt"
19 "os"
20 "path"
21 "path/filepath"
22 "regexp"
23 "strconv"
24 "strings"
25 "time"
26
27 "github.com/gohugoio/hugo/common/hmaps"
28 "github.com/gohugoio/hugo/common/hstrings"
29 "github.com/gohugoio/hugo/common/loggers"
30 "github.com/gohugoio/hugo/helpers"
31 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
32 "github.com/gohugoio/hugo/resources/kinds"
33 "github.com/mitchellh/mapstructure"
34 )
35
36 // PermalinkConfig holds a single permalink rule with a target matcher and a pattern.
37 type PermalinkConfig struct {
38 Target PageMatcher
39 Pattern string
40 }
41
42 // PermalinksConfig is an ordered slice of permalink rules.
43 // For any given Page, the first matching rule wins.
44 type PermalinksConfig []PermalinkConfig
45
46 // InitConfig compiles the sites matrix for each permalink target.
47 func (c PermalinksConfig) InitConfig(logger loggers.Logger, defaultSitesMatrix sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error {
48 for i := range c {
49 if err := c[i].Target.compileSitesMatrix(nil, configuredDimensions); err != nil {
50 return fmt.Errorf("failed to compile permalink target %d: %w", i, err)
51 }
52 }
53 return nil
54 }
55
56 // PermalinkExpander holds permalink mappings.
57 type PermalinkExpander struct {
58 // knownPermalinkAttributes maps :tags in a permalink specification to a
59 // function which, given a page and the tag, returns the resulting string
60 // to be used to replace that tag.
61 knownPermalinkAttributes map[string]pageToPermaAttribute
62
63 configs PermalinksConfig
64
65 urlize func(uri string) string
66
67 patternCache *hmaps.Cache[string, func(Page) (string, error)]
68 }
69
70 // Time for checking date formats. Every field is different than the
71 // Go reference time for date formatting. This ensures that formatting this date
72 // with a Go time format always has a different output than the format itself.
73 var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC)
74
75 // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not.
76 func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) {
77 if callback, ok := p.knownPermalinkAttributes[attr]; ok {
78 return callback, true
79 }
80
81 if strings.HasPrefix(attr, "sections[") {
82 fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections"))
83 return func(p Page, s string) (string, error) {
84 return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil
85 }, true
86 }
87
88 if strings.HasPrefix(attr, "sectionslugs[") {
89 fn := p.toSliceFunc(strings.TrimPrefix(attr, "sectionslugs"))
90 sectionSlugsFunc := p.withSectionPagesFunc(p.pageToPermalinkSlugElseTitle, func(s ...string) string {
91 return path.Join(fn(s)...)
92 })
93 return sectionSlugsFunc, true
94 }
95
96 // Make sure this comes after all the other checks.
97 if referenceTime.Format(attr) != attr {
98 return p.pageToPermalinkDate, true
99 }
100
101 return nil, false
102 }
103
104 // NewPermalinkExpander creates a new PermalinkExpander configured by the given
105 // urlize func.
106 func NewPermalinkExpander(urlize func(uri string) string, configs PermalinksConfig) (PermalinkExpander, error) {
107 p := PermalinkExpander{
108 urlize: urlize,
109 configs: configs,
110 patternCache: hmaps.NewCache[string, func(Page) (string, error)](),
111 }
112
113 p.knownPermalinkAttributes = map[string]pageToPermaAttribute{
114 "year": p.pageToPermalinkDate,
115 "month": p.pageToPermalinkDate,
116 "monthname": p.pageToPermalinkDate,
117 "day": p.pageToPermalinkDate,
118 "weekday": p.pageToPermalinkDate,
119 "weekdayname": p.pageToPermalinkDate,
120 "yearday": p.pageToPermalinkDate,
121 "section": p.pageToPermalinkSection,
122 "sectionslug": p.pageToPermalinkSectionSlug,
123 "sections": p.pageToPermalinkSections,
124 "sectionslugs": p.pageToPermalinkSectionSlugs,
125 "title": p.pageToPermalinkTitle,
126 "slug": p.pageToPermalinkSlugElseTitle,
127 "slugorfilename": p.pageToPermalinkSlugElseFilename,
128 "filename": p.pageToPermalinkFilename,
129 "contentbasename": p.pageToPermalinkContentBaseName,
130 "slugorcontentbasename": p.pageToPermalinkSlugOrContentBaseName,
131 }
132
133 // Validate all patterns and compile matcher globs at init time.
134 for i := range configs {
135 if _, err := p.getOrParsePattern(configs[i].Pattern); err != nil {
136 return p, err
137 }
138 if err := configs[i].Target.compileGlobs(); err != nil {
139 return p, err
140 }
141
142 }
143
144 return p, nil
145 }
146
147 // Escape sequence for colons in permalink patterns.
148 const escapePlaceholderColon = "\x00"
149
150 func (l PermalinkExpander) normalizeEscapeSequencesIn(s string) (string, bool) {
151 s2 := strings.ReplaceAll(s, "\\:", escapePlaceholderColon)
152 return s2, s2 != s
153 }
154
155 func (l PermalinkExpander) normalizeEscapeSequencesOut(result string) string {
156 return strings.ReplaceAll(result, escapePlaceholderColon, ":")
157 }
158
159 // ExpandPattern expands the path in p with the specified expand pattern.
160 func (l PermalinkExpander) ExpandPattern(pattern string, p Page) (string, error) {
161 expand, err := l.getOrParsePattern(pattern)
162 if err != nil {
163 return "", err
164 }
165
166 return expand(p)
167 }
168
169 // Expand expands the path in p according to the first matching permalink rule.
170 // If no rules match, an empty string is returned.
171 func (l PermalinkExpander) Expand(p Page) (string, error) {
172 kind := p.Kind()
173 if !hstrings.InSlice(permalinksKindsSupport, kind) {
174 return "", nil
175 }
176 var siteVector sitesmatrix.VectorProvider
177 if sv, ok := LookupSiteVector(p); ok {
178 siteVector = sv
179 }
180 var environment string
181 var environmentResolved bool
182 for _, cfg := range l.configs {
183 if cfg.Target.Environment != "" && !environmentResolved {
184 environment = p.Site().Hugo().Environment()
185 environmentResolved = true
186 }
187 if cfg.Target.Match(kind, p.Path(), environment, siteVector) {
188 return l.ExpandPattern(cfg.Pattern, p)
189 }
190 }
191 return "", nil
192 }
193
194 // Allow " " and / to represent the root section.
195 var sectionCutSet = " /"
196
197 func init() {
198 if string(os.PathSeparator) != "/" {
199 sectionCutSet += string(os.PathSeparator)
200 }
201 }
202
203 func (l PermalinkExpander) getOrParsePattern(pattern string) (func(Page) (string, error), error) {
204 return l.patternCache.GetOrCreate(pattern, func() (func(Page) (string, error), error) {
205 var normalized bool
206 pattern, normalized = l.normalizeEscapeSequencesIn(pattern)
207
208 matches := attributeRegexp.FindAllStringSubmatch(pattern, -1)
209 if matches == nil {
210 result := pattern
211 if normalized {
212 result = l.normalizeEscapeSequencesOut(result)
213 }
214 return func(p Page) (string, error) {
215 return result, nil
216 }, nil
217 }
218
219 callbacks := make([]pageToPermaAttribute, len(matches))
220 replacements := make([]string, len(matches))
221 for i, m := range matches {
222 replacement := m[0]
223 attr := replacement[1:]
224 replacements[i] = replacement
225 callback, ok := l.callback(attr)
226
227 if !ok {
228 return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown}
229 }
230
231 callbacks[i] = callback
232 }
233
234 return func(p Page) (string, error) {
235 newField := pattern
236
237 for i, replacement := range replacements {
238 attr := replacement[1:]
239 callback := callbacks[i]
240 newAttr, err := callback(p, attr)
241 if err != nil {
242 return "", &permalinkExpandError{pattern: pattern, err: err}
243 }
244
245 newField = strings.Replace(newField, replacement, newAttr, 1)
246 }
247
248 if normalized {
249 newField = l.normalizeEscapeSequencesOut(newField)
250 }
251
252 return newField, nil
253 }, nil
254 })
255 }
256
257 // pageToPermaAttribute is the type of a function which, given a page and a tag
258 // can return a string to go in that position in the page (or an error)
259 type pageToPermaAttribute func(Page, string) (string, error)
260
261 var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`)
262
263 type permalinkExpandError struct {
264 pattern string
265 err error
266 }
267
268 func (pee *permalinkExpandError) Error() string {
269 return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err)
270 }
271
272 var errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised")
273
274 func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) {
275 // a Page contains a Node which provides a field Date, time.Time
276 switch dateField {
277 case "year":
278 return strconv.Itoa(p.Date().Year()), nil
279 case "month":
280 return fmt.Sprintf("%02d", int(p.Date().Month())), nil
281 case "monthname":
282 return p.Date().Month().String(), nil
283 case "day":
284 return fmt.Sprintf("%02d", p.Date().Day()), nil
285 case "weekday":
286 return strconv.Itoa(int(p.Date().Weekday())), nil
287 case "weekdayname":
288 return p.Date().Weekday().String(), nil
289 case "yearday":
290 return strconv.Itoa(p.Date().YearDay()), nil
291 }
292
293 return p.Date().Format(dateField), nil
294 }
295
296 // pageToPermalinkTitle returns the URL-safe form of the title
297 func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) {
298 return l.urlize(p.Title()), nil
299 }
300
301 // pageToPermalinkFilename returns the URL-safe form of the filename
302 func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) {
303 name := l.translationBaseName(p)
304 if name == "index" {
305 // Page bundles; the directory name will hopefully have a better name.
306 dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator)
307 _, name = filepath.Split(dir)
308 } else if name == "_index" {
309 return "", nil
310 }
311
312 return l.urlize(name), nil
313 }
314
315 // if the page has a slug, return the slug, else return the title
316 func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) {
317 if p.Slug() != "" {
318 return l.urlize(p.Slug()), nil
319 }
320 return l.pageToPermalinkTitle(p, a)
321 }
322
323 // if the page has a slug, return the slug, else return the filename
324 func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) {
325 if p.Slug() != "" {
326 return l.urlize(p.Slug()), nil
327 }
328 return l.pageToPermalinkFilename(p, a)
329 }
330
331 func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) {
332 return p.Section(), nil
333 }
334
335 // pageToPermalinkSectionSlug returns the URL-safe form of the first section's slug or title
336 func (l PermalinkExpander) pageToPermalinkSectionSlug(p Page, attr string) (string, error) {
337 sectionPage := p.FirstSection()
338 if sectionPage == nil || sectionPage.IsHome() {
339 return "", nil
340 }
341 return l.pageToPermalinkSlugElseTitle(sectionPage, attr)
342 }
343
344 func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) {
345 return p.CurrentSection().SectionsPath(), nil
346 }
347
348 // pageToPermalinkSectionSlugs returns a path built from all ancestor sections using their slugs or titles
349 func (l PermalinkExpander) pageToPermalinkSectionSlugs(p Page, attr string) (string, error) {
350 sectionSlugsFunc := l.withSectionPagesFunc(l.pageToPermalinkSlugElseTitle, path.Join)
351 return sectionSlugsFunc(p, attr)
352 }
353
354 // pageToPermalinkContentBaseName returns the URL-safe form of the content base name.
355 func (l PermalinkExpander) pageToPermalinkContentBaseName(p Page, _ string) (string, error) {
356 return l.urlize(p.PathInfo().Unnormalized().BaseNameNoIdentifier()), nil
357 }
358
359 // pageToPermalinkSlugOrContentBaseName returns the URL-safe form of the slug, content base name.
360 func (l PermalinkExpander) pageToPermalinkSlugOrContentBaseName(p Page, a string) (string, error) {
361 if p.Slug() != "" {
362 return l.urlize(p.Slug()), nil
363 }
364 name, err := l.pageToPermalinkContentBaseName(p, a)
365 if err != nil {
366 return "", nil
367 }
368 return name, nil
369 }
370
371 func (l PermalinkExpander) translationBaseName(p Page) string {
372 if p.File() == nil {
373 return ""
374 }
375 return p.File().TranslationBaseName()
376 }
377
378 // withSectionPagesFunc returns a function that builds permalink attributes from section pages.
379 // It applies the transformation function f to each ancestor section (Page), then joins the results with the join function.
380 //
381 // Current use is create section-based hierarchical paths using section slugs.
382 func (l PermalinkExpander) withSectionPagesFunc(f func(Page, string) (string, error), join func(...string) string) func(p Page, s string) (string, error) {
383 return func(p Page, s string) (string, error) {
384 var entries []string
385 currentSection := p.CurrentSection()
386
387 // Build section hierarchy: ancestors (reversed to root-first) + current section
388 sections := currentSection.Ancestors().Reverse()
389 sections = append(sections, currentSection)
390
391 for _, section := range sections {
392 if section.IsHome() {
393 continue
394 }
395 entry, err := f(section, s)
396 if err != nil {
397 return "", err
398 }
399 entries = append(entries, entry)
400 }
401
402 return join(entries...), nil
403 }
404 }
405
406 var (
407 nilSliceFunc = func(s []string) []string {
408 return nil
409 }
410 allSliceFunc = func(s []string) []string {
411 return s
412 }
413 )
414
415 // toSliceFunc returns a slice func that slices s according to the cut spec.
416 // The cut spec must be on form [low:high] (one or both can be omitted),
417 // also allowing single slice indices (e.g. [2]) and the special [last] keyword
418 // giving the last element of the slice.
419 // The returned function will be lenient and not panic in out of bounds situation.
420 //
421 // The current use case for this is to use parts of the sections path in permalinks.
422 func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string {
423 cut = strings.ToLower(strings.TrimSpace(cut))
424 if cut == "" {
425 return allSliceFunc
426 }
427
428 if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') {
429 return nilSliceFunc
430 }
431
432 toNFunc := func(s string, low bool) func(ss []string) int {
433 if s == "" {
434 if low {
435 return func(ss []string) int {
436 return 0
437 }
438 } else {
439 return func(ss []string) int {
440 return len(ss)
441 }
442 }
443 }
444
445 if s == "last" {
446 return func(ss []string) int {
447 return len(ss) - 1
448 }
449 }
450
451 n, _ := strconv.Atoi(s)
452 if n < 0 {
453 n = 0
454 }
455 return func(ss []string) int {
456 // Prevent out of bound situations. It would not make
457 // much sense to panic here.
458 if n >= len(ss) {
459 if low {
460 return -1
461 }
462 return len(ss)
463 }
464 return n
465 }
466 }
467
468 opsStr := cut[1 : len(cut)-1]
469 opts := strings.Split(opsStr, ":")
470
471 if !strings.Contains(opsStr, ":") {
472 toN := toNFunc(opts[0], true)
473 return func(s []string) []string {
474 if len(s) == 0 {
475 return nil
476 }
477 n := toN(s)
478 if n < 0 {
479 return []string{}
480 }
481 v := s[n]
482 if v == "" {
483 return nil
484 }
485 return []string{v}
486 }
487 }
488
489 toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false)
490
491 return func(s []string) []string {
492 if len(s) == 0 {
493 return nil
494 }
495 n1, n2 := toN1(s), toN2(s)
496 if n1 < 0 || n2 < 0 {
497 return []string{}
498 }
499 return s[n1:n2]
500 }
501 }
502
503 var permalinksKindsSupport = []string{kinds.KindPage, kinds.KindHome, kinds.KindSection, kinds.KindTaxonomy, kinds.KindTerm}
504
505 func sectionToPathGlob(section string) string {
506 section = strings.Trim(section, sectionCutSet)
507 if section == "" {
508 return "/*"
509 }
510 return "/{" + section + "," + section + "/**}"
511 }
512
513 // DecodePermalinksConfig decodes the permalinks configuration.
514 // It supports both the new slice-based format and the legacy map-based formats.
515 func DecodePermalinksConfig(in any) (PermalinksConfig, error) {
516 if in == nil {
517 return nil, nil
518 }
519
520 switch v := in.(type) {
521 // Check legacy formats first.
522 case map[string]any:
523 return decodePermalinksMap(v)
524 case hmaps.Params:
525 return decodePermalinksMap(v)
526 default:
527 if ms, err := hmaps.ToSliceStringMap(in); err == nil {
528 // New slice format.
529 return decodePermalinksSlice(ms)
530 }
531 return nil, fmt.Errorf("permalinks: unsupported config type %T", in)
532 }
533 }
534
535 func decodePermalinksSlice(ms []map[string]any) (PermalinksConfig, error) {
536 var configs PermalinksConfig
537 for _, m := range ms {
538 m = hmaps.CleanConfigStringMap(m)
539 var cfg PermalinkConfig
540
541 if targetVal, ok := m["target"]; ok {
542 if err := mapstructure.WeakDecode(targetVal, &cfg.Target); err != nil {
543 return nil, fmt.Errorf("permalinks: failed to decode target: %w", err)
544 }
545 cfg.Target.Kind = strings.ToLower(cfg.Target.Kind)
546 cfg.Target.Path = filepath.ToSlash(strings.ToLower(cfg.Target.Path))
547 }
548
549 if patternVal, ok := m["pattern"]; ok {
550 cfg.Pattern, ok = patternVal.(string)
551 if !ok {
552 return nil, fmt.Errorf("permalinks: pattern must be a string, got %T", patternVal)
553 }
554 } else {
555 return nil, fmt.Errorf("permalinks: missing pattern")
556 }
557
558 configs = append(configs, cfg)
559 }
560
561 return configs, nil
562 }
563
564 func decodePermalinksMap(m map[string]any) (PermalinksConfig, error) {
565 var configs PermalinksConfig
566 config := hmaps.CleanConfigStringMap(m)
567
568 for k, v := range config {
569 switch v := v.(type) {
570 case string:
571 // [permalinks]
572 // key = '...'
573 // Backward compat: set for both page and term.
574 configs = append(configs,
575 PermalinkConfig{Target: PageMatcher{Kind: kinds.KindPage, Path: sectionToPathGlob(k)}, Pattern: v},
576 PermalinkConfig{Target: PageMatcher{Kind: kinds.KindTerm, Path: sectionToPathGlob(k)}, Pattern: v},
577 )
578
579 case hmaps.Params:
580 // [permalinks.kind]
581 // section = '...'
582 if !hstrings.InSlice(permalinksKindsSupport, k) {
583 return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSupport)
584 }
585 for k2, v2 := range v {
586 switch v2 := v2.(type) {
587 case string:
588 configs = append(configs,
589 PermalinkConfig{Target: PageMatcher{Kind: k, Path: sectionToPathGlob(k2)}, Pattern: v2},
590 )
591 default:
592 return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k)
593 }
594 }
595
596 default:
597 return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k)
598 }
599 }
600 return configs, nil
601 }