/
create.go
576 lines (510 loc) · 15.7 KB
/
create.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package app
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/cockroachdb/errors"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/tailscale/hujson"
"encr.dev/cli/cmd/encore/auth"
"encr.dev/cli/cmd/encore/cmdutil"
"encr.dev/cli/internal/platform"
"encr.dev/internal/conf"
"encr.dev/internal/env"
"encr.dev/internal/version"
"encr.dev/pkg/github"
"encr.dev/pkg/xos"
)
var (
createAppTemplate string
createAppOnPlatform bool
)
var createAppCmd = &cobra.Command{
Use: "create [name]",
Short: "Create a new Encore app",
Args: cobra.MaximumNArgs(1),
DisableFlagsInUseLine: true,
Run: func(cmd *cobra.Command, args []string) {
name := ""
if len(args) > 0 {
name = args[0]
}
if err := createApp(context.Background(), name, createAppTemplate); err != nil {
cmdutil.Fatal(err)
}
},
}
func init() {
appCmd.AddCommand(createAppCmd)
createAppCmd.Flags().BoolVar(&createAppOnPlatform, "platform", true, "whether to create the app with the Encore Platform")
createAppCmd.Flags().StringVar(&createAppTemplate, "example", "", "URL to example code to use.")
}
// createApp is the implementation of the "encore app create" command.
func createApp(ctx context.Context, name, template string) (err error) {
cyan := color.New(color.FgCyan)
green := color.New(color.FgGreen)
if _, err := conf.CurrentUser(); errors.Is(err, fs.ErrNotExist) && createAppOnPlatform {
_, _ = cyan.Fprint(os.Stderr, "Log in to create your app [press enter to continue]: ")
_, _ = fmt.Scanln()
if err := auth.DoLogin(auth.AutoFlow); err != nil {
cmdutil.Fatal(err)
}
}
if name == "" || template == "" {
name, template, _ = selectTemplate(name, template, false)
}
// Treat the special name "empty" as the empty app template
// (the rest of the code assumes that's the empty string).
if template == "empty" {
template = ""
}
if err := validateName(name); err != nil {
return err
} else if _, err := os.Stat(name); err == nil {
return fmt.Errorf("directory %s already exists", name)
}
// Parse template information, if provided.
var ex *github.Tree
if template != "" {
var err error
ex, err = parseTemplate(ctx, template)
if err != nil {
return err
}
}
if err := os.Mkdir(name, 0755); err != nil {
return err
}
defer func() {
if err != nil {
// Clean up the directory we just created in case of an error.
_ = os.RemoveAll(name)
}
}()
if ex != nil {
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Prefix = fmt.Sprintf("Downloading template %s ", ex.Name())
s.Start()
err := github.ExtractTree(ctx, ex, name)
s.Stop()
fmt.Println()
if err != nil {
return fmt.Errorf("failed to download template %s: %v", ex.Name(), err)
}
gray := color.New(color.Faint)
_, _ = gray.Printf("Downloaded template %s.\n", ex.Name())
} else {
// Set up files that we need when we don't have an example
if err := xos.WriteFile(filepath.Join(name, ".gitignore"), []byte("/.encore\n"), 0644); err != nil {
cmdutil.Fatal(err)
}
encoreModData := []byte("module encore.app\n")
if err := xos.WriteFile(filepath.Join(name, "go.mod"), encoreModData, 0644); err != nil {
cmdutil.Fatal(err)
}
}
// Create the app on the server.
_, err = conf.CurrentUser()
loggedIn := err == nil
var app *platform.App
if loggedIn && createAppOnPlatform {
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Prefix = "Creating app on encore.dev "
s.Start()
exCfg, ok := parseExampleConfig(name)
app, err = createAppOnServer(name, exCfg)
s.Stop()
if err != nil {
return fmt.Errorf("creating app on encore.dev: %v", err)
}
// Remove the example.json file if the app was successfully created.
if ok {
_ = os.Remove(exampleJSONPath(name))
}
} else {
// Remove the example config file since we're not creating the app on the platform.
_ = os.Remove(exampleJSONPath(name))
}
encoreAppPath := filepath.Join(name, "encore.app")
appData, err := os.ReadFile(encoreAppPath)
if err != nil {
appData, err = []byte("{}"), nil
}
if app != nil {
appData, err = setEncoreAppID(appData, app.Slug, []string{})
} else {
appData, err = setEncoreAppID(appData, "", []string{
"The app is not currently linked to the encore.dev platform.",
`Use "encore app link" to link it.`,
})
}
if err != nil {
return errors.Wrap(err, "write encore.app file")
}
if err := xos.WriteFile(encoreAppPath, appData, 0644); err != nil {
return errors.Wrap(err, "write encore.app file")
}
// Update to latest encore.dev release
if _, err := os.Stat(filepath.Join(name, "go.mod")); err == nil {
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Prefix = "Running go get encore.dev@latest"
s.Start()
if err := gogetEncore(name); err != nil {
s.FinalMSG = fmt.Sprintf("failed, skipping: %v", err.Error())
}
s.Stop()
} else if _, err := os.Stat(filepath.Join(name, "package.json")); err == nil {
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Prefix = "Running npm install encore.dev@latest"
s.Start()
if err := npmInstallEncore(name); err != nil {
s.FinalMSG = fmt.Sprintf("failed, skipping: %v", err.Error())
}
s.Stop()
}
// Rewrite any existence of ENCORE_APP_ID to the allocated app id.
if app != nil {
if err := rewritePlaceholders(name, app); err != nil {
red := color.New(color.FgRed)
_, _ = red.Printf("Failed rewriting source code placeholders, skipping: %v\n", err)
}
}
if err := initGitRepo(name, app); err != nil {
return err
}
// Try to generate wrappers. Don't error out if it fails for some reason,
// it's a nice-to-have to avoid IDEs thinking there are compile errors before 'encore run' runs.
_ = generateWrappers(name)
_, _ = green.Printf("\nSuccessfully created app %s!\n", name)
cyanf := cyan.SprintfFunc()
if app != nil {
fmt.Printf("App ID: %s\n", cyanf(app.Slug))
fmt.Printf("Web URL: %s%s", cyanf("https://app.encore.dev/"+app.Slug), cmdutil.Newline)
}
fmt.Print("\nUseful commands:\n\n")
_, _ = cyan.Printf(" encore run\n")
fmt.Print(" Run your app locally\n\n")
if detectLang(name) == languageGo {
_, _ = cyan.Printf(" encore test ./...\n")
} else {
_, _ = cyan.Printf(" encore test\n")
}
fmt.Print(" Run tests\n\n")
if app != nil {
_, _ = cyan.Printf(" git push encore\n")
fmt.Print(" Deploys your app\n\n")
}
greenBoldF := green.Add(color.Bold).SprintfFunc()
fmt.Printf("Get started now: %s\n", greenBoldF("cd %s && encore run", name))
return nil
}
// detectLang attempts to detect the application language for an Encore application
// situated at appRoot.
func detectLang(appRoot string) language {
if _, err := os.Stat(filepath.Join(appRoot, "go.mod")); err == nil {
return languageGo
} else if _, err := os.Stat(filepath.Join(appRoot, "package.json")); err == nil {
return languageTS
}
return languageGo
}
func validateName(name string) error {
ln := len(name)
if ln == 0 {
return fmt.Errorf("name must not be empty")
} else if ln > 50 {
return fmt.Errorf("name too long (max 50 chars)")
}
for i, s := range name {
// Outside of [a-z], [0-9] and != '-'?
if !((s >= 'a' && s <= 'z') || (s >= '0' && s <= '9') || s == '-') {
return fmt.Errorf("name must only contain lowercase letters, digits, or dashes")
} else if s == '-' {
if i == 0 {
return fmt.Errorf("name cannot start with a dash")
} else if (i + 1) == ln {
return fmt.Errorf("name cannot end with a dash")
} else if name[i-1] == '-' {
return fmt.Errorf("name cannot contain repeated dashes")
}
}
}
return nil
}
func gogetEncore(dir string) error {
var goBinPath string
// Prefer the 'go' binary from the Encore GOROOT if available.
if goroot, ok := env.OptEncoreGoRoot().Get(); ok {
goBinPath = filepath.Join(goroot, "bin", "go")
} else {
// Otherwise fall back to just "go", so that exec.Command
// does a path lookup.
goBinPath = "go"
}
// Use the 'go' binary from the Encore GOROOT in case the user
// does not have Go installed separately from Encore.
// nosemgrep go.lang.security.audit.dangerous-exec-command.dangerous-exec-command
cmd := exec.Command(goBinPath, "get", "encore.dev@latest")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
return errors.Newf("go get failed: %v: %s", err, out)
}
return nil
}
func npmInstallEncore(dir string) error {
verToInstall := version.Version
if version.Channel == version.DevBuild {
verToInstall = "latest"
}
// First install the 'encore.dev' package.
cmd := exec.Command("npm", "install", fmt.Sprintf("encore.dev@%s", verToInstall))
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("'npm install encore.dev@%s' failed: %v: %s", verToInstall, err, out)
}
// Then run 'npm install'.
cmd = exec.Command("npm", "install")
cmd.Dir = dir
if out2, err2 := cmd.CombinedOutput(); err2 != nil && err == nil {
err = fmt.Errorf("'npm install' failed: %v: %s", err2, out2)
}
return err
}
func createAppOnServer(name string, cfg exampleConfig) (*platform.App, error) {
if _, err := conf.CurrentUser(); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
params := &platform.CreateAppParams{
Name: name,
InitialSecrets: cfg.InitialSecrets,
}
return platform.CreateApp(ctx, params)
}
func parseTemplate(ctx context.Context, tmpl string) (*github.Tree, error) {
// If the template does not contain a colon or a dot, it's definitely
// not a github.com URL. Assume it's a simple template name.
if !strings.Contains(tmpl, ":") && !strings.Contains(tmpl, ".") {
tmpl = "https://github.com/encoredev/examples/tree/main/" + tmpl
}
return github.ParseTree(ctx, tmpl)
}
// initGitRepo initializes the git repo.
// If app is not nil, it configures the repo to push to the given app.
// If git does not exist, it reports an error matching exec.ErrNotFound.
func initGitRepo(path string, app *platform.App) (err error) {
defer func() {
if e := recover(); e != nil {
if ee, ok := e.(error); ok {
err = ee
} else {
panic(e)
}
}
}()
git := func(args ...string) []byte {
cmd := exec.Command("git", args...)
cmd.Dir = path
out, err := cmd.CombinedOutput()
if err != nil && !errors.Is(err, exec.ErrNotFound) {
panic(fmt.Errorf("git %s: %s (%w)", strings.Join(args, " "), out, err))
}
return out
}
// Initialize git repo
git("init")
if app != nil && app.MainBranch != nil {
git("checkout", "-b", *app.MainBranch)
}
git("config", "--local", "push.default", "current")
git("add", "-A")
cmd := exec.Command("git", "commit", "-m", "Initial commit")
cmd.Dir = path
// Configure the committer if the user hasn't done it themselves yet.
if ok, _ := gitUserConfigured(); !ok {
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=Encore",
"GIT_AUTHOR_EMAIL=git-bot@encore.dev",
"GIT_COMMITTER_NAME=Encore",
"GIT_COMMITTER_EMAIL=git-bot@encore.dev",
)
}
if out, err := cmd.CombinedOutput(); err != nil && !errors.Is(err, exec.ErrNotFound) {
return fmt.Errorf("create initial commit repository: %s (%v)", out, err)
}
if app != nil {
git("remote", "add", defaultGitRemoteName, defaultGitRemoteURL+app.Slug)
}
return nil
}
func addEncoreRemote(root, appID string) {
// Determine if there are any remotes
cmd := exec.Command("git", "remote")
cmd.Dir = root
out, err := cmd.CombinedOutput()
if err != nil {
return
}
out = bytes.TrimSpace(out)
if len(out) == 0 {
cmd = exec.Command("git", "remote", "add", defaultGitRemoteName, defaultGitRemoteURL+appID)
cmd.Dir = root
if err := cmd.Run(); err == nil {
fmt.Println("Configured git remote 'encore' to push/pull with Encore.")
}
}
}
// gitUserConfigured reports whether the user has configured
// user.name and user.email in git.
func gitUserConfigured() (bool, error) {
for _, s := range []string{"user.name", "user.email"} {
out, err := exec.Command("git", "config", s).CombinedOutput()
if err != nil {
return false, err
} else if len(bytes.TrimSpace(out)) == 0 {
return false, nil
}
}
return true, nil
}
// rewritePlaceholders recursively rewrites all files within basePath
// to replace placeholders with the actual values for this particular app.
func rewritePlaceholders(basePath string, app *platform.App) error {
var first error
err := filepath.WalkDir(basePath, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if err := rewritePlaceholder(path, info, app); err != nil {
if first == nil {
first = err
}
}
return nil
})
if err == nil {
err = first
}
return err
}
// rewritePlaceholder rewrites a file to replace placeholders with the
// actual values for this particular app. If the file contains none of
// the placeholders, this is a no-op.
func rewritePlaceholder(path string, info fs.DirEntry, app *platform.App) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
placeholders := []string{
"{{ENCORE_APP_ID}}", app.Slug,
}
var replaced bool
for i := 0; i < len(placeholders); i += 2 {
placeholder := []byte(placeholders[i])
target := []byte(placeholders[i+1])
if bytes.Contains(data, placeholder) {
data = bytes.ReplaceAll(data, placeholder, target)
replaced = true
}
}
if replaced {
return xos.WriteFile(path, data, info.Type().Perm())
}
return nil
}
// exampleConfig is the optional configuration file for example apps.
type exampleConfig struct {
InitialSecrets map[string]string `json:"initial_secrets"`
}
func parseExampleConfig(repoPath string) (cfg exampleConfig, exists bool) {
if data, err := os.ReadFile(exampleJSONPath(repoPath)); err == nil {
if data, err = hujson.Standardize(data); err == nil {
if err := json.Unmarshal(data, &cfg); err == nil {
return cfg, true
}
}
}
return exampleConfig{}, false
}
func exampleJSONPath(repoPath string) string {
return filepath.Join(repoPath, "example-initial-setup.json")
}
// setEncoreAppID rewrites the encore.app file to replace the app id, preserving comments.
// It optionally adds comment lines before the "id" field if commentLines is not nil.
func setEncoreAppID(data []byte, id string, commentLines []string) ([]byte, error) {
if len(data) == 0 {
data = []byte("{}")
}
root, err := hujson.Parse(data)
if err != nil {
return data, errors.Wrap(err, "parse encore.app")
}
obj, ok := root.Value.(*hujson.Object)
if !ok {
return data, errors.New("invalid encore.app format: not a json object")
}
var buf bytes.Buffer
for i, ln := range commentLines {
if i == 0 {
fmt.Fprintf(&buf, "\n")
}
fmt.Fprintf(&buf, "\t// %s\n", strings.TrimSpace(ln))
}
extra := hujson.Extra(buf.Bytes())
jsonValue, _ := json.Marshal(id)
value := hujson.Value{
Value: hujson.Literal(jsonValue),
}
found := false
for i := range obj.Members {
m := &obj.Members[i]
if lit, ok := m.Name.Value.(hujson.Literal); ok && lit.String() == "id" {
if commentLines != nil {
m.Name.BeforeExtra = extra
}
m.Value = value
found = true
break
}
}
if !found {
obj.Members = append([]hujson.ObjectMember{{
Name: hujson.Value{
BeforeExtra: extra,
Value: hujson.Literal(`"id"`),
},
Value: value,
}}, obj.Members...)
}
root.Format()
return root.Pack(), nil
}
// generateWrappers runs 'encore gen wrappers' in the given directory.
func generateWrappers(dir string) error {
// Use this executable if we can.
exe, err := os.Executable()
if err != nil {
exe = "encore"
}
// nosemgrep go.lang.security.audit.dangerous-exec-command.dangerous-exec-command
cmd := exec.Command(exe, "gen", "wrappers")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("encore gen wrappers failed: %v: %s", err, out)
}
return nil
}