github.com/helmwave/helmwave@v0.36.4-0.20240509190856-b35563eba4c6/pkg/clictx/clictx.go (about) 1 package clictx 2 3 import ( 4 "context" 5 6 log "github.com/sirupsen/logrus" 7 "github.com/urfave/cli/v2" 8 ) 9 10 type ( 11 flagName string 12 ) 13 14 var cliFlag = struct{}{} 15 16 //nolint:fatcontext 17 func CLIContextToContext(c *cli.Context) context.Context { 18 ctx := c.Context 19 20 for _, f := range c.FlagNames() { 21 g := c.Value(f) 22 log.WithField("name", f).WithField("value", g).Trace("adding flag to action context.Context") 23 ctx = addFlagToContext(ctx, f, g) 24 } 25 26 ctx = addCLIToContext(ctx, c) 27 28 return ctx 29 } 30 31 func addFlagToContext(ctx context.Context, name string, value any) context.Context { 32 return context.WithValue(ctx, flagName(name), value) 33 } 34 35 func GetFlagFromContext(ctx context.Context, name string) any { 36 return ctx.Value(flagName(name)) 37 } 38 39 func addCLIToContext(ctx context.Context, c *cli.Context) context.Context { 40 return context.WithValue(ctx, cliFlag, c) 41 } 42 43 func GetCLIFromContext(ctx context.Context) *cli.Context { 44 c, ok := ctx.Value(cliFlag).(*cli.Context) 45 if !ok { 46 return nil 47 } 48 49 return c 50 }