1package operations
2
3import (
4 "fmt"
5 "github.com/MichaelMure/git-bug/bug"
6 "github.com/MichaelMure/git-bug/util"
7 "io"
8 "io/ioutil"
9 "sort"
10)
11
12// LabelChangeOperation will add or remove a set of labels
13
14var _ bug.Operation = LabelChangeOperation{}
15
16type LabelChangeOperation struct {
17 bug.OpBase
18 Added []bug.Label
19 Removed []bug.Label
20}
21
22func (op LabelChangeOperation) Apply(snapshot bug.Snapshot) bug.Snapshot {
23 // Add in the set
24AddLoop:
25 for _, added := range op.Added {
26 for _, label := range snapshot.Labels {
27 if label == added {
28 // Already exist
29 continue AddLoop
30 }
31 }
32
33 snapshot.Labels = append(snapshot.Labels, added)
34 }
35
36 // Remove in the set
37 for _, removed := range op.Removed {
38 for i, label := range snapshot.Labels {
39 if label == removed {
40 snapshot.Labels[i] = snapshot.Labels[len(snapshot.Labels)-1]
41 snapshot.Labels = snapshot.Labels[:len(snapshot.Labels)-1]
42 }
43 }
44 }
45
46 // Sort
47 sort.Slice(snapshot.Labels, func(i, j int) bool {
48 return string(snapshot.Labels[i]) < string(snapshot.Labels[j])
49 })
50
51 return snapshot
52}
53
54func (op LabelChangeOperation) Files() []util.Hash {
55 return nil
56}
57
58func NewLabelChangeOperation(author bug.Person, added, removed []bug.Label) LabelChangeOperation {
59 return LabelChangeOperation{
60 OpBase: bug.NewOpBase(bug.LabelChangeOp, author),
61 Added: added,
62 Removed: removed,
63 }
64}
65
66// Convenience function to apply the operation
67func ChangeLabels(out io.Writer, b *bug.Bug, author bug.Person, add, remove []string) error {
68 var added, removed []bug.Label
69
70 if out == nil {
71 out = ioutil.Discard
72 }
73
74 snap := b.Compile()
75
76 for _, str := range add {
77 label := bug.Label(str)
78
79 // check for duplicate
80 if labelExist(added, label) {
81 fmt.Fprintf(out, "label \"%s\" is a duplicate\n", str)
82 continue
83 }
84
85 // check that the label doesn't already exist
86 if labelExist(snap.Labels, label) {
87 fmt.Fprintf(out, "label \"%s\" is already set on this bug\n", str)
88 continue
89 }
90
91 added = append(added, label)
92 }
93
94 for _, str := range remove {
95 label := bug.Label(str)
96
97 // check for duplicate
98 if labelExist(removed, label) {
99 fmt.Fprintf(out, "label \"%s\" is a duplicate\n", str)
100 continue
101 }
102
103 // check that the label actually exist
104 if !labelExist(snap.Labels, label) {
105 fmt.Fprintf(out, "label \"%s\" doesn't exist on this bug\n", str)
106 continue
107 }
108
109 removed = append(removed, label)
110 }
111
112 if len(added) == 0 && len(removed) == 0 {
113 return fmt.Errorf("no label added or removed")
114 }
115
116 labelOp := NewLabelChangeOperation(author, added, removed)
117
118 b.Append(labelOp)
119
120 return nil
121}
122
123func labelExist(labels []bug.Label, label bug.Label) bool {
124 for _, l := range labels {
125 if l == label {
126 return true
127 }
128 }
129
130 return false
131}