github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/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/config"
    20  	"github.com/gohugoio/hugo/config/testconfig"
    21  	"github.com/gohugoio/hugo/helpers"
    22  	"github.com/gohugoio/hugo/hugofs"
    23  	"github.com/gohugoio/hugo/resources"
    24  	"github.com/spf13/afero"
    25  )
    26  
    27  func NewTestResourceSpec() (*resources.Spec, error) {
    28  	cfg := config.New()
    29  
    30  	imagingCfg := map[string]any{
    31  		"resampleFilter": "linear",
    32  		"quality":        68,
    33  		"anchor":         "left",
    34  	}
    35  
    36  	cfg.Set("imaging", imagingCfg)
    37  	afs := afero.NewMemMapFs()
    38  
    39  	conf := testconfig.GetTestConfig(afs, cfg)
    40  	fs := hugofs.NewFrom(hugofs.NewBaseFileDecorator(afs), conf.BaseConfig())
    41  	s, err := helpers.NewPathSpec(fs, conf, nil)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	spec, err := resources.NewSpec(s, nil, nil, nil, nil, nil, nil)
    47  	return spec, err
    48  }
    49  
    50  func NewResourceTransformer(filename, content string) (resources.ResourceTransformer, error) {
    51  	spec, err := NewTestResourceSpec()
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	return NewResourceTransformerForSpec(spec, filename, content)
    56  }
    57  
    58  func NewResourceTransformerForSpec(spec *resources.Spec, filename, content string) (resources.ResourceTransformer, error) {
    59  	filename = filepath.FromSlash(filename)
    60  
    61  	fs := spec.Fs.Source
    62  	if err := afero.WriteFile(fs, filename, []byte(content), 0777); err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	r, err := spec.New(resources.ResourceSourceDescriptor{Fs: fs, SourceFilename: filename})
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	return r.(resources.ResourceTransformer), nil
    72  }