-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.go
More file actions
581 lines (501 loc) · 15.8 KB
/
Copy pathdeploy.go
File metadata and controls
581 lines (501 loc) · 15.8 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
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
577
578
579
580
581
// Package deploy provides the deploy command for creating new deployments.
package deploy
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/pterm/pterm"
"github.com/urfave/cli/v2"
"github.com/NodeOps-app/createos-cli/internal/api"
"github.com/NodeOps-app/createos-cli/internal/config"
"github.com/NodeOps-app/createos-cli/internal/git"
"github.com/NodeOps-app/createos-cli/internal/terminal"
)
const maxZipSize = 50 * 1024 * 1024 // 50 MB
// defaultIgnorePatterns are files/dirs excluded when zipping for upload.
var defaultIgnorePatterns = []string{
// Version control
".git",
// CreateOS config
".createos.json",
// Secrets and credentials
".env",
".env.*",
"*.pem",
"*.key",
"*.p12",
"*.pfx",
"*.crt",
"*.cer",
"*.jks",
".npmrc",
".pypirc",
"credentials.json",
"service-account*.json",
// Dependencies
"node_modules",
".venv",
"venv",
"vendor", // Go
// Build artifacts
"target", // Rust
"coverage",
".nyc_output",
".pytest_cache",
"__pycache__",
// Database files
"*.sqlite",
"*.sqlite3",
"*.db",
// Log files
"*.log",
// Terraform state
".terraform",
"terraform.tfstate",
"terraform.tfstate.*",
// OS/editor noise
".DS_Store",
"Thumbs.db",
".idea",
".vscode",
"*.swp",
"*.swo",
}
// NewDeployCommand returns the deploy command.
func NewDeployCommand() *cli.Command {
return &cli.Command{
Name: "deploy",
Usage: "Deploy your project to CreateOS",
Description: "Creates a new deployment for the current project.\n\n" +
" The deploy method is chosen automatically based on your project type:\n" +
" VCS (GitHub) projects → triggers from the latest commit\n" +
" Upload projects → zips and uploads the current directory\n" +
" Image projects → deploys the specified Docker image\n\n" +
" Link your project first with 'createos init' if you haven't already.",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "project",
Usage: "Project ID (auto-detected from .createos.json)",
},
&cli.StringFlag{
Name: "branch",
Usage: "Branch to deploy from (VCS projects only, defaults to repo default branch)",
},
&cli.StringFlag{
Name: "image",
Usage: "Docker image to deploy (image projects only, e.g. nginx:latest)",
},
&cli.StringFlag{
Name: "dir",
Value: ".",
Usage: "Directory to deploy (upload projects only)",
},
},
Action: func(c *cli.Context) error {
client, ok := c.App.Metadata[api.ClientKey].(*api.APIClient)
if !ok {
return fmt.Errorf("you're not signed in — run 'createos login' to get started")
}
projectID := c.String("project")
if projectID == "" {
cfg, err := config.FindProjectConfig()
if err != nil {
return err
}
if cfg != nil {
projectID = cfg.ProjectID
}
}
// If still no project, try auto-detect then interactive picker
if projectID == "" && terminal.IsInteractive() {
projects, err := client.ListProjects()
if err != nil {
return err
}
// Filter to active projects
activeProjects := make([]api.Project, 0, len(projects))
for _, p := range projects {
if p.Status == "active" {
activeProjects = append(activeProjects, p)
}
}
if len(activeProjects) == 0 {
return fmt.Errorf("you don't have any active projects yet\n\n Create one first:\n createos projects add")
}
// Try to auto-detect from git remote
dir, err := os.Getwd()
if err != nil {
return fmt.Errorf("couldn't determine your current directory — please try again from a valid working directory")
}
repoFullName := git.GetRemoteFullName(dir)
if repoFullName != "" {
for _, p := range activeProjects {
if p.Type != "vcs" && p.Type != "githubImport" {
continue
}
var src api.VCSSource
if err := json.Unmarshal(p.Source, &src); err != nil {
continue
}
if src.VCSFullName == repoFullName {
pterm.Info.Printf("Detected project %s from git remote (%s)\n", p.DisplayName, repoFullName)
confirm := pterm.DefaultInteractiveConfirm.
WithDefaultText(fmt.Sprintf("Deploy %s?", p.DisplayName)).
WithDefaultValue(true)
useDetected, _ := confirm.Show() //nolint:errcheck
if useDetected {
projectID = p.ID
}
break
}
}
}
// Fall back to interactive selection
if projectID == "" {
options := make([]string, len(activeProjects))
for i, p := range activeProjects {
options[i] = fmt.Sprintf("%s (%s) [%s]", p.DisplayName, p.ID, p.Type)
}
selected, err := pterm.DefaultInteractiveSelect.
WithDefaultText("Select a project to deploy").
WithOptions(options).
WithFilter(true).
Show()
if err != nil {
return fmt.Errorf("selection cancelled")
}
for i, opt := range options {
if opt == selected {
projectID = activeProjects[i].ID
break
}
}
}
}
if projectID == "" {
return fmt.Errorf("no project linked to this directory\n\n Link a project first:\n createos init\n\n Or specify one:\n createos deploy --project <id>")
}
project, err := client.GetProject(projectID)
if err != nil {
return err
}
// Validate flag/type combinations
isVCS := project.Type == "vcs" || project.Type == "githubImport"
if c.IsSet("branch") && !isVCS {
return fmt.Errorf("--branch is only supported for Git-connected projects (this project uses %q deployment)", project.Type)
}
if c.IsSet("dir") && project.Type != "upload" {
return fmt.Errorf("--dir is only supported for upload projects (this project uses %q deployment)", project.Type)
}
// Route based on project type
switch {
case c.IsSet("image") || project.Type == "image":
return deployImage(c, client, project)
case project.Type == "upload":
return deployUpload(c, client, project)
case project.Type == "vcs" || project.Type == "githubImport":
return deployVCS(c, client, project)
default:
return fmt.Errorf("unsupported project type %q — please deploy from the dashboard", project.Type)
}
},
}
}
// deployVCS triggers a new deployment from the latest commit, optionally on a specific branch.
func deployVCS(c *cli.Context, client *api.APIClient, project *api.Project) error {
branch := c.String("branch")
if branch == "" && terminal.IsInteractive() {
result, err := pterm.DefaultInteractiveTextInput.
WithDefaultText("Branch to deploy (leave empty for default branch)").
Show()
if err != nil {
return err
}
branch = strings.TrimSpace(result)
}
branchLabel := "default branch"
if branch != "" {
branchLabel = branch
}
pterm.Info.Printf("Deploying %s from %s...\n", project.DisplayName, branchLabel)
deployment, err := client.TriggerLatestDeployment(project.ID, branch)
if err != nil {
return err
}
return waitForDeployment(client, project.ID, deployment)
}
// UploadDir zips a directory and uploads it as a deployment.
// Exported so other packages (e.g. projects add) can trigger an upload deploy.
func UploadDir(client *api.APIClient, projectID, displayName, dir string) error {
absDir, err := filepath.Abs(dir)
if err != nil {
return err
}
info, err := os.Stat(absDir)
if err != nil || !info.IsDir() {
return fmt.Errorf("directory %q not found", dir)
}
pterm.Info.Printf("Deploying %s from %s...\n", displayName, absDir)
zipFile, err := os.CreateTemp("", "createos-deploy-*.zip")
if err != nil {
return fmt.Errorf("could not create temp file: %w", err)
}
defer os.Remove(zipFile.Name()) //nolint:errcheck
defer zipFile.Close() //nolint:errcheck
spinner, _ := pterm.DefaultSpinner.Start("Packaging files...") //nolint:errcheck
if err = createZip(zipFile, absDir); err != nil {
spinner.Fail("Packaging failed")
return err
}
stat, statErr := zipFile.Stat()
if statErr == nil && stat.Size() > maxZipSize {
spinner.Fail("Package too large")
return fmt.Errorf("deployment package is %d MB (max %d MB)\n\n Tip: check that node_modules, .git, and build artifacts are excluded",
stat.Size()/(1024*1024), maxZipSize/(1024*1024))
}
spinner.UpdateText("Uploading...")
if err = zipFile.Close(); err != nil {
return fmt.Errorf("could not flush deployment package: %w", err)
}
deployment, err := client.UploadDeploymentZip(projectID, zipFile.Name())
if err != nil {
spinner.Fail("Upload failed")
return err
}
spinner.Success("Uploaded")
return waitForDeployment(client, projectID, deployment)
}
// deployUpload zips the local directory and uploads it.
func deployUpload(c *cli.Context, client *api.APIClient, project *api.Project) error {
dir := c.String("dir")
absDir, err := filepath.Abs(dir)
if err != nil {
return err
}
info, err := os.Stat(absDir)
if err != nil || !info.IsDir() {
return fmt.Errorf("directory %q not found", dir)
}
pterm.Info.Printf("Deploying %s from %s...\n", project.DisplayName, absDir)
// Create temporary zip
zipFile, err := os.CreateTemp("", "createos-deploy-*.zip")
if err != nil {
return fmt.Errorf("could not create temp file: %w", err)
}
defer os.Remove(zipFile.Name()) //nolint:errcheck
defer zipFile.Close() //nolint:errcheck
spinner, _ := pterm.DefaultSpinner.Start("Packaging files...") //nolint:errcheck
if err = createZip(zipFile, absDir); err != nil {
spinner.Fail("Packaging failed")
return err
}
stat, statErr := zipFile.Stat()
if statErr == nil && stat.Size() > maxZipSize {
spinner.Fail("Package too large")
return fmt.Errorf("deployment package is %d MB (max %d MB)\n\n Tip: check that node_modules, .git, and build artifacts are excluded",
stat.Size()/(1024*1024), maxZipSize/(1024*1024))
}
spinner.UpdateText("Uploading...")
// Close before uploading so the file is flushed
if err = zipFile.Close(); err != nil {
return fmt.Errorf("could not flush deployment package: %w", err)
}
deployment, err := client.UploadDeploymentZip(project.ID, zipFile.Name())
if err != nil {
spinner.Fail("Upload failed")
return err
}
spinner.Success("Uploaded")
return waitForDeployment(client, project.ID, deployment)
}
// deployImage deploys a Docker image.
func deployImage(c *cli.Context, client *api.APIClient, project *api.Project) error {
image := c.String("image")
if image == "" {
if !terminal.IsInteractive() {
return fmt.Errorf("please provide a Docker image with --image\n\n Example:\n createos deploy --image nginx:latest")
}
result, err := pterm.DefaultInteractiveTextInput.
WithDefaultText("Docker image (e.g. nginx:latest)").
Show()
if err != nil || result == "" {
return fmt.Errorf("no image provided")
}
image = result
}
pterm.Info.Printf("Deploying %s with image %s...\n", project.DisplayName, image)
deployment, err := client.CreateDeployment(project.ID, map[string]any{
"image": image,
})
if err != nil {
return err
}
return waitForDeployment(client, project.ID, deployment)
}
// waitForDeployment streams build logs while building, then runtime logs on success.
func waitForDeployment(client *api.APIClient, projectID string, deployment *api.Deployment) error {
fmt.Println()
timeout := time.After(10 * time.Minute)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
lastBuildLine := 0
for {
select {
case <-timeout:
fmt.Println()
pterm.Warning.Println("Deployment is still in progress — check back with: createos deployments build-logs")
return nil
case <-ticker.C:
d, err := client.GetDeployment(projectID, deployment.ID)
if err != nil {
continue // transient error, keep polling
}
// Stream new build log lines
buildLogs, err := client.GetDeploymentBuildLogs(projectID, deployment.ID)
if err == nil {
for _, e := range buildLogs {
if e.LineNumber > lastBuildLine {
fmt.Println(e.Log)
lastBuildLine = e.LineNumber
}
}
}
switch d.Status {
case "successful", "running", "active", "deployed":
fmt.Println()
pterm.Success.Println("Deployed successfully")
fmt.Println()
if d.Extra.Endpoint != "" {
url := d.Extra.Endpoint
if !strings.HasPrefix(url, "http") {
url = "https://" + url
}
pterm.Info.Printf("Live at: %s\n", url)
fmt.Println()
}
// Stream initial runtime logs
streamRuntimeLogs(client, projectID, deployment.ID)
return nil
case "failed", "error", "cancelled":
fmt.Println()
pterm.Error.Println("Deployment failed")
return fmt.Errorf("deployment %s failed with status: %s", d.ID, d.Status)
}
}
}
}
// streamRuntimeLogs fetches and prints runtime logs after a successful deployment.
func streamRuntimeLogs(client *api.APIClient, projectID, deploymentID string) {
logs, err := client.GetDeploymentLogs(projectID, deploymentID)
if err != nil || logs == "" {
pterm.Println(pterm.Gray(" View logs: createos deployments logs"))
pterm.Println(pterm.Gray(" Redeploy: createos deploy"))
return
}
fmt.Println(" Runtime logs:")
fmt.Println()
for _, line := range strings.Split(strings.TrimRight(logs, "\n"), "\n") {
fmt.Println(" " + line)
}
fmt.Println()
pterm.Println(pterm.Gray(" Follow logs: createos deployments logs --follow"))
pterm.Println(pterm.Gray(" Redeploy: createos deploy"))
}
// loadGitignorePatterns reads .gitignore from srcDir and returns usable patterns.
func loadGitignorePatterns(srcDir string) []string {
data, err := os.ReadFile(filepath.Join(srcDir, ".gitignore")) // #nosec G304 -- srcDir is from filepath.Abs, filename is a constant
if err != nil {
return nil
}
var patterns []string
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
// Skip comments and empty lines
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Skip negations — we don't support re-including files
if strings.HasPrefix(line, "!") {
continue
}
// Strip trailing slash (directory marker) — we handle dirs via SkipDir
line = strings.TrimSuffix(line, "/")
// Strip leading slash (root-anchored) — use basename matching
line = strings.TrimPrefix(line, "/")
if line != "" {
patterns = append(patterns, line)
}
}
return patterns
}
// createZip creates a zip archive of the directory, excluding default ignore patterns and .gitignore rules.
func createZip(w io.Writer, srcDir string) error {
zw := zip.NewWriter(w)
defer zw.Close() //nolint:errcheck
ignorePatterns := append(defaultIgnorePatterns, loadGitignorePatterns(srcDir)...) //nolint:gocritic
return filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(srcDir, path)
if err != nil {
return err
}
// Skip root
if relPath == "." {
return nil
}
// Check ignore patterns against basename and full relative path
baseName := filepath.Base(relPath)
for _, pattern := range ignorePatterns {
var matchedBase, matchedRel bool
matchedBase, err = filepath.Match(pattern, baseName)
if err != nil {
return fmt.Errorf("invalid ignore pattern %q: %w", pattern, err)
}
matchedRel, err = filepath.Match(pattern, filepath.ToSlash(relPath))
if err != nil {
return fmt.Errorf("invalid ignore pattern %q: %w", pattern, err)
}
if matchedBase || matchedRel {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
// Skip symlinks
if info.Mode()&os.ModeSymlink != 0 {
return nil
}
if info.IsDir() {
return nil
}
// Skip files larger than 10MB individually
if info.Size() > 10*1024*1024 {
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = filepath.ToSlash(relPath)
header.Method = zip.Deflate
writer, err := zw.CreateHeader(header)
if err != nil {
return err
}
f, err := os.Open(path) // #nosec G304,G122 -- path comes from filepath.Walk on a local directory
if err != nil {
return err
}
defer f.Close() //nolint:errcheck
_, err = io.Copy(writer, f)
return err
})
}