label.go

  1package commands
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"github.com/MichaelMure/git-bug/bug"
  7	"github.com/MichaelMure/git-bug/bug/operations"
  8	"github.com/spf13/cobra"
  9)
 10
 11var labelRemove bool
 12
 13func runLabel(cmd *cobra.Command, args []string) error {
 14	if len(args) == 0 {
 15		return errors.New("You must provide a bug id")
 16	}
 17
 18	if len(args) == 1 {
 19		return errors.New("You must provide a label")
 20	}
 21
 22	prefix := args[0]
 23
 24	b, err := bug.FindBug(repo, prefix)
 25	if err != nil {
 26		return err
 27	}
 28
 29	author, err := bug.GetUser(repo)
 30	if err != nil {
 31		return err
 32	}
 33
 34	var added, removed []bug.Label
 35
 36	snap := b.Compile()
 37
 38	for _, arg := range args[1:] {
 39		label := bug.Label(arg)
 40
 41		if labelRemove {
 42			// check for duplicate
 43			if labelExist(removed, label) {
 44				fmt.Printf("label \"%s\" is a duplicate\n", arg)
 45				continue
 46			}
 47
 48			// check that the label actually exist
 49			if !labelExist(snap.Labels, label) {
 50				fmt.Printf("label \"%s\" doesn't exist on this bug\n", arg)
 51				continue
 52			}
 53
 54			removed = append(removed, label)
 55		} else {
 56			// check for duplicate
 57			if labelExist(added, label) {
 58				fmt.Printf("label \"%s\" is a duplicate\n", arg)
 59				continue
 60			}
 61
 62			// check that the label doesn't already exist
 63			if labelExist(snap.Labels, label) {
 64				fmt.Printf("label \"%s\" is already set on this bug\n", arg)
 65				continue
 66			}
 67
 68			added = append(added, label)
 69		}
 70	}
 71
 72	if len(added) == 0 && len(removed) == 0 {
 73		return errors.New("no label added or removed")
 74	}
 75
 76	labelOp := operations.NewLabelChangeOperation(author, added, removed)
 77
 78	b.Append(labelOp)
 79
 80	err = b.Commit(repo)
 81
 82	return err
 83}
 84
 85func labelExist(labels []bug.Label, label bug.Label) bool {
 86	for _, l := range labels {
 87		if l == label {
 88			return true
 89		}
 90	}
 91
 92	return false
 93}
 94
 95var labelCmd = &cobra.Command{
 96	Use:   "label [<option>...] <id> [<label>...]",
 97	Short: "Manipulate bug's label",
 98	RunE:  runLabel,
 99}
100
101func init() {
102	RootCmd.AddCommand(labelCmd)
103
104	labelCmd.Flags().BoolVarP(&labelRemove, "remove", "r", false,
105		"Remove a label",
106	)
107}