git-bug/bug/op_create.go

115 lines
2.5 KiB
Go
Raw Normal View History

package bug
2018-07-12 22:31:41 +03:00
import (
"fmt"
"strings"
"github.com/MichaelMure/git-bug/util/git"
"github.com/MichaelMure/git-bug/util/text"
2018-07-12 22:31:41 +03:00
)
var _ Operation = &CreateOperation{}
2018-07-12 22:31:41 +03:00
// CreateOperation define the initial creation of a bug
2018-07-12 22:31:41 +03:00
type CreateOperation struct {
*OpBase
Title string `json:"title"`
Message string `json:"message"`
Files []git.Hash `json:"files"`
2018-07-12 22:31:41 +03:00
}
func (op *CreateOperation) base() *OpBase {
return op.OpBase
}
func (op *CreateOperation) Hash() (git.Hash, error) {
return hashOperation(op)
}
func (op *CreateOperation) Apply(snapshot *Snapshot) {
2018-07-12 22:31:41 +03:00
snapshot.Title = op.Title
comment := Comment{
Message: op.Message,
Author: op.Author,
2018-09-30 12:00:39 +03:00
UnixTime: Timestamp(op.UnixTime),
2018-07-12 22:31:41 +03:00
}
snapshot.Comments = []Comment{comment}
2018-08-01 03:15:40 +03:00
snapshot.Author = op.Author
snapshot.CreatedAt = op.Time()
hash, err := op.Hash()
if err != nil {
// Should never error unless a programming error happened
// (covered in OpBase.Validate())
panic(err)
}
snapshot.Timeline = []TimelineItem{
&CreateTimelineItem{
CommentTimelineItem: NewCommentTimelineItem(hash, comment),
},
}
2018-07-12 22:31:41 +03:00
}
func (op *CreateOperation) GetFiles() []git.Hash {
return op.Files
}
func (op *CreateOperation) Validate() error {
if err := opBaseValidate(op, CreateOp); err != nil {
return err
}
if text.Empty(op.Title) {
return fmt.Errorf("title is empty")
}
if strings.Contains(op.Title, "\n") {
return fmt.Errorf("title should be a single line")
}
if !text.Safe(op.Title) {
return fmt.Errorf("title is not fully printable")
}
if !text.Safe(op.Message) {
return fmt.Errorf("message is not fully printable")
}
return nil
}
func NewCreateOp(author Person, unixTime int64, title, message string, files []git.Hash) *CreateOperation {
return &CreateOperation{
OpBase: newOpBase(CreateOp, author, unixTime),
2018-07-25 22:25:26 +03:00
Title: title,
Message: message,
Files: files,
2018-07-25 22:25:26 +03:00
}
}
// CreateTimelineItem replace a Create operation in the Timeline and hold its edition history
type CreateTimelineItem struct {
CommentTimelineItem
}
2018-07-25 22:25:26 +03:00
// Convenience function to apply the operation
func Create(author Person, unixTime int64, title, message string) (*Bug, error) {
return CreateWithFiles(author, unixTime, title, message, nil)
}
func CreateWithFiles(author Person, unixTime int64, title, message string, files []git.Hash) (*Bug, error) {
newBug := NewBug()
createOp := NewCreateOp(author, unixTime, title, message, files)
if err := createOp.Validate(); err != nil {
return nil, err
}
newBug.Append(createOp)
return newBug, nil
}