aboutsummaryrefslogtreecommitdiffstats
path: root/entity/dag/op_set_metadata.go
blob: 9ba80259b25238ac85488c84c5fbf43d357deeed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package dag

import (
	"fmt"

	"github.com/pkg/errors"

	"github.com/git-bug/git-bug/entities/identity"
	"github.com/git-bug/git-bug/entity"
	"github.com/git-bug/git-bug/util/text"
)

var _ Operation = &SetMetadataOperation[Snapshot]{}
var _ OperationDoesntChangeSnapshot = &SetMetadataOperation[Snapshot]{}

type SetMetadataOperation[SnapT Snapshot] struct {
	OpBase
	Target      entity.Id         `json:"target"`
	NewMetadata map[string]string `json:"new_metadata"`
}

func NewSetMetadataOp[SnapT Snapshot](opType OperationType, author identity.Interface, unixTime int64, target entity.Id, newMetadata map[string]string) *SetMetadataOperation[SnapT] {
	return &SetMetadataOperation[SnapT]{
		OpBase:      NewOpBase(opType, author, unixTime),
		Target:      target,
		NewMetadata: newMetadata,
	}
}

func (op *SetMetadataOperation[SnapT]) Id() entity.Id {
	return IdOperation(op, &op.OpBase)
}

func (op *SetMetadataOperation[SnapT]) Apply(snapshot SnapT) {
	for _, target := range snapshot.AllOperations() {
		if target.Id() == op.Target {
			// Apply the metadata in an immutable way: if a metadata already
			// exist, it's not possible to override it.
			for key, value := range op.NewMetadata {
				target.setExtraMetadataImmutable(key, value)
			}
			return
		}
	}
}

func (op *SetMetadataOperation[SnapT]) Validate() error {
	if err := op.OpBase.Validate(op, op.OperationType); err != nil {
		return err
	}

	if err := op.Target.Validate(); err != nil {
		return errors.Wrap(err, "target invalid")
	}

	for key, val := range op.NewMetadata {
		if !text.SafeOneLine(key) {
			return fmt.Errorf("metadata key is unsafe")
		}
		if !text.Safe(val) {
			return fmt.Errorf("metadata value is not fully printable")
		}
	}

	return nil
}

func (op *SetMetadataOperation[SnapT]) DoesntChangeSnapshot() {}