github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/genny/actions/build_actions.go (about)

     1  package actions
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/gobuffalo/flect/name"
     8  	"github.com/gobuffalo/genny/v2"
     9  )
    10  
    11  // buildActions is the top level action builder
    12  // it determines whether to build a new actions/foo.go file
    13  // or append to an existing one
    14  func buildActions(pres *presenter) genny.RunFn {
    15  	return func(r *genny.Runner) error {
    16  		fn := fmt.Sprintf("actions/%s.go", pres.Name.File())
    17  		xf, err := r.FindFile(fn)
    18  		if err != nil {
    19  			return buildNewActions(fn, pres)(r)
    20  		}
    21  		if err := appendActions(xf, pres)(r); err != nil {
    22  			return err
    23  		}
    24  
    25  		return nil
    26  	}
    27  }
    28  
    29  // buildNewActions builds a brand new actions/foo.go file
    30  // and files it with actions
    31  func buildNewActions(fn string, pres *presenter) genny.RunFn {
    32  	return func(r *genny.Runner) error {
    33  		for _, a := range pres.Options.Actions {
    34  			pres.Actions = append(pres.Actions, name.New(a))
    35  		}
    36  
    37  		h, err := box.FindString("actions_header.go.tmpl")
    38  		if err != nil {
    39  			return err
    40  		}
    41  		a, err := box.FindString("actions.go.tmpl")
    42  		if err != nil {
    43  			return err
    44  		}
    45  
    46  		f := genny.NewFileS(fn+".tmpl", h+a)
    47  
    48  		f, err = transform(pres, f)
    49  		if err != nil {
    50  			return err
    51  		}
    52  		return r.File(f)
    53  	}
    54  }
    55  
    56  // appendActions appends *only* actions that don't exist in
    57  // actions/foo.go. if the action already exists it is not touched.
    58  func appendActions(f genny.File, pres *presenter) genny.RunFn {
    59  	return func(r *genny.Runner) error {
    60  		body := f.String()
    61  		for _, ac := range pres.Options.Actions {
    62  			a := name.New(ac)
    63  			x := fmt.Sprintf("func %s%s", pres.Name.Pascalize(), a.Pascalize())
    64  			if strings.Contains(body, x) {
    65  				continue
    66  			}
    67  			pres.Actions = append(pres.Actions, a)
    68  		}
    69  
    70  		a, err := box.FindString("actions.go.tmpl")
    71  		if err != nil {
    72  			return err
    73  		}
    74  
    75  		f = genny.NewFileS(f.Name()+".tmpl", f.String()+a)
    76  
    77  		f, err = transform(pres, f)
    78  		if err != nil {
    79  			return err
    80  		}
    81  		return r.File(f)
    82  	}
    83  }