github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/resources/resource_transformers/htesting/testhelpers.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 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.New() 31 cfg.Set("baseURL", "https://example.org") 32 cfg.Set("publishDir", "public") 33 34 imagingCfg := map[string]interface{}{ 35 "resampleFilter": "linear", 36 "quality": 68, 37 "anchor": "left", 38 } 39 40 cfg.Set("imaging", imagingCfg) 41 42 fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(afero.NewMemMapFs()), cfg) 43 44 s, err := helpers.NewPathSpec(fs, cfg, nil) 45 if err != nil { 46 return nil, err 47 } 48 49 filecaches, err := filecache.NewCaches(s) 50 if err != nil { 51 return nil, err 52 } 53 54 spec, err := resources.NewSpec(s, filecaches, nil, nil, nil, nil, output.DefaultFormats, media.DefaultTypes) 55 return spec, err 56 } 57 58 func NewResourceTransformer(filename, content string) (resources.ResourceTransformer, error) { 59 spec, err := NewTestResourceSpec() 60 if err != nil { 61 return nil, err 62 } 63 return NewResourceTransformerForSpec(spec, filename, content) 64 } 65 66 func NewResourceTransformerForSpec(spec *resources.Spec, filename, content string) (resources.ResourceTransformer, error) { 67 filename = filepath.FromSlash(filename) 68 69 fs := spec.Fs.Source 70 if err := afero.WriteFile(fs, filename, []byte(content), 0777); err != nil { 71 return nil, err 72 } 73 74 r, err := spec.New(resources.ResourceSourceDescriptor{Fs: fs, SourceFilename: filename}) 75 if err != nil { 76 return nil, err 77 } 78 79 return r.(resources.ResourceTransformer), nil 80 }