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 snapshot.Timeline = append(snapshot.Timeline, NewCommentTimelineItem(hash, comment))
46}
47
48func (op *AddCommentOperation) GetFiles() []git.Hash {
49 return op.Files
50}
51
52func (op *AddCommentOperation) Validate() error {
53 if err := opBaseValidate(op, AddCommentOp); err != nil {
54 return err
55 }
56
57 if text.Empty(op.Message) {
58 return fmt.Errorf("message is empty")
59 }
60
61 if !text.Safe(op.Message) {
62 return fmt.Errorf("message is not fully printable")
63 }
64
65 return nil
66}
67
68func NewAddCommentOp(author Person, unixTime int64, message string, files []git.Hash) *AddCommentOperation {
69 return &AddCommentOperation{
70 OpBase: newOpBase(AddCommentOp, author, unixTime),
71 Message: message,
72 Files: files,
73 }
74}
75
76// Convenience function to apply the operation
77func AddComment(b Interface, author Person, unixTime int64, message string) error {
78 return AddCommentWithFiles(b, author, unixTime, message, nil)
79}
80
81func AddCommentWithFiles(b Interface, author Person, unixTime int64, message string, files []git.Hash) error {
82 addCommentOp := NewAddCommentOp(author, unixTime, message, files)
83 if err := addCommentOp.Validate(); err != nil {
84 return err
85 }
86 b.Append(addCommentOp)
87 return nil
88}