github.com/wawandco/oxpecker@v1.5.7-0.20210910201653-5958d4afdd89/tools/grift/generator.go (about) 1 package grift 2 3 import ( 4 "context" 5 _ "embed" 6 "os" 7 "path/filepath" 8 9 "github.com/gobuffalo/flect" 10 "github.com/pkg/errors" 11 "github.com/wawandco/oxpecker/internal/log" 12 "github.com/wawandco/oxpecker/internal/source" 13 ) 14 15 var ( 16 //go:embed templates/task.go.tmpl 17 taskTemplate string 18 ) 19 20 type Generator struct { 21 name string 22 filename string 23 dir string 24 } 25 26 // Name returns the name of the plugin 27 func (g Generator) Name() string { 28 return "grift/generate-task" 29 } 30 31 // InvocationName is used to identify the generator when 32 // the generate command is called. 33 func (g Generator) InvocationName() string { 34 return "task" 35 } 36 37 func (g Generator) Generate(ctx context.Context, root string, args []string) error { 38 if len(args) < 3 { 39 return errors.Errorf("no name specified, please use `ox generate task [name]`") 40 } 41 42 dirPath := filepath.Join(root, "app", "tasks") 43 if !g.exists(dirPath) { 44 err := os.MkdirAll(filepath.Dir(dirPath), 0755) 45 if err != nil { 46 return (err) 47 } 48 } 49 50 g.name = flect.Singularize(args[2]) 51 g.filename = flect.Singularize(flect.Underscore(args[2])) 52 g.dir = dirPath 53 54 if g.exists(filepath.Join(g.dir, g.filename+".go")) { 55 return errors.Errorf("Task file already exists") 56 } 57 58 if err := g.createTaskFile(args); err != nil { 59 return errors.Wrap(err, "creating action file") 60 } 61 62 log.Infof("task generated in: \n-- app/tasks/%s.go\n", g.name) 63 64 return nil 65 } 66 67 func (g Generator) createTaskFile(args []string) error { 68 path := filepath.Join(g.dir, g.filename+".go") 69 err := source.Build(path, taskTemplate, g.name) 70 71 return errors.Wrap(err, "parsing new template error") 72 } 73 74 func (g Generator) exists(path string) bool { 75 _, err := os.Stat(path) 76 77 return !os.IsNotExist(err) 78 }