File: list.go

package info (click to toggle)
hcloud-cli 1.39.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,628 kB
  • sloc: sh: 36; makefile: 7
file content (69 lines) | stat: -rw-r--r-- 2,072 bytes parent folder | download | duplicates (2)
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
package sshkey

import (
	"context"
	"time"

	"github.com/spf13/pflag"

	"github.com/hetznercloud/cli/internal/cmd/base"
	"github.com/hetznercloud/cli/internal/cmd/output"
	"github.com/hetznercloud/cli/internal/cmd/util"
	"github.com/hetznercloud/cli/internal/hcapi2"
	"github.com/hetznercloud/hcloud-go/v2/hcloud"
	"github.com/hetznercloud/hcloud-go/v2/hcloud/schema"
)

var ListCmd = base.ListCmd{
	ResourceNamePlural: "SSH keys",
	JSONKeyGetByName:   "ssh_keys",
	DefaultColumns:     []string{"id", "name", "fingerprint", "age"},

	Fetch: func(ctx context.Context, client hcapi2.Client, _ *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
		opts := hcloud.SSHKeyListOpts{ListOpts: listOpts}
		if len(sorts) > 0 {
			opts.Sort = sorts
		}
		sshKeys, err := client.SSHKey().AllWithOpts(ctx, opts)

		var resources []interface{}
		for _, n := range sshKeys {
			resources = append(resources, n)
		}
		return resources, err
	},

	OutputTable: func(_ hcapi2.Client) *output.Table {
		return output.NewTable().
			AddAllowedFields(hcloud.SSHKey{}).
			AddFieldFn("labels", output.FieldFn(func(obj interface{}) string {
				sshKey := obj.(*hcloud.SSHKey)
				return util.LabelsToString(sshKey.Labels)
			})).
			AddFieldFn("created", output.FieldFn(func(obj interface{}) string {
				sshKey := obj.(*hcloud.SSHKey)
				return util.Datetime(sshKey.Created)
			})).
			AddFieldFn("age", output.FieldFn(func(obj interface{}) string {
				sshKey := obj.(*hcloud.SSHKey)
				return util.Age(sshKey.Created, time.Now())
			}))
	},

	JSONSchema: func(resources []interface{}) interface{} {
		sshKeySchemas := make([]schema.SSHKey, 0, len(resources))
		for _, resource := range resources {
			sshKey := resource.(*hcloud.SSHKey)
			sshKeySchema := schema.SSHKey{
				ID:          sshKey.ID,
				Name:        sshKey.Name,
				Fingerprint: sshKey.Fingerprint,
				PublicKey:   sshKey.PublicKey,
				Labels:      sshKey.Labels,
				Created:     sshKey.Created,
			}
			sshKeySchemas = append(sshKeySchemas, sshKeySchema)
		}
		return sshKeySchemas
	},
}