From 8c95b53a0673aeac44b8a47b9fedfbc61b50b40e Mon Sep 17 00:00:00 2001 From: Andy Doan Date: Fri, 19 Nov 2021 14:17:57 -0600 Subject: [PATCH] targets-tag: Add "--append" option Fixes #127 Signed-off-by: Andy Doan --- subcommands/targets/tag.go | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/subcommands/targets/tag.go b/subcommands/targets/tag.go index d0bde850..8e15217e 100644 --- a/subcommands/targets/tag.go +++ b/subcommands/targets/tag.go @@ -15,6 +15,7 @@ import ( var ( tagTags string + tagAppend bool tagNoTail bool tagByVersion bool ) @@ -34,11 +35,27 @@ func init() { } cmd.AddCommand(tagCmd) tagCmd.Flags().StringVarP(&tagTags, "tags", "T", "", "comma,separate,list") + tagCmd.Flags().BoolVarP(&tagAppend, "append", "", false, "Append the given tags rather than set them") tagCmd.Flags().BoolVarP(&tagNoTail, "no-tail", "", false, "Don't tail output of CI Job") tagCmd.Flags().BoolVarP(&tagByVersion, "by-version", "", false, "Apply tags to all targets matching the given version(s)") tagCmd.Flags().BoolVarP(&dryRun, "dryrun", "", false, "Just show the changes that would be applied") } +func Set(a, b []string) []string { + unique := make([]string, len(a), len(a)+len(b)) + items := make(map[string]bool, len(a)) + for i, item := range a { + unique[i] = item + items[item] = true + } + for _, item := range b { + if ok := items[item]; !ok { + unique = append(unique, item) + } + } + return unique +} + func doTag(cmd *cobra.Command, args []string) { factory := viper.GetString("factory") tags := strings.Split(tagTags, ",") @@ -55,10 +72,14 @@ func doTag(cmd *cobra.Command, args []string) { fmt.Printf("ERROR: %s\n", err) } else { if intersectionInSlices([]string{custom.Version}, args) { + targetTags := tags + if tagAppend { + targetTags = Set(custom.Tags, tags) + } updates[name] = client.UpdateTarget{ - Custom: client.TufCustom{Tags: tags}, + Custom: client.TufCustom{Tags: targetTags}, } - fmt.Printf("Changing tags of %s from %s -> %s\n", name, custom.Tags, tags) + fmt.Printf("Changing tags of %s from %s -> %s\n", name, custom.Tags, targetTags) } } } @@ -71,10 +92,14 @@ func doTag(cmd *cobra.Command, args []string) { if target, ok := targets[name]; ok { custom, err := api.TargetCustom(target) subcommands.DieNotNil(err) + targetTags := tags + if tagAppend { + targetTags = Set(custom.Tags, tags) + } updates[name] = client.UpdateTarget{ - Custom: client.TufCustom{Tags: tags}, + Custom: client.TufCustom{Tags: targetTags}, } - fmt.Printf("Changing tags of %s from %s -> %s\n", name, custom.Tags, tags) + fmt.Printf("Changing tags of %s from %s -> %s\n", name, custom.Tags, targetTags) } else { fmt.Printf("Target(%s) not found in targets.json\n", name) os.Exit(1)