github.com/wawandco/oxpecker@v1.5.7-0.20210910201653-5958d4afdd89/tools/webpack/build.go (about)

     1  package webpack
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  
     9  	"github.com/wawandco/oxpecker/internal/log"
    10  )
    11  
    12  const (
    13  	javascriptPackageManagerYarn = "YARN"
    14  	javascriptPackageManagerNPM  = "NPM"
    15  	javascriptPackageManagerNone = "NONE"
    16  )
    17  
    18  // packageManagerType returns yarn or npm depending on the files
    19  // found in the folder where the CLI is run. The first file found
    20  // will determine the Javascript package manager.
    21  func (w Plugin) packageManagerType(root string) string {
    22  	info, err := os.Stat(filepath.Join(root, "yarn.lock"))
    23  	if err == nil && !info.IsDir() {
    24  		return javascriptPackageManagerYarn
    25  	}
    26  
    27  	info, err = os.Stat(filepath.Join(root, "package-lock.json"))
    28  	if err == nil && !info.IsDir() {
    29  		return javascriptPackageManagerNPM
    30  	}
    31  
    32  	return javascriptPackageManagerNone
    33  }
    34  
    35  // Build runs webpack build from the package.json scripts.
    36  // if the project uses yarn will run `yarn run build`,
    37  // if the project uses npm will run `npm run build`.
    38  // otherwise will not run any of those.
    39  //
    40  // [Important] it assumes:
    41  // - that there is a build script in package.json.
    42  // - that yarn or npm is installed in the system.
    43  func (w Plugin) Build(ctx context.Context, root string, args []string) error {
    44  	var cmd *exec.Cmd
    45  	switch w.packageManagerType(root) {
    46  	case javascriptPackageManagerYarn:
    47  		cmd = exec.CommandContext(ctx, "yarn", "run", "build")
    48  	case javascriptPackageManagerNPM:
    49  		cmd = exec.CommandContext(ctx, "npm", "run", "build")
    50  	case javascriptPackageManagerNone:
    51  		log.Warn("did not find yarn.lock nor package-lock.json, skipping webpack build.")
    52  
    53  		return nil
    54  	}
    55  
    56  	cmd.Stdout = os.Stdout
    57  	cmd.Stderr = os.Stderr
    58  	cmd.Stdin = os.Stdin
    59  
    60  	return cmd.Run()
    61  }