|
| 1 | +package gateway |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" |
| 8 | + "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" |
| 9 | + "github.com/UpCloudLtd/upcloud-cli/v3/internal/ui" |
| 10 | + "github.com/UpCloudLtd/upcloud-go-api/v6/upcloud" |
| 11 | + "github.com/jedib0t/go-pretty/v6/text" |
| 12 | +) |
| 13 | + |
| 14 | +// ListCommand creates the "gateway list" command |
| 15 | +func ListCommand() commands.Command { |
| 16 | + return &listCommand{ |
| 17 | + BaseCommand: commands.New("list", "List gateways", "upctl gateway list"), |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +type listCommand struct { |
| 22 | + *commands.BaseCommand |
| 23 | +} |
| 24 | + |
| 25 | +// ExecuteWithoutArguments implements commands.NoArgumentCommand |
| 26 | +func (c *listCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Output, error) { |
| 27 | + svc := exec.All() |
| 28 | + gateways, err := svc.GetGateways(exec.Context()) |
| 29 | + if err != nil { |
| 30 | + return nil, err |
| 31 | + } |
| 32 | + |
| 33 | + rows := []output.TableRow{} |
| 34 | + for _, gtw := range gateways { |
| 35 | + rows = append(rows, output.TableRow{ |
| 36 | + gtw.UUID, |
| 37 | + gtw.Name, |
| 38 | + gtw.Routers, |
| 39 | + gtw.OperationalState, |
| 40 | + gtw.Zone, |
| 41 | + }) |
| 42 | + } |
| 43 | + |
| 44 | + // For JSON and YAML output, passthrough API response |
| 45 | + return output.MarshaledWithHumanOutput{ |
| 46 | + Value: gateways, |
| 47 | + Output: output.Table{ |
| 48 | + Columns: []output.TableColumn{ |
| 49 | + {Key: "uuid", Header: "UUID", Colour: ui.DefaultUUUIDColours}, |
| 50 | + {Key: "name", Header: "Name"}, |
| 51 | + {Key: "routers", Header: "Routers", Format: formatRouters}, |
| 52 | + {Key: "status", Header: "Status"}, |
| 53 | + {Key: "zone", Header: "Zone"}, |
| 54 | + }, |
| 55 | + Rows: rows, |
| 56 | + }, |
| 57 | + }, nil |
| 58 | +} |
| 59 | + |
| 60 | +func formatRouters(val interface{}) (text.Colors, string, error) { |
| 61 | + routers, ok := val.([]upcloud.GatewayRouter) |
| 62 | + if !ok { |
| 63 | + return nil, "", fmt.Errorf("cannot parse routers from %T, expected []upcloud.GatewayRouter", val) |
| 64 | + } |
| 65 | + |
| 66 | + var rows []string |
| 67 | + for _, rt := range routers { |
| 68 | + rows = append(rows, ui.DefaultUUUIDColours.Sprint(rt.UUID)) |
| 69 | + } |
| 70 | + |
| 71 | + return nil, strings.Join(rows, ",\n"), nil |
| 72 | +} |
0 commit comments