github.com/windmilleng/wat@v0.0.2-0.20180626175338-9349b638e250/cli/wat/plugin_nodejs.go (about)

     1  package wat
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  )
    12  
    13  // A simple whitelist of common nodejs testing frameworks and how they
    14  // are typically called. This doesn't need to be exhaustive.
    15  var commonNodeTestScripts = map[string]bool{
    16  	"jest":  true,
    17  	"mocha": true,
    18  	"mocha --require babel-register": true,
    19  	"eslint .":                       true,
    20  	"jasmine":                        true,
    21  }
    22  
    23  type PackageJSON struct {
    24  	Scripts map[string]string `json:"scripts"`
    25  }
    26  
    27  type PluginNodeJS struct {
    28  }
    29  
    30  func (p PluginNodeJS) name() string {
    31  	return "nodejs"
    32  }
    33  
    34  func (p PluginNodeJS) parsePackageJSON(root string) (PackageJSON, error) {
    35  	packageJSONPath := filepath.Join(root, "package.json")
    36  	packageJSONContents, err := ioutil.ReadFile(packageJSONPath)
    37  	if err != nil {
    38  		if os.IsNotExist(err) {
    39  			return PackageJSON{}, nil
    40  		}
    41  		return PackageJSON{}, fmt.Errorf("Read package.json: %v", err)
    42  	}
    43  
    44  	packageJSON := PackageJSON{}
    45  	err = json.Unmarshal(packageJSONContents, &packageJSON)
    46  	if err != nil {
    47  		return PackageJSON{}, fmt.Errorf("Parse package.json: %v", err)
    48  	}
    49  
    50  	return packageJSON, nil
    51  }
    52  
    53  func (p PluginNodeJS) run(ctx context.Context, root string) ([]WatCommand, error) {
    54  	packageJSON, err := p.parsePackageJSON(root)
    55  	if len(packageJSON.Scripts) == 0 || err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	cmds := make([]WatCommand, 0)
    60  	for key, value := range packageJSON.Scripts {
    61  		value = strings.TrimSpace(value)
    62  
    63  		if key == "test" {
    64  			cmds = append(cmds, p.toWatCommand(value))
    65  			continue
    66  		}
    67  
    68  		if commonNodeTestScripts[value] {
    69  			cmds = append(cmds, p.toWatCommand(value))
    70  			continue
    71  		}
    72  	}
    73  	return cmds, nil
    74  }
    75  
    76  func (p PluginNodeJS) toWatCommand(test string) WatCommand {
    77  	return WatCommand{
    78  		Command:     fmt.Sprintf(`PATH="node_modules/.bin:$PATH" %s`, test),
    79  		FilePattern: "**/*.js",
    80  	}
    81  }
    82  
    83  var _ plugin = PluginNodeJS{}