github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/buildtools/npm/npm.go (about)

     1  package npm
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  
     7  	"github.com/apex/log"
     8  	"github.com/fossas/fossa-cli/exec"
     9  	"github.com/fossas/fossa-cli/files"
    10  )
    11  
    12  type Options struct {
    13  	AllowNPMErr bool `mapstructure:"allow-npm-err"`
    14  }
    15  
    16  type NPM interface {
    17  	List(dir string) (Output, error)
    18  	Clean(dir string) error
    19  	Install(dir string) error
    20  	Exists() bool
    21  }
    22  
    23  type SystemNPM struct {
    24  	Cmd      string
    25  	AllowErr bool
    26  }
    27  
    28  type Output struct {
    29  	Version      string
    30  	From         string
    31  	Resolved     string
    32  	Dependencies map[string]Output
    33  }
    34  
    35  func (n SystemNPM) Exists() bool {
    36  	return n.Cmd != ""
    37  }
    38  
    39  func (n SystemNPM) List(dir string) (Output, error) {
    40  	stdout, _, err := exec.Run(exec.Cmd{
    41  		Name: n.Cmd,
    42  		Argv: []string{"ls", "--json", "--production"},
    43  		Dir:  dir,
    44  	})
    45  	log.Debugf("err: %#v", err)
    46  	log.Debugf("AllowErr: %#v", n.AllowErr)
    47  	if err != nil && !n.AllowErr {
    48  		return Output{}, err
    49  	}
    50  	var output Output
    51  	err = json.Unmarshal([]byte(stdout), &output)
    52  	if err != nil {
    53  		return Output{}, err
    54  	}
    55  	return output, nil
    56  }
    57  
    58  func (n SystemNPM) Clean(dir string) error {
    59  	return files.Rm(dir, "node_modules")
    60  }
    61  
    62  func (n SystemNPM) Install(dir string) error {
    63  	_, _, err := exec.Run(exec.Cmd{
    64  		Name: n.Cmd,
    65  		Argv: []string{"install", "--production"},
    66  		Dir:  dir,
    67  	})
    68  	if err != nil && !n.AllowErr {
    69  		return err
    70  	}
    71  	return nil
    72  }
    73  
    74  func New() (NPM, error) {
    75  	npmCmd, _, npmErr := exec.Which("-v", os.Getenv("FOSSA_NPM_CMD"), "npm")
    76  
    77  	if npmErr != nil {
    78  		log.Warnf("Could not find NPM: %s", npmErr.Error())
    79  	}
    80  
    81  	return SystemNPM{
    82  		Cmd:      npmCmd,
    83  		AllowErr: true,
    84  	}, nil
    85  }