github.com/lenfree/buffalo@v0.7.3-0.20170207163156-891616ea4064/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/buffalo/cmd/generate" 11 "github.com/gobuffalo/velvet" 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(generate.WebpackPath, "--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 f, err := os.Create(cfgFile) 75 if err != nil { 76 return err 77 } 78 defer f.Close() 79 t, err := velvet.Render(nRefresh, velvet.NewContextWith(map[string]interface{}{ 80 "name": "buffalo", 81 })) 82 if err != nil { 83 return err 84 } 85 _, err = f.WriteString(t) 86 if err != nil { 87 return err 88 } 89 } 90 c := &refresh.Configuration{} 91 err = c.Load(cfgFile) 92 if err != nil { 93 return err 94 } 95 r := refresh.NewWithContext(c, ctx) 96 return r.Start() 97 } 98 99 func init() { 100 RootCmd.AddCommand(devCmd) 101 }