op_add_comment.go

 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.Empty(op.Message) {
62		return fmt.Errorf("message is empty")
63	}
64
65	if !text.Safe(op.Message) {
66		return fmt.Errorf("message is not fully printable")
67	}
68
69	return nil
70}
71
72func NewAddCommentOp(author Person, unixTime int64, message string, files []git.Hash) *AddCommentOperation {
73	return &AddCommentOperation{
74		OpBase:  newOpBase(AddCommentOp, author, unixTime),
75		Message: message,
76		Files:   files,
77	}
78}
79
80// CreateTimelineItem replace a AddComment operation in the Timeline and hold its edition history
81type AddCommentTimelineItem struct {
82	CommentTimelineItem
83}
84
85// Convenience function to apply the operation
86func AddComment(b Interface, author Person, unixTime int64, message string) error {
87	return AddCommentWithFiles(b, author, unixTime, message, nil)
88}
89
90func AddCommentWithFiles(b Interface, author Person, unixTime int64, message string, files []git.Hash) error {
91	addCommentOp := NewAddCommentOp(author, unixTime, message, files)
92	if err := addCommentOp.Validate(); err != nil {
93		return err
94	}
95	b.Append(addCommentOp)
96	return nil
97}