New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
v2 bug: how to pass down global information into subcommand #1009
Comments
In case it's unclear, @renzhengeek I don't know the answer to your question offhand 🙂 |
I think the intended way of doing this is leveraging the Lines 80 to 81 in db3269c
Here's an example of that in use: package main
import (
"fmt"
"log"
"os"
"github.com/urfave/cli/v2"
)
func main() {
app := cli.NewApp()
app.Before = func(c *cli.Context) error {
// Parse a config file here to get data
// ...
c.App.Metadata["some key"] = "some value"
return nil
}
app.Commands = []*cli.Command{
{
Name: "cmd",
Action: func(c *cli.Context) error {
val := c.App.Metadata["some key"].(string)
fmt.Println(val)
return nil
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
} While in this case I am doing everything in the The one consideration is that the type of |
I would like to offer an alternative solution. Although it looks like func Action(data dType) func(c *cli.Context) error{
return func(c *cli.Context) error{
//use data and c freely here
}
} You can use this with This a common pattern for any kind of handler function you may write. |
Thanks for the idea. I will give a try later. But, it seems not working: we can only register subcommand with the function signature:
The problem is, when the wrapper should/can be called instead of calling subcommand action fn directly?
|
@rliebz Thanks very much for your example. I think the example is good enough to be putted in the doc. Thanks all for your kind help. Closed:-) |
Hi,
It's great package! I'm not sure it's a problem or I just haven't known how to achieve this task.
I have a 2-level cli tool:
--config xxx
global option, which accepts a config file, parses it and need to pass down some subcommand-specific items if needed;monitor
subcommand, which need to consume some items in config file;monitor
subcommand as a seperate package, now the entrypoint (subcommand action) is in control ofcli
, I cannot find a opportunity to pass down some information in top-level app into the subcommand.Thanks for your help in advance:-)
The text was updated successfully, but these errors were encountered: