亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在眼鏡蛇 cli 中將命令狀態傳遞給 Postrun

如何在眼鏡蛇 cli 中將命令狀態傳遞給 Postrun

Go
白衣染霜花 2022-09-05 17:04:20
Cobra CLI 支持在執行命令后調用 PostRun。https://github.com/spf13/cobra#prerun-and-postrun-hooks如何將命令狀態傳遞給 PostRun 調用?我需要在執行命令后將命令狀態發布到服務器
查看完整描述

2 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

更簡潔的方法是利用 cobra 命令中提供的注釋


package main


import (

    "fmt"


    "github.com/spf13/cobra"

)



func main() {

    var rootCmd = &cobra.Command{

        Use:   "root [sub]",

        Short: "My root command",

        Run: func(cmd *cobra.Command, args []string) {

            // Do your processing here

            // Set the command annotations

            cmd.Annotations = make(map[string]string)

            cmd.Annotations["status"] = "status_goes_here"

            cmd.Annotations["error"] = "error_goes_here"

        },

        PostRun: func(cmd *cobra.Command, args []string) {

            // Retrieve the annotations

            fmt.Println(cmd.Annotations["status"])

            fmt.Println(cmd.Annotations["error"])

        },

    }


    rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})

    rootCmd.Execute()

}

真的很喜歡@Bracken在這里采取的方法,盡管有一些調整可以使其工作


package main


import (

    "fmt"

    "errors"


    "github.com/spf13/cobra"

)


type wrapper struct {

    err error

}


// RunE fails to proceed further in case of error resulting in not executing PostRun actions

func (w *wrapper) Run(f func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) {

    return func(cmd *cobra.Command, args []string) {

        err := f(cmd, args)

        w.err = err

    }

}


func (w *wrapper) PostRun(f func(cmd *cobra.Command, args []string, cmdErr error)) func(cmd *cobra.Command, args []string) {

    return func(cmd *cobra.Command, args []string) {

        f(cmd, args, w.err)

    }

}


func main() {

    cmdWrap := wrapper{}

    var rootCmd = &cobra.Command{

        Use:   "root [sub]",

        Short: "My root command",

        Run: cmdWrap.Run(func(cmd *cobra.Command, args []string) error {

            return errors.New("i'm not in the book, you know")

        }),

        PostRun: cmdWrap.PostRun(func(cmd *cobra.Command, args []string, cmdErr error) {

            fmt.Printf("error was %v\n", cmdErr)

        }),

    }


    rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})

    rootCmd.Execute()

}


----- 舊答案-----


如果我理解正確,有一些狀態需要從cmd.Execute傳遞到PostRun。


您可以使用方法代替并設置需要在上下文中設置的任何鍵值。ExecuteContext(ctx context.Context)Execute()


ctx := context.WithValue(context.Background(), "status", "statusValue")

rootCmd.ExecuteContext(ctx)

可以使用在 PostRun 中檢索相同的值cmd.Context()


PostRun: func(cmd *cobra.Command, args []string) {

   ctx := cmd.Context()

   status := ctx.Value("status")

}


查看完整回答
反對 回復 2022-09-05
?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

我會使用高階函數來包裝你的(或)函數和你的函數來捕獲錯誤或恐慌,然后將它們傳遞到你的:RunRunEPostRunPostRun


package main


import (

    "fmt"


    "github.com/spf13/cobra"

)


type wrapper struct {

    err error

}


func (w *wrapper) RunE(f func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {

    return func(cmd *cobra.Command, args []string) (err error) {

        defer func() {

            if r := recover(); r != nil {

                err = fmt.Errorf("panic: %v", r)

                w.err = err

            }

        }()

        err = f(cmd, args)

        w.err = err

        return

    }

}


func (w *wrapper) PostRun(f func(cmd *cobra.Command, args []string, cmdErr error)) func(cmd *cobra.Command, args []string) {

    return func(cmd *cobra.Command, args []string) {

        f(cmd, args, w.err)

    }

}


func main() {

    cmdWrap := wrapper{}

    var cmdFail = &cobra.Command{

        Use:   "fail",

        Short: "Doesn't work",

        RunE: cmdWrap.RunE(func(cmd *cobra.Command, args []string) error {

            panic("i'm not in the book, you know")

        }),

        PostRun: cmdWrap.PostRun(func(cmd *cobra.Command, args []string, cmdErr error) {

            fmt.Printf("error was %v\n", cmdErr)

        }),

    }


    var rootCmd = &cobra.Command{}

    rootCmd.AddCommand(cmdFail)

    rootCmd.Execute()

}


查看完整回答
反對 回復 2022-09-05
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號