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