|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "strconv" |
| 7 | + |
| 8 | + "github.com/hetznercloud/hcloud-go/hcloud" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +func newFloatingIPRemoveLabelCommand(cli *CLI) *cobra.Command { |
| 13 | + cmd := &cobra.Command{ |
| 14 | + Use: "remove-label [FLAGS] FLOATINGIP LABELKEY", |
| 15 | + Short: "Remove a label from a Floating IP", |
| 16 | + Args: cobra.RangeArgs(1, 2), |
| 17 | + TraverseChildren: true, |
| 18 | + DisableFlagsInUseLine: true, |
| 19 | + PreRunE: chainRunE(validateFloatingIPRemoveLabel, cli.ensureToken), |
| 20 | + RunE: cli.wrap(runFloatingIPRemoveLabel), |
| 21 | + } |
| 22 | + |
| 23 | + cmd.Flags().BoolP("all", "a", false, "Remove all labels") |
| 24 | + return cmd |
| 25 | +} |
| 26 | + |
| 27 | +func validateFloatingIPRemoveLabel(cmd *cobra.Command, args []string) error { |
| 28 | + all, _ := cmd.Flags().GetBool("all") |
| 29 | + |
| 30 | + if all && len(args) == 2 { |
| 31 | + return errors.New("must not specify a label key when using --all/-a") |
| 32 | + } |
| 33 | + if !all && len(args) != 2 { |
| 34 | + return errors.New("must specify a label key when not using --all/-a") |
| 35 | + } |
| 36 | + |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +func runFloatingIPRemoveLabel(cli *CLI, cmd *cobra.Command, args []string) error { |
| 41 | + all, _ := cmd.Flags().GetBool("all") |
| 42 | + id, err := strconv.Atoi(args[0]) |
| 43 | + if err != nil { |
| 44 | + return errors.New("invalid Floating IP ID") |
| 45 | + } |
| 46 | + floatingIP, _, err := cli.Client().FloatingIP.GetByID(cli.Context, id) |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + if floatingIP == nil { |
| 51 | + return fmt.Errorf("Floating IP not found: %d", id) |
| 52 | + } |
| 53 | + |
| 54 | + labels := floatingIP.Labels |
| 55 | + if all { |
| 56 | + labels = make(map[string]string) |
| 57 | + } else { |
| 58 | + label := args[1] |
| 59 | + if _, ok := floatingIP.Labels[label]; !ok { |
| 60 | + return fmt.Errorf("label %s on Floating IP %d does not exist", label, floatingIP.ID) |
| 61 | + } |
| 62 | + delete(labels, label) |
| 63 | + } |
| 64 | + |
| 65 | + opts := hcloud.FloatingIPUpdateOpts{ |
| 66 | + Labels: labels, |
| 67 | + } |
| 68 | + _, _, err = cli.Client().FloatingIP.Update(cli.Context, floatingIP, opts) |
| 69 | + if err != nil { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + if all { |
| 74 | + fmt.Printf("All labels removed from Floating IP %d\n", floatingIP.ID) |
| 75 | + } else { |
| 76 | + fmt.Printf("Label %s removed from Floating IP %d\n", args[1], floatingIP.ID) |
| 77 | + } |
| 78 | + |
| 79 | + return nil |
| 80 | +} |
0 commit comments