forked from hetznercloud/cli
/
sshkey_list.go
70 lines (61 loc) · 1.55 KB
/
sshkey_list.go
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
package cli
import (
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/spf13/cobra"
)
var sshKeyListTableOutput *tableOutput
func init() {
sshKeyListTableOutput = newTableOutput().
AddAllowedFields(hcloud.SSHKey{})
}
func newSSHKeyListCommand(cli *CLI) *cobra.Command {
cmd := &cobra.Command{
Use: "list [FLAGS]",
Short: "List SSH keys",
Long: listLongDescription(
"Displays a list of SSH keys.",
sshKeyListTableOutput.Columns(),
),
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: cli.ensureToken,
RunE: cli.wrap(runSSHKeyList),
}
addListOutputFlag(cmd, sshKeyListTableOutput.Columns())
cmd.Flags().StringP("selector", "l", "", "Selector to filter by labels")
return cmd
}
func runSSHKeyList(cli *CLI, cmd *cobra.Command, args []string) error {
out, _ := cmd.Flags().GetStringArray("output")
outOpts, err := parseOutputOpts(out)
if err != nil {
return err
}
labelSelector, _ := cmd.Flags().GetString("selector")
opts := hcloud.SSHKeyListOpts{
ListOpts: hcloud.ListOpts{
LabelSelector: labelSelector,
PerPage: 50,
},
}
sshKeys, err := cli.Client().SSHKey.AllWithOpts(cli.Context, opts)
if err != nil {
return err
}
cols := []string{"id", "name", "fingerprint"}
if outOpts.IsSet("columns") {
cols = outOpts["columns"]
}
tw := sshKeyListTableOutput
if err = tw.ValidateColumns(cols); err != nil {
return err
}
if !outOpts.IsSet("noheader") {
tw.WriteHeader(cols)
}
for _, sshKey := range sshKeys {
tw.Write(cols, sshKey)
}
tw.Flush()
return nil
}