github.com/jacobsoderblom/buffalo@v0.11.0/buffalo/cmd/updater/npm.go (about)

     1  package updater
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  	"os/exec"
     9  
    10  	"html/template"
    11  
    12  	"github.com/gobuffalo/buffalo/generators/assets/webpack"
    13  	"github.com/gobuffalo/buffalo/generators/newapp"
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  // PackageJSONCheck will compare the current default Buffalo
    18  // package.json against the applications package.json. If they are
    19  // different you have the option to overwrite the existing package.json
    20  // file with the new one.
    21  func PackageJSONCheck(r *Runner) error {
    22  	fmt.Println("~~~ Checking package.json ~~~")
    23  
    24  	if !r.App.WithWebpack {
    25  		return nil
    26  	}
    27  
    28  	g := newapp.Generator{
    29  		App:       r.App,
    30  		Bootstrap: 3,
    31  	}
    32  
    33  	box := webpack.TemplateBox
    34  
    35  	f, err := box.MustString("package.json.tmpl")
    36  	if err != nil {
    37  		return errors.WithStack(err)
    38  	}
    39  
    40  	tmpl, err := template.New("package.json").Parse(f)
    41  	if err != nil {
    42  		return errors.WithStack(err)
    43  	}
    44  
    45  	bb := &bytes.Buffer{}
    46  	err = tmpl.Execute(bb, map[string]interface{}{
    47  		"opts": g,
    48  	})
    49  	if err != nil {
    50  		return errors.WithStack(err)
    51  	}
    52  
    53  	b, err := ioutil.ReadFile("package.json")
    54  	if err != nil {
    55  		return errors.WithStack(err)
    56  	}
    57  
    58  	if string(b) == bb.String() {
    59  		return nil
    60  	}
    61  
    62  	if !ask("Your package.json file is different from the latest Buffalo template.\nWould you like to REPLACE yours with the latest template?") {
    63  		fmt.Println("\tskipping package.json")
    64  		return nil
    65  	}
    66  
    67  	pf, err := os.Create("package.json")
    68  	if err != nil {
    69  		return errors.WithStack(err)
    70  	}
    71  	_, err = pf.Write(bb.Bytes())
    72  	if err != nil {
    73  		return errors.WithStack(err)
    74  	}
    75  	err = pf.Close()
    76  	if err != nil {
    77  		return errors.WithStack(err)
    78  	}
    79  
    80  	var cmd *exec.Cmd
    81  	if r.App.WithYarn {
    82  		cmd = exec.Command("yarn", "install")
    83  	} else {
    84  		cmd = exec.Command("npm", "install")
    85  	}
    86  
    87  	cmd.Stdin = os.Stdin
    88  	cmd.Stdout = os.Stdout
    89  	cmd.Stderr = os.Stderr
    90  	return cmd.Run()
    91  }