Table of Contents generated with DocToc

docker源码阅读笔记

命令行

基于cobra开发

cobra实现

operationSubCommands方法

解析命令行入参,返回参数数组:

若命令存在(未被移除 && 非隐藏类型命令)且不含子命令,依次放入数组中

func operationSubCommands(cmd *cobra.Command) []*cobra.Command {
    var cmds []*cobra.Command
    for _, sub := range cmd.Commands() {
        if sub.IsAvailableCommand() && !sub.HasSubCommands() {
            cmds = append(cmds, sub)
        }
    }
    return cmds
}

hasSubCommands方法

判断docker命令是否含有子命令或参数

调用operationSubCommands对返回的数组进行容量判断,长度大于0返回true(即含有子命令)

docker ps不含有子命令,而docker save含有子命令(-o)

func hasSubCommands(cmd *cobra.Command) bool {
    return len(operationSubCommands(cmd)) > 0
}

FlagErrorFunc方法

判断docker命令合法性:

func FlagErrorFunc(cmd *cobra.Command, err error) error {
    if err == nil {
        return nil
    }

    usage := ""
    if cmd.HasSubCommands() {
        usage = "\n\n" + cmd.UsageString()
    }
    return StatusError{
        Status:     fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
        StatusCode: 125,
    }
} 
Copyright © weiliang 2021 all right reserved,powered by Gitbook本书发布时间: 2024-04-22 16:03:42

results matching ""

    No results matching ""