aboutsummaryrefslogtreecommitdiffstats
path: root/commands/label.go
blob: ad3a388b38a4af4fb33f1adbc87bd688d2e41332 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package commands

import (
	"errors"
	"flag"
	"fmt"
	"github.com/MichaelMure/git-bug/bug"
	"github.com/MichaelMure/git-bug/bug/operations"
	"github.com/MichaelMure/git-bug/repository"
)

var labelFlagSet = flag.NewFlagSet("label", flag.ExitOnError)

var (
	labelRemove = newFlagSet.Bool("r", false, "Remove a label")
)

func runLabel(repo repository.Repo, args []string) error {
	labelFlagSet.Parse(args)
	args = labelFlagSet.Args()

	if len(args) == 0 {
		return errors.New("You must provide a bug id")
	}

	if len(args) == 1 {
		return errors.New("You must provide a label")
	}

	prefix := args[0]

	b, err := bug.FindBug(repo, prefix)
	if err != nil {
		return err
	}

	author, err := bug.GetUser(repo)
	if err != nil {
		return err
	}

	var added, removed []bug.Label

	snap := b.Compile()

	for _, arg := range args[1:] {
		label := bug.Label(arg)

		if *labelRemove {
			// check for duplicate
			if labelExist(removed, label) {
				fmt.Printf("label \"%s\" is a duplicate\n", arg)
				continue
			}

			// check that the label actually exist
			if !labelExist(snap.Labels, label) {
				fmt.Printf("label \"%s\" doesn't exist on this bug\n", arg)
				continue
			}

			removed = append(removed, label)
		} else {
			// check for duplicate
			if labelExist(added, label) {
				fmt.Printf("label \"%s\" is a duplicate\n", arg)
				continue
			}

			// check that the label doesn't already exist
			if labelExist(snap.Labels, label) {
				fmt.Printf("label \"%s\" is already set on this bug\n", arg)
				continue
			}

			added = append(added, label)
		}
	}

	if len(added) == 0 && len(removed) == 0 {
		return errors.New("no label added or removed")
	}

	labelOp := operations.NewLabelChangeOperation(author, added, removed)

	b.Append(labelOp)

	err = b.Commit(repo)

	return err
}

func labelExist(labels []bug.Label, label bug.Label) bool {
	for _, l := range labels {
		if l == label {
			return true
		}
	}

	return false
}

var labelCmd = &Command{
	Description: "Manipulate bug's label",
	Usage:       "<id> [<option>...] [<label>...]",
	flagSet:     labelFlagSet,
	RunMethod:   runLabel,
}