github.com/robinwassen/hugo@v0.47.1/resource/create/create.go (about)

     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 create contains functions for to create Resource objects. This will
    15  // typically non-files.
    16  package create
    17  
    18  import (
    19  	"path/filepath"
    20  
    21  	"github.com/spf13/afero"
    22  
    23  	"github.com/gohugoio/hugo/resource"
    24  )
    25  
    26  // Client contains methods to create Resource objects.
    27  // tasks to Resource objects.
    28  type Client struct {
    29  	rs *resource.Spec
    30  }
    31  
    32  // New creates a new Client with the given specification.
    33  func New(rs *resource.Spec) *Client {
    34  	return &Client{rs: rs}
    35  }
    36  
    37  // Get creates a new Resource by opening the given filename in the given filesystem.
    38  func (c *Client) Get(fs afero.Fs, filename string) (resource.Resource, error) {
    39  	filename = filepath.Clean(filename)
    40  	return c.rs.ResourceCache.GetOrCreate(resource.ResourceKeyPartition(filename), filename, func() (resource.Resource, error) {
    41  		return c.rs.NewForFs(fs,
    42  			resource.ResourceSourceDescriptor{
    43  				LazyPublish:    true,
    44  				SourceFilename: filename})
    45  	})
    46  
    47  }
    48  
    49  // FromString creates a new Resource from a string with the given relative target path.
    50  func (c *Client) FromString(targetPath, content string) (resource.Resource, error) {
    51  	return c.rs.ResourceCache.GetOrCreate(resource.CACHE_OTHER, targetPath, func() (resource.Resource, error) {
    52  		return c.rs.NewForFs(
    53  			c.rs.BaseFs.Resources.Fs,
    54  			resource.ResourceSourceDescriptor{
    55  				LazyPublish: true,
    56  				OpenReadSeekCloser: func() (resource.ReadSeekCloser, error) {
    57  					return resource.NewReadSeekerNoOpCloserFromString(content), nil
    58  				},
    59  				RelTargetFilename: filepath.Clean(targetPath)})
    60  
    61  	})
    62  
    63  }