github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/statushooks/context.go (about) 1 package statushooks 2 3 import ( 4 "context" 5 "fmt" 6 "github.com/turbot/steampipe/pkg/contexthelpers" 7 ) 8 9 var ( 10 contextKeySnapshotProgress = contexthelpers.ContextKey("snapshot_progress") 11 contextKeyStatusHook = contexthelpers.ContextKey("status_hook") 12 contextKeyMessageRenderer = contexthelpers.ContextKey("message_renderer") 13 ) 14 15 func DisableStatusHooks(ctx context.Context) context.Context { 16 return AddStatusHooksToContext(ctx, NullHooks) 17 } 18 19 func AddStatusHooksToContext(ctx context.Context, statusHooks StatusHooks) context.Context { 20 return context.WithValue(ctx, contextKeyStatusHook, statusHooks) 21 } 22 23 func StatusHooksFromContext(ctx context.Context) StatusHooks { 24 if ctx == nil { 25 return NullHooks 26 } 27 if val, ok := ctx.Value(contextKeyStatusHook).(StatusHooks); ok { 28 return val 29 } 30 // no status hook in context - return null status hook 31 return NullHooks 32 } 33 34 func AddSnapshotProgressToContext(ctx context.Context, snapshotProgress SnapshotProgress) context.Context { 35 return context.WithValue(ctx, contextKeySnapshotProgress, snapshotProgress) 36 } 37 38 func SnapshotProgressFromContext(ctx context.Context) SnapshotProgress { 39 if ctx == nil { 40 return NullProgress 41 } 42 if val, ok := ctx.Value(contextKeySnapshotProgress).(SnapshotProgress); ok { 43 return val 44 } 45 // no snapshot progress in context - return null progress 46 return NullProgress 47 } 48 49 func AddMessageRendererToContext(ctx context.Context, messageRenderer MessageRenderer) context.Context { 50 return context.WithValue(ctx, contextKeyMessageRenderer, messageRenderer) 51 } 52 53 func SetStatus(ctx context.Context, msg string) { 54 StatusHooksFromContext(ctx).SetStatus(msg) 55 } 56 57 func Done(ctx context.Context) { 58 hook := StatusHooksFromContext(ctx) 59 hook.SetStatus("") 60 hook.Hide() 61 } 62 63 func Warn(ctx context.Context, warning string) { 64 StatusHooksFromContext(ctx).Warn(warning) 65 } 66 67 func Show(ctx context.Context) { 68 StatusHooksFromContext(ctx).Show() 69 } 70 71 func Message(ctx context.Context, msgs ...string) { 72 StatusHooksFromContext(ctx).Message(msgs...) 73 } 74 75 type MessageRenderer func(format string, a ...any) 76 77 func MessageRendererFromContext(ctx context.Context) MessageRenderer { 78 defaultRenderer := func(format string, a ...any) { 79 fmt.Printf(format, a...) 80 } 81 if ctx == nil { 82 return defaultRenderer 83 } 84 if val, ok := ctx.Value(contextKeyMessageRenderer).(MessageRenderer); ok { 85 return val 86 } 87 // no message renderer - return fmt.Printf 88 return defaultRenderer 89 }