github.com/octohelm/cuemod@v0.9.4/pkg/cli/name.go (about)

     1  package cli
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  type Name struct {
     9  	Name      string
    10  	Desc      string
    11  	ValidArgs ValidArgs
    12  
    13  	subcommands []Command
    14  	parent      Command
    15  }
    16  
    17  func (n *Name) Naming() *Name {
    18  	return n
    19  }
    20  
    21  func (n *Name) Add(c Command) {
    22  	n.subcommands = append(n.subcommands, c)
    23  }
    24  
    25  func ParseValidArgs(s string) ValidArgs {
    26  	if s == "" {
    27  		return ValidArgs{}
    28  	}
    29  
    30  	v := make(ValidArgs, 0)
    31  
    32  	args := strings.Split(s, " ")
    33  
    34  	for i := range args {
    35  		arg := strings.TrimSpace(args[i])
    36  		v = append(v, arg)
    37  	}
    38  
    39  	return v
    40  }
    41  
    42  type ValidArgs []string
    43  
    44  func (as ValidArgs) HasVariadic() bool {
    45  	for _, a := range as {
    46  		if strings.HasSuffix(a, "...") {
    47  			return true
    48  		}
    49  	}
    50  	return false
    51  }
    52  
    53  func (as ValidArgs) Validate(args []string) error {
    54  	if as.HasVariadic() {
    55  		if len(args) < len(as) {
    56  			return fmt.Errorf("requires at least %d arg(s), only received %d", len(as), len(args))
    57  		}
    58  		return nil
    59  	}
    60  	if len(as) != len(args) {
    61  		return fmt.Errorf("accepts %d arg(s), received %d", len(as), len(args))
    62  	}
    63  	return nil
    64  
    65  }