moby/cli/required.go
Yong Tang d5971c230d Use spf13/cobra for docker port
This fix is part of the effort to convert commands to spf13/cobra #23211.

Thif fix coverted command `docker port` to use spf13/cobra

Note: As part of this fix, a new function `RequiresMinMaxArgs(min int, max int)`
has been added in cli/required.go. This function restrict the args
to be at least min and at most max.

Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
2016-06-06 05:32:34 -07:00

79 lines
1.8 KiB
Go

package cli
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
// NoArgs validate args and returns an error if there are any args
func NoArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
if cmd.HasSubCommands() {
return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n"))
}
return fmt.Errorf(
"\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(),
cmd.CommandPath(),
cmd.UseLine(),
cmd.Short,
)
}
// RequiresMinArgs returns an error if there is not at least min args
func RequiresMinArgs(min int) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) >= min {
return nil
}
return fmt.Errorf(
"\"%s\" requires at least %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(),
min,
cmd.CommandPath(),
cmd.UseLine(),
cmd.Short,
)
}
}
// RequiresMinMaxArgs returns an error if there is not at least min args and at most max args
func RequiresMinMaxArgs(min int, max int) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) >= min && len(args) <= max {
return nil
}
return fmt.Errorf(
"\"%s\" requires at least %d and at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(),
min,
max,
cmd.CommandPath(),
cmd.UseLine(),
cmd.Short,
)
}
}
// ExactArgs returns an error if there is not the exact number of args
func ExactArgs(number int) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) == number {
return nil
}
return fmt.Errorf(
"\"%s\" requires exactly %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(),
number,
cmd.CommandPath(),
cmd.UseLine(),
cmd.Short,
)
}
}