1package operations
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/MichaelMure/git-bug/bug"
8 "github.com/MichaelMure/git-bug/util/text"
9)
10
11// SetTitleOperation will change the title of a bug
12
13var _ bug.Operation = SetTitleOperation{}
14
15type SetTitleOperation struct {
16 bug.OpBase
17 Title string `json:"title"`
18 Was string `json:"was"`
19}
20
21func (op SetTitleOperation) Apply(snapshot bug.Snapshot) bug.Snapshot {
22 snapshot.Title = op.Title
23
24 return snapshot
25}
26
27func (op SetTitleOperation) Validate() error {
28 if err := bug.OpBaseValidate(op, bug.SetTitleOp); err != nil {
29 return err
30 }
31
32 if text.Empty(op.Title) {
33 return fmt.Errorf("title is empty")
34 }
35
36 if strings.Contains(op.Title, "\n") {
37 return fmt.Errorf("title should be a single line")
38 }
39
40 if !text.Safe(op.Title) {
41 return fmt.Errorf("title should be fully printable")
42 }
43
44 if strings.Contains(op.Was, "\n") {
45 return fmt.Errorf("previous title should be a single line")
46 }
47
48 if !text.Safe(op.Was) {
49 return fmt.Errorf("previous title should be fully printable")
50 }
51
52 return nil
53}
54
55func NewSetTitleOp(author bug.Person, title string, was string) SetTitleOperation {
56 return SetTitleOperation{
57 OpBase: bug.NewOpBase(bug.SetTitleOp, author),
58 Title: title,
59 Was: was,
60 }
61}
62
63// Convenience function to apply the operation
64func SetTitle(b bug.Interface, author bug.Person, title string) error {
65 it := bug.NewOperationIterator(b)
66
67 var lastTitleOp bug.Operation
68 for it.Next() {
69 op := it.Value()
70 if op.OpType() == bug.SetTitleOp {
71 lastTitleOp = op
72 }
73 }
74
75 var was string
76 if lastTitleOp != nil {
77 was = lastTitleOp.(SetTitleOperation).Title
78 } else {
79 was = b.FirstOp().(CreateOperation).Title
80 }
81
82 setTitleOp := NewSetTitleOp(author, title, was)
83
84 if err := setTitleOp.Validate(); err != nil {
85 return err
86 }
87
88 b.Append(setTitleOp)
89 return nil
90}