-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathapp.go
More file actions
534 lines (489 loc) · 13.7 KB
/
app.go
File metadata and controls
534 lines (489 loc) · 13.7 KB
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
// Copyright 2024 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"errors"
"fmt"
"os"
"regexp"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/huh/spinner"
"github.com/charmbracelet/lipgloss"
"github.com/livekit/livekit-cli/pkg/bootstrap"
"github.com/livekit/livekit-cli/pkg/config"
"github.com/urfave/cli/v3"
)
var (
template *bootstrap.Template
templateName string
templateURL string
sandboxID string
appName string
appNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
destinationFile string
exampleFile string
project *config.ProjectConfig
AppCommands = []*cli.Command{
{
Name: "app",
Usage: "Initialize and manage applications",
Commands: []*cli.Command{
{
Name: "create",
Usage: "Bootstrap a new application from a template or through guided creation",
Before: requireProject,
Action: setupTemplate,
ArgsUsage: "`APP_NAME`",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "template",
Usage: "`TEMPLATE` to instantiate, see " + bootstrap.TemplateBaseURL,
Destination: &templateName,
},
&cli.StringFlag{
Name: "template-url",
Usage: "`URL` to instantiate, must contain a taskfile.yaml",
Destination: &templateURL,
},
&cli.StringFlag{
Name: "sandbox",
Usage: "`NAME` of the sandbox, see your cloud dashboard",
Destination: &sandboxID,
},
&cli.StringFlag{
Name: "server-url",
Value: cloudAPIServerURL,
Destination: &serverURL,
Hidden: true,
},
&cli.BoolFlag{
Name: "install",
Aliases: []string{"i"},
Usage: "Run installation tasks after creating the app",
Hidden: true,
},
},
},
{
Name: "list-templates",
Usage: "List available templates to bootstrap a new application",
Flags: []cli.Flag{jsonFlag},
Action: listTemplates,
},
{
Hidden: true,
Name: "install",
Usage: "Execute installation defined in " + bootstrap.TaskFile,
ArgsUsage: "[DIR] location of the project directory (default: current directory)",
Before: requireProject,
Action: installTemplate,
},
{
Hidden: true,
Name: "run",
Usage: "Execute a task defined in " + bootstrap.TaskFile,
ArgsUsage: "[TASK] to run in the project's taskfile.yaml",
Action: runTask,
},
{
Name: "env",
Usage: "Fill environment variables based on .env.example (optional) and project credentials",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "write",
Aliases: []string{"w"},
Usage: "Write environment variables to file",
},
&cli.StringFlag{
Name: "destination",
Aliases: []string{"d"},
Usage: "Destination file path, when used with --write",
Value: ".env.local",
TakesFile: true,
Destination: &destinationFile,
},
&cli.StringFlag{
Name: "example",
Aliases: []string{"e"},
Usage: "Example file path",
Value: ".env.example",
TakesFile: true,
Destination: &exampleFile,
},
},
ArgsUsage: "[DIR] location of the project directory (default: current directory)",
Before: requireProject,
Action: manageEnv,
},
},
},
}
)
func requireProject(ctx context.Context, cmd *cli.Command) error {
var err error
if project, err = loadProjectDetails(cmd); err != nil {
if err = loadProjectConfig(ctx, cmd); err != nil {
// something is wrong with config file
return err
}
// choose from existing credentials or authenticate
if len(cliConfig.Projects) > 0 {
var options []huh.Option[*config.ProjectConfig]
for _, p := range cliConfig.Projects {
options = append(options, huh.NewOption(p.Name+" ["+p.APIKey+"]", &p))
}
if err = huh.NewSelect[*config.ProjectConfig]().
Title("Select a project to use for this app").
Description("If you'd like to use a different project, run `lk cloud auth` to add credentials").
Options(options...).
Value(&project).
WithTheme(theme).
Run(); err != nil {
return err
}
} else {
shouldAuth := true
if err = huh.NewConfirm().
Title("No local projects found. Authenticate one now?").
Inline(true).
Value(&shouldAuth).
WithTheme(theme).
Run(); err != nil {
return err
}
if shouldAuth {
initAuth(ctx, cmd)
if err = tryAuthIfNeeded(ctx, cmd); err != nil {
return err
}
return requireProject(ctx, cmd)
} else {
return errors.New("no project selected")
}
}
}
return err
}
func listTemplates(ctx context.Context, cmd *cli.Command) error {
templates, err := bootstrap.FetchTemplates(ctx)
if err != nil {
return err
}
if cmd.Bool("json") {
PrintJSON(templates)
} else {
const maxDescLength = 64
table := CreateTable().Headers("Template", "Description").BorderRow(true)
for _, t := range templates {
desc := strings.Join(wrapToLines(t.Desc, maxDescLength), "\n")
url := theme.Focused.Title.Render(t.URL)
tags := theme.Help.ShortDesc.Render("#" + strings.Join(t.Tags, " #"))
table.Row(
t.Name,
desc+"\n\n"+url+"\n"+tags,
)
}
fmt.Println(table)
}
return nil
}
func setupTemplate(ctx context.Context, cmd *cli.Command) error {
verbose := cmd.Bool("verbose")
install := cmd.Bool("install")
isSandbox := sandboxID != ""
var preinstallPrompts []huh.Field
var templateOptions []bootstrap.Template
if templateName != "" && templateURL != "" {
return errors.New("only one of template or template-url can be specified")
}
if isSandbox {
token, err := requireToken(ctx, cmd)
if err != nil {
return err
}
if templateURL == "" {
details, err := bootstrap.FetchSandboxDetails(ctx, sandboxID, token, serverURL)
if err != nil {
return err
}
if len(details.ChildTemplates) == 0 {
return errors.New("no child templates found for sandbox")
}
templateOptions = details.ChildTemplates
}
} else {
var err error
templateOptions, err = bootstrap.FetchTemplates(ctx)
if err != nil {
return err
}
}
// if no template name or URL is specified, prompt user to choose from available templates
if templateName == "" && templateURL == "" {
templateSelect := huh.NewSelect[string]().
Title("Select Template").
Value(&templateURL).
WithTheme(theme)
var options []huh.Option[string]
for _, t := range templateOptions {
descStyle := theme.Help.ShortDesc
optionText := t.Name + " " + descStyle.Render("#"+strings.Join(t.Tags, " #"))
options = append(options, huh.NewOption(optionText, t.URL))
}
templateSelect.(*huh.Select[string]).Options(options...)
preinstallPrompts = append(preinstallPrompts, templateSelect)
// if templateName is specified, locate it in the list of templates
} else if templateName != "" {
for _, t := range templateOptions {
if t.Name == templateName {
template = &t
templateURL = t.URL
break
}
}
if template == nil {
return errors.New("template not found: " + templateName)
}
}
appName = cmd.Args().First()
if appName == "" {
appName = sandboxID
preinstallPrompts = append(preinstallPrompts, huh.NewInput().
Title("Application Name").
Placeholder("my-app").
Value(&appName).
Validate(func(s string) error {
if len(s) < 3 {
return errors.New("name is too short")
}
if !appNameRegex.MatchString(s) {
return errors.New("try a simpler name")
}
if s, _ := os.Stat(s); s != nil {
return errors.New("that name is in use")
}
return nil
}).
WithTheme(theme))
}
if len(preinstallPrompts) > 0 {
group := huh.NewGroup(preinstallPrompts...)
if err := huh.NewForm(group).
WithTheme(theme).
RunWithContext(ctx); err != nil {
return err
}
}
fmt.Println("Cloning template...")
if err := cloneTemplate(ctx, cmd, templateURL, appName); err != nil {
return err
}
tf, err := bootstrap.ParseTaskfile(appName)
if err != nil {
return err
}
fmt.Println("Instantiating environment...")
addlEnv := &map[string]string{
"LIVEKIT_SANDBOX_ID": sandboxID,
"NEXT_PUBLIC_LIVEKIT_SANDBOX_ID": sandboxID,
}
envOutputFile := ".env.local"
envExampleFile := ".env.example"
if tf != nil {
if customOutput, ok := tf.Vars.Get("env_file").Value.(string); ok {
envOutputFile = customOutput
}
if customExample, ok := tf.Vars.Get("env_example").Value.(string); ok {
envExampleFile = customExample
}
}
env, err := instantiateEnv(ctx, cmd, appName, addlEnv, envExampleFile)
if err != nil {
return err
}
bootstrap.WriteDotEnv(appName, envOutputFile, env)
if install {
fmt.Println("Installing template...")
if err := doInstall(ctx, bootstrap.TaskInstall, appName, verbose); err != nil {
return err
}
} else {
if err := doPostCreate(ctx, cmd, appName, verbose); err != nil {
return err
}
}
return cleanupTemplate(ctx, cmd, appName)
}
func cloneTemplate(_ context.Context, cmd *cli.Command, url, appName string) error {
var stdout string
var stderr string
var cmdErr error
tempName, relocate, cleanup := useTempPath(appName)
defer cleanup()
if err := spinner.New().
Title("Cloning template from " + url).
Action(func() {
stdout, stderr, cmdErr = bootstrap.CloneTemplate(url, tempName)
}).
Style(theme.Focused.Title).
Run(); err != nil {
return err
}
if len(stdout) > 0 && cmd.Bool("verbose") {
fmt.Println(string(stdout))
}
if len(stderr) > 0 && cmd.Bool("verbose") {
fmt.Fprintln(os.Stderr, string(stderr))
}
if cmdErr != nil {
return cmdErr
}
return relocate()
}
func cleanupTemplate(ctx context.Context, cmd *cli.Command, appName string) error {
return bootstrap.CleanupTemplate(appName)
}
func manageEnv(ctx context.Context, cmd *cli.Command) error {
rootDir := cmd.Args().First()
if rootDir == "" {
rootDir = "."
}
env, err := instantiateEnv(ctx, cmd, rootDir, nil, exampleFile)
if err != nil {
return err
}
if cmd.Bool("write") {
return bootstrap.WriteDotEnv(rootDir, destinationFile, env)
} else {
return bootstrap.PrintDotEnv(env)
}
}
func instantiateEnv(ctx context.Context, cmd *cli.Command, rootPath string, addlEnv *map[string]string, exampleFile string) (map[string]string, error) {
env := map[string]string{
"LIVEKIT_API_KEY": project.APIKey,
"LIVEKIT_API_SECRET": project.APISecret,
"LIVEKIT_URL": project.URL,
"NEXT_PUBLIC_LIVEKIT_URL": project.URL,
}
if addlEnv != nil {
for k, v := range *addlEnv {
env[k] = v
}
}
prompt := func(key, oldValue string) (string, error) {
var newValue string
if err := huh.NewInput().
EchoMode(huh.EchoModePassword).
Title("Enter " + key + "?").
Placeholder(oldValue).
Value(&newValue).
WithTheme(theme).
Run(); err != nil || newValue == "" {
return oldValue, err
}
return newValue, nil
}
return bootstrap.InstantiateDotEnv(ctx, rootPath, exampleFile, env, cmd.Bool("verbose"), prompt)
}
func installTemplate(ctx context.Context, cmd *cli.Command) error {
verbose := cmd.Bool("verbose")
rootPath := cmd.Args().First()
if rootPath == "" {
rootPath = "."
}
return doInstall(ctx, bootstrap.TaskInstall, rootPath, verbose)
}
func doPostCreate(ctx context.Context, _ *cli.Command, rootPath string, verbose bool) error {
tf, err := bootstrap.ParseTaskfile(rootPath)
if err != nil {
return err
}
if tf == nil {
return nil
}
task, err := bootstrap.NewTask(ctx, tf, rootPath, string(bootstrap.TaskPostCreate), verbose)
if task == nil || err != nil {
return nil
}
var cmdErr error
if err := spinner.New().
Title("Cleaning up...").
TitleStyle(lipgloss.NewStyle()).
Style(lipgloss.NewStyle()).
Action(func() { cmdErr = task() }).
Accessible(true).
Run(); err != nil {
return err
}
return cmdErr
}
func doInstall(ctx context.Context, task bootstrap.KnownTask, rootPath string, verbose bool) error {
tf, err := bootstrap.ParseTaskfile(rootPath)
if err != nil {
return err
}
install, err := bootstrap.NewTask(ctx, tf, rootPath, string(task), verbose)
if err != nil {
return err
}
var cmdErr error
if err := spinner.New().
Title("Installing...").
Action(func() { cmdErr = install() }).
Style(theme.Focused.Title).
Accessible(true).
Run(); err != nil {
return err
}
return cmdErr
}
func runTask(ctx context.Context, cmd *cli.Command) error {
verbose := cmd.Bool("verbose")
rootDir := "."
tf, err := bootstrap.ParseTaskfile(rootDir)
if err != nil {
return err
}
taskName := cmd.Args().First()
if taskName == "" {
var options []huh.Option[string]
for _, name := range tf.Tasks.Keys() {
options = append(options, huh.NewOption(name, name))
}
if err := huh.NewSelect[string]().
Title("Select Task").
Options(options...).
Value(&taskName).
WithTheme(theme).
Run(); err != nil {
return err
}
}
task, err := bootstrap.NewTask(ctx, tf, rootDir, taskName, verbose)
if err != nil {
return err
}
var cmdErr error
if err := spinner.New().
Title("Running task " + taskName + "...").
Action(func() { cmdErr = task() }).
Style(theme.Focused.Title).
Accessible(verbose).
Run(); err != nil {
return err
}
return cmdErr
}