operation.go

  1package bug
  2
  3import (
  4	"github.com/MichaelMure/git-bug/util/git"
  5	"github.com/pkg/errors"
  6
  7	"fmt"
  8	"time"
  9)
 10
 11// OperationType is an operation type identifier
 12type OperationType int
 13
 14const (
 15	_ OperationType = iota
 16	CreateOp
 17	SetTitleOp
 18	AddCommentOp
 19	SetStatusOp
 20	LabelChangeOp
 21)
 22
 23// Operation define the interface to fulfill for an edit operation of a Bug
 24type Operation interface {
 25	// OpType return the type of operation
 26	OpType() OperationType
 27	// Time return the time when the operation was added
 28	Time() time.Time
 29	// GetUnixTime return the unix timestamp when the operation was added
 30	GetUnixTime() int64
 31	// GetAuthor return the author of the operation
 32	GetAuthor() Person
 33	// GetFiles return the files needed by this operation
 34	GetFiles() []git.Hash
 35	// Apply the operation to a Snapshot to create the final state
 36	Apply(snapshot Snapshot) Snapshot
 37	// Validate check if the operation is valid (ex: a title is a single line)
 38	Validate() error
 39}
 40
 41// OpBase implement the common code for all operations
 42type OpBase struct {
 43	OperationType OperationType `json:"type"`
 44	Author        Person        `json:"author"`
 45	UnixTime      int64         `json:"timestamp"`
 46}
 47
 48// NewOpBase is the constructor for an OpBase
 49func NewOpBase(opType OperationType, author Person) OpBase {
 50	return OpBase{
 51		OperationType: opType,
 52		Author:        author,
 53		UnixTime:      time.Now().Unix(),
 54	}
 55}
 56
 57// OpType return the type of operation
 58func (op OpBase) OpType() OperationType {
 59	return op.OperationType
 60}
 61
 62// Time return the time when the operation was added
 63func (op OpBase) Time() time.Time {
 64	return time.Unix(op.UnixTime, 0)
 65}
 66
 67// GetUnixTime return the unix timestamp when the operation was added
 68func (op OpBase) GetUnixTime() int64 {
 69	return op.UnixTime
 70}
 71
 72// GetAuthor return the author of the operation
 73func (op OpBase) GetAuthor() Person {
 74	return op.Author
 75}
 76
 77// GetFiles return the files needed by this operation
 78func (op OpBase) GetFiles() []git.Hash {
 79	return nil
 80}
 81
 82// Validate check the OpBase for errors
 83func OpBaseValidate(op Operation, opType OperationType) error {
 84	if op.OpType() != opType {
 85		return fmt.Errorf("incorrect operation type (expected: %v, actual: %v)", opType, op.OpType())
 86	}
 87
 88	if op.GetUnixTime() == 0 {
 89		return fmt.Errorf("time not set")
 90	}
 91
 92	if err := op.GetAuthor().Validate(); err != nil {
 93		return errors.Wrap(err, "author")
 94	}
 95
 96	for _, hash := range op.GetFiles() {
 97		if !hash.IsValid() {
 98			return fmt.Errorf("file with invalid hash %v", hash)
 99		}
100	}
101
102	return nil
103}