-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpull.go
More file actions
97 lines (83 loc) · 2.51 KB
/
Copy pathpull.go
File metadata and controls
97 lines (83 loc) · 2.51 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
package env
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/pterm/pterm"
"github.com/urfave/cli/v2"
"github.com/NodeOps-app/createos-cli/internal/api"
"github.com/NodeOps-app/createos-cli/internal/terminal"
)
func newEnvPullCommand() *cli.Command {
return &cli.Command{
Name: "pull",
Usage: "Download environment variables to a local .env file",
Flags: []cli.Flag{
&cli.StringFlag{Name: "project", Usage: "Project ID"},
&cli.StringFlag{Name: "environment", Usage: "Environment ID"},
&cli.StringFlag{Name: "file", Usage: "Output file path (default: .env.<environment>)"},
&cli.BoolFlag{Name: "force", Usage: "Overwrite existing file without confirmation"},
},
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, env, err := resolveProjectEnv(c, client)
if err != nil {
return err
}
filePath := c.String("file")
if filePath == "" {
filePath = ".env." + env.UniqueName
}
if filepath.IsAbs(filePath) || strings.Contains(filePath, "..") {
return fmt.Errorf("--file must be a relative path without '..' (got %q)", filePath)
}
// Check if file exists
if !c.Bool("force") {
if _, err = os.Stat(filePath); err == nil {
if !terminal.IsInteractive() {
return fmt.Errorf("%s already exists — use --force to overwrite", filePath)
}
prompt := pterm.DefaultInteractiveConfirm.
WithDefaultText(fmt.Sprintf("%s already exists. Overwrite?", filePath)).
WithDefaultValue(false)
result, _ := prompt.Show() //nolint:errcheck //nolint:errcheck
if !result {
return nil
}
}
}
vars, err := client.GetEnvironmentVariables(projectID, env.ID)
if err != nil {
return err
}
if len(vars) == 0 {
fmt.Println("No environment variables to pull.")
return nil
}
// Sort keys for deterministic output
keys := make([]string, 0, len(vars))
for k := range vars {
keys = append(keys, k)
}
sort.Strings(keys)
var b strings.Builder
for _, k := range keys {
b.WriteString(k)
b.WriteString("=")
b.WriteString(vars[k])
b.WriteString("\n")
}
if err := os.WriteFile(filePath, []byte(b.String()), 0600); err != nil {
return fmt.Errorf("could not write %s: %w", filePath, err)
}
pterm.Success.Printf("Pulled %d variables to %s\n", len(vars), filePath)
ensureEnvGitignored()
return nil
},
}
}