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

     1  package build
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"strings"
     7  
     8  	"github.com/gobuffalo/genny/v2"
     9  	"github.com/gobuffalo/packd"
    10  	"github.com/gobuffalo/plush/v4"
    11  	"github.com/markbates/safe"
    12  )
    13  
    14  // TemplateValidator is given a file and returns an
    15  // effort if there is a template validation error
    16  // with the template
    17  type TemplateValidator func(f genny.File) error
    18  
    19  // ValidateTemplates returns a genny.RunFn that will walk the
    20  // given box and run each of the files found through each of the
    21  // template validators
    22  func ValidateTemplates(walk packd.Walker, tvs []TemplateValidator) genny.RunFn {
    23  	if len(tvs) == 0 {
    24  		return func(r *genny.Runner) error {
    25  			return nil
    26  		}
    27  	}
    28  	return func(r *genny.Runner) error {
    29  		var errs []string
    30  		err := packd.SkipWalker(walk, packd.CommonSkipPrefixes, func(path string, file packd.File) error {
    31  			info, err := file.FileInfo()
    32  			if err != nil {
    33  				return err
    34  			}
    35  			if info.IsDir() {
    36  				return nil
    37  			}
    38  
    39  			f := genny.NewFile(path, file)
    40  			for _, tv := range tvs {
    41  				err := safe.Run(func() {
    42  					if err := tv(f); err != nil {
    43  						errs = append(errs, fmt.Sprintf("template error in file %s: %s", path, err.Error()))
    44  					}
    45  				})
    46  				if err != nil {
    47  					return err
    48  				}
    49  			}
    50  
    51  			return nil
    52  		})
    53  		if err != nil {
    54  			return err
    55  		}
    56  		if len(errs) == 0 {
    57  			return nil
    58  		}
    59  		return fmt.Errorf(strings.Join(errs, "\n"))
    60  	}
    61  }
    62  
    63  // PlushValidator validates the file is a valid
    64  // Plush file if the extension is .md, .html, or .plush
    65  func PlushValidator(f genny.File) error {
    66  	if !genny.HasExt(f, ".html", ".md", ".plush") {
    67  		return nil
    68  	}
    69  	_, err := plush.Parse(f.String())
    70  	return err
    71  }
    72  
    73  // GoTemplateValidator validates the file is a
    74  // valid Go text/template file if the extension
    75  // is .tmpl
    76  func GoTemplateValidator(f genny.File) error {
    77  	if !genny.HasExt(f, ".tmpl") {
    78  		return nil
    79  	}
    80  	t := template.New(f.Name())
    81  	_, err := t.Parse(f.String())
    82  	return err
    83  }