op_create.go

 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) {
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}
42
43func (op CreateOperation) GetFiles() []git.Hash {
44	return op.Files
45}
46
47func (op CreateOperation) Validate() error {
48	if err := opBaseValidate(op, CreateOp); err != nil {
49		return err
50	}
51
52	if text.Empty(op.Title) {
53		return fmt.Errorf("title is empty")
54	}
55
56	if strings.Contains(op.Title, "\n") {
57		return fmt.Errorf("title should be a single line")
58	}
59
60	if !text.Safe(op.Title) {
61		return fmt.Errorf("title is not fully printable")
62	}
63
64	if !text.Safe(op.Message) {
65		return fmt.Errorf("message is not fully printable")
66	}
67
68	return nil
69}
70
71func NewCreateOp(author Person, unixTime int64, title, message string, files []git.Hash) CreateOperation {
72	return CreateOperation{
73		OpBase:  newOpBase(CreateOp, author, unixTime),
74		Title:   title,
75		Message: message,
76		Files:   files,
77	}
78}
79
80// Convenience function to apply the operation
81func Create(author Person, unixTime int64, title, message string) (*Bug, error) {
82	return CreateWithFiles(author, unixTime, title, message, nil)
83}
84
85func CreateWithFiles(author Person, unixTime int64, title, message string, files []git.Hash) (*Bug, error) {
86	newBug := NewBug()
87	createOp := NewCreateOp(author, unixTime, title, message, files)
88
89	if err := createOp.Validate(); err != nil {
90		return nil, err
91	}
92
93	newBug.Append(createOp)
94
95	return newBug, nil
96}