-
Notifications
You must be signed in to change notification settings - Fork 224
/
jsFramework.go
324 lines (272 loc) · 8.31 KB
/
jsFramework.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package scanner
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/blang/semver"
)
var packageJson map[string]interface{}
// Handle js frameworks separate from other node applications. Currently the requirements
// for a framework is pretty low: to have a "start" script. Because we are actually
// going to be running a js application to generate a Dockerfile there is one more
// criteria: if you are running node, the running node version must be at least 16,
// for bun the running bun version must be at least 0.5.3. If there turns out to be
// demand for earlier versions of node or bun, we can adjust this requirement.
func configureJsFramework(sourceDir string, config *ScannerConfig) (*SourceInfo, error) {
// first ensure that there is a package.json
if !checksPass(sourceDir, fileExists("package.json")) {
return nil, nil
}
// ensure package.json has a main, module, or start script
data, err := os.ReadFile("package.json")
if err != nil {
return nil, nil
} else {
err = json.Unmarshal(data, &packageJson)
if err != nil {
return nil, nil
}
// see if package.json has a "main"
main, _ := packageJson["main"].(string)
// check for tyep="module" and a module being defined
ptype, ok := packageJson["type"].(string)
if ok && ptype == "module" {
module, ok := packageJson["type"].(string)
if ok {
main = module
}
}
// check for a start script
scripts, ok := packageJson["scripts"].(map[string]interface{})
if ok && scripts["start"] != nil {
start, ok := scripts["start"].(string)
if ok {
main = start
}
}
// bail if no entrypoint can be found
if main == "" {
return nil, nil
}
}
srcInfo := &SourceInfo{
Family: "NodeJS",
SkipDeploy: true,
Callback: JsFrameworkCallback,
}
_, err = os.Stat("bun.lockb")
if errors.Is(err, fs.ErrNotExist) {
// ensure node is in $PATH
node, err := exec.LookPath("node")
if err != nil && !errors.Is(err, exec.ErrDot) {
return nil, nil
}
// resolve to absolute path, see: https://tip.golang.org/doc/go1.19#os-exec-path
node, err = filepath.Abs(node)
if err != nil {
return nil, nil
}
// ensure node version is at least 16.0.0
out, err := exec.Command(node, "-v").Output()
if err != nil {
return nil, nil
} else {
minVersion, err := semver.Make("16.0.0")
if err != nil {
panic(err)
}
nodeVersionString := strings.TrimSpace(string(out))
if nodeVersionString[:1] == "v" {
nodeVersionString = nodeVersionString[1:]
}
nodeVersion, err := semver.Make(nodeVersionString)
if err != nil || nodeVersion.LT(minVersion) {
return nil, nil
}
}
} else {
// ensure bun is in $PATH
bun, err := exec.LookPath("bun")
if err != nil && !errors.Is(err, exec.ErrDot) {
return nil, nil
}
// resolve to absolute path, see: https://tip.golang.org/doc/go1.19#os-exec-path
bun, err = filepath.Abs(bun)
if err != nil {
return nil, nil
}
// ensure bun version is at least 0.5.3, as that's when docker images started
// getting published: https://hub.docker.com/r/oven/bun/tags
out, err := exec.Command(bun, "-v").Output()
if err != nil {
return nil, nil
} else {
minVersion, err := semver.Make("0.5.3")
if err != nil {
panic(err)
}
bunVersionString := strings.TrimSpace(string(out))
bunVersion, err := semver.Make(bunVersionString)
if err != nil || bunVersion.LT(minVersion) {
return nil, nil
}
}
// set family
srcInfo.Family = "Bun"
}
// don't prompt for redis or postgres unless they are used
deps, ok := packageJson["dependencies"].(map[string]interface{})
if !ok || (deps["pg"] == nil && deps["redis"] == nil) {
srcInfo.SkipDatabase = true
}
return srcInfo, nil
}
func JsFrameworkCallback(appName string, srcInfo *SourceInfo, options map[string]bool) error {
// create temporary fly.toml for merge purposes
flyToml := "fly.toml"
_, err := os.Stat(flyToml)
if os.IsNotExist(err) {
// create a fly.toml consisting only of an app name
contents := fmt.Sprintf("app = \"%s\"\n", appName)
err := os.WriteFile(flyToml, []byte(contents), 0644)
if err != nil {
log.Fatal(err)
}
// inform caller of the presence of this file
srcInfo.MergeConfig = &MergeConfigStruct{
Name: flyToml,
Temporary: true,
}
}
// generate Dockerfile if it doesn't already exist
_, err = os.Stat("Dockerfile")
if errors.Is(err, fs.ErrNotExist) {
var args []string
_, err = os.Stat("node_modules")
if errors.Is(err, fs.ErrNotExist) {
// no existing node_modules directory: run package directly
args = []string{"npx", "--yes", "@flydotio/dockerfile@latest"}
} else {
// build command to install package using preferred package manager
args = []string{"npm", "install", "@flydotio/dockerfile@latest", "--save-dev"}
_, err = os.Stat("yarn.lock")
if !errors.Is(err, fs.ErrNotExist) {
args = []string{"yarn", "add", "@flydotio/dockerfile@latest", "--dev"}
}
_, err = os.Stat("pnpm-lock.yaml")
if !errors.Is(err, fs.ErrNotExist) {
args = []string{"pnpm", "add", "-D", "@flydotio/dockerfile@latest"}
}
_, err = os.Stat("bun.lockb")
if !errors.Is(err, fs.ErrNotExist) {
args = []string{"bun", "add", "-d", "@flydotio/dockerfile@latest"}
}
}
// check first to see if the package is already installed
installed := false
deps, ok := packageJson["dependencies"].(map[string]interface{})
if ok && deps["@flydotio/dockerfile"] != nil {
installed = true
}
deps, ok = packageJson["devDependencies"].(map[string]interface{})
if ok && deps["@flydotio/dockerfile"] != nil {
installed = true
}
// install/run command
if !installed || args[0] == "npx" {
fmt.Printf("installing: %s\n", strings.Join(args[:], " "))
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to install @flydotio/dockerfile: %w", err)
}
}
// run the package if we haven't already
if args[0] != "npx" {
// determine whether we need bunx or npx
var xcmd string
if args[0] == "bun" {
xcmd = "bunx"
} else {
xcmd = "npx"
}
// build a new command
args = []string{"dockerfile"}
// find npx/bunx in path
xcmdpath, err := exec.LookPath(xcmd)
if err != nil && !errors.Is(err, exec.ErrDot) {
if xcmd != "bunx" {
return fmt.Errorf("failure finding %s executable in PATH", xcmd)
} else {
// switch to "bun x" if bunx is not found.
// see: https://github.com/oven-sh/bun/issues/2786
xcmd = "bun"
xcmdpath, err = exec.LookPath("bun")
if err != nil && !errors.Is(err, exec.ErrDot) {
return fmt.Errorf("failure finding %s executable in PATH", xcmd)
}
args = append([]string{"x"}, args...)
}
}
// resolve to absolute path, see: https://tip.golang.org/doc/go1.19#os-exec-path
xcmdpath, err = filepath.Abs(xcmdpath)
if err != nil {
return fmt.Errorf("failure finding %s executable in PATH", xcmd)
}
// execute (via npx, bunx, or bun x) the docker module
cmd := exec.Command(xcmdpath, args...)
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to generate Dockerfile: %w", err)
}
}
}
// read dockerfile
dockerfile, err := os.ReadFile("Dockerfile")
if err != nil {
return err
}
// extract family
family := "NodeJS"
re := regexp.MustCompile(`(?m)^LABEL\s+fly_launch_runtime="(?P<family>.+?)"`)
m := re.FindStringSubmatch(string(dockerfile))
for i, name := range re.SubexpNames() {
if len(m) > 0 && name == "family" {
family = m[i]
}
}
srcInfo.Family = family
// extract port
port := 3000
re = regexp.MustCompile(`(?m)^EXPOSE\s+(?P<port>\d+)`)
m = re.FindStringSubmatch(string(dockerfile))
for i, name := range re.SubexpNames() {
if len(m) > 0 && name == "port" {
port, err = strconv.Atoi(m[i])
if err != nil {
panic(err)
}
}
}
srcInfo.Port = port
// provide some advice
srcInfo.DeployDocs += fmt.Sprintf(`
If you need custom packages installed, or have problems with your deployment
build, you may need to edit the Dockerfile for app-specific changes. If you
need help, please post on https://community.fly.io.
Now: run 'fly deploy' to deploy your %s app.
`, srcInfo.Family)
return nil
}