forked from hetznercloud/cli
/
image_add_label.go
61 lines (52 loc) · 1.56 KB
/
image_add_label.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
package cli
import (
"fmt"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/spf13/cobra"
)
func newImageAddLabelCommand(cli *CLI) *cobra.Command {
cmd := &cobra.Command{
Use: "add-label [FLAGS] IMAGE LABEL",
Short: "Add a label to an image",
Args: cobra.ExactArgs(2),
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: chainRunE(validateImageAddLabel, cli.ensureToken),
RunE: cli.wrap(runImageAddLabel),
}
cmd.Flags().BoolP("overwrite", "o", false, "Overwrite label if it exists already")
return cmd
}
func validateImageAddLabel(cmd *cobra.Command, args []string) error {
label := splitLabel(args[1])
if len(label) != 2 {
return fmt.Errorf("invalid label: %s", args[1])
}
return nil
}
func runImageAddLabel(cli *CLI, cmd *cobra.Command, args []string) error {
overwrite, _ := cmd.Flags().GetBool("overwrite")
idOrName := args[0]
image, _, err := cli.Client().Image.Get(cli.Context, idOrName)
if err != nil {
return err
}
if image == nil {
return fmt.Errorf("image not found: %s", idOrName)
}
label := splitLabel(args[1])
if _, ok := image.Labels[label[0]]; ok && !overwrite {
return fmt.Errorf("label %s on image %d already exists", label[0], image.ID)
}
labels := image.Labels
labels[label[0]] = label[1]
opts := hcloud.ImageUpdateOpts{
Labels: labels,
}
_, _, err = cli.Client().Image.Update(cli.Context, image, opts)
if err != nil {
return err
}
fmt.Printf("Label %s added to image %d\n", label[0], image.ID)
return nil
}