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

     1  package template
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // Generator allows to identify template as a plugin
    14  type Generator struct{}
    15  
    16  // Name returns the name of the generator plugin
    17  func (g Generator) Name() string {
    18  	return "template"
    19  }
    20  
    21  // Generate generates an empty [name].plush.html file
    22  func (g Generator) Generate(ctx context.Context, root string, args []string) error {
    23  	if len(args) < 3 {
    24  		return errors.Errorf("no name specified, please use `ox generate template [name]`")
    25  	}
    26  
    27  	if err := g.generateTemplate(root, args[2]); err != nil {
    28  		return err
    29  	}
    30  
    31  	fmt.Printf("[info] Template generated in app/templates/%s.plush.html \n", args[2])
    32  
    33  	return nil
    34  }
    35  
    36  func (g Generator) generateTemplate(root, filename string) error {
    37  	dirpath := filepath.Join(root, "app", "templates")
    38  
    39  	if !g.exists(dirpath) {
    40  		return errors.Errorf("folder '%s' do not exists on your buffalo app, please ensure the folder exists in order to proceed", dirpath)
    41  	}
    42  
    43  	tmpl := g.generateFilePath(dirpath, filename)
    44  	if g.exists(tmpl) {
    45  		return errors.Errorf("template already exists")
    46  	}
    47  
    48  	if err := os.MkdirAll(filepath.Dir(tmpl), 0755); err != nil {
    49  		return errors.Wrap(err, "error creating subfolders")
    50  	}
    51  
    52  	file, err := os.Create(tmpl)
    53  	if err != nil {
    54  		return errors.Wrap(err, "error creating file")
    55  	}
    56  
    57  	defer file.Close()
    58  
    59  	return nil
    60  }
    61  
    62  // generateFilePath translates the required path to create the file properly
    63  func (g Generator) generateFilePath(dirPath, filename string) string {
    64  	base := strings.Split(filename, ".")[0]
    65  	file := base + ".plush.html"
    66  
    67  	return filepath.Join(dirPath, file)
    68  }
    69  
    70  func (g Generator) exists(path string) bool {
    71  	_, err := os.Stat(path)
    72  
    73  	return !os.IsNotExist(err)
    74  }