Debian Codegraph @

resources/transform.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 resources
15
16 import (
17 "bytes"
18 "context"
19 "fmt"
20 "image"
21 "io"
22 "path"
23 "strings"
24 "sync"
25
26 "github.com/gohugoio/hugo/common/constants"
27 "github.com/gohugoio/hugo/common/hashing"
28 "github.com/gohugoio/hugo/common/hmaps"
29 "github.com/gohugoio/hugo/common/paths"
30 "github.com/gohugoio/hugo/identity"
31
32 "github.com/gohugoio/hugo/resources/images"
33 "github.com/gohugoio/hugo/resources/images/meta"
34 "github.com/spf13/afero"
35
36 bp "github.com/gohugoio/hugo/bufferpool"
37
38 "github.com/gohugoio/hugo/common/herrors"
39 "github.com/gohugoio/hugo/common/hugio"
40 "github.com/gohugoio/hugo/resources/internal"
41 "github.com/gohugoio/hugo/resources/resource"
42
43 "github.com/gohugoio/hugo/media"
44 )
45
46 var (
47 _ resource.ContentResource = (*resourceAdapter)(nil)
48 _ resourceCopier = (*resourceAdapter)(nil)
49 _ resource.ReadSeekCloserResource = (*resourceAdapter)(nil)
50 _ resource.Resource = (*resourceAdapter)(nil)
51 _ resource.Staler = (*resourceAdapterInner)(nil)
52 _ identity.IdentityGroupProvider = (*resourceAdapterInner)(nil)
53 _ resource.Source = (*resourceAdapter)(nil)
54 _ resource.Identifier = (*resourceAdapter)(nil)
55 _ resource.TransientIdentifier = (*resourceAdapter)(nil)
56 _ targetPathProvider = (*resourceAdapter)(nil)
57 _ sourcePathProvider = (*resourceAdapter)(nil)
58 _ resource.Identifier = (*resourceAdapter)(nil)
59 _ resource.ResourceNameTitleProvider = (*resourceAdapter)(nil)
60 _ resource.WithResourceMetaProvider = (*resourceAdapter)(nil)
61 _ identity.DependencyManagerProvider = (*resourceAdapter)(nil)
62 _ identity.IdentityGroupProvider = (*resourceAdapter)(nil)
63 _ resource.NameNormalizedProvider = (*resourceAdapter)(nil)
64 _ isPublishedProvider = (*resourceAdapter)(nil)
65 )
66
67 // These are transformations that need special support in Hugo that may not
68 // be available when building the theme/site so we write the transformation
69 // result to disk and reuse if needed for these,
70 // TODO(bep) it's a little fragile having these constants redefined here.
71 var transformationsToCacheOnDisk = map[string]bool{
72 "postcss": true,
73 "tocss": true,
74 "tocss-dart": true,
75 }
76
77 func newResourceAdapter(spec *Spec, lazyPublish bool, target transformableResource) *resourceAdapter {
78 var po *publishOnce
79 if lazyPublish {
80 po = &publishOnce{}
81 }
82 return &resourceAdapter{
83 resourceTransformations: &resourceTransformations{},
84 metaProvider: target,
85 sourceTarget: target,
86 resourceAdapterInner: &resourceAdapterInner{
87 ctx: context.Background(),
88 spec: spec,
89 publishOnce: po,
90 target: target,
91 Staler: &AtomicStaler{},
92 },
93 }
94 }
95
96 // ResourceTransformation is the interface that a resource transformation step
97 // needs to implement.
98 type ResourceTransformation interface {
99 Key() internal.ResourceTransformationKey
100 Transform(ctx *ResourceTransformationCtx) error
101 }
102
103 type ResourceTransformationCtx struct {
104 // The context that started the transformation.
105 Ctx context.Context
106
107 // The dependency manager to use for dependency tracking.
108 DependencyManager identity.Manager
109
110 // The content to transform.
111 From io.Reader
112
113 // The target of content transformation.
114 // The current implementation requires that r is written to w
115 // even if no transformation is performed.
116 To io.Writer
117
118 // This is the relative path to the original source. Unix styled slashes.
119 SourcePath string
120
121 // This is the relative target path to the resource. Unix styled slashes.
122 InPath string
123
124 // The relative target path to the transformed resource. Unix styled slashes.
125 OutPath string
126
127 // The input media type
128 InMediaType media.Type
129
130 // The media type of the transformed resource.
131 OutMediaType media.Type
132
133 // Data can be set on the transformed Resource. For transformations
134 // cached to disk (see transformationsToCacheOnDisk), this needs to be
135 // simple types, as it will be serialized to JSON and back.
136 Data map[string]any
137
138 // This is used to publish additional artifacts, e.g. source maps.
139 // We may improve this.
140 OpenResourcePublisher func(relTargetPath string) (io.WriteCloser, error)
141 }
142
143 // AddOutPathIdentifier transforming InPath to OutPath adding an identifier,
144 // eg '.min' before any extension.
145 func (ctx *ResourceTransformationCtx) AddOutPathIdentifier(identifier string) {
146 ctx.OutPath = ctx.addPathIdentifier(ctx.InPath, identifier)
147 }
148
149 // PublishSourceMap writes the content to the target folder of the main resource
150 // with the ".map" extension added.
151 func (ctx *ResourceTransformationCtx) PublishSourceMap(content []byte) error {
152 target := ctx.OutPath + ".map"
153 return ctx.PublishTo(target, content)
154 }
155
156 // PublishTo writes the content to the target folder.
157 func (ctx *ResourceTransformationCtx) PublishTo(target string, content []byte) error {
158 f, err := ctx.OpenResourcePublisher(target)
159 if err != nil {
160 return err
161 }
162 defer f.Close()
163 _, err = f.Write(content)
164 return err
165 }
166
167 // ReplaceOutPathExtension transforming InPath to OutPath replacing the file
168 // extension, e.g. ".scss"
169 func (ctx *ResourceTransformationCtx) ReplaceOutPathExtension(newExt string) {
170 dir, file := path.Split(ctx.InPath)
171 base, _ := paths.PathAndExt(file)
172 ctx.OutPath = path.Join(dir, (base + newExt))
173 }
174
175 func (ctx *ResourceTransformationCtx) addPathIdentifier(inPath, identifier string) string {
176 dir, file := path.Split(inPath)
177 base, ext := paths.PathAndExt(file)
178 return path.Join(dir, (base + identifier + ext))
179 }
180
181 type publishOnce struct {
182 publisherInit sync.Once
183 publisherErr error
184 }
185
186 type resourceAdapter struct {
187 commonResource
188 *resourceTransformations
189 *resourceAdapterInner
190
191 // The original untransformed target. The inner target is replaced with the
192 // transformed resource once the transformation chain has run, so any new
193 // transformations appended to the chain must start from this.
194 sourceTarget transformableResource
195
196 metaProvider resource.ResourceMetaProvider
197 }
198
199 var _ identity.ForEeachIdentityByNameProvider = (*resourceAdapter)(nil)
200
201 func (r *resourceAdapter) Content(ctx context.Context) (any, error) {
202 r.init(false, true)
203 if r.transformationsErr != nil {
204 return nil, r.transformationsErr
205 }
206 return r.target.Content(ctx)
207 }
208
209 func (r *resourceAdapter) GetIdentity() identity.Identity {
210 return identity.FirstIdentity(r.target)
211 }
212
213 func (r *resourceAdapter) Data() any {
214 r.init(false, false)
215 return r.target.Data()
216 }
217
218 func (r *resourceAdapter) ForEeachIdentityByName(name string, f func(identity.Identity) bool) {
219 if constants.IsFieldRelOrPermalink(name) && !r.resourceTransformations.hasTransformationPermalinkHash() {
220 // Special case for links without any content hash in the URL.
221 // We don't need to rebuild all pages that use this resource,
222 // but we want to make sure that the resource is accessed at least once.
223 f(identity.NewFindFirstManagerIdentityProvider(r.target.GetDependencyManager(), r.target.GetIdentityGroup()))
224 return
225 }
226 f(r.target.GetIdentityGroup())
227 f(r.target.GetDependencyManager())
228 }
229
230 func (r *resourceAdapter) GetIdentityGroup() identity.Identity {
231 return r.target.GetIdentityGroup()
232 }
233
234 func (r *resourceAdapter) GetDependencyManager() identity.Manager {
235 return r.target.GetDependencyManager()
236 }
237
238 func (r resourceAdapter) cloneTo(targetPath string) resource.Resource {
239 newtTarget := r.target.cloneTo(targetPath)
240 r.sourceTarget = newtTarget.(transformableResource)
241 newInner := &resourceAdapterInner{
242 ctx: r.ctx,
243 spec: r.spec,
244 Staler: r.Staler,
245 target: newtTarget.(transformableResource),
246 }
247 if r.resourceAdapterInner.publishOnce != nil {
248 newInner.publishOnce = &publishOnce{}
249 }
250 r.resourceAdapterInner = newInner
251 return &r
252 }
253
254 func (r *resourceAdapter) Process(spec string) (images.ImageResource, error) {
255 return r.getImageOps().Process(spec)
256 }
257
258 func (r *resourceAdapter) Crop(spec string) (images.ImageResource, error) {
259 return r.getImageOps().Crop(spec)
260 }
261
262 func (r *resourceAdapter) Fill(spec string) (images.ImageResource, error) {
263 return r.getImageOps().Fill(spec)
264 }
265
266 func (r *resourceAdapter) Fit(spec string) (images.ImageResource, error) {
267 return r.getImageOps().Fit(spec)
268 }
269
270 func (r *resourceAdapter) Filter(filters ...any) (images.ImageResource, error) {
271 return r.getImageOps().Filter(filters...)
272 }
273
274 func (r *resourceAdapter) Resize(spec string) (images.ImageResource, error) {
275 return r.getImageOps().Resize(spec)
276 }
277
278 func (r *resourceAdapter) Height() int {
279 return r.getImageOps().Height()
280 }
281
282 func (r *resourceAdapter) Exif() *meta.ExifInfo {
283 return r.getImageOps().Exif()
284 }
285
286 func (r *resourceAdapter) Meta() *meta.MetaInfo {
287 return r.getImageOps().Meta()
288 }
289
290 func (r *resourceAdapter) Colors() ([]images.Color, error) {
291 return r.getImageOps().Colors()
292 }
293
294 func (r *resourceAdapter) Key() string {
295 r.init(false, false)
296 return r.target.(resource.Identifier).Key()
297 }
298
299 func (r *resourceAdapter) TransientKey() string {
300 return r.Key()
301 }
302
303 func (r *resourceAdapter) targetPath() string {
304 r.init(false, false)
305 return r.target.(targetPathProvider).targetPath()
306 }
307
308 func (r *resourceAdapter) sourcePath() string {
309 r.init(false, false)
310 if sp, ok := r.target.(sourcePathProvider); ok {
311 return sp.sourcePath()
312 }
313 return ""
314 }
315
316 func (r *resourceAdapter) MediaType() media.Type {
317 r.init(false, false)
318 return r.target.MediaType()
319 }
320
321 func (r *resourceAdapter) Name() string {
322 r.init(false, false)
323 return r.metaProvider.Name()
324 }
325
326 func (r *resourceAdapter) NameNormalized() string {
327 r.init(false, false)
328 return r.target.(resource.NameNormalizedProvider).NameNormalized()
329 }
330
331 func (r *resourceAdapter) Params() hmaps.Params {
332 r.init(false, false)
333 return r.metaProvider.Params()
334 }
335
336 func (r *resourceAdapter) Permalink() string {
337 r.init(true, false)
338 return r.target.Permalink()
339 }
340
341 func (r *resourceAdapter) Publish() error {
342 r.init(false, false)
343
344 return r.target.Publish()
345 }
346
347 func (r *resourceAdapter) isPublished() bool {
348 r.init(false, false)
349 return r.target.isPublished()
350 }
351
352 func (r *resourceAdapter) ReadSeekCloser() (hugio.ReadSeekCloser, error) {
353 r.init(false, false)
354 return r.target.ReadSeekCloser()
355 }
356
357 func (r *resourceAdapter) RelPermalink() string {
358 r.init(true, false)
359 return r.target.RelPermalink()
360 }
361
362 func (r *resourceAdapter) ResourceType() string {
363 r.init(false, false)
364 return r.target.ResourceType()
365 }
366
367 func (r *resourceAdapter) String() string {
368 return r.Name()
369 }
370
371 func (r *resourceAdapter) Title() string {
372 r.init(false, false)
373 return r.metaProvider.Title()
374 }
375
376 func (r resourceAdapter) Transform(t ...ResourceTransformation) (ResourceTransformer, error) {
377 return r.TransformWithContext(context.Background(), t...)
378 }
379
380 func (r resourceAdapter) TransformWithContext(ctx context.Context, t ...ResourceTransformation) (ResourceTransformer, error) {
381 r.resourceTransformations = &resourceTransformations{
382 transformations: append(r.transformations, t...),
383 }
384
385 r.resourceAdapterInner = &resourceAdapterInner{
386 ctx: ctx,
387 spec: r.spec,
388 Staler: r.Staler,
389 publishOnce: &publishOnce{},
390 target: r.sourceTarget,
391 }
392
393 return &r, nil
394 }
395
396 func (r *resourceAdapter) Width() int {
397 return r.getImageOps().Width()
398 }
399
400 func (r *resourceAdapter) DecodeImage() (image.Image, error) {
401 return r.getImageOps().DecodeImage()
402 }
403
404 func (r resourceAdapter) WithResourceMeta(mp resource.ResourceMetaProvider) resource.Resource {
405 r.metaProvider = mp
406 return &r
407 }
408
409 func (r *resourceAdapter) getImageOps() images.ImageResourceOps {
410 img, ok := r.target.(images.ImageResourceOps)
411 if !ok {
412 instructions := "use reflect.IsImageResource, " +
413 "reflect.IsImageResourceProcessable, or " +
414 "reflect.IsImageResourceWithMeta to check if the resource " +
415 "supports this method before calling it"
416 msg := fmt.Sprintf(
417 "resource %q of media type %q does not support this method: %s",
418 r.Name(),
419 r.MediaType(),
420 instructions,
421 )
422 panic(msg)
423 }
424 r.init(false, false)
425
426 return img
427 }
428
429 // ResolveImageOpsSupport reports the ImageOpsSupport for the given resource. This can be used to determine if a resource supports image operations like Resize, Crop, etc.
430 func ResolveImageOpsSupport(v any) images.ImageResourceType {
431 r, ok := v.(resource.Resource)
432 if !ok {
433 return images.ImageResourceTypeNone
434 }
435 mt := r.MediaType()
436 if mt.MainType != "image" {
437 return images.ImageResourceTypeNone
438 }
439 _, support := images.ImageFormatFromMediaSubType(mt.SubType)
440 return support
441 }
442
443 func (r *resourceAdapter) publish() {
444 if r.publishOnce == nil {
445 return
446 }
447
448 r.publisherInit.Do(func() {
449 r.publisherErr = r.target.Publish()
450
451 if r.publisherErr != nil {
452 r.spec.Logger.Errorf("Failed to publish Resource: %s", r.publisherErr)
453 }
454 })
455 }
456
457 func (r *resourceAdapter) TransformationKey() string {
458 return r.transformationKey(r.transformations)
459 }
460
461 func (r *resourceAdapter) transformationKey(trs []ResourceTransformation) string {
462 sb := bp.GetBuffer()
463 defer bp.PutBuffer(sb)
464
465 for _, tr := range trs {
466 sb.WriteString("_")
467 sb.WriteString(tr.Key().Value())
468 }
469
470 h := hashing.MD5FromReaderHexEncoded(sb)
471
472 sb.Reset()
473
474 sb.WriteString(r.spec.ResourceCache.cleanKey(r.target.Key()))
475 sb.WriteString(h)
476
477 return sb.String()
478 }
479
480 func (r *resourceAdapter) getOrTransform(publish, setContent bool) error {
481 key := r.TransformationKey()
482
483 var created bool
484 res, err := r.spec.ResourceCache.cacheResourceTransformation.GetOrCreate(key, func(string) (*resourceAdapterInner, error) {
485 created = true
486 return r.transform(key, publish, setContent)
487 })
488 if err != nil {
489 return err
490 }
491
492 r.resourceAdapterInner = res
493
494 if publish && r.spec.Rebuilder.IsRebuild() {
495 targetPath := r.target.TargetPath()
496 var republish bool
497
498 r.spec.ResourceCache.cacheResourceTransformationPublished.WithWriteLock(func(m map[string]string) error {
499 if created {
500 m[targetPath] = key
501 } else {
502 key2, found := m[targetPath]
503 republish = !found || key2 != key
504 m[targetPath] = key
505 }
506 return nil
507 })
508
509 if !created && republish {
510 src, err := contentReadSeekerCloser(r.target)
511 if err != nil {
512 return err
513 }
514 defer src.Close()
515 dest, err := r.target.openPublishFileForWriting(targetPath)
516 if err != nil {
517 return err
518 }
519 defer dest.Close()
520 _, err = io.Copy(dest, src)
521 if err != nil {
522 return err
523 }
524 }
525 }
526
527 return nil
528 }
529
530 func (r *resourceAdapter) transform(key string, publish, setContent bool) (*resourceAdapterInner, error) {
531 cache := r.spec.ResourceCache
532
533 trs := r.transformations
534 writeToFileCache := false
535
536 // If a prefix of this chain has already run (e.g. .Content or .Data was
537 // accessed before more transformations were chained), resume from the
538 // longest cached prefix instead of re-running it.
539 for i := len(trs) - 1; i > 0; i-- {
540 if inner, found := cache.cacheResourceTransformation.Get(r.ctx, r.transformationKey(trs[:i])); found {
541 for _, tr := range trs[:i] {
542 if transformationsToCacheOnDisk[tr.Key().Name] {
543 writeToFileCache = true
544 }
545 }
546 r.target = inner.target
547 trs = trs[i:]
548 break
549 }
550 }
551
552 b1 := bp.GetBuffer()
553 b2 := bp.GetBuffer()
554 defer bp.PutBuffer(b1)
555 defer bp.PutBuffer(b2)
556
557 tctx := &ResourceTransformationCtx{
558 Ctx: r.ctx,
559 Data: make(map[string]any),
560 OpenResourcePublisher: r.target.openPublishFileForWriting,
561 DependencyManager: r.target.GetDependencyManager(),
562 }
563
564 tctx.InMediaType = r.target.MediaType()
565 tctx.OutMediaType = r.target.MediaType()
566
567 startCtx := *tctx
568 updates := &transformationUpdate{startCtx: startCtx}
569
570 var contentrc hugio.ReadSeekCloser
571
572 contentrc, err := contentReadSeekerCloser(r.target)
573 if err != nil {
574 return nil, err
575 }
576
577 defer contentrc.Close()
578
579 tctx.From = contentrc
580 tctx.To = b1
581
582 tctx.InPath = r.target.TargetPath()
583 tctx.SourcePath = strings.TrimPrefix(tctx.InPath, "/")
584
585 counter := 0
586
587 var transformedContentr io.Reader
588
589 for i, tr := range trs {
590 if i != 0 {
591 tctx.InMediaType = tctx.OutMediaType
592 }
593
594 mayBeCachedOnDisk := transformationsToCacheOnDisk[tr.Key().Name]
595 if !writeToFileCache {
596 writeToFileCache = mayBeCachedOnDisk
597 }
598
599 if i > 0 {
600 hasWrites := tctx.To.(*bytes.Buffer).Len() > 0
601 if hasWrites {
602 counter++
603 // Switch the buffers
604 if counter%2 == 0 {
605 tctx.From = b2
606 b1.Reset()
607 tctx.To = b1
608 } else {
609 tctx.From = b1
610 b2.Reset()
611 tctx.To = b2
612 }
613 }
614 }
615
616 newErr := func(err error) error {
617 msg := fmt.Sprintf("%s: failed to transform %q (%s)", strings.ToUpper(tr.Key().Name), tctx.InPath, tctx.InMediaType.Type)
618
619 if herrors.IsFeatureNotAvailableError(err) {
620 var errMsg string
621 switch strings.ToLower(tr.Key().Name) {
622 case "postcss":
623 // This transformation is not available in this
624 // Most likely because PostCSS is not installed.
625 errMsg = ". You need to install PostCSS. See https://gohugo.io/functions/css/postcss/"
626 case "tailwindcss":
627 errMsg = ". You need to install TailwindCSS CLI. See https://gohugo.io/functions/css/tailwindcss/"
628 case "tocss":
629 errMsg = ". Check your Hugo installation; you need the extended version to build SCSS/SASS with transpiler set to 'libsass'."
630 case "tocss-dart":
631 errMsg = ". You need to install Dart Sass, see https://gohugo.io//functions/css/sass/#dart-sass"
632 case "babel":
633 errMsg = ". You need to install Babel, see https://gohugo.io/functions/js/babel/"
634
635 }
636
637 return fmt.Errorf(msg+errMsg+": %w", err)
638 }
639
640 return fmt.Errorf(msg+": %w", err)
641 }
642
643 bcfg := r.spec.BuildConfig()
644 var tryFileCache bool
645 if mayBeCachedOnDisk && bcfg.UseResourceCache(nil) {
646 tryFileCache = true
647 } else {
648 err = tr.Transform(tctx)
649 if err != nil && err != herrors.ErrFeatureNotAvailable {
650 return nil, newErr(err)
651 }
652
653 if mayBeCachedOnDisk {
654 tryFileCache = bcfg.UseResourceCache(err)
655 }
656 if err != nil && !tryFileCache {
657 return nil, newErr(err)
658 }
659 }
660
661 if tryFileCache {
662 f := r.target.tryTransformedFileCache(key, updates)
663 if f == nil {
664 if err != nil {
665 return nil, newErr(err)
666 }
667 return nil, newErr(fmt.Errorf("resource %q not found in file cache", key))
668 }
669 transformedContentr = f
670 updates.sourceFs = cache.fileCache.Fs
671 defer f.Close()
672
673 // The reader above is all we need.
674 break
675 }
676
677 if tctx.OutPath != "" {
678 tctx.InPath = tctx.OutPath
679 tctx.OutPath = ""
680 }
681 }
682
683 if transformedContentr == nil {
684 updates.updateFromCtx(tctx)
685 }
686
687 var publishwriters []io.WriteCloser
688
689 if publish {
690 publicw, err := r.target.openPublishFileForWriting(updates.targetPath)
691 if err != nil {
692 return nil, err
693 }
694 publishwriters = append(publishwriters, publicw)
695 }
696
697 if transformedContentr == nil {
698 if writeToFileCache {
699 // Also write it to the cache
700 fi, metaw, err := cache.writeMeta(key, updates.toTransformedResourceMetadata())
701 if err != nil {
702 return nil, err
703 }
704 updates.sourceFilename = &fi.Name
705 updates.sourceFs = cache.fileCache.Fs
706 publishwriters = append(publishwriters, metaw)
707 }
708
709 // Any transformations reading from From must also write to To.
710 // This means that if the target buffer is empty, we can just reuse
711 // the original reader.
712 if b, ok := tctx.To.(*bytes.Buffer); ok && b.Len() > 0 {
713 transformedContentr = tctx.To.(*bytes.Buffer)
714 } else {
715 transformedContentr = contentrc
716 }
717 }
718
719 // Also write it to memory
720 var contentmemw *bytes.Buffer
721
722 setContent = setContent || !writeToFileCache
723
724 if setContent {
725 contentmemw = bp.GetBuffer()
726 defer bp.PutBuffer(contentmemw)
727 publishwriters = append(publishwriters, hugio.ToWriteCloser(contentmemw))
728 }
729
730 publishw := hugio.NewMultiWriteCloser(publishwriters...)
731 _, err = io.Copy(publishw, transformedContentr)
732 if err != nil {
733 return nil, err
734 }
735 publishw.Close()
736
737 if setContent {
738 s := contentmemw.String()
739 updates.content = &s
740 }
741
742 newTarget, err := r.target.cloneWithUpdates(updates)
743 if err != nil {
744 return nil, err
745 }
746 r.target = newTarget
747
748 return r.resourceAdapterInner, nil
749 }
750
751 func (r *resourceAdapter) init(publish, setContent bool) {
752 if err := r.doInit(publish, setContent); err != nil {
753 // The panic will be handled and converted to an error by the template framework.
754 panic(err)
755 }
756 }
757
758 func (r *resourceAdapter) doInit(publish, setContent bool) error {
759 r.transformationsInit.Do(func() {
760 if len(r.transformations) == 0 {
761 // Nothing to do.
762 return
763 }
764
765 if publish {
766 // The transformation will write the content directly to
767 // the destination.
768 r.publishOnce = nil
769 }
770
771 r.transformationsErr = r.getOrTransform(publish, setContent)
772 })
773
774 if publish && r.publishOnce != nil {
775 r.publish()
776 }
777
778 return r.transformationsErr
779 }
780
781 type resourceAdapterInner struct {
782 // The context that started this transformation.
783 ctx context.Context
784
785 target transformableResource
786
787 resource.Staler
788
789 spec *Spec
790
791 // Handles publishing (to /public) if needed.
792 *publishOnce
793 }
794
795 func (r *resourceAdapterInner) GetIdentityGroup() identity.Identity {
796 return r.target.GetIdentityGroup()
797 }
798
799 func (r *resourceAdapterInner) StaleVersion() uint32 {
800 // Both of these are incremented on change.
801 return r.Staler.StaleVersion() + r.target.StaleVersion()
802 }
803
804 type resourceTransformations struct {
805 transformationsInit sync.Once
806 transformationsErr error
807 transformations []ResourceTransformation
808 }
809
810 // hasTransformationPermalinkHash reports whether any of the transformations
811 // in the chain creates a permalink that's based on the content, e.g. fingerprint.
812 func (r *resourceTransformations) hasTransformationPermalinkHash() bool {
813 for _, t := range r.transformations {
814 if constants.IsResourceTransformationPermalinkHash(t.Key().Name) {
815 return true
816 }
817 }
818 return false
819 }
820
821 type transformableResource interface {
822 baseResourceInternal
823
824 resource.ContentProvider
825 resource.Resource
826 resource.Identifier
827 resource.Staler
828 resourceCopier
829 }
830
831 type transformationUpdate struct {
832 content *string
833 sourceFilename *string
834 sourceFs afero.Fs
835 targetPath string
836 mediaType media.Type
837 data map[string]any
838
839 startCtx ResourceTransformationCtx
840 }
841
842 func (u *transformationUpdate) isContentChanged() bool {
843 return u.content != nil || u.sourceFilename != nil
844 }
845
846 func (u *transformationUpdate) toTransformedResourceMetadata() transformedResourceMetadata {
847 return transformedResourceMetadata{
848 MediaTypeV: u.mediaType.Type,
849 Target: u.targetPath,
850 MetaData: u.data,
851 }
852 }
853
854 func (u *transformationUpdate) updateFromCtx(ctx *ResourceTransformationCtx) {
855 u.targetPath = ctx.OutPath
856 u.mediaType = ctx.OutMediaType
857 u.data = ctx.Data
858 u.targetPath = ctx.InPath
859 }
860
861 // We will persist this information to disk.
862 type transformedResourceMetadata struct {
863 Target string `json:"Target"`
864 MediaTypeV string `json:"MediaType"`
865 MetaData map[string]any `json:"Data"`
866 }
867
868 // contentReadSeekerCloser returns a ReadSeekerCloser if possible for a given Resource.
869 func contentReadSeekerCloser(r resource.Resource) (hugio.ReadSeekCloser, error) {
870 switch rr := r.(type) {
871 case resource.ReadSeekCloserResource:
872 rc, err := rr.ReadSeekCloser()
873 if err != nil {
874 return nil, err
875 }
876 return rc, nil
877 default:
878 return nil, fmt.Errorf("cannot transform content of Resource of type %T", r)
879
880 }
881 }