44package set
55
66import (
7+ "errors"
78 "fmt"
89
910 "github.com/spf13/cobra"
@@ -17,6 +18,7 @@ import (
1718type setLabelOptions struct {
1819 metadata map [string ]string
1920 mapValidator func (map [string ]string ) error
21+ fields string // TODO does enum type exists in Go?
2022}
2123
2224// newCmdSetLabel sets one or more commonLabels to the kustomization file.
@@ -25,14 +27,23 @@ func newCmdSetLabel(fSys filesys.FileSystem, v func(map[string]string) error) *c
2527 o .mapValidator = v
2628 cmd := & cobra.Command {
2729 Use : "label" ,
28- Short : "Sets one or more commonLabels in " +
30+ Short : "Sets one or more labels/ commonLabels in " +
2931 konfig .DefaultKustomizationFileName (),
3032 Example : `
31- set label {labelKey1:labelValue1} {labelKey2:labelValue2}` ,
33+ # Set commonLabels (default)
34+ set label {labelKey1:labelValue1} {labelKey2:labelValue2}
35+
36+ # Set commonLabels
37+ set label --fields=commonLabels {labelKey1:labelValue1} {labelKey2:labelValue2}
38+
39+ # Set labels
40+ set label --fields=labels {labelKey1:labelValue1} {labelKey2:labelValue2}
41+ ` ,
3242 RunE : func (cmd * cobra.Command , args []string ) error {
3343 return o .runE (args , fSys , o .setLabels )
3444 },
3545 }
46+ cmd .Flags ().StringVar (& o .fields , "fields" , "commonLabels" , "Name of the fields to set (commonLabels or labels)" )
3647 return cmd
3748}
3849
@@ -62,6 +73,9 @@ func (o *setLabelOptions) validateAndParse(args []string) error {
6273 if len (args ) < 1 {
6374 return fmt .Errorf ("must specify label" )
6475 }
76+ if o .fields != "labels" && o .fields != "commonLabels" {
77+ return errors .New ("fields must be \" labels\" or \" commonLabels\" " )
78+ }
6579 m , err := util .ConvertSliceToMap (args , "label" )
6680 if err != nil {
6781 return err
@@ -74,10 +88,20 @@ func (o *setLabelOptions) validateAndParse(args []string) error {
7488}
7589
7690func (o * setLabelOptions ) setLabels (m * types.Kustomization ) error {
77- if m .CommonLabels == nil {
78- m .CommonLabels = make (map [string ]string )
91+ if o .fields == "commonLabels" {
92+ if m .CommonLabels == nil {
93+ m .CommonLabels = make (map [string ]string )
94+ }
95+ return o .writeToMap (m .CommonLabels )
96+ } else if o .fields == "labels" {
97+ if m .Labels == nil {
98+ m .Labels = make ([]types.Label , len (o .metadata ))
99+ }
100+ m .Labels = o .addLabels (m .Labels )
101+ return nil
102+ } else {
103+ return nil
79104 }
80- return o .writeToMap (m .CommonLabels )
81105}
82106
83107func (o * setLabelOptions ) writeToMap (m map [string ]string ) error {
@@ -86,3 +110,8 @@ func (o *setLabelOptions) writeToMap(m map[string]string) error {
86110 }
87111 return nil
88112}
113+
114+ func (o * setLabelOptions ) addLabels (m []types.Label ) []types.Label {
115+ newLabel := types.Label {Pairs : o .metadata , IncludeSelectors : false }
116+ return append (m , newLabel )
117+ }
0 commit comments