Table of Contents generated with DocToc
基于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,
}
}