Debian Codegraph @

tpl/resources/resources.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 provides template functions for working with resources.
15 package resources
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21
22 "github.com/gohugoio/hugo/common/hmaps"
23 "github.com/gohugoio/hugo/common/hugo"
24
25 "github.com/gohugoio/hugo/resources/postpub"
26
27 "github.com/gohugoio/hugo/deps"
28 "github.com/gohugoio/hugo/resources"
29 "github.com/gohugoio/hugo/resources/resource"
30
31 "github.com/gohugoio/hugo/resources/resource_factories/bundler"
32 "github.com/gohugoio/hugo/resources/resource_factories/create"
33 "github.com/gohugoio/hugo/resources/resource_transformers/integrity"
34 "github.com/gohugoio/hugo/resources/resource_transformers/minifier"
35 "github.com/gohugoio/hugo/resources/resource_transformers/templates"
36
37 "github.com/spf13/cast"
38 )
39
40 // New returns a new instance of the resources-namespaced template functions.
41 func New(deps *deps.Deps) (*Namespace, error) {
42 if deps.ResourceSpec == nil {
43 return &Namespace{}, nil
44 }
45
46 minifyClient, err := minifier.New(deps.ResourceSpec)
47 if err != nil {
48 return nil, err
49 }
50
51 return &Namespace{
52 deps: deps,
53 createClient: create.New(deps.ResourceSpec),
54 bundlerClient: bundler.New(deps.ResourceSpec),
55 integrityClient: integrity.New(deps.ResourceSpec),
56 minifyClient: minifyClient,
57 templatesClient: templates.New(deps.ResourceSpec, deps),
58 }, nil
59 }
60
61 var (
62 _ resource.ResourceFinder = (*Namespace)(nil)
63 _ resource.Identifier = (*Namespace)(nil)
64 )
65
66 // Namespace provides template functions for the "resources" namespace.
67 type Namespace struct {
68 deps *deps.Deps
69
70 createClient *create.Client
71 bundlerClient *bundler.Client
72 integrityClient *integrity.Client
73 minifyClient *minifier.Client
74 templatesClient *templates.Client
75 }
76
77 // Copy copies r to the new targetPath in s.
78 func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) {
79 targetPath, err := cast.ToStringE(s)
80 if err != nil {
81 panic(err)
82 }
83 return ns.createClient.Copy(r, targetPath)
84 }
85
86 // Get locates the filename given in Hugo's assets filesystem
87 // and creates a Resource object that can be used for further transformations.
88 func (ns *Namespace) Get(filename any) resource.Resource {
89 filenamestr, err := cast.ToStringE(filename)
90 if err != nil {
91 panic(err)
92 }
93
94 if filenamestr == "" {
95 return nil
96 }
97
98 r, err := ns.createClient.Get(filenamestr)
99 if err != nil {
100 panic(err)
101 }
102
103 return r
104 }
105
106 // GetRemote gets the URL (via HTTP(s)) in the first argument in args and creates Resource object that can be used for
107 // further transformations.
108 //
109 // A second argument may be provided with an option map.
110 //
111 // Note: This method does not return any error as a second return value,
112 // for any error situations the error can be checked in .Err.
113 func (ns *Namespace) GetRemote(args ...any) (resource.Resource, error) {
114 get := func(args ...any) (resource.Resource, error) {
115 if len(args) < 1 || len(args) > 2 {
116 return nil, errors.New("must provide an URL and optionally an options map")
117 }
118
119 urlstr, err := cast.ToStringE(args[0])
120 if err != nil {
121 return nil, err
122 }
123
124 var options map[string]any
125
126 if len(args) > 1 {
127 options, err = hmaps.ToStringMapE(args[1])
128 if err != nil {
129 return nil, err
130 }
131 }
132
133 return ns.createClient.FromRemote(urlstr, options)
134 }
135
136 r, err := get(args...)
137 if err != nil {
138 switch v := err.(type) {
139 case *create.HTTPError:
140 return nil, resource.NewResourceError(v, v.Data)
141 default:
142 return nil, resource.NewResourceError(err, nil)
143 }
144 }
145 return r, nil
146 }
147
148 // GetMatch finds the first Resource matching the given pattern, or nil if none found.
149 //
150 // It looks for files in the assets file system.
151 //
152 // See Match for a more complete explanation about the rules used.
153 func (ns *Namespace) GetMatch(pattern any) resource.Resource {
154 patternStr, err := cast.ToStringE(pattern)
155 if err != nil {
156 panic(err)
157 }
158
159 r, err := ns.createClient.GetMatch(patternStr)
160 if err != nil {
161 panic(err)
162 }
163
164 return r
165 }
166
167 // ByType returns resources of a given resource type (e.g. "image").
168 func (ns *Namespace) ByType(typ any) resource.Resources {
169 return ns.createClient.ByType(cast.ToString(typ))
170 }
171
172 // Match gets all resources matching the given base path prefix, e.g
173 // "*.png" will match all png files. The "*" does not match path delimiters (/),
174 // so if you organize your resources in sub-folders, you need to be explicit about it, e.g.:
175 // "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and
176 // to match all PNG images below the images folder, use "images/**.jpg".
177 //
178 // The matching is case insensitive.
179 //
180 // Match matches by using the files name with path relative to the file system root
181 // with Unix style slashes (/) and no leading slash, e.g. "images/logo.png".
182 //
183 // See https://github.com/gobwas/glob for the full rules set.
184 //
185 // It looks for files in the assets file system.
186 //
187 // See Match for a more complete explanation about the rules used.
188 func (ns *Namespace) Match(pattern any) resource.Resources {
189 patternStr, err := cast.ToStringE(pattern)
190 if err != nil {
191 panic(err)
192 }
193
194 r, err := ns.createClient.Match(patternStr)
195 if err != nil {
196 panic(err)
197 }
198
199 return r
200 }
201
202 // Concat concatenates a slice of Resource objects. These resources must
203 // (currently) be of the same Media Type.
204 func (ns *Namespace) Concat(targetPathIn any, r any) (resource.Resource, error) {
205 targetPath, err := cast.ToStringE(targetPathIn)
206 if err != nil {
207 return nil, err
208 }
209
210 var rr resource.Resources
211
212 switch v := r.(type) {
213 case resource.Resources:
214 rr = v
215 case resource.ResourcesConverter:
216 rr = v.ToResources()
217 default:
218 return nil, fmt.Errorf("expected slice of Resource objects, received %T instead", r)
219 }
220
221 if len(rr) == 0 {
222 return nil, errors.New("must provide one or more Resource objects to concat")
223 }
224
225 return ns.bundlerClient.Concat(targetPath, rr)
226 }
227
228 // FromString creates a Resource from a string published to the relative target path.
229 func (ns *Namespace) FromString(targetPathIn, contentIn any) (resource.Resource, error) {
230 targetPath, err := cast.ToStringE(targetPathIn)
231 if err != nil {
232 return nil, err
233 }
234 content, err := cast.ToStringE(contentIn)
235 if err != nil {
236 return nil, err
237 }
238
239 return ns.createClient.FromString(targetPath, content)
240 }
241
242 // ExecuteAsTemplate creates a Resource from a Go template, parsed and executed with
243 // the given data, and published to the relative target path.
244 func (ns *Namespace) ExecuteAsTemplate(ctx context.Context, args ...any) (resource.Resource, error) {
245 if len(args) != 3 {
246 return nil, fmt.Errorf("must provide targetPath, the template data context and a Resource object")
247 }
248 targetPath, err := cast.ToStringE(args[0])
249 if err != nil {
250 return nil, err
251 }
252 data := args[1]
253
254 r, ok := args[2].(resources.ResourceTransformer)
255 if !ok {
256 return nil, fmt.Errorf("type %T not supported in Resource transformations", args[2])
257 }
258
259 return ns.templatesClient.ExecuteAsTemplate(ctx, r, targetPath, data)
260 }
261
262 // Fingerprint transforms the given Resource with a MD5 hash of the content in
263 // the RelPermalink and Permalink.
264 func (ns *Namespace) Fingerprint(args ...any) (resource.Resource, error) {
265 if len(args) < 1 {
266 return nil, errors.New("must provide a Resource object")
267 }
268
269 if len(args) > 2 {
270 return nil, errors.New("must not provide more arguments than Resource and hash algorithm")
271 }
272
273 var algo string
274 resIdx := 0
275
276 if len(args) == 2 {
277 resIdx = 1
278 var err error
279 algo, err = cast.ToStringE(args[0])
280 if err != nil {
281 return nil, err
282 }
283 }
284
285 r, ok := args[resIdx].(resources.ResourceTransformer)
286 if !ok {
287 return nil, fmt.Errorf("%T can not be transformed", args[resIdx])
288 }
289
290 return ns.integrityClient.Fingerprint(r, algo)
291 }
292
293 // Minify minifies the given Resource using the MediaType to pick the correct
294 // minifier.
295 func (ns *Namespace) Minify(r resources.ResourceTransformer) (resource.Resource, error) {
296 return ns.minifyClient.Minify(r)
297 }
298
299 // Publish publishes r to the destination and returns it.
300 func (ns *Namespace) Publish(r resource.Resource) (resource.Resource, error) {
301 s, ok := r.(resource.Source)
302 if !ok {
303 return nil, fmt.Errorf("%T can not be published", r)
304 }
305 if err := s.Publish(); err != nil {
306 return nil, err
307 }
308 return r, nil
309 }
310
311 // PostProcess processes r after the build.
312 //
313 // Deprecated: Use templates.Defer instead.
314 func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) {
315 hugo.DeprecateWithLogger("resources.PostProcess", "Use templates.Defer instead. See https://gohugo.io/functions/templates/defer/", "v0.164.0", ns.deps.Log.Logger())
316 return ns.deps.ResourceSpec.PostProcess(r)
317 }
318
319 // For internal use only.
320 func (ns *Namespace) Key() string {
321 return "tpl.resources"
322 }