op_set_title.go

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