github.com/gobuffalo/buffalo-cli/v2@v2.0.0-alpha.15.0.20200919213536-a7350c8e6799/cli/internal/plugins/webpack/build/build.go (about) 1 package build 2 3 import ( 4 "context" 5 "os" 6 "os/exec" 7 8 "github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/webpack/internal/scripts" 9 "github.com/gobuffalo/plugins" 10 "github.com/gobuffalo/plugins/plugio" 11 "github.com/gobuffalo/plugins/plugprint" 12 ) 13 14 type packageJSON struct { 15 Scripts map[string]string `json:"scripts"` 16 } 17 18 // BeforeBuild implements the build.BeforeBuilder interface to 19 // hook into the `buffalo build` lifecycle. 20 func (a *Builder) BeforeBuild(ctx context.Context, root string, args []string) error { 21 return a.Build(ctx, root, args) 22 } 23 24 // Build implements the build.Builder interface to so it can be run 25 // as `buffalo build webpack`. 26 func (bc *Builder) Build(ctx context.Context, root string, args []string) error { 27 var help bool 28 flags := bc.Flags() 29 flags.StringVarP(&bc.environment, "environment", "", "development", "set the environment for the binary") 30 flags.BoolVarP(&help, "help", "h", false, "print this help") 31 flags.Parse(args) 32 33 if help { 34 return plugprint.Print(plugio.Stdout(bc.ScopedPlugins()...), bc) 35 } 36 37 if bc.skip { 38 return nil 39 } 40 41 ne := os.Getenv("NODE_ENV") 42 defer os.Setenv("NODE_ENV", ne) 43 os.Setenv("NODE_ENV", bc.environment) 44 45 c, err := bc.cmd(ctx, root, args) 46 if err != nil { 47 return plugins.Wrap(bc, err) 48 } 49 50 var fn func() error = c.Run 51 for _, p := range bc.ScopedPlugins() { 52 if br, ok := p.(AssetBuilder); ok { 53 fn = func() error { 54 return br.BuildAssets(ctx, root, c) 55 } 56 break 57 } 58 } 59 60 if err := fn(); err != nil { 61 return plugins.Wrap(bc, err) 62 } 63 64 if err := bc.archive(ctx, root, args); err != nil { 65 return plugins.Wrap(bc, err) 66 } 67 68 return nil 69 } 70 71 func (bc *Builder) cmd(ctx context.Context, root string, args []string) (*exec.Cmd, error) { 72 tool := bc.tool 73 74 var err error 75 if len(tool) == 0 { 76 tool, err = scripts.Tool(bc, ctx, root) 77 if err != nil { 78 return nil, plugins.Wrap(bc, err) 79 } 80 } 81 82 // Fallback on legacy runner 83 cmd := exec.CommandContext(ctx, scripts.WebpackBin(root)) 84 85 if _, err := scripts.ScriptFor(bc, ctx, root, "build"); err == nil { 86 cmd = exec.CommandContext(ctx, tool, "run", "build") 87 } 88 89 plugs := bc.ScopedPlugins() 90 cmd.Stdin = plugio.Stdin(plugs...) 91 cmd.Stdout = plugio.Stdout(plugs...) 92 cmd.Stderr = plugio.Stderr(plugs...) 93 94 return cmd, nil 95 }