Debian Codegraph @

resources/resource.go

raw
1 // Copyright 2024 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 resources
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "io"
21 "mime"
22 "strings"
23 "sync"
24 "sync/atomic"
25
26 "github.com/gohugoio/hugo/identity"
27 "github.com/gohugoio/hugo/resources/internal"
28 "github.com/spf13/cast"
29
30 "github.com/gohugoio/hugo/common/hashing"
31 "github.com/gohugoio/hugo/common/herrors"
32 "github.com/gohugoio/hugo/common/hmaps"
33 "github.com/gohugoio/hugo/common/hsync"
34 "github.com/gohugoio/hugo/common/paths"
35
36 "github.com/gohugoio/hugo/media"
37
38 "github.com/gohugoio/hugo/common/hugio"
39 "github.com/gohugoio/hugo/resources/resource"
40
41 "github.com/gohugoio/hugo/helpers"
42 )
43
44 var (
45 _ resource.ContentResource = (*genericResource)(nil)
46 _ resource.ReadSeekCloserResource = (*genericResource)(nil)
47 _ resource.Resource = (*genericResource)(nil)
48 _ resource.Source = (*genericResource)(nil)
49 _ resource.Cloner = (*genericResource)(nil)
50 _ resource.ResourcesLanguageMerger = (*resource.Resources)(nil)
51 _ resource.Identifier = (*genericResource)(nil)
52 _ resource.TransientIdentifier = (*genericResource)(nil)
53 _ targetPathProvider = (*genericResource)(nil)
54 _ sourcePathProvider = (*genericResource)(nil)
55 _ identity.IdentityGroupProvider = (*genericResource)(nil)
56 _ identity.DependencyManagerProvider = (*genericResource)(nil)
57 _ identity.Identity = (*genericResource)(nil)
58 _ fileInfo = (*genericResource)(nil)
59 _ isPublishedProvider = (*genericResource)(nil)
60 )
61
62 type ResourceSourceDescriptor struct {
63 // The source content.
64 OpenReadSeekCloser hugio.OpenReadSeekCloser
65
66 // The canonical source path.
67 Path *paths.Path
68
69 // The normalized name of the resource.
70 NameNormalized string
71
72 // The name of the resource as it was read from the source.
73 NameOriginal string
74
75 // The title of the resource.
76 Title string
77
78 // Any base paths prepended to the target path. This will also typically be the
79 // language code, but setting it here means that it should not have any effect on
80 // the permalink.
81 // This may be several values. In multihost mode we may publish the same resources to
82 // multiple targets.
83 TargetBasePaths []string
84
85 TargetPath string
86 BasePathRelPermalink string
87 BasePathTargetPath string
88 SourceFilenameOrPath string // Used for error logging.
89
90 // The Data to associate with this resource.
91 Data map[string]any
92
93 // The Params to associate with this resource.
94 Params hmaps.Params
95
96 // Delay publishing until either Permalink or RelPermalink is called. Maybe never.
97 LazyPublish bool
98
99 // Whether to include the hash of the source content in the resource key.
100 IncludeHashInKey bool
101
102 // Set when its known up front, else it's resolved from the target filename.
103 MediaType media.Type
104
105 // Used to track dependencies (e.g. imports). May be nil if that's of no concern.
106 DependencyManager identity.Manager
107
108 // A shared identity for this resource and all its clones.
109 // If this is not set, an Identity is created.
110 GroupIdentity identity.Identity
111 }
112
113 func (fd *ResourceSourceDescriptor) init(r *Spec) error {
114 if len(fd.TargetBasePaths) == 0 {
115 // If not set, we publish the same resource to all hosts.
116 fd.TargetBasePaths = r.MultihostTargetBasePaths
117 }
118
119 if fd.OpenReadSeekCloser == nil {
120 panic(errors.New("OpenReadSeekCloser is nil"))
121 }
122
123 if fd.TargetPath == "" {
124 panic(errors.New("RelPath is empty"))
125 }
126
127 if fd.Params == nil {
128 fd.Params = make(hmaps.Params)
129 }
130
131 if fd.Path == nil {
132 fd.Path = r.Cfg.PathParser().Parse("", fd.TargetPath)
133 }
134
135 if fd.TargetPath == "" {
136 fd.TargetPath = fd.Path.Path()
137 } else {
138 fd.TargetPath = paths.ToSlashPreserveLeading(fd.TargetPath)
139 }
140
141 fd.BasePathRelPermalink = paths.ToSlashPreserveLeading(fd.BasePathRelPermalink)
142 if fd.BasePathRelPermalink == "/" {
143 fd.BasePathRelPermalink = ""
144 }
145 fd.BasePathTargetPath = paths.ToSlashPreserveLeading(fd.BasePathTargetPath)
146 if fd.BasePathTargetPath == "/" {
147 fd.BasePathTargetPath = ""
148 }
149
150 fd.TargetPath = paths.ToSlashPreserveLeading(fd.TargetPath)
151
152 if fd.NameNormalized == "" {
153 fd.NameNormalized = fd.TargetPath
154 }
155
156 if fd.NameOriginal == "" {
157 fd.NameOriginal = fd.NameNormalized
158 }
159
160 if fd.Title == "" {
161 fd.Title = fd.NameOriginal
162 }
163
164 mediaType := fd.MediaType
165 if mediaType.IsZero() {
166 ext := fd.Path.Ext()
167 var (
168 found bool
169 suffixInfo media.SuffixInfo
170 )
171 mediaType, suffixInfo, found = r.MediaTypes().GetFirstBySuffix(ext)
172 // TODO(bep) we need to handle these ambiguous types better, but in this context
173 // we most likely want the application/xml type.
174 if suffixInfo.Suffix == "xml" && mediaType.SubType == "rss" {
175 mediaType, found = r.MediaTypes().GetByType("application/xml")
176 }
177
178 if !found {
179 // A fallback. Note that mime.TypeByExtension is slow by Hugo standards,
180 // so we should configure media types to avoid this lookup for most
181 // situations.
182 mimeStr := mime.TypeByExtension("." + ext)
183 if mimeStr != "" {
184 mediaType, _ = media.FromStringAndExt(mimeStr, ext)
185 }
186 }
187 }
188
189 fd.MediaType = mediaType
190
191 if fd.DependencyManager == nil {
192 fd.DependencyManager = r.Cfg.NewIdentityManager()
193 }
194
195 return nil
196 }
197
198 type ResourceTransformer interface {
199 resource.Resource
200 Transformer
201 }
202
203 type Transformer interface {
204 Transform(...ResourceTransformation) (ResourceTransformer, error)
205 TransformWithContext(context.Context, ...ResourceTransformation) (ResourceTransformer, error)
206 }
207
208 func NewFeatureNotAvailableTransformer(key string, elements ...any) ResourceTransformation {
209 return transformerNotAvailable{
210 key: internal.NewResourceTransformationKey(key, elements...),
211 }
212 }
213
214 type transformerNotAvailable struct {
215 key internal.ResourceTransformationKey
216 }
217
218 func (t transformerNotAvailable) Transform(ctx *ResourceTransformationCtx) error {
219 return herrors.ErrFeatureNotAvailable
220 }
221
222 func (t transformerNotAvailable) Key() internal.ResourceTransformationKey {
223 return t.key
224 }
225
226 // resourceCopier is for internal use.
227 type resourceCopier interface {
228 cloneTo(targetPath string) resource.Resource
229 }
230
231 // Copy copies r to the targetPath given.
232 func Copy(r resource.Resource, targetPath string) resource.Resource {
233 return r.(resourceCopier).cloneTo(targetPath)
234 }
235
236 type baseResourceResource interface {
237 resource.Cloner
238 resourceCopier
239 resource.ContentProvider
240 resource.Resource
241 resource.Identifier
242 }
243
244 type baseResourceInternal interface {
245 resource.Source
246 resource.NameNormalizedProvider
247
248 sourcePath() string
249 fileInfo
250 mediaTypeAssigner
251 targetPather
252 isPublishedProvider
253
254 ReadSeekCloser() (hugio.ReadSeekCloser, error)
255
256 identity.IdentityGroupProvider
257 identity.DependencyManagerProvider
258
259 // For internal use.
260 cloneWithUpdates(*transformationUpdate) (baseResource, error)
261 tryTransformedFileCache(key string, u *transformationUpdate) io.ReadCloser
262
263 getResourcePaths() internal.ResourcePaths
264
265 specProvider
266 openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error)
267 }
268
269 type specProvider interface {
270 getSpec() *Spec
271 }
272
273 type baseResource interface {
274 baseResourceResource
275 baseResourceInternal
276 resource.Staler
277 }
278
279 type commonResource struct{}
280
281 // Slice is for internal use.
282 // for the template functions. See collections.Slice.
283 func (commonResource) Slice(in any) (any, error) {
284 switch items := in.(type) {
285 case resource.Resources:
286 return items, nil
287 case []any:
288 groups := make(resource.Resources, len(items))
289 for i, v := range items {
290 g, ok := v.(resource.Resource)
291 if !ok {
292 return nil, fmt.Errorf("type %T is not a Resource", v)
293 }
294 groups[i] = g
295 {
296 }
297 }
298 return groups, nil
299 default:
300 return nil, fmt.Errorf("invalid slice type %T", items)
301 }
302 }
303
304 type fileInfo interface {
305 setOpenSource(hugio.OpenReadSeekCloser)
306 setSourceFilenameIsHash(bool)
307 setTargetPath(internal.ResourcePaths)
308 size() int64
309 hashProvider
310 }
311
312 type hashProvider interface {
313 hash() uint64
314 }
315
316 var _ resource.StaleInfo = (*StaleValue[any])(nil)
317
318 type StaleValue[V any] struct {
319 // The value.
320 Value V
321
322 // StaleVersionFunc reports the current version of the value.
323 // This always starts out at 0 and get incremented on staleness.
324 StaleVersionFunc func() uint32
325 }
326
327 func (s *StaleValue[V]) StaleVersion() uint32 {
328 return s.StaleVersionFunc()
329 }
330
331 type AtomicStaler struct {
332 stale uint32
333 }
334
335 func (s *AtomicStaler) MarkStale() {
336 atomic.AddUint32(&s.stale, 1)
337 }
338
339 func (s *AtomicStaler) StaleVersion() uint32 {
340 return atomic.LoadUint32(&(s.stale))
341 }
342
343 // For internal use.
344 type GenericResourceTestInfo struct {
345 Paths internal.ResourcePaths
346 }
347
348 // For internal use.
349 func GetTestInfoForResource(r resource.Resource) GenericResourceTestInfo {
350 var gr *genericResource
351 switch v := r.(type) {
352 case *genericResource:
353 gr = v
354 case *resourceAdapter:
355 gr = v.target.(*genericResource)
356 default:
357 panic(fmt.Sprintf("unknown resource type: %T", r))
358 }
359 return GenericResourceTestInfo{
360 Paths: gr.paths,
361 }
362 }
363
364 // genericResource represents a generic linkable resource.
365 type genericResource struct {
366 publishInit *hsync.OnceMore
367
368 key string
369 keyInit *sync.Once
370
371 sd ResourceSourceDescriptor
372 paths internal.ResourcePaths
373
374 includeHashInKey bool
375 sourceFilenameIsHash bool
376
377 h *resourceHash // A hash of the source content. Is only calculated in caching situations.
378
379 resource.Staler
380
381 title string
382 name string
383 params map[string]any
384
385 spec *Spec
386 }
387
388 func (l *genericResource) IdentifierBase() string {
389 return l.sd.Path.IdentifierBase()
390 }
391
392 func (l *genericResource) GetIdentityGroup() identity.Identity {
393 return l.sd.GroupIdentity
394 }
395
396 func (l *genericResource) GetDependencyManager() identity.Manager {
397 return l.sd.DependencyManager
398 }
399
400 func (l *genericResource) ReadSeekCloser() (hugio.ReadSeekCloser, error) {
401 return l.sd.OpenReadSeekCloser()
402 }
403
404 func (l *genericResource) Clone() resource.Resource {
405 return l.clone()
406 }
407
408 func (l *genericResource) size() int64 {
409 l.hash()
410 return l.h.size
411 }
412
413 func (l *genericResource) hash() uint64 {
414 if err := l.h.init(l); err != nil {
415 panic(err)
416 }
417 return l.h.value
418 }
419
420 func (l *genericResource) setOpenSource(openSource hugio.OpenReadSeekCloser) {
421 l.sd.OpenReadSeekCloser = openSource
422 }
423
424 func (l *genericResource) setSourceFilenameIsHash(b bool) {
425 l.sourceFilenameIsHash = b
426 }
427
428 func (l *genericResource) setTargetPath(d internal.ResourcePaths) {
429 l.paths = d
430 }
431
432 func (l *genericResource) cloneTo(targetPath string) resource.Resource {
433 c := l.clone()
434 c.paths = c.paths.FromTargetPath(targetPath)
435 return c
436 }
437
438 func (l *genericResource) Content(context.Context) (any, error) {
439 r, err := l.ReadSeekCloser()
440 if err != nil {
441 return "", err
442 }
443 defer r.Close()
444
445 return hugio.ReadString(r)
446 }
447
448 func (l *genericResource) Data() any {
449 return l.sd.Data
450 }
451
452 func (l *genericResource) Key() string {
453 l.keyInit.Do(func() {
454 basePath := l.spec.Cfg.BaseURL().BasePathNoTrailingSlash
455 if basePath == "" {
456 l.key = l.RelPermalink()
457 } else {
458 l.key = strings.TrimPrefix(l.RelPermalink(), basePath)
459 }
460
461 if l.spec.Cfg.IsMultihost() {
462 l.key = l.spec.Lang() + l.key
463 }
464
465 if l.includeHashInKey && !l.sourceFilenameIsHash {
466 l.key += fmt.Sprintf("_%d", l.hash())
467 }
468 })
469
470 return l.key
471 }
472
473 func (l *genericResource) TransientKey() string {
474 return l.Key()
475 }
476
477 func (l *genericResource) targetPath() string {
478 return l.paths.TargetPath()
479 }
480
481 func (l *genericResource) sourcePath() string {
482 if p := l.sd.SourceFilenameOrPath; p != "" {
483 return p
484 }
485 return ""
486 }
487
488 func (l *genericResource) MediaType() media.Type {
489 return l.sd.MediaType
490 }
491
492 func (l *genericResource) setMediaType(mediaType media.Type) {
493 l.sd.MediaType = mediaType
494 }
495
496 func (l *genericResource) Name() string {
497 return l.name
498 }
499
500 func (l *genericResource) NameNormalized() string {
501 return l.sd.NameNormalized
502 }
503
504 func (l *genericResource) Params() hmaps.Params {
505 return l.params
506 }
507
508 func (l *genericResource) Publish() error {
509 var err error
510 l.publishInit.Do(func() {
511 targetFilenames := l.getResourcePaths().TargetFilenames()
512
513 if l.sourceFilenameIsHash {
514 // This is a processed image. We want to avoid copying it if it hasn't changed.
515 var changedFilenames []string
516 for _, targetFilename := range targetFilenames {
517 if _, err := l.getSpec().BaseFs.PublishFs.Stat(targetFilename); err == nil {
518 continue
519 }
520 changedFilenames = append(changedFilenames, targetFilename)
521 }
522 if len(changedFilenames) == 0 {
523 return
524 }
525 targetFilenames = changedFilenames
526 }
527 var fr hugio.ReadSeekCloser
528 fr, err = l.ReadSeekCloser()
529 if err != nil {
530 return
531 }
532 defer fr.Close()
533
534 var fw io.WriteCloser
535 fw, err = helpers.OpenFilesForWriting(l.spec.BaseFs.PublishFs, targetFilenames...)
536 if err != nil {
537 return
538 }
539 defer fw.Close()
540
541 _, err = io.Copy(fw, fr)
542 })
543
544 return err
545 }
546
547 func (l *genericResource) isPublished() bool {
548 return l.publishInit.Done()
549 }
550
551 func (l *genericResource) RelPermalink() string {
552 return l.spec.PathSpec.GetBasePath(false) + paths.PathEscape(l.paths.TargetLink())
553 }
554
555 func (l *genericResource) Permalink() string {
556 return l.spec.Cfg.BaseURL().WithPathNoTrailingSlash + paths.PathEscape(l.paths.TargetPath())
557 }
558
559 func (l *genericResource) ResourceType() string {
560 return l.MediaType().MainType
561 }
562
563 func (l *genericResource) String() string {
564 return fmt.Sprintf("Resource(%s: %s)", l.ResourceType(), l.name)
565 }
566
567 // Path is stored with Unix style slashes.
568 func (l *genericResource) TargetPath() string {
569 return l.paths.TargetPath()
570 }
571
572 func (l *genericResource) Title() string {
573 return l.title
574 }
575
576 func (l *genericResource) getSpec() *Spec {
577 return l.spec
578 }
579
580 func (l *genericResource) getResourcePaths() internal.ResourcePaths {
581 return l.paths
582 }
583
584 func (r *genericResource) tryTransformedFileCache(key string, u *transformationUpdate) io.ReadCloser {
585 fi, f, meta, found := r.spec.ResourceCache.getFromFile(key)
586 if !found {
587 return nil
588 }
589 u.sourceFilename = &fi.Name
590 mt, _ := r.spec.MediaTypes().GetByType(meta.MediaTypeV)
591 u.mediaType = mt
592 u.data = meta.MetaData
593 u.targetPath = meta.Target
594 return f
595 }
596
597 func (r *genericResource) mergeData(in map[string]any) {
598 if len(in) == 0 {
599 return
600 }
601 if r.sd.Data == nil {
602 r.sd.Data = make(map[string]any)
603 }
604 for k, v := range in {
605 if _, found := r.sd.Data[k]; !found {
606 r.sd.Data[k] = v
607 }
608 }
609 }
610
611 func (rc *genericResource) cloneWithUpdates(u *transformationUpdate) (baseResource, error) {
612 r := rc.clone()
613
614 if u.content != nil {
615 r.sd.OpenReadSeekCloser = func() (hugio.ReadSeekCloser, error) {
616 return hugio.NewReadSeekerNoOpCloserFromString(*u.content), nil
617 }
618 }
619
620 r.sd.MediaType = u.mediaType
621
622 if u.sourceFilename != nil {
623 if u.sourceFs == nil {
624 return nil, errors.New("sourceFs is nil")
625 }
626 r.setOpenSource(func() (hugio.ReadSeekCloser, error) {
627 return u.sourceFs.Open(*u.sourceFilename)
628 })
629 } else if u.sourceFs != nil {
630 return nil, errors.New("sourceFs is set without sourceFilename")
631 }
632
633 if u.targetPath == "" {
634 return nil, errors.New("missing targetPath")
635 }
636
637 r.setTargetPath(r.paths.FromTargetPath(u.targetPath))
638 r.mergeData(u.data)
639
640 return r, nil
641 }
642
643 func (l genericResource) clone() *genericResource {
644 l.publishInit = &hsync.OnceMore{}
645 l.keyInit = &sync.Once{}
646 return &l
647 }
648
649 func (r *genericResource) openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) {
650 filenames := r.paths.FromTargetPath(relTargetPath).TargetFilenames()
651 return helpers.OpenFilesForWriting(r.spec.BaseFs.PublishFs, filenames...)
652 }
653
654 type targetPather interface {
655 TargetPath() string
656 }
657
658 type isPublishedProvider interface {
659 isPublished() bool
660 }
661
662 type resourceHash struct {
663 value uint64
664 size int64
665 initOnce sync.Once
666 }
667
668 func (r *resourceHash) init(l hugio.ReadSeekCloserProvider) error {
669 var initErr error
670 r.initOnce.Do(func() {
671 var hash uint64
672 var size int64
673 f, err := l.ReadSeekCloser()
674 if err != nil {
675 initErr = fmt.Errorf("failed to open source: %w", err)
676 return
677 }
678 defer f.Close()
679 hash, size, err = hashImage(f)
680 if err != nil {
681 initErr = fmt.Errorf("failed to calculate hash: %w", err)
682 return
683 }
684 r.value = hash
685 r.size = size
686 })
687
688 return initErr
689 }
690
691 func hashImage(r io.ReadSeeker) (uint64, int64, error) {
692 return hashing.XXHashFromReader(r)
693 }
694
695 // InternalResourceTargetPath is used internally to get the target path for a Resource.
696 func InternalResourceTargetPath(r resource.Resource) string {
697 return r.(targetPathProvider).targetPath()
698 }
699
700 // InternalResourceSourcePathBestEffort is used internally to get the source path for a Resource.
701 // It returns an empty string if the source path is not available.
702 func InternalResourceSourcePath(r resource.Resource) string {
703 if sp, ok := r.(sourcePathProvider); ok {
704 if p := sp.sourcePath(); p != "" {
705 return p
706 }
707 }
708 return ""
709 }
710
711 // InternalResourceSourceContent is used internally to get the source content for a Resource.
712 func InternalResourceSourceContent(ctx context.Context, r resource.Resource) (string, error) {
713 if cp, ok := r.(resource.ContentProvider); ok {
714 c, err := cp.Content(ctx)
715 if err != nil {
716 return "", err
717 }
718 return cast.ToStringE(c)
719 }
720 return "", nil
721 }
722
723 // InternalResourceSourcePathBestEffort is used internally to get the source path for a Resource.
724 // Used for error messages etc.
725 // It will fall back to the target path if the source path is not available.
726 func InternalResourceSourcePathBestEffort(r resource.Resource) string {
727 if s := InternalResourceSourcePath(r); s != "" {
728 return s
729 }
730 return InternalResourceTargetPath(r)
731 }
732
733 // isPublished returns true if the resource is published.
734 func IsPublished(r resource.Resource) bool {
735 return r.(isPublishedProvider).isPublished()
736 }
737
738 type targetPathProvider interface {
739 // targetPath is the relative path to this resource.
740 // In most cases this will be the same as the RelPermalink(),
741 // but it will not trigger any lazy publishing.
742 targetPath() string
743 }
744
745 // Optional interface implemented by resources that can provide the source path.
746 type sourcePathProvider interface {
747 // sourcePath is the source path to this resource's source.
748 // This is used in error messages etc.
749 sourcePath() string
750 }