github.com/tcnksm/gcli@v0.2.4-0.20170129033839-7eb950507e5a/command/flag_command.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/tcnksm/gcli/skeleton"
     8  )
     9  
    10  // CommandFlag implements the flag.Value interface and allows multiple
    11  // calls to the same variable to append a list. It parses string and set them
    12  // as skeleton.Command.
    13  type CommandFlag []*skeleton.Command
    14  
    15  // String
    16  func (c *CommandFlag) String() string {
    17  	return ""
    18  }
    19  
    20  // Set parses input string and appends it on CommandFlags.
    21  // Input format must be NAME[:SYNOPSIS] format.x
    22  func (c *CommandFlag) Set(v string) error {
    23  	cmdStrs := strings.Split(v, ",")
    24  	for _, cmdStrs := range cmdStrs {
    25  
    26  		parsedCmdStr := strings.Split(cmdStrs, ":")
    27  		if len(parsedCmdStr) > 2 {
    28  			return fmt.Errorf("command flag must be specified by NAME:SYNOPSIS format")
    29  		}
    30  
    31  		name := parsedCmdStr[0]
    32  
    33  		// synopsis is optional
    34  		synopsis := ""
    35  		if len(parsedCmdStr) == 2 {
    36  			synopsis = parsedCmdStr[1]
    37  
    38  			// Delete unnessary characters
    39  			// TODO, this should not here..? or extract this as other function
    40  			synopsis = strings.Trim(synopsis, "\"")
    41  			synopsis = strings.Trim(synopsis, "'")
    42  		}
    43  
    44  		command := &skeleton.Command{
    45  			Name:     name,
    46  			Synopsis: synopsis,
    47  		}
    48  
    49  		if err := command.Fix(); err != nil {
    50  			return err
    51  		}
    52  
    53  		*c = append(*c, command)
    54  	}
    55  
    56  	return nil
    57  }