mrun: use mcmp.SeriesGetElement to iterate through hooks, so that hooks which get added while the iteration is happening (e.g. from CLISubCommand) can still get hit

This commit is contained in:
Brian Picciano 2019-07-09 20:54:31 -04:00
parent de56d14739
commit d54954cd8e

View File

@ -27,27 +27,31 @@ func triggerHooks(
ctx context.Context, ctx context.Context,
cmp *mcmp.Component, cmp *mcmp.Component,
key interface{}, key interface{},
next func([]mcmp.SeriesElement) (mcmp.SeriesElement, []mcmp.SeriesElement), start func(*mcmp.Component) int,
next func(int) int,
) error { ) error {
els := mcmp.SeriesElements(cmp, hookKey{key}) i := start(cmp)
var el mcmp.SeriesElement
for { for {
if len(els) == 0 { if i < 0 {
break return nil
} }
el, els = next(els)
if el.Child != nil { el, ok := mcmp.SeriesGetElement(cmp, hookKey{key}, i)
if err := triggerHooks(ctx, el.Child, key, next); err != nil { if !ok {
return nil
} else if el.Child != nil {
if err := triggerHooks(ctx, el.Child, key, start, next); err != nil {
return err
}
} else {
hook := el.Value.(Hook)
if err := hook(ctx); err != nil {
return err return err
} }
continue
}
hook := el.Value.(Hook)
if err := hook(ctx); err != nil {
return err
} }
i = next(i)
} }
return nil
} }
// TriggerHooks causes all Hooks registered with AddHook on the Component under // TriggerHooks causes all Hooks registered with AddHook on the Component under
@ -65,24 +69,20 @@ func TriggerHooks(
cmp *mcmp.Component, cmp *mcmp.Component,
key interface{}, key interface{},
) error { ) error {
next := func(els []mcmp.SeriesElement) ( start := func(*mcmp.Component) int { return 0 }
mcmp.SeriesElement, []mcmp.SeriesElement, next := func(i int) int { return i + 1 }
) { return triggerHooks(ctx, cmp, key, start, next)
return els[0], els[1:]
}
return triggerHooks(ctx, cmp, key, next)
} }
// TriggerHooksReverse is the same as TriggerHooks except that registered Hooks // TriggerHooksReverse is the same as TriggerHooks except that registered Hooks
// are called in the reverse order in which they were registered. // are called in the reverse order in which they were registered.
func TriggerHooksReverse(ctx context.Context, cmp *mcmp.Component, key interface{}) error { func TriggerHooksReverse(ctx context.Context, cmp *mcmp.Component, key interface{}) error {
next := func(els []mcmp.SeriesElement) ( start := func(cmp *mcmp.Component) int {
mcmp.SeriesElement, []mcmp.SeriesElement, els := mcmp.SeriesElements(cmp, hookKey{key})
) { return len(els) - 1
last := len(els) - 1
return els[last], els[:last]
} }
return triggerHooks(ctx, cmp, key, next) next := func(i int) int { return i - 1 }
return triggerHooks(ctx, cmp, key, start, next)
} }
type builtinEvent int type builtinEvent int