github.com/mayra-cabrera/buffalo@v0.9.4-0.20170814145312-66d2e7772f11/generators/files.go (about)

     1  package generators
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/gobuffalo/envy"
    11  )
    12  
    13  // File represents the file to be templated
    14  type File struct {
    15  	ReadPath  string
    16  	WritePath string
    17  	Body      string
    18  }
    19  
    20  // Files is a slice of File
    21  type Files []File
    22  
    23  // Find all the .tmpl files inside the buffalo GOPATH
    24  func Find(path string) (Files, error) {
    25  	gp, err := goPath()
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	root := filepath.Join(gp, "src", "github.com", "gobuffalo", "buffalo", "generators", path, "templates")
    30  	files := Files{}
    31  	err = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
    32  		if info != nil && !info.IsDir() {
    33  			if filepath.Ext(p) == ".tmpl" {
    34  				f := File{ReadPath: p}
    35  				rel := strings.TrimPrefix(p, root)
    36  
    37  				paths := strings.Split(rel, string(os.PathSeparator))
    38  
    39  				li := len(paths) - 1
    40  				base := paths[li]
    41  				base = strings.TrimSuffix(base, ".tmpl")
    42  				if strings.HasPrefix(base, "dot-") {
    43  					base = "." + strings.TrimPrefix(base, "dot-")
    44  				}
    45  				paths[li] = base
    46  				f.WritePath = filepath.Join(paths...)
    47  
    48  				b, err := ioutil.ReadFile(p)
    49  				if err != nil {
    50  					return err
    51  				}
    52  				f.Body = string(b)
    53  				files = append(files, f)
    54  			}
    55  		}
    56  		return nil
    57  	})
    58  	return files, err
    59  }
    60  
    61  func goPath() (string, error) {
    62  	for _, path := range envy.GoPaths() {
    63  		pp := filepath.Join(path, "src", "github.com", "gobuffalo", "buffalo")
    64  		if exists(pp) {
    65  			return path, nil
    66  		}
    67  	}
    68  	return "", errors.New("buffalo was not found")
    69  }
    70  
    71  func exists(path string) bool {
    72  	_, err := os.Stat(path)
    73  	return err == nil
    74  }