add_comment.go

 1package operations
 2
 3import (
 4	"fmt"
 5
 6	"github.com/MichaelMure/git-bug/bug"
 7	"github.com/MichaelMure/git-bug/util/git"
 8	"github.com/MichaelMure/git-bug/util/text"
 9)
10
11// AddCommentOperation will add a new comment in the bug
12
13var _ bug.Operation = AddCommentOperation{}
14
15type AddCommentOperation struct {
16	bug.OpBase
17	Message string `json:"message"`
18	// TODO: change for a map[string]util.hash to store the filename ?
19	Files []git.Hash `json:"files"`
20}
21
22func (op AddCommentOperation) Apply(snapshot bug.Snapshot) bug.Snapshot {
23	comment := bug.Comment{
24		Message:  op.Message,
25		Author:   op.Author,
26		Files:    op.Files,
27		UnixTime: op.UnixTime,
28	}
29
30	snapshot.Comments = append(snapshot.Comments, comment)
31
32	return snapshot
33}
34
35func (op AddCommentOperation) GetFiles() []git.Hash {
36	return op.Files
37}
38
39func (op AddCommentOperation) Validate() error {
40	if err := bug.OpBaseValidate(op, bug.AddCommentOp); err != nil {
41		return err
42	}
43
44	if text.Empty(op.Message) {
45		return fmt.Errorf("message is empty")
46	}
47
48	if !text.Safe(op.Message) {
49		return fmt.Errorf("message is not fully printable")
50	}
51
52	return nil
53}
54
55func NewAddCommentOp(author bug.Person, message string, files []git.Hash) AddCommentOperation {
56	return AddCommentOperation{
57		OpBase:  bug.NewOpBase(bug.AddCommentOp, author),
58		Message: message,
59		Files:   files,
60	}
61}
62
63// Convenience function to apply the operation
64func Comment(b bug.Interface, author bug.Person, message string) error {
65	return CommentWithFiles(b, author, message, nil)
66}
67
68func CommentWithFiles(b bug.Interface, author bug.Person, message string, files []git.Hash) error {
69	addCommentOp := NewAddCommentOp(author, message, files)
70	if err := addCommentOp.Validate(); err != nil {
71		return err
72	}
73	b.Append(addCommentOp)
74	return nil
75}