github.com/wawandco/oxplugins@v0.7.11/tools/tasks/generator.go (about)

     1  package tasks
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"html/template"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	"github.com/gobuffalo/flect"
    13  	"github.com/pkg/errors"
    14  )
    15  
    16  type Generator struct {
    17  	name     string
    18  	filename string
    19  	dir      string
    20  }
    21  
    22  func (g Generator) Name() string {
    23  	return "task"
    24  }
    25  
    26  func (g Generator) Generate(ctx context.Context, root string, args []string) error {
    27  	if len(args) < 3 {
    28  		return errors.Errorf("no name specified, please use `ox generate task [name]`")
    29  	}
    30  
    31  	dirPath := filepath.Join(root, "app", "tasks")
    32  	if !g.exists(dirPath) {
    33  		err := os.MkdirAll(filepath.Dir(dirPath), 0755)
    34  		if err != nil {
    35  			return (err)
    36  		}
    37  	}
    38  
    39  	g.name = flect.Singularize(args[2])
    40  	g.filename = flect.Singularize(flect.Underscore(args[2]))
    41  	g.dir = dirPath
    42  
    43  	if g.exists(filepath.Join(g.dir, g.filename+".go")) {
    44  		return errors.Errorf("Task file already exists")
    45  	}
    46  
    47  	if err := g.createTaskFile(args); err != nil {
    48  		return errors.Wrap(err, "creating action file")
    49  	}
    50  
    51  	fmt.Printf("[info] task generated in: \n-- app/tasks/%s.go\n", g.name)
    52  
    53  	return nil
    54  }
    55  
    56  func (g Generator) createTaskFile(args []string) error {
    57  	filename := g.filename + ".go"
    58  	path := filepath.Join(g.dir, filename)
    59  	data := struct {
    60  		Name string
    61  	}{
    62  		Name: g.name,
    63  	}
    64  
    65  	tmpl, err := template.New(filename).Funcs(templateFuncs).Parse(taskTemplate)
    66  	if err != nil {
    67  		return errors.Wrap(err, "parsing new template error")
    68  	}
    69  
    70  	var tpl bytes.Buffer
    71  	if err := tmpl.Execute(&tpl, data); err != nil {
    72  		return errors.Wrap(err, "executing new template error")
    73  	}
    74  
    75  	err = ioutil.WriteFile(path, tpl.Bytes(), 0655)
    76  	if err != nil {
    77  		return errors.Wrap(err, "writing new template error")
    78  	}
    79  
    80  	return nil
    81  }
    82  
    83  func (g Generator) exists(path string) bool {
    84  	_, err := os.Stat(path)
    85  
    86  	return !os.IsNotExist(err)
    87  }