github.com/JarrahG/buffalocli@v0.0.0-20230801092127-b85bfd5d395a/internal/genny/fix/webpack.go (about)

     1  package fix
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"html/template"
     7  
     8  	"github.com/JarrahG/buffalocli/internal/genny/assets/webpack"
     9  	"github.com/gobuffalo/genny/v2"
    10  	"github.com/gobuffalo/meta"
    11  )
    12  
    13  // WebpackCheck will compare the current default Buffalo
    14  // webpack.config.js against the applications webpack.config.js. If they are
    15  // different you have the option to overwrite the existing webpack.config.js
    16  // file with the new one.
    17  func WebpackCheck(opts *Options) genny.RunFn {
    18  	return func(r *genny.Runner) error {
    19  		if !opts.App.WithWebpack {
    20  			return nil
    21  		}
    22  
    23  		fmt.Println("~~~ Checking webpack.config.js ~~~")
    24  		bb, err := defaultWebpack(opts.App)
    25  		if err != nil {
    26  			return err
    27  		}
    28  
    29  		f, err := r.FindFile("webpack.config.js")
    30  		if err != nil {
    31  			return err
    32  		}
    33  
    34  		if f.String() == bb.String() {
    35  			return nil
    36  		}
    37  
    38  		if !opts.YesToAll && !ask("Your webpack.config.js file is different from the latest Buffalo template.\nWould you like to replace yours with the latest template?") {
    39  			fmt.Println("\tSkipping webpack.config.js")
    40  			return nil
    41  		}
    42  
    43  		if _, err := f.Write(bb.Bytes()); err != nil {
    44  			return err
    45  		}
    46  		return r.File(f)
    47  	}
    48  }
    49  
    50  func defaultWebpack(app meta.App) (*bytes.Buffer, error) {
    51  	templates, err := webpack.Templates()
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	tmpl, err := template.New("webpack").ParseFS(templates, "webpack.config.js.tmpl")
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	bb := &bytes.Buffer{}
    62  	err = tmpl.ExecuteTemplate(bb, "webpack.config.js.tmpl", map[string]interface{}{
    63  		"opts": &webpack.Options{
    64  			App: app,
    65  		},
    66  	})
    67  
    68  	return bb, err
    69  }