github.com/ashleymcnamara/buffalo@v0.8.0/buffalo/cmd/dev.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"os/exec"
     9  
    10  	"github.com/gobuffalo/buffalo/generators/assets/webpack"
    11  	rg "github.com/gobuffalo/buffalo/generators/refresh"
    12  	"github.com/markbates/refresh/refresh"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  // devCmd represents the dev command
    17  var devCmd = &cobra.Command{
    18  	Use:   "dev",
    19  	Short: "Runs your Buffalo app in 'development' mode",
    20  	Long: `Runs your Buffalo app in 'development' mode.
    21  This includes rebuilding your application when files change.
    22  This behavior can be changed in your .buffalo.dev.yml file.`,
    23  	Run: func(c *cobra.Command, args []string) {
    24  		defer func() {
    25  			msg := "There was a problem starting the dev server, Please review the troubleshooting docs: %s\n"
    26  			cause := "Unknown"
    27  			if r := recover(); r != nil {
    28  				if err, ok := r.(error); ok {
    29  					cause = err.Error()
    30  				}
    31  			}
    32  			fmt.Printf(msg, cause)
    33  		}()
    34  		os.Setenv("GO_ENV", "development")
    35  		ctx := context.Background()
    36  		ctx, cancelFunc := context.WithCancel(ctx)
    37  		go func() {
    38  			err := startDevServer(ctx)
    39  			if err != nil {
    40  				cancelFunc()
    41  				log.Fatal(err)
    42  			}
    43  		}()
    44  		go func() {
    45  			err := startWebpack(ctx)
    46  			if err != nil {
    47  				cancelFunc()
    48  				log.Fatal(err)
    49  			}
    50  		}()
    51  		// wait for the ctx to finish
    52  		<-ctx.Done()
    53  	},
    54  }
    55  
    56  func startWebpack(ctx context.Context) error {
    57  	cfgFile := "./webpack.config.js"
    58  	_, err := os.Stat(cfgFile)
    59  	if err != nil {
    60  		// there's no webpack, so don't do anything
    61  		return nil
    62  	}
    63  	cmd := exec.Command(webpack.BinPath, "--watch")
    64  	cmd.Stdin = os.Stdin
    65  	cmd.Stderr = os.Stderr
    66  	cmd.Stdout = os.Stdout
    67  	return cmd.Run()
    68  }
    69  
    70  func startDevServer(ctx context.Context) error {
    71  	cfgFile := "./.buffalo.dev.yml"
    72  	_, err := os.Stat(cfgFile)
    73  	if err != nil {
    74  		g, err := rg.New()
    75  		if err != nil {
    76  			return err
    77  		}
    78  		err = g.Run("./", map[string]interface{}{
    79  			"name": "buffalo",
    80  		})
    81  	}
    82  	c := &refresh.Configuration{}
    83  	err = c.Load(cfgFile)
    84  	if err != nil {
    85  		return err
    86  	}
    87  	r := refresh.NewWithContext(c, ctx)
    88  	return r.Start()
    89  }
    90  
    91  func init() {
    92  	RootCmd.AddCommand(devCmd)
    93  }