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