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
 72// Sign post method for gqlgen
 73func (op *AddCommentOperation) IsAuthored() {}
 74
 75func NewAddCommentOp(author Person, unixTime int64, message string, files []git.Hash) *AddCommentOperation {
 76	return &AddCommentOperation{
 77		OpBase:  newOpBase(AddCommentOp, author, unixTime),
 78		Message: message,
 79		Files:   files,
 80	}
 81}
 82
 83// CreateTimelineItem replace a AddComment operation in the Timeline and hold its edition history
 84type AddCommentTimelineItem struct {
 85	CommentTimelineItem
 86}
 87
 88// Convenience function to apply the operation
 89func AddComment(b Interface, author Person, unixTime int64, message string) (*AddCommentOperation, error) {
 90	return AddCommentWithFiles(b, author, unixTime, message, nil)
 91}
 92
 93func AddCommentWithFiles(b Interface, author Person, unixTime int64, message string, files []git.Hash) (*AddCommentOperation, error) {
 94	addCommentOp := NewAddCommentOp(author, unixTime, message, files)
 95	if err := addCommentOp.Validate(); err != nil {
 96		return nil, err
 97	}
 98	b.Append(addCommentOp)
 99	return addCommentOp, nil
100}