Golang Cobra的使用

在閱讀Docker源碼時發(fā)現(xiàn),Docker命令行是使用cobra庫創(chuàng)建的,為了更好的理解源碼,先來熟悉一下Cobra。
Cobra既是一個用來創(chuàng)建強(qiáng)大的現(xiàn)代命令行應(yīng)用的庫,又是一個用來生成應(yīng)用和命令文件的腳手架。
很多流行的Go項(xiàng)目都使用Cobra,例如Kubernetes, Hugo, rkt, etcd, Moby (former Docker), Docker (distribution), OpenShift, Delve, GopherJS, CockroachDB, Bleve, ProjectAtomic (enterprise), Giant Swarm's gsctl, Nanobox/Nanopack, rclone, nehm, Pouch, Istio, Prototool, mattermost-server, Gardener, Linkerd等。

概念

命令(Commands),參數(shù)(Args)和標(biāo)識(Flags)是Cobra重要的三個概念。

  • 命令(Commands)代表動作
  • 參數(shù)(Args)代表事件
  • 標(biāo)示(Flags)是對動作的修飾
    好的命令行應(yīng)該像自然語句一樣流暢,讓用戶一眼就明白其作用。
    例如以下例子,docker是根命令,pull是命令。
docker pull hello-world

命令(Commands)

下列代碼將docker作為根命令,pull作為其子命令。

package main
import (
    "fmt"
    "strings"
    "github.com/spf13/cobra"
)

func main() {
    var cmdPull = &cobra.Command{
        Use:   "pull [OPTIONS] NAME[:TAG|@DIGEST]",
        Short: "Pull an image or a repository from a registry",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Pull: " + strings.Join(args, " "))
        },
    }

    var rootCmd = &cobra.Command{Use: "docker"}
    rootCmd.AddCommand(cmdPull)
    rootCmd.Execute()
}

運(yùn)行結(jié)果

Commands.png

當(dāng)然,這里只是展示cobra的基本使用方法,docker命令的具體實(shí)現(xiàn)見源碼https://github.com/docker/cli/blob/v19.03.5/cmd/docker/docker.go

參數(shù)(Args)

通過Command的Args屬性對參數(shù)進(jìn)行校驗(yàn)。

標(biāo)示(Flags)

標(biāo)示分為全局標(biāo)示(Persistent Flags)和局部標(biāo)示(Local Flags)

全局標(biāo)示(Persistent Flags)

全局標(biāo)示(Persistent Flags)會作用于其指定的命令與指定命令所有的子命令。
例如在上例中加入一行代碼

rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
image.png

局部標(biāo)示(Local Flags)

局部標(biāo)示(Local Flags)僅作用于其指定命令。
例如docker image inspect命令的源碼中定義了局部標(biāo)示-fhttps://github.com/docker/cli/blob/v19.03.5/cli/command/image/inspect.go

flags := cmd.Flags()
    flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
image.png

注:Docker自定義了命令行模版,所以Flags在docker命令中顯示的是Options
https://github.com/docker/cli/blob/v19.03.5/cli/cobra.go#L304

Demo

參照Docker源碼,實(shí)現(xiàn)類似docker ps的功能:返回運(yùn)行中的容器ID

package main

import (
    "fmt"
    "context"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client" // v1.13.1
    "github.com/spf13/cobra"
)


func runPs(dockerCli *client.Client) {
    containers, err := dockerCli.ContainerList(context.Background(), types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }

    fmt.Println("運(yùn)行中的容器ID:")
    for _, container := range containers {
        fmt.Printf("%s \n", container.ID[:10])
    }

}


func main() {
    dockerCli, _ := client.NewEnvClient()

    // 定義ps命令
    var cmdPs = &cobra.Command{
        Use:              "ps",
        Short:            "List containers",
        Run: func(cmd *cobra.Command, args []string)  {
            runPs(dockerCli)
        },
    }
    // 定義根命令
    var rootCmd = &cobra.Command{Use: "play_docker"}
    // 加入ps命令
    rootCmd.AddCommand(cmdPs)
    // 初始化cobra
    rootCmd.Execute()
}

執(zhí)行我們的山寨命令行./play_docker ps看到返回的結(jié)果和docker ps是一致的??

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容