github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/automation/hook/runtime_hook.go (about) 1 package hook 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "github.com/qri-io/qri/event" 8 ) 9 10 // A RuntimeHook implements rhe Hook interface & keeps track of rhe number 11 // of times it had been advanced 12 type RuntimeHook struct { 13 enabled bool 14 AdvanceCount int 15 payload interface{} 16 } 17 18 var _ Hook = (*RuntimeHook)(nil) 19 20 // RuntimeType denotes a `RuntimeHook` 21 const RuntimeType = "Runtime Hook" 22 23 // ETRuntimeHook denotes a `RuntimeHook` event 24 // TODO (ramfox): this will probably move to the `event` package 25 const ETRuntimeHook = event.Type("workflow:runtimehook") 26 27 // NewRuntimeHook returns an enabled `RuntimeHook` 28 func NewRuntimeHook(payload interface{}) *RuntimeHook { 29 return &RuntimeHook{ 30 enabled: true, 31 AdvanceCount: 0, 32 payload: payload, 33 } 34 } 35 36 // Enabled returns the enabled status 37 func (rh *RuntimeHook) Enabled() bool { 38 return rh.enabled 39 } 40 41 // SetEnabled sets the enabled status 42 func (rh *RuntimeHook) SetEnabled(enabled bool) error { 43 rh.enabled = enabled 44 return nil 45 } 46 47 // Type returns the type of Hook 48 func (rh *RuntimeHook) Type() string { 49 return RuntimeType 50 } 51 52 // Advance increments the AdvanceCount 53 func (rh *RuntimeHook) Advance() error { 54 rh.AdvanceCount++ 55 return nil 56 } 57 58 // Event returns the event.Type ETRuntimeHook as well as the associated payload 59 func (rh *RuntimeHook) Event() (event.Type, interface{}) { 60 return ETRuntimeHook, rh.payload 61 } 62 63 type runtimeHook struct { 64 Enabled bool `json:"enabled"` 65 Type string `json:"type"` 66 AdvanceCount int `json:"advancedCount"` 67 Payload interface{} `json:"payload"` 68 } 69 70 // MarshalJSON satisfies the json.Marshaller interface 71 func (rh *RuntimeHook) MarshalJSON() ([]byte, error) { 72 if rh == nil { 73 rh = &RuntimeHook{} 74 } 75 return json.Marshal(runtimeHook{ 76 Enabled: rh.enabled, 77 Type: rh.Type(), 78 AdvanceCount: rh.AdvanceCount, 79 Payload: rh.payload, 80 }) 81 } 82 83 // UnmarshalJSON satisfies the json.Unmarshaller interface 84 func (rh *RuntimeHook) UnmarshalJSON(d []byte) error { 85 h := &runtimeHook{} 86 err := json.Unmarshal(d, h) 87 if err != nil { 88 return err 89 } 90 if h.Type != RuntimeType { 91 return fmt.Errorf("%w, got %q expected %q", ErrUnexpectedType, h.Type, RuntimeType) 92 } 93 if rh == nil { 94 rh = &RuntimeHook{} 95 } 96 rh.enabled = h.Enabled 97 rh.AdvanceCount = h.AdvanceCount 98 rh.payload = h.Payload 99 return nil 100 }