github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/resources/resource_factories/bundler/bundler.go (about)

     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 bundler contains functions for concatenation etc. of Resource objects.
    15  package bundler
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  	"path"
    21  	"path/filepath"
    22  
    23  	"github.com/gohugoio/hugo/common/hugio"
    24  	"github.com/gohugoio/hugo/media"
    25  	"github.com/gohugoio/hugo/resources"
    26  	"github.com/gohugoio/hugo/resources/resource"
    27  )
    28  
    29  // Client contains methods perform concatenation and other bundling related
    30  // tasks to Resource objects.
    31  type Client struct {
    32  	rs *resources.Spec
    33  }
    34  
    35  // New creates a new Client with the given specification.
    36  func New(rs *resources.Spec) *Client {
    37  	return &Client{rs: rs}
    38  }
    39  
    40  type multiReadSeekCloser struct {
    41  	mr      io.Reader
    42  	sources []hugio.ReadSeekCloser
    43  }
    44  
    45  func toReaders(sources []hugio.ReadSeekCloser) []io.Reader {
    46  	readers := make([]io.Reader, len(sources))
    47  	for i, r := range sources {
    48  		readers[i] = r
    49  	}
    50  	return readers
    51  }
    52  
    53  func newMultiReadSeekCloser(sources ...hugio.ReadSeekCloser) *multiReadSeekCloser {
    54  	mr := io.MultiReader(toReaders(sources)...)
    55  	return &multiReadSeekCloser{mr, sources}
    56  }
    57  
    58  func (r *multiReadSeekCloser) Read(p []byte) (n int, err error) {
    59  	return r.mr.Read(p)
    60  }
    61  
    62  func (r *multiReadSeekCloser) Seek(offset int64, whence int) (newOffset int64, err error) {
    63  	for _, s := range r.sources {
    64  		newOffset, err = s.Seek(offset, whence)
    65  		if err != nil {
    66  			return
    67  		}
    68  	}
    69  
    70  	r.mr = io.MultiReader(toReaders(r.sources)...)
    71  
    72  	return
    73  }
    74  
    75  func (r *multiReadSeekCloser) Close() error {
    76  	for _, s := range r.sources {
    77  		s.Close()
    78  	}
    79  	return nil
    80  }
    81  
    82  // Concat concatenates the list of Resource objects.
    83  func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resource, error) {
    84  	// The CACHE_OTHER will make sure this will be re-created and published on rebuilds.
    85  	return c.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) {
    86  		var resolvedm media.Type
    87  
    88  		// The given set of resources must be of the same Media Type.
    89  		// We may improve on that in the future, but then we need to know more.
    90  		for i, r := range r {
    91  			if i > 0 && r.MediaType().Type() != resolvedm.Type() {
    92  				return nil, fmt.Errorf("resources in Concat must be of the same Media Type, got %q and %q", r.MediaType().Type(), resolvedm.Type())
    93  			}
    94  			resolvedm = r.MediaType()
    95  		}
    96  
    97  		concatr := func() (hugio.ReadSeekCloser, error) {
    98  			var rcsources []hugio.ReadSeekCloser
    99  			for _, s := range r {
   100  				rcr, ok := s.(resource.ReadSeekCloserResource)
   101  				if !ok {
   102  					return nil, fmt.Errorf("resource %T does not implement resource.ReadSeekerCloserResource", s)
   103  				}
   104  				rc, err := rcr.ReadSeekCloser()
   105  				if err != nil {
   106  					// Close the already opened.
   107  					for _, rcs := range rcsources {
   108  						rcs.Close()
   109  					}
   110  					return nil, err
   111  				}
   112  
   113  				rcsources = append(rcsources, rc)
   114  			}
   115  
   116  			// Arbitrary JavaScript files require a barrier between them to be safely concatenated together.
   117  			// Without this, the last line of one file can affect the first line of the next file and change how both files are interpreted.
   118  			if resolvedm.MainType == media.JavascriptType.MainType && resolvedm.SubType == media.JavascriptType.SubType {
   119  				readers := make([]hugio.ReadSeekCloser, 2*len(rcsources)-1)
   120  				j := 0
   121  				for i := 0; i < len(rcsources); i++ {
   122  					if i > 0 {
   123  						readers[j] = hugio.NewReadSeekerNoOpCloserFromString("\n;\n")
   124  						j++
   125  					}
   126  					readers[j] = rcsources[i]
   127  					j++
   128  				}
   129  				return newMultiReadSeekCloser(readers...), nil
   130  			}
   131  
   132  			return newMultiReadSeekCloser(rcsources...), nil
   133  		}
   134  
   135  		composite, err := c.rs.New(
   136  			resources.ResourceSourceDescriptor{
   137  				Fs:                 c.rs.FileCaches.AssetsCache().Fs,
   138  				LazyPublish:        true,
   139  				OpenReadSeekCloser: concatr,
   140  				RelTargetFilename:  filepath.Clean(targetPath),
   141  			})
   142  		if err != nil {
   143  			return nil, err
   144  		}
   145  
   146  		return composite, nil
   147  	})
   148  }