github.com/hairyhenderson/templater@v3.5.0+incompatible/data/datasource_file.go (about)

     1  package data
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"net/url"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  
    12  	"github.com/spf13/afero"
    13  
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  func readFile(source *Source, args ...string) ([]byte, error) {
    18  	if source.fs == nil {
    19  		source.fs = afero.NewOsFs()
    20  	}
    21  
    22  	p := filepath.FromSlash(source.URL.Path)
    23  
    24  	if len(args) == 1 {
    25  		parsed, err := url.Parse(args[0])
    26  		if err != nil {
    27  			return nil, err
    28  		}
    29  
    30  		if parsed.Path != "" {
    31  			p = filepath.Join(p, parsed.Path)
    32  		}
    33  	}
    34  
    35  	// make sure we can access the file
    36  	i, err := source.fs.Stat(p)
    37  	if err != nil {
    38  		return nil, errors.Wrapf(err, "Can't stat %s", p)
    39  	}
    40  
    41  	if strings.HasSuffix(p, string(filepath.Separator)) {
    42  		source.mediaType = jsonArrayMimetype
    43  		if i.IsDir() {
    44  			return readFileDir(source, p)
    45  		}
    46  		return nil, errors.Errorf("%s is not a directory", p)
    47  	}
    48  
    49  	f, err := source.fs.OpenFile(p, os.O_RDONLY, 0)
    50  	if err != nil {
    51  		return nil, errors.Wrapf(err, "Can't open %s", p)
    52  	}
    53  
    54  	b, err := ioutil.ReadAll(f)
    55  	if err != nil {
    56  		return nil, errors.Wrapf(err, "Can't read %s", p)
    57  	}
    58  	return b, nil
    59  }
    60  
    61  func readFileDir(source *Source, p string) ([]byte, error) {
    62  	names, err := afero.ReadDir(source.fs, p)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	files := make([]string, len(names))
    67  	for i, v := range names {
    68  		files[i] = v.Name()
    69  	}
    70  
    71  	var buf bytes.Buffer
    72  	enc := json.NewEncoder(&buf)
    73  	if err := enc.Encode(files); err != nil {
    74  		return nil, err
    75  	}
    76  	b := buf.Bytes()
    77  	// chop off the newline added by the json encoder
    78  	return b[:len(b)-1], nil
    79  }