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) Snapshot {
30	snapshot.Title = op.Title
31
32	return snapshot
33}
34
35func (op SetTitleOperation) Validate() error {
36	if err := opBaseValidate(op, SetTitleOp); err != nil {
37		return err
38	}
39
40	if text.Empty(op.Title) {
41		return fmt.Errorf("title is empty")
42	}
43
44	if strings.Contains(op.Title, "\n") {
45		return fmt.Errorf("title should be a single line")
46	}
47
48	if !text.Safe(op.Title) {
49		return fmt.Errorf("title should be fully printable")
50	}
51
52	if strings.Contains(op.Was, "\n") {
53		return fmt.Errorf("previous title should be a single line")
54	}
55
56	if !text.Safe(op.Was) {
57		return fmt.Errorf("previous title should be fully printable")
58	}
59
60	return nil
61}
62
63func NewSetTitleOp(author Person, unixTime int64, title string, was string) SetTitleOperation {
64	return SetTitleOperation{
65		OpBase: newOpBase(SetTitleOp, author, unixTime),
66		Title:  title,
67		Was:    was,
68	}
69}
70
71// Convenience function to apply the operation
72func SetTitle(b Interface, author Person, unixTime int64, title string) error {
73	it := NewOperationIterator(b)
74
75	var lastTitleOp Operation
76	for it.Next() {
77		op := it.Value()
78		if op.base().OperationType == SetTitleOp {
79			lastTitleOp = op
80		}
81	}
82
83	var was string
84	if lastTitleOp != nil {
85		was = lastTitleOp.(SetTitleOperation).Title
86	} else {
87		was = b.FirstOp().(CreateOperation).Title
88	}
89
90	setTitleOp := NewSetTitleOp(author, unixTime, title, was)
91
92	if err := setTitleOp.Validate(); err != nil {
93		return err
94	}
95
96	b.Append(setTitleOp)
97	return nil
98}