operation_pack.go

 1package bug
 2
 3import (
 4	"bytes"
 5	"encoding/gob"
 6	"github.com/MichaelMure/git-bug/repository"
 7	"github.com/MichaelMure/git-bug/util"
 8)
 9
10// OperationPack represent an ordered set of operation to apply
11// to a Bug. These operations are stored in a single Git commit.
12//
13// These commits will be linked together in a linear chain of commits
14// inside Git to form the complete ordered chain of operation to
15// apply to get the final state of the Bug
16type OperationPack struct {
17	Operations []Operation
18
19	// Private field so not serialized by gob
20	commitHash util.Hash
21}
22
23func ParseOperationPack(data []byte) (*OperationPack, error) {
24	reader := bytes.NewReader(data)
25	decoder := gob.NewDecoder(reader)
26
27	var opp OperationPack
28
29	err := decoder.Decode(&opp)
30
31	if err != nil {
32		return nil, err
33	}
34
35	return &opp, nil
36}
37
38func (opp *OperationPack) Serialize() ([]byte, error) {
39	var data bytes.Buffer
40
41	encoder := gob.NewEncoder(&data)
42	err := encoder.Encode(*opp)
43
44	if err != nil {
45		return nil, err
46	}
47
48	return data.Bytes(), nil
49}
50
51// Append a new operation to the pack
52func (opp *OperationPack) Append(op Operation) {
53	opp.Operations = append(opp.Operations, op)
54}
55
56func (opp *OperationPack) IsEmpty() bool {
57	return len(opp.Operations) == 0
58}
59
60func (opp *OperationPack) IsValid() bool {
61	return !opp.IsEmpty()
62}
63
64func (opp *OperationPack) Write(repo repository.Repo) (util.Hash, error) {
65	data, err := opp.Serialize()
66
67	if err != nil {
68		return "", err
69	}
70
71	hash, err := repo.StoreData(data)
72
73	if err != nil {
74		return "", err
75	}
76
77	return hash, nil
78}
79
80// Make a deep copy
81func (opp *OperationPack) Clone() OperationPack {
82
83	clone := OperationPack{
84		Operations: make([]Operation, len(opp.Operations)),
85		commitHash: opp.commitHash,
86	}
87
88	for i, op := range opp.Operations {
89		clone.Operations[i] = op
90	}
91
92	return clone
93}