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