1package operations
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/MichaelMure/git-bug/bug"
8 "github.com/MichaelMure/git-bug/util/git"
9 "github.com/MichaelMure/git-bug/util/text"
10)
11
12// CreateOperation define the initial creation of a bug
13
14var _ bug.Operation = CreateOperation{}
15
16type CreateOperation struct {
17 bug.OpBase
18 Title string `json:"title"`
19 Message string `json:"message"`
20 Files []git.Hash `json:"files"`
21}
22
23func (op CreateOperation) Apply(snapshot bug.Snapshot) bug.Snapshot {
24 snapshot.Title = op.Title
25 snapshot.Comments = []bug.Comment{
26 {
27 Message: op.Message,
28 Author: op.Author,
29 UnixTime: op.UnixTime,
30 },
31 }
32 snapshot.Author = op.Author
33 snapshot.CreatedAt = op.Time()
34 return snapshot
35}
36
37func (op CreateOperation) GetFiles() []git.Hash {
38 return op.Files
39}
40
41func (op CreateOperation) Validate() error {
42 if err := bug.OpBaseValidate(op, bug.CreateOp); err != nil {
43 return err
44 }
45
46 if text.Empty(op.Title) {
47 return fmt.Errorf("title is empty")
48 }
49
50 if strings.Contains(op.Title, "\n") {
51 return fmt.Errorf("title should be a single line")
52 }
53
54 if !text.Safe(op.Title) {
55 return fmt.Errorf("title is not fully printable")
56 }
57
58 if !text.Safe(op.Message) {
59 return fmt.Errorf("message is not fully printable")
60 }
61
62 return nil
63}
64
65func NewCreateOp(author bug.Person, title, message string, files []git.Hash) CreateOperation {
66 return CreateOperation{
67 OpBase: bug.NewOpBase(bug.CreateOp, author),
68 Title: title,
69 Message: message,
70 Files: files,
71 }
72}
73
74// Convenience function to apply the operation
75func Create(author bug.Person, title, message string) (*bug.Bug, error) {
76 return CreateWithFiles(author, title, message, nil)
77}
78
79func CreateWithFiles(author bug.Person, title, message string, files []git.Hash) (*bug.Bug, error) {
80 newBug := bug.NewBug()
81 createOp := NewCreateOp(author, title, message, files)
82
83 if err := createOp.Validate(); err != nil {
84 return nil, err
85 }
86
87 newBug.Append(createOp)
88
89 return newBug, nil
90}