1package board
2
3import (
4 "fmt"
5
6 "github.com/MichaelMure/git-bug/entities/identity"
7 "github.com/MichaelMure/git-bug/entity"
8 "github.com/MichaelMure/git-bug/entity/dag"
9 "github.com/MichaelMure/git-bug/util/text"
10)
11
12var _ Operation = &SetTitleOperation{}
13
14// SetTitleOperation will change the title of a board
15type SetTitleOperation struct {
16 dag.OpBase
17 Title string `json:"title"`
18 Was string `json:"was"`
19}
20
21func (op *SetTitleOperation) Id() entity.Id {
22 return dag.IdOperation(op, &op.OpBase)
23}
24
25func (op *SetTitleOperation) Validate() error {
26 if err := op.OpBase.Validate(op, SetTitleOp); err != nil {
27 return err
28 }
29
30 if text.Empty(op.Title) {
31 return fmt.Errorf("title is empty")
32 }
33
34 if !text.SafeOneLine(op.Title) {
35 return fmt.Errorf("title has unsafe characters")
36 }
37
38 if !text.SafeOneLine(op.Was) {
39 return fmt.Errorf("previous title has unsafe characters")
40 }
41
42 return nil
43}
44
45func (op *SetTitleOperation) Apply(snapshot *Snapshot) {
46 snapshot.Title = op.Title
47 snapshot.addActor(op.Author())
48}
49
50func NewSetTitleOp(author identity.Interface, unixTime int64, title string, was string) *SetTitleOperation {
51 return &SetTitleOperation{
52 OpBase: dag.NewOpBase(SetTitleOp, author, unixTime),
53 Title: title,
54 Was: was,
55 }
56}
57
58// SetTitle is a convenience function to change a board title
59func SetTitle(b Interface, author identity.Interface, unixTime int64, title string, metadata map[string]string) (*SetTitleOperation, error) {
60 var lastTitleOp *SetTitleOperation
61 for _, op := range b.Operations() {
62 switch op := op.(type) {
63 case *SetTitleOperation:
64 lastTitleOp = op
65 }
66 }
67
68 var was string
69 if lastTitleOp != nil {
70 was = lastTitleOp.Title
71 } else {
72 was = b.FirstOp().(*CreateOperation).Title
73 }
74
75 op := NewSetTitleOp(author, unixTime, title, was)
76 for key, val := range metadata {
77 op.SetMetadata(key, val)
78 }
79 if err := op.Validate(); err != nil {
80 return nil, err
81 }
82
83 b.Append(op)
84 return op, nil
85}