args.go
This file
Path
args.go
144 lines · 4.4 KiB · Go
Last changed by
Add cobra unique args validator (#2397)takanuva15before adoptionad460ea
History of this fileTake it
1// Copyright 2013-2023 The Cobra Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package cobra1617import (18 "fmt"19 "strings"20)2122type PositionalArgs func(cmd *Command, args []string) error2324// legacyArgs validation has the following behaviour:25// - root commands with no subcommands can take arbitrary arguments26// - root commands with subcommands will do subcommand validity checking27// - subcommands will always accept arbitrary arguments28func legacyArgs(cmd *Command, args []string) error {29 // no subcommand, always take args30 if !cmd.HasSubCommands() {31 return nil32 }3334 // root command with subcommands, do subcommand checking.35 if !cmd.HasParent() && len(args) > 0 {36 return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))37 }38 return nil39}4041// NoArgs returns an error if any args are included.42func NoArgs(cmd *Command, args []string) error {43 if len(args) > 0 {44 return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())45 }46 return nil47}4849// OnlyValidArgs returns an error if there are any positional args that are not in50// the `ValidArgs` field of `Command`51func OnlyValidArgs(cmd *Command, args []string) error {52 if len(cmd.ValidArgs) > 0 {53 // Remove any description that may be included in ValidArgs.54 // A description is following a tab character.55 validArgs := make([]string, 0, len(cmd.ValidArgs))56 for _, v := range cmd.ValidArgs {57 validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])58 }59 for _, v := range args {60 if !stringInSlice(v, validArgs) {61 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))62 }63 }64 }65 return nil66}6768// NoDuplicateArgs returns an error if there are any duplicate positional args.69func NoDuplicateArgs(cmd *Command, args []string) error {70 seen := make(map[string]struct{}, len(args))71 for _, arg := range args {72 if _, ok := seen[arg]; ok {73 return fmt.Errorf("duplicate argument %q for %q", arg, cmd.CommandPath())74 }75 seen[arg] = struct{}{}76 }7778 return nil79}8081// ArbitraryArgs never returns an error.82func ArbitraryArgs(cmd *Command, args []string) error {83 return nil84}8586// MinimumNArgs returns an error if there is not at least N args.87func MinimumNArgs(n int) PositionalArgs {88 return func(cmd *Command, args []string) error {89 if len(args) < n {90 return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))91 }92 return nil93 }94}9596// MaximumNArgs returns an error if there are more than N args.97func MaximumNArgs(n int) PositionalArgs {98 return func(cmd *Command, args []string) error {99 if len(args) > n {100 return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))101 }102 return nil103 }104}105106// ExactArgs returns an error if there are not exactly n args.107func ExactArgs(n int) PositionalArgs {108 return func(cmd *Command, args []string) error {109 if len(args) != n {110 return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))111 }112 return nil113 }114}115116// RangeArgs returns an error if the number of args is not within the expected range.117func RangeArgs(min int, max int) PositionalArgs {118 return func(cmd *Command, args []string) error {119 if len(args) < min || len(args) > max {120 return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))121 }122 return nil123 }124}125126// MatchAll allows combining several PositionalArgs to work in concert.127func MatchAll(pargs ...PositionalArgs) PositionalArgs {128 return func(cmd *Command, args []string) error {129 for _, parg := range pargs {130 if err := parg(cmd, args); err != nil {131 return err132 }133 }134 return nil135 }136}137138// ExactValidArgs returns an error if there are not exactly N positional args OR139// there are any positional args that are not in the `ValidArgs` field of `Command`140//141// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead142func ExactValidArgs(n int) PositionalArgs {143 return MatchAll(ExactArgs(n), OnlyValidArgs)144}