1package bug
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/timestamp"
10
11 "github.com/MichaelMure/git-bug/util/text"
12)
13
14var _ Operation = &SetTitleOperation{}
15
16// SetTitleOperation will change the title of a bug
17type SetTitleOperation struct {
18 dag.OpBase
19 Title string `json:"title"`
20 Was string `json:"was"`
21}
22
23func (op *SetTitleOperation) Id() entity.Id {
24 return dag.IdOperation(op, &op.OpBase)
25}
26
27func (op *SetTitleOperation) Apply(snapshot *Snapshot) {
28 snapshot.Title = op.Title
29 snapshot.addActor(op.Author())
30
31 id := op.Id()
32 item := &SetTitleTimelineItem{
33 combinedId: entity.CombineIds(snapshot.Id(), id),
34 Author: op.Author(),
35 UnixTime: timestamp.Timestamp(op.UnixTime),
36 Title: op.Title,
37 Was: op.Was,
38 }
39
40 snapshot.Timeline = append(snapshot.Timeline, item)
41}
42
43func (op *SetTitleOperation) Validate() error {
44 if err := op.OpBase.Validate(op, SetTitleOp); err != nil {
45 return err
46 }
47
48 if text.Empty(op.Title) {
49 return fmt.Errorf("title is empty")
50 }
51
52 if !text.SafeOneLine(op.Title) {
53 return fmt.Errorf("title has unsafe characters")
54 }
55
56 if !text.SafeOneLine(op.Was) {
57 return fmt.Errorf("previous title has unsafe characters")
58 }
59
60 return nil
61}
62
63func NewSetTitleOp(author identity.Interface, unixTime int64, title string, was string) *SetTitleOperation {
64 return &SetTitleOperation{
65 OpBase: dag.NewOpBase(SetTitleOp, author, unixTime),
66 Title: title,
67 Was: was,
68 }
69}
70
71type SetTitleTimelineItem struct {
72 combinedId entity.CombinedId
73 Author identity.Interface
74 UnixTime timestamp.Timestamp
75 Title string
76 Was string
77}
78
79func (s SetTitleTimelineItem) CombinedId() entity.CombinedId {
80 return s.combinedId
81}
82
83// IsAuthored is a sign post method for gqlgen
84func (s *SetTitleTimelineItem) IsAuthored() {}
85
86// SetTitle is a convenience function to change a bugs title
87func SetTitle(b Interface, author identity.Interface, unixTime int64, title string, metadata map[string]string) (*SetTitleOperation, error) {
88 var lastTitleOp *SetTitleOperation
89 for _, op := range b.Operations() {
90 switch op := op.(type) {
91 case *SetTitleOperation:
92 lastTitleOp = op
93 }
94 }
95
96 var was string
97 if lastTitleOp != nil {
98 was = lastTitleOp.Title
99 } else {
100 was = b.FirstOp().(*CreateOperation).Title
101 }
102
103 op := NewSetTitleOp(author, unixTime, title, was)
104 for key, value := range metadata {
105 op.SetMetadata(key, value)
106 }
107 if err := op.Validate(); err != nil {
108 return nil, err
109 }
110
111 b.Append(op)
112 return op, nil
113}