testhelpers.go (2258B)
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 htesting
15
16 import (
17 "path/filepath"
18
19 "github.com/gohugoio/hugo/cache/filecache"
20 "github.com/gohugoio/hugo/config"
21 "github.com/gohugoio/hugo/helpers"
22 "github.com/gohugoio/hugo/hugofs"
23 "github.com/gohugoio/hugo/media"
24 "github.com/gohugoio/hugo/output"
25 "github.com/gohugoio/hugo/resources"
26 "github.com/spf13/afero"
27 )
28
29 func NewTestResourceSpec() (*resources.Spec, error) {
30 cfg := config.NewWithTestDefaults()
31
32 imagingCfg := map[string]any{
33 "resampleFilter": "linear",
34 "quality": 68,
35 "anchor": "left",
36 }
37
38 cfg.Set("imaging", imagingCfg)
39
40 fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(afero.NewMemMapFs()), cfg)
41
42 s, err := helpers.NewPathSpec(fs, cfg, nil)
43 if err != nil {
44 return nil, err
45 }
46
47 filecaches, err := filecache.NewCaches(s)
48 if err != nil {
49 return nil, err
50 }
51
52 spec, err := resources.NewSpec(s, filecaches, nil, nil, nil, nil, output.DefaultFormats, media.DefaultTypes)
53 return spec, err
54 }
55
56 func NewResourceTransformer(filename, content string) (resources.ResourceTransformer, error) {
57 spec, err := NewTestResourceSpec()
58 if err != nil {
59 return nil, err
60 }
61 return NewResourceTransformerForSpec(spec, filename, content)
62 }
63
64 func NewResourceTransformerForSpec(spec *resources.Spec, filename, content string) (resources.ResourceTransformer, error) {
65 filename = filepath.FromSlash(filename)
66
67 fs := spec.Fs.Source
68 if err := afero.WriteFile(fs, filename, []byte(content), 0777); err != nil {
69 return nil, err
70 }
71
72 r, err := spec.New(resources.ResourceSourceDescriptor{Fs: fs, SourceFilename: filename})
73 if err != nil {
74 return nil, err
75 }
76
77 return r.(resources.ResourceTransformer), nil
78 }