|
| 1 | +// Copyright 2017 CoreOS, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package gcloud |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "os" |
| 20 | + "strings" |
| 21 | + |
| 22 | + "github.com/spf13/cobra" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + cmdLabelImage = &cobra.Command{ |
| 27 | + Use: "label-image --name <name> --labels foo=bar ...", |
| 28 | + Short: "label an image", |
| 29 | + Run: runLabelImage, |
| 30 | + } |
| 31 | + name string |
| 32 | + labels []string |
| 33 | +) |
| 34 | + |
| 35 | +func init() { |
| 36 | + // Initialize the command and its flags |
| 37 | + GCloud.AddCommand(cmdLabelImage) |
| 38 | + cmdLabelImage.Flags().StringVar(&name, "name", "", "GCloud Image Name") |
| 39 | + cmdLabelImage.Flags().StringSliceVar(&labels, "labels", []string{}, "list of key=value labels to attach to the GCloud image") |
| 40 | +} |
| 41 | + |
| 42 | +func runLabelImage(cmd *cobra.Command, args []string) { |
| 43 | + if name == "" { |
| 44 | + fmt.Fprintf(os.Stderr, "Provide --name to label\n") |
| 45 | + os.Exit(1) |
| 46 | + } |
| 47 | + |
| 48 | + if len(labels) < 1 { |
| 49 | + fmt.Fprintf(os.Stderr, "Provide at least one --label to label\n") |
| 50 | + os.Exit(1) |
| 51 | + } |
| 52 | + |
| 53 | + labelMap := make(map[string]string) |
| 54 | + for _, label := range labels { |
| 55 | + splitLabel := strings.SplitN(label, "=", 2) |
| 56 | + if len(splitLabel) != 2 { |
| 57 | + fmt.Fprintf(os.Stderr, "invalid label format; should be key=value, not %v\n", label) |
| 58 | + os.Exit(1) |
| 59 | + } |
| 60 | + key, value := splitLabel[0], splitLabel[1] |
| 61 | + labelMap[key] = value |
| 62 | + } |
| 63 | + |
| 64 | + err := api.SetImageLabels(name, labelMap) |
| 65 | + if err != nil { |
| 66 | + fmt.Fprintf(os.Stderr, "couldn't create image labels: %v", err) |
| 67 | + os.Exit(1) |
| 68 | + } |
| 69 | +} |
0 commit comments