github.com/wuhuizuo/gomplate@v3.5.0+incompatible/funcs/file.go (about)

     1  package funcs
     2  
     3  import (
     4  	"os"
     5  	"sync"
     6  
     7  	"github.com/hairyhenderson/gomplate/conv"
     8  	"github.com/hairyhenderson/gomplate/file"
     9  	"github.com/spf13/afero"
    10  )
    11  
    12  var (
    13  	ff     *FileFuncs
    14  	ffInit sync.Once
    15  )
    16  
    17  // FileNS - the File namespace
    18  func FileNS() *FileFuncs {
    19  	ffInit.Do(func() { ff = &FileFuncs{afero.NewOsFs()} })
    20  	return ff
    21  }
    22  
    23  // AddFileFuncs -
    24  func AddFileFuncs(f map[string]interface{}) {
    25  	f["file"] = FileNS
    26  }
    27  
    28  // FileFuncs -
    29  type FileFuncs struct {
    30  	fs afero.Fs
    31  }
    32  
    33  // Read -
    34  func (f *FileFuncs) Read(path interface{}) (string, error) {
    35  	return file.Read(conv.ToString(path))
    36  }
    37  
    38  // Stat -
    39  func (f *FileFuncs) Stat(path interface{}) (os.FileInfo, error) {
    40  	return f.fs.Stat(conv.ToString(path))
    41  }
    42  
    43  // Exists -
    44  func (f *FileFuncs) Exists(path interface{}) bool {
    45  	_, err := f.Stat(conv.ToString(path))
    46  	return err == nil
    47  }
    48  
    49  // IsDir -
    50  func (f *FileFuncs) IsDir(path interface{}) bool {
    51  	i, err := f.Stat(conv.ToString(path))
    52  	return err == nil && i.IsDir()
    53  }
    54  
    55  // ReadDir -
    56  func (f *FileFuncs) ReadDir(path interface{}) ([]string, error) {
    57  	return file.ReadDir(conv.ToString(path))
    58  }
    59  
    60  // Walk -
    61  func (f *FileFuncs) Walk(path interface{}) ([]string, error) {
    62  	files := make([]string, 0)
    63  	err := afero.Walk(f.fs, conv.ToString(path), func(subpath string, finfo os.FileInfo, err error) error {
    64  		if err != nil {
    65  			return err
    66  		}
    67  		files = append(files, subpath)
    68  		return nil
    69  	})
    70  	return files, err
    71  }
    72  
    73  // Write -
    74  func (f *FileFuncs) Write(path interface{}, data interface{}) (s string, err error) {
    75  	if b, ok := data.([]byte); ok {
    76  		err = file.Write(conv.ToString(path), b)
    77  	} else {
    78  		err = file.Write(conv.ToString(path), []byte(conv.ToString(data)))
    79  	}
    80  	return "", err
    81  }