-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (89 loc) · 2.12 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
)
type packageInfo struct {
Path string
Scripts map[string]string
}
func getPackageInfo(searchPath string) (packageInfo, error) {
for {
f, err := os.Open(filepath.Join(searchPath, "package.json"))
if err != nil {
next := filepath.Dir(searchPath)
if !os.IsNotExist(err) || next == searchPath {
return packageInfo{}, err
}
searchPath = next
continue
}
defer f.Close()
decoder := json.NewDecoder(f)
var decoded map[string]*json.RawMessage
result := packageInfo{Path: searchPath}
if err := decoder.Decode(&decoded); err != nil {
return packageInfo{}, err
}
scripts_json := decoded["scripts"]
if scripts_json == nil {
return result, nil
}
if err := json.Unmarshal(*scripts_json, &result.Scripts); err != nil {
return packageInfo{}, err
}
return result, nil
}
}
func showUsage() {
fmt.Println("Usage: pqr <command> [<args>...]")
}
func main() {
if len(os.Args) < 2 {
showUsage()
os.Exit(1)
}
scriptName := os.Args[1]
scriptArgs := os.Args[2:]
wd, err := os.Getwd()
if err != nil {
panic(err)
}
info, err := getPackageInfo(wd)
if err != nil {
if !os.IsNotExist(err) {
panic(err)
}
fmt.Fprintf(os.Stderr, "No package.json found at any level above %s\n", wd)
os.Exit(1)
}
commandText, ok := info.Scripts[scriptName]
if !ok {
fmt.Fprintf(os.Stderr, "No script named %s in %s/package.json\n", scriptName, info.Path)
os.Exit(1)
}
commandArgs := append([]string{"sh", "-c", "--", commandText + " \"$@\"", "sh"}, scriptArgs...)
// : is impossible to escape in $PATH
if !strings.ContainsRune(info.Path, ':') {
extendPath := filepath.Join(info.Path, "node_modules/.bin")
envPath := os.Getenv("PATH")
var extendedPath string
if envPath == "" {
extendedPath = extendPath
} else {
extendedPath = extendPath + ":" + envPath
}
os.Setenv("PATH", extendedPath)
}
err = os.Chdir(info.Path)
if err != nil {
panic(err)
}
err = syscall.Exec("/bin/sh", commandArgs, os.Environ())
fmt.Fprintf(os.Stderr, "exec failed: %s\n", err)
os.Exit(1)
}