1package bug
2
3import (
4 "fmt"
5
6 "github.com/MichaelMure/git-bug/util/git"
7 "github.com/MichaelMure/git-bug/util/text"
8)
9
10var _ Operation = &AddCommentOperation{}
11
12// AddCommentOperation will add a new comment in the bug
13type AddCommentOperation struct {
14 OpBase
15 Message string `json:"message"`
16 // TODO: change for a map[string]util.hash to store the filename ?
17 Files []git.Hash `json:"files"`
18}
19
20func (op *AddCommentOperation) base() *OpBase {
21 return &op.OpBase
22}
23
24func (op *AddCommentOperation) Hash() (git.Hash, error) {
25 return hashOperation(op)
26}
27
28func (op *AddCommentOperation) Apply(snapshot *Snapshot) {
29 comment := Comment{
30 Message: op.Message,
31 Author: op.Author,
32 Files: op.Files,
33 UnixTime: Timestamp(op.UnixTime),
34 }
35
36 snapshot.Comments = append(snapshot.Comments, comment)
37
38 hash, err := op.Hash()
39 if err != nil {
40 // Should never error unless a programming error happened
41 // (covered in OpBase.Validate())
42 panic(err)
43 }
44
45 item := &AddCommentTimelineItem{
46 CommentTimelineItem: NewCommentTimelineItem(hash, comment),
47 }
48
49 snapshot.Timeline = append(snapshot.Timeline, item)
50}
51
52func (op *AddCommentOperation) GetFiles() []git.Hash {
53 return op.Files
54}
55
56func (op *AddCommentOperation) Validate() error {
57 if err := opBaseValidate(op, AddCommentOp); err != nil {
58 return err
59 }
60
61 if !text.Safe(op.Message) {
62 return fmt.Errorf("message is not fully printable")
63 }
64
65 return nil
66}
67
68// Sign post method for gqlgen
69func (op *AddCommentOperation) IsAuthored() {}
70
71func NewAddCommentOp(author Person, unixTime int64, message string, files []git.Hash) *AddCommentOperation {
72 return &AddCommentOperation{
73 OpBase: newOpBase(AddCommentOp, author, unixTime),
74 Message: message,
75 Files: files,
76 }
77}
78
79// CreateTimelineItem replace a AddComment operation in the Timeline and hold its edition history
80type AddCommentTimelineItem struct {
81 CommentTimelineItem
82}
83
84// Convenience function to apply the operation
85func AddComment(b Interface, author Person, unixTime int64, message string) (*AddCommentOperation, error) {
86 return AddCommentWithFiles(b, author, unixTime, message, nil)
87}
88
89func AddCommentWithFiles(b Interface, author Person, unixTime int64, message string, files []git.Hash) (*AddCommentOperation, error) {
90 addCommentOp := NewAddCommentOp(author, unixTime, message, files)
91 if err := addCommentOp.Validate(); err != nil {
92 return nil, err
93 }
94 b.Append(addCommentOp)
95 return addCommentOp, nil
96}