【问题标题】:Pass resource from Command To Subcommands in urfave/cli/v2将资源从命令传递到 urfave/cli/v2 中的子命令
【发布时间】:2021-11-15 07:16:52
【问题描述】:

是可能的,如果是这样的话,如何让Command 初始化一个资源并将其传递给它的Subcommands。想象一个接受它的参数的应用程序,比如

$ mycmd db --connect <...> create <...>
$ mycmd db --connect <...> update <...>

这可能不是一个很好的例子,但它说明了这个概念。这里db 是所有子命令所依赖的一些资源。我想要一个函数来负责db 资源的初始化,然后将初始化的资源传递给子命令。我不知道如何使用 urfave/cli/v2 来做到这一点。

您可以通过创建两个单独的cli.Apps 来做到这一点,一个解析参数的db 部分只是为了使用context.WithValue 创建一个context.Context,然后使用该上下文创建第二个cli.App这将解析其余的参数。我确信有更好的方法来做到这一点。

感谢您的帮助!

【问题讨论】:

    标签: go command-line-interface


    【解决方案1】:

    您可以使用上下文值来实现这一点。您在父 CommandBefore 回调中设置值。以下代码是从subcommands 示例中复制和修改的:

    package main
    
    import (
        "context"
        "fmt"
        "log"
        "os"
    
        "github.com/urfave/cli/v2"
    )
    
    func main() {
        app := &cli.App{
            Commands: []*cli.Command{
                {
                    Name:   "db",
                    Before: func(c *cli.Context) error {
                        db := "example"
                        c.Context = context.WithValue(c.Context, "db", db)
                        return nil
                    },
                    Subcommands: []*cli.Command{
                        {
                            Name:  "connect",
                            Action: func(c *cli.Context) error {
                                db := c.Context.Value("db").(string) // remember to assert to original type
                                fmt.Println("sub command:", db)
                                return nil
                            },
                        },
                    },
                },
            },
        }
    
        err := app.Run(os.Args)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    这个 main 使用 string 以便您可以复制粘贴并运行它。您可以用您的数据库对象替换字符串。

    如何测试:

    $ go build -o example
    $ ./example db connect
    sub command: example
    

    【讨论】:

    • 您好,谢谢!是的,这行得通,没有意识到你可以重新分配 cli.Context 的内部 context.Context 但这可能是最好的解决方案:)
    猜你喜欢
    • 2020-10-09
    • 2017-07-12
    • 1970-01-01
    • 2019-01-07
    • 2013-05-30
    • 2020-12-14
    • 1970-01-01
    • 2022-09-29
    • 2023-04-02
    相关资源
    最近更新 更多