urfave / cli

A simple, fast, and fun package for building command line apps in Go
https://cli.urfave.org
MIT License
21.89k stars 1.69k forks source link

Ability to add context values #1927

Open nejtr0n opened 4 days ago

nejtr0n commented 4 days ago

Checklist

What problem does this solve?

In old versions we could add context fields in Before function like this

  Before: func(c *cli.Context) error {
      db := "example"
      c.Context = context.WithValue(c.Context, "db", db)
      return nil
  },

It's useful for example for passing logger through all commands.

Solution description

Add some middleware layer to command with signature

func(ctx context.Context, command *cli.Command) func(ctx context.Context, command *cli.Command)

where we could modify passing ctx

Describe alternatives you've considered

Return back Context field to command

ccoVeille commented 4 days ago

I agree context should be available everywhere 🥳

dearchap commented 2 days ago

@nejtr0n What exactly are you trying to achieve ? when calling rootCmd.Run(ctx, args) you can pass in a ctx of your choice with whatever values you define. All subcmds will have a context with parent context set to that so you should have able to retrieve said values. Do you mean you want to pass in a new context to the Action function for the command based on what you set in Before ? I hadnt really thought about that use case. If you can give me a sample of Before/Action functions of your older code I can see what can be done.