-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
237 lines (199 loc) · 6.29 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/errorutil"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/sliceutil"
semver "github.com/hashicorp/go-version"
"github.com/kballard/go-shellquote"
)
// Config model
type Config struct {
Workdir string `env:"workdir"`
Command string `env:"command,required"`
NpmVersion string `env:"npm_version"`
UseCache bool `env:"cache_local_deps,opt[true,false]"`
}
func getNpmVersionFromPackageJSON(path string) (string, error) {
jsonStr, err := fileutil.ReadStringFromFile(path)
if err != nil {
return "", fmt.Errorf("package.json file read error: %s", err)
}
ver, err := extractNpmVersion(jsonStr)
if err != nil {
return "", fmt.Errorf("failed to parse package.json: %s", err)
}
return ver, nil
}
func extractNpmVersion(jsonStr string) (string, error) {
type pkgJSON struct {
Engines struct {
Npm string
}
}
var m pkgJSON
if err := json.Unmarshal([]byte(jsonStr), &m); err != nil {
return "", fmt.Errorf("json unmarshal error: %s", err)
}
if m.Engines.Npm == "" {
return "", nil
}
v, err := semver.NewVersion(m.Engines.Npm)
if err != nil {
return "", fmt.Errorf("`%s` is not valid semver string: %s", m.Engines.Npm, err)
}
return v.String(), nil
}
func createInstallNpmCommand() (*command.Model, error) {
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"brew", "install", "node"}
case "linux":
args = []string{"apt-get", "-y", "install", "npm"}
default:
return nil, fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
}
return command.New(args[0], args[1:]...), nil
}
func setNpmVersion(ver string) error {
cmd := command.New("npm", "install", "-g", "--force", fmt.Sprintf("npm@%s", ver))
log.Donef(fmt.Sprintf("$ %s", cmd.PrintableCommandArgs()))
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
if errorutil.IsExitStatusError(err) {
return fmt.Errorf("npm command failed: %s", out)
}
return fmt.Errorf("error running npm command: %s", err)
}
return nil
}
func systemDefined() (string, error) {
if path, err := exec.LookPath("npm"); err == nil {
log.Printf("npm found at %s", path)
cmd := command.New("npm", "--version")
log.Donef(fmt.Sprintf("$ %s", cmd.PrintableCommandArgs()))
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
if errorutil.IsExitStatusError(err) {
return "", fmt.Errorf("npm command failed: %s", out)
}
return "", fmt.Errorf("error running npm command: %s", err)
}
return out, nil
}
return "", nil
}
func failf(f string, args ...interface{}) {
log.Errorf(f, args...)
os.Exit(1)
}
func main() {
var config Config
if err := stepconf.Parse(&config); err != nil {
failf("Process config: %s", err)
}
stepconf.Print(config)
workdir, err := pathutil.AbsPath(config.Workdir)
if err != nil {
failf("Process config: failed to normalize working directory path: %s", err)
}
exists, err := pathutil.IsDirExists(workdir)
if err != nil {
failf("Process config: failed to validate working directory path `%s`: %s", workdir, err)
}
if !exists {
failf("Process config: specified working directory path `%s` does not exist", workdir)
}
npmArgs, err := shellquote.Split(config.Command)
if err != nil {
failf("Process config: provided npm command/arguments is not a valid CLI command: %s", err)
}
if strings.HasPrefix(config.Command, "install") {
log.Donef("\n" +
"Info: From npm version >= v5.7.0, you can use the `npm ci` command insead of `npm install`. Using this command might speeds up your workflow.\n" +
"It does not work without `package-lock.json` so please commit it into the VCS repository. " +
"More info: https://github.com/npm/npm/releases/tag/v5.7.0")
}
toInstall := false
toSet := config.NpmVersion
if toSet == "" {
fmt.Println()
log.Infof("Autodetecting npm version")
log.Printf("Checking package.json for npm version")
path := filepath.Join(workdir, "package.json")
exists, err := pathutil.IsPathExists(path)
if err != nil {
failf("Install dependencies: failed to validate package.json path: %s", err)
}
if exists {
toSet, err = getNpmVersionFromPackageJSON(path)
if err != nil {
log.Warnf("error getting version: %s", err)
}
} else {
log.Warnf("No package.json found at path: %s", path)
}
}
if toSet == "" {
log.Warnf("Could not read version information from package.json")
log.Printf("Locating preinstalled npm")
systemVer, err := systemDefined()
if err != nil {
failf("Install dependencies: failed to check installed npm version: %s", err)
}
if systemVer == "" {
log.Warnf("npm not found on PATH")
toSet = "latest"
toInstall = true
}
log.Printf("Preinstalled npm version: %s", systemVer)
}
if toInstall {
fmt.Println()
log.Infof("Ensuring npm version %s", toSet)
cmd, err := createInstallNpmCommand()
if err != nil {
failf("Install dependencies: %s", err)
}
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
failf("Install dependencies: failed to install npm: %s", err)
}
}
if toSet != "" {
fmt.Println()
log.Infof("Ensuring npm version %s", toSet)
if err := setNpmVersion(toSet); err != nil {
failf("Install dependencies: failed to install npm version `%s`: %s", toSet, err)
}
}
fmt.Println()
log.Infof("Running user provided command")
cmd := command.NewWithStandardOuts("npm", npmArgs...)
log.Donef("$ %s", cmd.PrintableCommandArgs())
cmd.SetDir(workdir)
if err := cmd.Run(); err != nil {
failf("Run: provided npm command failed: %s", err)
}
// Only cache if npm command is install, node_modules could be included in the repository
// Expecting command as the first argument of npm
// npm commands: https://github.com/npm/cli/blob/36682d4482cddee0acc55e8d75b3bee6e78fff37/lib/config/cmd-list.js
if config.UseCache &&
(len(npmArgs) != 0) && sliceutil.IsStringInSlice(npmArgs[0], []string{"install", "isntall", "i", "add", "ci"}) {
if err := cacheNpm(workdir); err != nil {
log.Warnf("Failed to mark files for caching: %s", err)
}
}
fmt.Println()
log.Successf("Step success")
}