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
 11var _ Operation = &CreateOperation{}
 12
 13// CreateOperation define the initial creation of a bug
 14type CreateOperation struct {
 15	*OpBase
 16	Title   string     `json:"title"`
 17	Message string     `json:"message"`
 18	Files   []git.Hash `json:"files"`
 19}
 20
 21func (op *CreateOperation) base() *OpBase {
 22	return op.OpBase
 23}
 24
 25func (op *CreateOperation) Hash() (git.Hash, error) {
 26	return hashOperation(op)
 27}
 28
 29func (op *CreateOperation) Apply(snapshot *Snapshot) {
 30	snapshot.Title = op.Title
 31
 32	comment := Comment{
 33		Message:  op.Message,
 34		Author:   op.Author,
 35		UnixTime: op.UnixTime,
 36	}
 37
 38	snapshot.Comments = []Comment{comment}
 39	snapshot.Author = op.Author
 40	snapshot.CreatedAt = op.Time()
 41
 42	hash, err := op.Hash()
 43	if err != nil {
 44		// Should never error unless a programming error happened
 45		// (covered in OpBase.Validate())
 46		panic(err)
 47	}
 48
 49	snapshot.Timeline = []TimelineItem{
 50		NewCreateTimelineItem(hash, comment),
 51	}
 52}
 53
 54func (op *CreateOperation) GetFiles() []git.Hash {
 55	return op.Files
 56}
 57
 58func (op *CreateOperation) Validate() error {
 59	if err := opBaseValidate(op, CreateOp); err != nil {
 60		return err
 61	}
 62
 63	if text.Empty(op.Title) {
 64		return fmt.Errorf("title is empty")
 65	}
 66
 67	if strings.Contains(op.Title, "\n") {
 68		return fmt.Errorf("title should be a single line")
 69	}
 70
 71	if !text.Safe(op.Title) {
 72		return fmt.Errorf("title is not fully printable")
 73	}
 74
 75	if !text.Safe(op.Message) {
 76		return fmt.Errorf("message is not fully printable")
 77	}
 78
 79	return nil
 80}
 81
 82func NewCreateOp(author Person, unixTime int64, title, message string, files []git.Hash) *CreateOperation {
 83	return &CreateOperation{
 84		OpBase:  newOpBase(CreateOp, author, unixTime),
 85		Title:   title,
 86		Message: message,
 87		Files:   files,
 88	}
 89}
 90
 91// Convenience function to apply the operation
 92func Create(author Person, unixTime int64, title, message string) (*Bug, error) {
 93	return CreateWithFiles(author, unixTime, title, message, nil)
 94}
 95
 96func CreateWithFiles(author Person, unixTime int64, title, message string, files []git.Hash) (*Bug, error) {
 97	newBug := NewBug()
 98	createOp := NewCreateOp(author, unixTime, title, message, files)
 99
100	if err := createOp.Validate(); err != nil {
101		return nil, err
102	}
103
104	newBug.Append(createOp)
105
106	return newBug, nil
107}