github.com/dominikszabo/hugo-ds-clean@v0.47.1/resource/minifier/minify.go (about)

     1  // Copyright 2018 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 minifier
    15  
    16  import (
    17  	"github.com/gohugoio/hugo/minifiers"
    18  	"github.com/gohugoio/hugo/resource"
    19  )
    20  
    21  // Client for minification of Resource objects. Supported minfiers are:
    22  // css, html, js, json, svg and xml.
    23  type Client struct {
    24  	rs *resource.Spec
    25  	m  minifiers.Client
    26  }
    27  
    28  // New creates a new Client given a specification. Note that it is the media types
    29  // configured for the site that is used to match files to the correct minifier.
    30  func New(rs *resource.Spec) *Client {
    31  	return &Client{rs: rs, m: minifiers.New(rs.MediaTypes, rs.OutputFormats)}
    32  }
    33  
    34  type minifyTransformation struct {
    35  	rs *resource.Spec
    36  	m  minifiers.Client
    37  }
    38  
    39  func (t *minifyTransformation) Key() resource.ResourceTransformationKey {
    40  	return resource.NewResourceTransformationKey("minify")
    41  }
    42  
    43  func (t *minifyTransformation) Transform(ctx *resource.ResourceTransformationCtx) error {
    44  	if err := t.m.Minify(ctx.InMediaType, ctx.To, ctx.From); err != nil {
    45  		return err
    46  	}
    47  	ctx.AddOutPathIdentifier(".min")
    48  	return nil
    49  }
    50  
    51  func (c *Client) Minify(res resource.Resource) (resource.Resource, error) {
    52  	return c.rs.Transform(
    53  		res,
    54  		&minifyTransformation{
    55  			rs: c.rs,
    56  			m:  c.m},
    57  	)
    58  }