-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapp.go
More file actions
356 lines (311 loc) · 9.65 KB
/
Copy pathapp.go
File metadata and controls
356 lines (311 loc) · 9.65 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
package cmd
import (
"fmt"
"strings"
"github.com/kernel/cli/pkg/util"
"github.com/kernel/kernel-go-sdk"
"github.com/pterm/pterm"
"github.com/samber/lo"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
var appCmd = &cobra.Command{
Use: "app",
Aliases: []string{"apps"},
Short: "Manage deployed applications",
Long: "Commands for managing deployed Kernel applications",
}
// --- app list subcommand
var appListCmd = &cobra.Command{
Use: "list",
Short: "List deployed application versions",
RunE: runAppList,
}
var appDeleteCmd = &cobra.Command{
Use: "delete <app_name>",
Short: "Delete an app and all its deployments",
Long: "Deletes all deployments for an application. Use --version to scope deletion to a specific version.",
Args: cobra.ExactArgs(1),
RunE: runAppDelete,
}
var appHistoryCmd = &cobra.Command{
Use: "history <app_name>",
Short: "Show deployment history for an application",
Args: cobra.ExactArgs(1),
RunE: runAppHistory,
}
func init() {
// register subcommands under app
appCmd.AddCommand(appListCmd)
appCmd.AddCommand(appDeleteCmd)
appCmd.AddCommand(appHistoryCmd)
// Flags for delete
appDeleteCmd.Flags().String("version", "", "Only delete deployments for this version (default: all versions)")
appDeleteCmd.Flags().BoolP("yes", "y", false, "Skip confirmation prompt")
// Add optional filters for list
appListCmd.Flags().String("name", "", "Filter by application name")
appListCmd.Flags().String("version", "", "Filter by version label")
appListCmd.Flags().Int("limit", 20, "Max apps to return (default 20)")
appListCmd.Flags().Int("per-page", 20, "Items per page (alias of --limit)")
appListCmd.Flags().Int("page", 1, "Page number (1-based)")
appListCmd.Flags().StringP("output", "o", "", "Output format: json for raw API response")
// Limit rows returned for app history (0 = all)
appHistoryCmd.Flags().Int("limit", 20, "Max deployments to return (default 20)")
appHistoryCmd.Flags().StringP("output", "o", "", "Output format: json for raw API response")
}
func runAppList(cmd *cobra.Command, args []string) error {
client := getKernelClient(cmd)
appName, _ := cmd.Flags().GetString("name")
version, _ := cmd.Flags().GetString("version")
lim, _ := cmd.Flags().GetInt("limit")
perPage, _ := cmd.Flags().GetInt("per-page")
page, _ := cmd.Flags().GetInt("page")
output, _ := cmd.Flags().GetString("output")
if output != "" && output != "json" {
return fmt.Errorf("unsupported --output value: use 'json'")
}
// Determine pagination inputs: prefer page/per-page if provided; else map legacy --limit
usePager := cmd.Flags().Changed("per-page") || cmd.Flags().Changed("page")
if !usePager && cmd.Flags().Changed("limit") {
if lim < 0 {
lim = 0
}
perPage = lim
page = 1
}
if perPage <= 0 {
perPage = 20
}
if page <= 0 {
page = 1
}
if output != "json" {
pterm.Debug.Println("Fetching deployed applications...")
}
params := kernel.AppListParams{}
if appName != "" {
params.AppName = kernel.Opt(appName)
}
if version != "" {
params.Version = kernel.Opt(version)
}
// Apply server-side pagination (request one extra to detect hasMore)
params.Limit = kernel.Opt(int64(perPage + 1))
params.Offset = kernel.Opt(int64((page - 1) * perPage))
apps, err := client.Apps.List(cmd.Context(), params)
if err != nil {
pterm.Error.Printf("Failed to list applications: %v\n", err)
return nil
}
if output == "json" {
if apps == nil || len(apps.Items) == 0 {
fmt.Println("[]")
return nil
}
return util.PrintPrettyJSONSlice(apps.Items)
}
if apps == nil || len(apps.Items) == 0 {
pterm.Info.Println("No applications found")
return nil
}
// Determine hasMore using +1 item trick and keep only perPage items for display
items := apps.Items
hasMore := false
if len(items) > perPage {
hasMore = true
items = items[:perPage]
}
itemsThisPage := len(items)
// Prepare table data
tableData := pterm.TableData{
{"App Name", "Version", "App Version ID", "Region", "Actions", "Env Vars"},
}
rows := 0
for _, app := range items {
// Format env vars
envVarsStr := "-"
if len(app.EnvVars) > 0 {
envVarsStr = strings.Join(lo.Keys(app.EnvVars), ", ")
}
actionsStr := "-"
if len(app.Actions) > 0 {
actionsStr = strings.Join(lo.Map(app.Actions, func(a kernel.AppAction, _ int) string {
return a.Name
}), ", ")
}
tableData = append(tableData, []string{
app.AppName,
app.Version,
app.ID,
string(app.Region),
actionsStr,
envVarsStr,
})
rows++
}
PrintTableNoPad(tableData, true)
// Footer with pagination details and next command suggestion
fmt.Printf("\nPage: %d Per-page: %d Items this page: %d Has more: %s\n", page, perPage, itemsThisPage, lo.Ternary(hasMore, "yes", "no"))
if hasMore {
nextPage := page + 1
nextCmd := fmt.Sprintf("kernel app list --page %d --per-page %d", nextPage, perPage)
if appName != "" {
nextCmd += fmt.Sprintf(" --name %s", appName)
}
if version != "" {
nextCmd += fmt.Sprintf(" --version %s", version)
}
fmt.Printf("Next: %s\n", nextCmd)
}
// Concise notes when user-specified per-page/limit/page are outside API-allowed range
if cmd.Flags().Changed("per-page") {
if v, _ := cmd.Flags().GetInt("per-page"); v > 100 {
pterm.Warning.Printfln("Requested --per-page %d; capped to 100.", v)
} else if v < 1 {
if cmd.Flags().Changed("page") {
if p, _ := cmd.Flags().GetInt("page"); p < 1 {
pterm.Warning.Println("Requested --per-page <1 and --page <1; using per-page=20, page=1.")
} else {
pterm.Warning.Println("Requested --per-page <1; using per-page=20.")
}
} else {
pterm.Warning.Println("Requested --per-page <1; using per-page=20.")
}
}
} else if !usePager && cmd.Flags().Changed("limit") {
if lim > 100 {
pterm.Warning.Printfln("Requested --limit %d; capped to 100.", lim)
} else if lim < 1 {
if cmd.Flags().Changed("page") {
if p, _ := cmd.Flags().GetInt("page"); p < 1 {
pterm.Warning.Println("Requested --limit <1 and --page <1; using per-page=20, page=1.")
} else {
pterm.Warning.Println("Requested --limit <1; using per-page=20.")
}
} else {
pterm.Warning.Println("Requested --limit <1; using per-page=20.")
}
}
} else if cmd.Flags().Changed("page") {
if p, _ := cmd.Flags().GetInt("page"); p < 1 {
pterm.Warning.Println("Requested --page <1; using page=1.")
}
}
return nil
}
func runAppDelete(cmd *cobra.Command, args []string) error {
client := getKernelClient(cmd)
appName := args[0]
version, _ := cmd.Flags().GetString("version")
skipConfirm, _ := cmd.Flags().GetBool("yes")
params := kernel.DeploymentListParams{
AppName: kernel.Opt(appName),
Limit: kernel.Opt(int64(100)),
Offset: kernel.Opt(int64(0)),
}
if version != "" {
params.AppVersion = kernel.Opt(version)
}
initial, err := client.Deployments.List(cmd.Context(), params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if initial == nil || len(initial.Items) == 0 {
pterm.Info.Printf("No deployments found for app '%s'\n", appName)
return nil
}
if !skipConfirm {
scope := "all versions"
if version != "" {
scope = fmt.Sprintf("version '%s'", version)
}
msg := fmt.Sprintf("Delete all deployments for app '%s' (%s)? This cannot be undone.", appName, scope)
pterm.DefaultInteractiveConfirm.DefaultText = msg
ok, _ := pterm.DefaultInteractiveConfirm.Show()
if !ok {
pterm.Info.Println("Deletion cancelled")
return nil
}
}
spinner, _ := pterm.DefaultSpinner.Start(fmt.Sprintf("Deleting deployments for app '%s'...", appName))
deleted := 0
for {
page, err := client.Deployments.List(cmd.Context(), params)
if err != nil {
spinner.Fail("Failed to list deployments")
return util.CleanedUpSdkError{Err: err}
}
items := page.Items
if len(items) == 0 {
break
}
g, gctx := errgroup.WithContext(cmd.Context())
for _, dep := range items {
g.Go(func() error {
return client.Deployments.Delete(gctx, dep.ID)
})
}
if err := g.Wait(); err != nil {
spinner.Fail("Failed to delete deployments")
return util.CleanedUpSdkError{Err: err}
}
deleted += len(items)
spinner.UpdateText(fmt.Sprintf("Deleted %d deployment(s) so far...", deleted))
}
spinner.Success(fmt.Sprintf("Deleted %d deployment(s) for app '%s'", deleted, appName))
return nil
}
func runAppHistory(cmd *cobra.Command, args []string) error {
client := getKernelClient(cmd)
appName := args[0]
lim, _ := cmd.Flags().GetInt("limit")
output, _ := cmd.Flags().GetString("output")
if output != "" && output != "json" {
return fmt.Errorf("unsupported --output value: use 'json'")
}
if output != "json" {
pterm.Debug.Printf("Fetching deployment history for app '%s'...\n", appName)
}
params := kernel.DeploymentListParams{}
if appName != "" {
params.AppName = kernel.Opt(appName)
}
deployments, err := client.Deployments.List(cmd.Context(), params)
if err != nil {
pterm.Error.Printf("Failed to list deployments: %v\n", err)
return nil
}
if output == "json" {
if deployments == nil || len(deployments.Items) == 0 {
fmt.Println("[]")
return nil
}
return util.PrintPrettyJSONSlice(deployments.Items)
}
if deployments == nil || len(deployments.Items) == 0 {
pterm.Info.Println("No deployments found for this application")
return nil
}
tableData := pterm.TableData{
{"Deployment ID", "Created At", "Region", "Status", "Entrypoint", "Reason"},
}
rows := 0
for _, dep := range deployments.Items {
created := util.FormatLocal(dep.CreatedAt)
status := string(dep.Status)
tableData = append(tableData, []string{
dep.ID,
created,
string(dep.Region),
status,
dep.EntrypointRelPath,
dep.StatusReason,
})
rows++
if lim > 0 && rows >= lim {
break
}
}
PrintTableNoPad(tableData, true)
return nil
}