Skip to content

Commit

Permalink
feat(server): allow to filter list by server status
Browse files Browse the repository at this point in the history
  • Loading branch information
phm07 committed Dec 12, 2023
1 parent 9464cc0 commit 857c88c
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion internal/cmd/server/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

humanize "github.com/dustin/go-humanize"
"github.com/spf13/cobra"
"github.com/spf13/pflag"

"github.com/hetznercloud/cli/internal/cmd/base"
Expand All @@ -24,11 +25,35 @@ var ListCmd = base.ListCmd{

DefaultColumns: []string{"id", "name", "status", "ipv4", "ipv6", "private_net", "datacenter", "age"},

Fetch: func(ctx context.Context, client hcapi2.Client, _ *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
AdditionalFlags: func(cmd *cobra.Command) {
cmd.Flags().StringSlice("status", nil, "Only servers with one of these statuses are displayed")
},

Fetch: func(ctx context.Context, client hcapi2.Client, flags *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
statuses, _ := flags.GetStringSlice("status")

opts := hcloud.ServerListOpts{ListOpts: listOpts}
if len(sorts) > 0 {
opts.Sort = sorts
}
if len(statuses) > 0 {
for _, status := range statuses {
switch status {
case string(hcloud.ServerStatusInitializing),
string(hcloud.ServerStatusOff),
string(hcloud.ServerStatusRunning),
string(hcloud.ServerStatusStarting),
string(hcloud.ServerStatusStopping),
string(hcloud.ServerStatusMigrating),
string(hcloud.ServerStatusRebuilding),
string(hcloud.ServerStatusDeleting),
string(hcloud.ServerStatusUnknown):
opts.Status = append(opts.Status, hcloud.ServerStatus(status))
default:
return nil, fmt.Errorf("invalid status: %s", status)
}
}
}
servers, err := client.Server().AllWithOpts(ctx, opts)

var resources []interface{}
Expand Down

0 comments on commit 857c88c

Please sign in to comment.