-
Notifications
You must be signed in to change notification settings - Fork 136
/
permission_verb.go
83 lines (69 loc) · 2.51 KB
/
permission_verb.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package queue
import (
"encoding/json"
"fmt"
"math/rand"
"reflect"
)
type PermissionVerb string
const (
PermissionVerbSubmit PermissionVerb = "submit"
PermissionVerbCancel PermissionVerb = "cancel"
PermissionVerbPreempt PermissionVerb = "preempt"
PermissionVerbReprioritize PermissionVerb = "reprioritize"
PermissionVerbWatch PermissionVerb = "watch"
)
// NewPermissionVerb returns PermissionVerb from input string. If input string doesn't match
// one of allowed verb values ["submit", "cancel", "preempt", "reprioritize", "watch"], and error is returned.
func NewPermissionVerb(in string) (PermissionVerb, error) {
switch verb := PermissionVerb(in); verb {
case PermissionVerbSubmit, PermissionVerbCancel, PermissionVerbPreempt, PermissionVerbReprioritize, PermissionVerbWatch:
return verb, nil
default:
return "", fmt.Errorf("invalid queue permission verb: %s", in)
}
}
// UnmarshalJSON is implementation of https://pkg.go.dev/encoding/json#Unmarshaler interface.
func (verb *PermissionVerb) UnmarshalJSON(data []byte) error {
permissionVerb := ""
if err := json.Unmarshal(data, &permissionVerb); err != nil {
return err
}
out, err := NewPermissionVerb(permissionVerb)
if err != nil {
return fmt.Errorf("failed to unmarshal queue permission verb: %s", err)
}
*verb = out
return nil
}
// Generate is implementation of https://pkg.go.dev/testing/quick#Generator interface.
// This method is used for writing tests usign https://pkg.go.dev/testing/quick package
func (verb PermissionVerb) Generate(rand *rand.Rand, size int) reflect.Value {
values := AllPermissionVerbs()
return reflect.ValueOf(values[rand.Intn(len(values))])
}
type PermissionVerbs []PermissionVerb
// NewPermissionVerbs returns PermissionVerbs from string slice. Every string from
// slice is transformed into PermissionVerb. Error is returned if a string cannot
// be transformed to PermissionVerb.
func NewPermissionVerbs(verbs []string) (PermissionVerbs, error) {
result := make([]PermissionVerb, len(verbs))
for index, verb := range verbs {
validVerb, err := NewPermissionVerb(verb)
if err != nil {
return nil, fmt.Errorf("failed to map verb string with index: %d. %s", index, err)
}
result[index] = validVerb
}
return result, nil
}
// AllPermissionVerbs returns PermissionsVerbs containing all PermissionVerb values
func AllPermissionVerbs() PermissionVerbs {
return []PermissionVerb{
PermissionVerbSubmit,
PermissionVerbCancel,
PermissionVerbPreempt,
PermissionVerbReprioritize,
PermissionVerbWatch,
}
}