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