File: image.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 (54 lines) | stat: -rw-r--r-- 1,263 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
package hcapi2

import (
	"context"
	"strconv"

	"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

// ImageClient embeds the Hetzner Cloud Image client and provides some
// additional helper functions.
type ImageClient interface {
	ImageClientBase
	Names() []string
	LabelKeys(string) []string
}

func NewImageClient(client ImageClientBase) ImageClient {
	return &imageClient{
		ImageClientBase: client,
	}
}

type imageClient struct {
	ImageClientBase
}

// Names obtains a list of available images. It returns nil if image names
// could not be fetched.
func (c *imageClient) Names() []string {
	imgs, err := c.AllWithOpts(context.Background(), hcloud.ImageListOpts{IncludeDeprecated: true})
	if err != nil || len(imgs) == 0 {
		return nil
	}
	names := make([]string, len(imgs))
	for i, img := range imgs {
		name := img.Name
		if name == "" {
			name = strconv.FormatInt(img.ID, 10)
		}
		names[i] = name
	}
	return names
}

// ImageLabelKeys returns a slice containing the keys of all labels assigned to
// the Image with the passed idOrName.
func (c *imageClient) LabelKeys(idOrName string) []string {
	img, _, err := c.Get(context.Background(), idOrName)
	if err != nil || img == nil || len(img.Labels) == 0 {
		return nil
	}
	return labelKeys(img.Labels)
}