github.com/jasonish/buffalo@v0.8.2-0.20170413145823-bacbdd415f1b/generators/resource/resource.go (about)

     1  package resource
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/gobuffalo/buffalo/generators"
    10  	"github.com/gobuffalo/makr"
    11  	"github.com/markbates/inflect"
    12  )
    13  
    14  // New generates a new actions/resource file and a stub test.
    15  func New(data makr.Data) (*makr.Generator, error) {
    16  	g := makr.New()
    17  	files, err := generators.Find("resource")
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  	// Get the flags
    22  	useModel := data["useModel"].(string)
    23  	skipModel := data["skipModel"].(bool)
    24  
    25  	tmplName := "resource-use_model"
    26  
    27  	if skipModel == true {
    28  		tmplName = "resource-name"
    29  	}
    30  	for _, f := range files {
    31  		// Adding the resource template to the generator
    32  		if strings.Contains(f.WritePath, tmplName) {
    33  			g.Add(makr.NewFile(strings.Replace(f.WritePath, tmplName, data["under"].(string), -1), f.Body))
    34  		}
    35  		// Adding the html templates to the generator
    36  		if strings.Contains(f.WritePath, "model-view-") {
    37  			targetPath := filepath.Join(
    38  				filepath.Dir(f.WritePath),
    39  				data["modelPluralUnder"].(string),
    40  				strings.Replace(filepath.Base(f.WritePath), "model-view-", "", -1),
    41  			)
    42  			g.Add(makr.NewFile(targetPath, f.Body))
    43  		}
    44  	}
    45  	g.Add(&makr.Func{
    46  		Should: func(data makr.Data) bool { return true },
    47  		Runner: func(root string, data makr.Data) error {
    48  			return generators.AddInsideAppBlock(fmt.Sprintf("app.Resource(\"/%s\", %sResource{&buffalo.BaseResource{}})", data["under"], data["camel"]))
    49  		},
    50  	})
    51  	if skipModel == false && useModel == "" {
    52  		g.Add(modelCommand(data))
    53  	}
    54  
    55  	g.Add(makr.NewCommand(makr.GoFmt()))
    56  
    57  	return g, nil
    58  }
    59  
    60  func modelCommand(data makr.Data) makr.Command {
    61  	modelName := inflect.Underscore(data["singular"].(string))
    62  
    63  	args := data["args"].([]string)
    64  	args = append(args[:0], args[0+1:]...)
    65  	args = append([]string{"db", "g", "model", modelName}, args...)
    66  
    67  	if skipMigration := data["skipMigration"].(bool); skipMigration == true {
    68  		args = append(args, "--skip-migration")
    69  	}
    70  
    71  	return makr.NewCommand(exec.Command("buffalo", args...))
    72  }