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 // segmentReplacer replaces path separators in a title before it's used to
297 // build a single path segment (e.g. an automatically derived slug). Without
298 // this, a title containing a "/" would silently introduce an extra, unintended
299 // path segment in the resulting URL. See #3577.
300 var segmentReplacer = strings.NewReplacer("/", "-", "\\", "-")
301
302 // pageToPermalinkTitle returns the URL-safe form of the title.
303 func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) {
304 title := p.Title()
305 if p.Kind() != kinds.KindTaxonomy && p.Kind() != kinds.KindTerm {
306 // Taxonomy and term pages are allowed to have '/' in their title
307 // (the term itself) to build multi-level taxonomy hierarchies.
308 // See #5571. All other kinds derive a single path segment from the
309 // title, so path separators must not be allowed through.
310 title = segmentReplacer.Replace(title)
311 }
312 return l.urlize(title), nil
313 }
314
315 // pageToPermalinkFilename returns the URL-safe form of the filename
316 func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) {
317 name := l.translationBaseName(p)
318 if name == "index" {
319 // Page bundles; the directory name will hopefully have a better name.
320 dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator)
321 _, name = filepath.Split(dir)
322 } else if name == "_index" {
323 return "", nil
324 }
325
326 return l.urlize(name), nil
327 }
328
329 // if the page has a slug, return the slug, else return the title
330 func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) {
331 if p.Slug() != "" {
332 return l.urlize(p.Slug()), nil
333 }
334 return l.pageToPermalinkTitle(p, a)
335 }
336
337 // if the page has a slug, return the slug, else return the filename
338 func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) {
339 if p.Slug() != "" {
340 return l.urlize(p.Slug()), nil
341 }
342 return l.pageToPermalinkFilename(p, a)
343 }
344
345 func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) {
346 return p.Section(), nil
347 }
348
349 // pageToPermalinkSectionSlug returns the URL-safe form of the first section's slug or title
350 func (l PermalinkExpander) pageToPermalinkSectionSlug(p Page, attr string) (string, error) {
351 sectionPage := p.FirstSection()
352 if sectionPage == nil || sectionPage.IsHome() {
353 return "", nil
354 }
355 return l.pageToPermalinkSlugElseTitle(sectionPage, attr)
356 }
357
358 func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) {
359 return p.CurrentSection().SectionsPath(), nil
360 }
361
362 // pageToPermalinkSectionSlugs returns a path built from all ancestor sections using their slugs or titles
363 func (l PermalinkExpander) pageToPermalinkSectionSlugs(p Page, attr string) (string, error) {
364 sectionSlugsFunc := l.withSectionPagesFunc(l.pageToPermalinkSlugElseTitle, path.Join)
365 return sectionSlugsFunc(p, attr)
366 }
367
368 // pageToPermalinkContentBaseName returns the URL-safe form of the content base name.
369 func (l PermalinkExpander) pageToPermalinkContentBaseName(p Page, _ string) (string, error) {
370 return l.urlize(p.PathInfo().Unnormalized().BaseNameNoIdentifier()), nil
371 }
372
373 // pageToPermalinkSlugOrContentBaseName returns the URL-safe form of the slug, content base name.
374 func (l PermalinkExpander) pageToPermalinkSlugOrContentBaseName(p Page, a string) (string, error) {
375 if p.Slug() != "" {
376 return l.urlize(p.Slug()), nil
377 }
378 name, err := l.pageToPermalinkContentBaseName(p, a)
379 if err != nil {
380 return "", nil
381 }
382 return name, nil
383 }
384
385 func (l PermalinkExpander) translationBaseName(p Page) string {
386 if p.File() == nil {
387 return ""
388 }
389 return p.File().TranslationBaseName()
390 }
391
392 // withSectionPagesFunc returns a function that builds permalink attributes from section pages.
393 // It applies the transformation function f to each ancestor section (Page), then joins the results with the join function.
394 //
395 // Current use is create section-based hierarchical paths using section slugs.
396 func (l PermalinkExpander) withSectionPagesFunc(f func(Page, string) (string, error), join func(...string) string) func(p Page, s string) (string, error) {
397 return func(p Page, s string) (string, error) {
398 var entries []string
399 currentSection := p.CurrentSection()
400
401 // Build section hierarchy: ancestors (reversed to root-first) + current section
402 sections := currentSection.Ancestors().Reverse()
403 sections = append(sections, currentSection)
404
405 for _, section := range sections {
406 if section.IsHome() {
407 continue
408 }
409 entry, err := f(section, s)
410 if err != nil {
411 return "", err
412 }
413 entries = append(entries, entry)
414 }
415
416 return join(entries...), nil
417 }
418 }
419
420 var (
421 nilSliceFunc = func(s []string) []string {
422 return nil
423 }
424 allSliceFunc = func(s []string) []string {
425 return s
426 }
427 )
428
429 // toSliceFunc returns a slice func that slices s according to the cut spec.
430 // The cut spec must be on form [low:high] (one or both can be omitted),
431 // also allowing single slice indices (e.g. [2]) and the special [last] keyword
432 // giving the last element of the slice.
433 // The returned function will be lenient and not panic in out of bounds situation.
434 //
435 // The current use case for this is to use parts of the sections path in permalinks.
436 func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string {
437 cut = strings.ToLower(strings.TrimSpace(cut))
438 if cut == "" {
439 return allSliceFunc
440 }
441
442 if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') {
443 return nilSliceFunc
444 }
445
446 toNFunc := func(s string, low bool) func(ss []string) int {
447 if s == "" {
448 if low {
449 return func(ss []string) int {
450 return 0
451 }
452 } else {
453 return func(ss []string) int {
454 return len(ss)
455 }
456 }
457 }
458
459 if s == "last" {
460 return func(ss []string) int {
461 return len(ss) - 1
462 }
463 }
464
465 n, _ := strconv.Atoi(s)
466 if n < 0 {
467 n = 0
468 }
469 return func(ss []string) int {
470 // Prevent out of bound situations. It would not make
471 // much sense to panic here.
472 if n >= len(ss) {
473 if low {
474 return -1
475 }
476 return len(ss)
477 }
478 return n
479 }
480 }
481
482 opsStr := cut[1 : len(cut)-1]
483 opts := strings.Split(opsStr, ":")
484
485 if !strings.Contains(opsStr, ":") {
486 toN := toNFunc(opts[0], true)
487 return func(s []string) []string {
488 if len(s) == 0 {
489 return nil
490 }
491 n := toN(s)
492 if n < 0 {
493 return []string{}
494 }
495 v := s[n]
496 if v == "" {
497 return nil
498 }
499 return []string{v}
500 }
501 }
502
503 toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false)
504
505 return func(s []string) []string {
506 if len(s) == 0 {
507 return nil
508 }
509 n1, n2 := toN1(s), toN2(s)
510 if n1 < 0 || n2 < 0 {
511 return []string{}
512 }
513 return s[n1:n2]
514 }
515 }
516
517 var permalinksKindsSupport = []string{kinds.KindPage, kinds.KindHome, kinds.KindSection, kinds.KindTaxonomy, kinds.KindTerm}
518
519 func sectionToPathGlob(section string) string {
520 section = strings.Trim(section, sectionCutSet)
521 if section == "" {
522 return "/*"
523 }
524 return "/{" + section + "," + section + "/**}"
525 }
526
527 // DecodePermalinksConfig decodes the permalinks configuration.
528 // It supports both the new slice-based format and the legacy map-based formats.
529 func DecodePermalinksConfig(in any) (PermalinksConfig, error) {
530 if in == nil {
531 return nil, nil
532 }
533
534 switch v := in.(type) {
535 // Check legacy formats first.
536 case map[string]any:
537 return decodePermalinksMap(v)
538 case hmaps.Params:
539 return decodePermalinksMap(v)
540 default:
541 if ms, err := hmaps.ToSliceStringMap(in); err == nil {
542 // New slice format.
543 return decodePermalinksSlice(ms)
544 }
545 return nil, fmt.Errorf("permalinks: unsupported config type %T", in)
546 }
547 }
548
549 func decodePermalinksSlice(ms []map[string]any) (PermalinksConfig, error) {
550 var configs PermalinksConfig
551 for _, m := range ms {
552 m = hmaps.CleanConfigStringMap(m)
553 var cfg PermalinkConfig
554
555 if targetVal, ok := m["target"]; ok {
556 if err := mapstructure.WeakDecode(targetVal, &cfg.Target); err != nil {
557 return nil, fmt.Errorf("permalinks: failed to decode target: %w", err)
558 }
559 cfg.Target.Kind = strings.ToLower(cfg.Target.Kind)
560 cfg.Target.Path = filepath.ToSlash(strings.ToLower(cfg.Target.Path))
561 }
562
563 if patternVal, ok := m["pattern"]; ok {
564 cfg.Pattern, ok = patternVal.(string)
565 if !ok {
566 return nil, fmt.Errorf("permalinks: pattern must be a string, got %T", patternVal)
567 }
568 } else {
569 return nil, fmt.Errorf("permalinks: missing pattern")
570 }
571
572 configs = append(configs, cfg)
573 }
574
575 return configs, nil
576 }
577
578 func decodePermalinksMap(m map[string]any) (PermalinksConfig, error) {
579 var configs PermalinksConfig
580 config := hmaps.CleanConfigStringMap(m)
581
582 for k, v := range config {
583 switch v := v.(type) {
584 case string:
585 // [permalinks]
586 // key = '...'
587 // Backward compat: set for both page and term.
588 configs = append(configs,
589 PermalinkConfig{Target: PageMatcher{Kind: kinds.KindPage, Path: sectionToPathGlob(k)}, Pattern: v},
590 PermalinkConfig{Target: PageMatcher{Kind: kinds.KindTerm, Path: sectionToPathGlob(k)}, Pattern: v},
591 )
592
593 case hmaps.Params:
594 // [permalinks.kind]
595 // section = '...'
596 if !hstrings.InSlice(permalinksKindsSupport, k) {
597 return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSupport)
598 }
599 for k2, v2 := range v {
600 switch v2 := v2.(type) {
601 case string:
602 configs = append(configs,
603 PermalinkConfig{Target: PageMatcher{Kind: k, Path: sectionToPathGlob(k2)}, Pattern: v2},
604 )
605 default:
606 return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k)
607 }
608 }
609
610 default:
611 return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k)
612 }
613 }
614 return configs, nil
615 }