Debian Codegraph @

resources/page/page_paths.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 "bytes"
18 "path"
19 "path/filepath"
20 "strings"
21 "sync"
22
23 "github.com/gohugoio/hugo/common/paths"
24 "github.com/gohugoio/hugo/common/urls"
25 "github.com/gohugoio/hugo/helpers"
26 "github.com/gohugoio/hugo/output"
27 "github.com/gohugoio/hugo/resources/kinds"
28 )
29
30 const slash = "/"
31
32 // TargetPathDescriptor describes how a file path for a given resource
33 // should look like on the file system. The same descriptor is then later used to
34 // create both the permalinks and the relative links, paginator URLs etc.
35 //
36 // The big motivating behind this is to have only one source of truth for URLs,
37 // and by that also get rid of most of the fragile string parsing/encoding etc.
38
39 type TargetPathDescriptor struct {
40 PathSpec *helpers.PathSpec
41
42 Type output.Format
43 Kind string
44
45 Path *paths.Path
46
47 // The directory part of the target path with any section slugs applied.
48 Dir string
49
50 // For regular content pages this is either
51 // 1) the Slug, if set,
52 // 2) the file base name (TranslationBaseName).
53 BaseName string
54
55 // PrefixFilePath contains zero or more content dimensions used as a file
56 // path prefix. Dimensions are ordered role/version/language for
57 // single-host and language/role/version for multihost.
58 // Example (single-host): guest/v1.0.0/en
59 // Example (multihost): en/guest/v1.0.0
60 PrefixFilePath string
61
62 // PrefixLink contains zero or more content dimensions used as a link
63 // prefix. Dimensions are ordered role/version/language for single-host,
64 // but the language dimension is excluded for multihost.
65 // Example (single-host): guest/v1.0.0/en
66 // Example (multihost): guest/v1.0.0
67 PrefixLink string
68
69 // If in multihost mode etc., every link/path needs to be prefixed, even
70 // if set in URL.
71 ForcePrefix bool
72
73 // URL from front matter if set. Will override any Slug etc.
74 URL string
75
76 // Used to create paginator links.
77 Addends string
78
79 // The expanded permalink if defined for the section, ready to use.
80 ExpandedPermalink string
81
82 // Some types cannot have uglyURLs, even if globally enabled, RSS being one example.
83 UglyURLs bool
84 }
85
86 // TODO(bep) move this type.
87 type TargetPaths struct {
88 // Where to store the file on disk relative to the publish dir. OS slashes.
89 TargetFilename string
90
91 // The directory to write sub-resources of the above.
92 SubResourceBaseTarget string
93
94 // The base for creating links to sub-resources of the above.
95 SubResourceBaseLink string
96
97 // The relative permalink to this resources. Unix slashes.
98 Link string
99 }
100
101 func (p TargetPaths) RelPermalink(s *helpers.PathSpec) string {
102 return s.PrependBasePath(p.Link, false)
103 }
104
105 func (p TargetPaths) PermalinkForOutputFormat(s *helpers.PathSpec, f output.Format) string {
106 var baseURL urls.BaseURL
107 var err error
108 if f.Protocol != "" {
109 baseURL, err = s.Cfg.BaseURL().WithProtocol(f.Protocol)
110 if err != nil {
111 return ""
112 }
113 } else {
114 baseURL = s.Cfg.BaseURL()
115 }
116 baseURLstr := baseURL.String()
117 return s.PermalinkForBaseURL(p.Link, baseURLstr)
118 }
119
120 func CreateTargetPaths(d TargetPathDescriptor) (tp TargetPaths) {
121 // Normalize all file Windows paths to simplify what's next.
122 if helpers.FilePathSeparator != "/" {
123 d.PrefixFilePath = filepath.ToSlash(d.PrefixFilePath)
124 }
125
126 if !d.Type.Root && d.URL != "" && !strings.HasPrefix(d.URL, "/") {
127 // Treat this as a context relative URL
128 d.ForcePrefix = true
129 }
130
131 if d.URL != "" {
132 d.URL = filepath.ToSlash(d.URL)
133 if strings.Contains(d.URL, "..") {
134 d.URL = path.Join("/", d.URL)
135 }
136 }
137
138 if d.Type.Root && !d.ForcePrefix {
139 d.PrefixFilePath = ""
140 d.PrefixLink = ""
141 }
142
143 pb := getPagePathBuilder(d)
144 defer putPagePathBuilder(pb)
145
146 pb.fullSuffix = d.Type.MediaType.FirstSuffix.FullSuffix
147
148 // The top level index files, i.e. the home page etc., needs
149 // the index base even when uglyURLs is enabled.
150 needsBase := true
151
152 pb.isUgly = (d.UglyURLs || d.Type.Ugly) && !d.Type.NoUgly
153 pb.baseNameSameAsType = !d.Path.IsBundle() && d.BaseName != "" && d.BaseName == d.Type.BaseName
154 indexIsUglyKind := d.Kind == kinds.KindHome || d.Kind == kinds.KindSection || d.Kind == kinds.KindTaxonomy
155 indexIsUglyKind = indexIsUglyKind && pb.isUgly
156
157 if d.ExpandedPermalink == "" && pb.baseNameSameAsType {
158 pb.isUgly = true
159 }
160
161 if d.Type.Path != "" {
162 pb.Add(d.Type.Path)
163 }
164
165 if d.Type == output.HTTPStatus404HTMLFormat || d.Type == output.SitemapFormat || d.Type == output.RobotsTxtFormat {
166 pb.noSubResources = true
167 } else if d.Kind != kinds.KindPage && d.URL == "" {
168 if d.ExpandedPermalink != "" {
169 pb.Add(d.ExpandedPermalink)
170 } else {
171 pb.Add(d.Dir)
172 }
173 needsBase = false
174 }
175
176 if d.Kind != kinds.KindHome && d.URL != "" {
177 pb.Add(paths.FieldsSlash(d.URL)...)
178
179 if d.Addends != "" {
180 pb.Add(d.Addends)
181 }
182
183 hasDot := strings.Contains(d.URL, ".")
184 hasSlash := strings.HasSuffix(d.URL, "/")
185
186 if hasSlash || !hasDot {
187 pb.Add(d.Type.BaseName + pb.fullSuffix)
188 } else if hasDot {
189 pb.fullSuffix = paths.Ext(d.URL)
190 }
191
192 if pb.IsHtmlIndex() {
193 pb.linkUpperOffset = 1
194 }
195
196 if d.ForcePrefix {
197
198 // Prepend language prefix if not already set in URL
199 if d.PrefixFilePath != "" && !strings.HasPrefix(d.URL, "/"+d.PrefixFilePath) {
200 pb.prefixPath = d.PrefixFilePath
201 }
202
203 if d.PrefixLink != "" && !strings.HasPrefix(d.URL, "/"+d.PrefixLink) {
204 pb.prefixLink = d.PrefixLink
205 }
206 }
207 } else if !kinds.IsBranch(d.Kind) {
208 if d.ExpandedPermalink != "" {
209 pb.Add(d.ExpandedPermalink)
210 } else {
211 pb.Add(d.Dir)
212 if d.BaseName != "" {
213 pb.Add(d.BaseName)
214 } else {
215 pb.Add(d.Path.BaseNameNoIdentifier())
216 }
217 }
218
219 if d.Addends != "" {
220 pb.Add(d.Addends)
221 }
222
223 if pb.isUgly {
224 pb.ConcatLast(pb.fullSuffix)
225 } else {
226 pb.Add(d.Type.BaseName + pb.fullSuffix)
227 }
228
229 if pb.IsHtmlIndex() {
230 pb.linkUpperOffset = 1
231 }
232
233 if d.PrefixFilePath != "" {
234 pb.prefixPath = d.PrefixFilePath
235 }
236
237 if d.PrefixLink != "" {
238 pb.prefixLink = d.PrefixLink
239 }
240 } else {
241 if d.Addends != "" {
242 pb.Add(d.Addends)
243 }
244
245 needsBase = needsBase && d.Addends == ""
246
247 if needsBase || (!pb.isUgly || indexIsUglyKind) {
248 pb.Add(d.Type.BaseName + pb.fullSuffix)
249 } else {
250 pb.ConcatLast(pb.fullSuffix)
251 }
252
253 if !indexIsUglyKind && pb.IsHtmlIndex() {
254 pb.linkUpperOffset = 1
255 }
256
257 if d.PrefixFilePath != "" {
258 pb.prefixPath = d.PrefixFilePath
259 }
260
261 if d.PrefixLink != "" {
262 pb.prefixLink = d.PrefixLink
263 }
264 }
265
266 // if page URL is explicitly set in frontmatter,
267 // preserve its value without sanitization
268 if d.URL == "" {
269 // Note: MakePathSanitized will lower case the path if
270 // disablePathToLower isn't set.
271 pb.Sanitize()
272 }
273
274 link := pb.Link()
275
276 pagePath := pb.PathFile()
277
278 tp.TargetFilename = filepath.FromSlash(pagePath)
279 if !pb.noSubResources {
280 tp.SubResourceBaseTarget = pb.PathDir()
281 tp.SubResourceBaseLink = pb.LinkDir()
282 }
283
284 // paths.{URL,Path}Escape rely on url.Parse which
285 // will consider # a fragment identifier, so it and
286 // and everything after it will be stripped from
287 // `link`, so we need to escape it first.
288 link = strings.ReplaceAll(link, "#", "%23")
289
290 if d.URL != "" {
291 tp.Link = paths.URLEscape(link)
292 } else {
293 // This is slightly faster for when we know we don't have any
294 // query or scheme etc.
295 tp.Link = paths.PathEscape(link)
296 }
297 if tp.Link == "" {
298 tp.Link = "/"
299 }
300
301 return
302 }
303
304 // When adding state here, remember to update putPagePathBuilder.
305 type pagePathBuilder struct {
306 els []string
307 b bytes.Buffer
308
309 d TargetPathDescriptor
310
311 // Builder state.
312 isUgly bool
313 baseNameSameAsType bool
314 noSubResources bool
315 fullSuffix string // File suffix including any ".".
316 prefixLink string
317 prefixPath string
318 linkUpperOffset int
319 }
320
321 func (p *pagePathBuilder) Add(el ...string) {
322 // Filter empty and slashes.
323 n := 0
324 for _, e := range el {
325 if e != "" && e != slash {
326 el[n] = e
327 n++
328 }
329 }
330 el = el[:n]
331
332 p.els = append(p.els, el...)
333 }
334
335 func (p *pagePathBuilder) ConcatLast(s string) {
336 if len(p.els) == 0 {
337 p.Add(s)
338 return
339 }
340 old := p.els[len(p.els)-1]
341 if old == "" {
342 p.els[len(p.els)-1] = s
343 return
344 }
345 if old[len(old)-1] == '/' {
346 old = old[:len(old)-1]
347 }
348 p.els[len(p.els)-1] = old + s
349 }
350
351 func (p *pagePathBuilder) IsHtmlIndex() bool {
352 return p.Last() == "index.html"
353 }
354
355 func (p *pagePathBuilder) Last() string {
356 if p.els == nil {
357 return ""
358 }
359 return p.els[len(p.els)-1]
360 }
361
362 func (p *pagePathBuilder) Link() string {
363 link := p.Path(p.linkUpperOffset)
364
365 if p.baseNameSameAsType {
366 link = strings.TrimSuffix(link, p.d.BaseName)
367 }
368
369 if p.prefixLink != "" {
370 link = "/" + p.prefixLink + link
371 }
372
373 if p.linkUpperOffset > 0 && !strings.HasSuffix(link, "/") {
374 link += "/"
375 }
376
377 return link
378 }
379
380 func (p *pagePathBuilder) LinkDir() string {
381 if p.noSubResources {
382 return ""
383 }
384
385 pathDir := p.PathDirBase()
386
387 if p.prefixLink != "" {
388 pathDir = "/" + p.prefixLink + pathDir
389 }
390
391 return pathDir
392 }
393
394 func (p *pagePathBuilder) Path(upperOffset int) string {
395 upper := len(p.els)
396 if upperOffset > 0 {
397 upper -= upperOffset
398 }
399 p.b.Reset()
400
401 var hadTrailingSlash bool
402 for _, el := range p.els[:upper] {
403 if !hadTrailingSlash && !strings.HasPrefix(el, "/") {
404 p.b.WriteByte('/')
405 }
406 hadTrailingSlash = strings.HasSuffix(el, "/")
407 p.b.WriteString(el)
408 }
409 return p.b.String()
410 }
411
412 func (p *pagePathBuilder) PathDir() string {
413 dir := p.PathDirBase()
414 if p.prefixPath != "" {
415 dir = "/" + p.prefixPath + dir
416 }
417 return dir
418 }
419
420 func (p *pagePathBuilder) PathDirBase() string {
421 if p.noSubResources {
422 return ""
423 }
424
425 dir := p.Path(0)
426 isIndex := strings.HasPrefix(p.Last(), p.d.Type.BaseName+".")
427
428 if isIndex {
429 dir = paths.Dir(dir)
430 } else {
431 dir = strings.TrimSuffix(dir, p.fullSuffix)
432 }
433
434 if dir == "/" {
435 dir = ""
436 }
437
438 return dir
439 }
440
441 func (p *pagePathBuilder) PathFile() string {
442 dir := p.Path(0)
443
444 if p.prefixPath != "" {
445 dir = "/" + p.prefixPath + dir
446 }
447 return dir
448 }
449
450 func (p *pagePathBuilder) Prepend(el ...string) {
451 p.els = append(p.els[:0], append(el, p.els[0:]...)...)
452 }
453
454 func (p *pagePathBuilder) Sanitize() {
455 for i, el := range p.els {
456 p.els[i] = p.d.PathSpec.MakePathSanitized(el)
457 }
458 }
459
460 var pagePathBuilderPool = &sync.Pool{
461 New: func() any {
462 return &pagePathBuilder{}
463 },
464 }
465
466 func getPagePathBuilder(d TargetPathDescriptor) *pagePathBuilder {
467 b := pagePathBuilderPool.Get().(*pagePathBuilder)
468 b.d = d
469 return b
470 }
471
472 func putPagePathBuilder(b *pagePathBuilder) {
473 b.els = b.els[:0]
474 b.fullSuffix = ""
475 b.baseNameSameAsType = false
476 b.isUgly = false
477 b.noSubResources = false
478 b.prefixLink = ""
479 b.prefixPath = ""
480 b.linkUpperOffset = 0
481 pagePathBuilderPool.Put(b)
482 }