github.com/bscott/buffalo@v0.11.1/generators/files.go (about) 1 package generators 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "runtime" 9 "strings" 10 "sync" 11 12 "github.com/gobuffalo/envy" 13 "github.com/gobuffalo/packr" 14 "github.com/sirupsen/logrus" 15 "golang.org/x/sync/errgroup" 16 ) 17 18 // File represents the file to be templated 19 type File struct { 20 ReadPath string 21 WritePath string 22 Body string 23 } 24 25 // Files is a slice of File 26 type Files []File 27 28 // FindByBox all the .tmpl files inside the packr.Box 29 func FindByBox(box packr.Box) (Files, error) { 30 files := Files{} 31 err := box.Walk(func(p string, file packr.File) error { 32 if filepath.Ext(p) == ".tmpl" { 33 p = strings.TrimPrefix(p, "/") 34 f := File{ReadPath: p} 35 p = strings.Replace(p, "dot-", ".", 1) 36 p = strings.Replace(p, ".tmpl", "", 1) 37 f.WritePath = p 38 b, err := ioutil.ReadAll(file) 39 if err != nil { 40 return err 41 } 42 f.Body = string(b) 43 files = append(files, f) 44 } 45 return nil 46 }) 47 return files, err 48 } 49 50 // TemplatesPath is the "base" path for generator templates 51 var TemplatesPath = filepath.Join("github.com", "gobuffalo", "buffalo", "generators") 52 53 // Find all the .tmpl files inside the buffalo GOPATH 54 func Find(path string) (Files, error) { 55 warningMsg := "Find is deprecated, and will be removed in v0.12.0. Use generators.FindByBox instead." 56 _, file, no, ok := runtime.Caller(1) 57 if ok { 58 warningMsg = fmt.Sprintf("%s Called from %s:%d", warningMsg, file, no) 59 } 60 61 logrus.Info(warningMsg) 62 mu := &sync.Mutex{} 63 wg := &errgroup.Group{} 64 files := Files{} 65 for _, gp := range envy.GoPaths() { 66 func(gp string) { 67 wg.Go(func() error { 68 root := filepath.Join(envy.GoPath(), "src", path, "templates") 69 return filepath.Walk(root, func(p string, info os.FileInfo, err error) error { 70 if info != nil && !info.IsDir() { 71 if filepath.Ext(p) == ".tmpl" { 72 f := File{ReadPath: p} 73 rel := strings.TrimPrefix(p, root) 74 75 paths := strings.Split(rel, string(os.PathSeparator)) 76 77 li := len(paths) - 1 78 base := paths[li] 79 base = strings.TrimSuffix(base, ".tmpl") 80 if strings.HasPrefix(base, "dot-") { 81 base = "." + strings.TrimPrefix(base, "dot-") 82 } 83 paths[li] = base 84 f.WritePath = filepath.Join(paths...) 85 86 b, err := ioutil.ReadFile(p) 87 if err != nil { 88 return err 89 } 90 f.Body = string(b) 91 mu.Lock() 92 files = append(files, f) 93 mu.Unlock() 94 } 95 } 96 return nil 97 }) 98 }) 99 }(gp) 100 } 101 err := wg.Wait() 102 return files, err 103 }