op_noop.go

 1package bug
 2
 3import (
 4	"encoding/json"
 5
 6	"github.com/MichaelMure/git-bug/identity"
 7	"github.com/MichaelMure/git-bug/util/git"
 8)
 9
10var _ Operation = &NoOpOperation{}
11
12// NoOpOperation is an operation that does not change the bug state. It can
13// however be used to store arbitrary metadata in the bug history, for example
14// to support a bridge feature.
15type NoOpOperation struct {
16	OpBase
17}
18
19func (op *NoOpOperation) base() *OpBase {
20	return &op.OpBase
21}
22
23func (op *NoOpOperation) Hash() (git.Hash, error) {
24	return hashOperation(op)
25}
26
27func (op *NoOpOperation) Apply(snapshot *Snapshot) {
28	// Nothing to do
29}
30
31func (op *NoOpOperation) Validate() error {
32	return opBaseValidate(op, NoOpOp)
33}
34
35// Workaround to avoid the inner OpBase.MarshalJSON overriding the outer op
36// MarshalJSON
37func (op *NoOpOperation) MarshalJSON() ([]byte, error) {
38	base, err := json.Marshal(op.OpBase)
39	if err != nil {
40		return nil, err
41	}
42
43	// revert back to a flat map to be able to add our own fields
44	var data map[string]interface{}
45	if err := json.Unmarshal(base, &data); err != nil {
46		return nil, err
47	}
48
49	return json.Marshal(data)
50}
51
52// Workaround to avoid the inner OpBase.MarshalJSON overriding the outer op
53// MarshalJSON
54func (op *NoOpOperation) UnmarshalJSON(data []byte) error {
55	// Unmarshal OpBase and the op separately
56
57	base := OpBase{}
58	err := json.Unmarshal(data, &base)
59	if err != nil {
60		return err
61	}
62
63	aux := struct{}{}
64
65	err = json.Unmarshal(data, &aux)
66	if err != nil {
67		return err
68	}
69
70	op.OpBase = base
71
72	return nil
73}
74
75// Sign post method for gqlgen
76func (op *NoOpOperation) IsAuthored() {}
77
78func NewNoOpOp(author identity.Interface, unixTime int64) *NoOpOperation {
79	return &NoOpOperation{
80		OpBase: newOpBase(NoOpOp, author, unixTime),
81	}
82}
83
84// Convenience function to apply the operation
85func NoOp(b Interface, author identity.Interface, unixTime int64, metadata map[string]string) (*NoOpOperation, error) {
86	op := NewNoOpOp(author, unixTime)
87
88	for key, value := range metadata {
89		op.SetMetadata(key, value)
90	}
91
92	if err := op.Validate(); err != nil {
93		return nil, err
94	}
95	b.Append(op)
96	return op, nil
97}