github.com/tiagovtristao/plz@v13.4.0+incompatible/src/core/config_flags.go (about)

     1  // +build !bootstrap
     2  
     3  package core
     4  
     5  import (
     6  	"github.com/jessevdk/go-flags"
     7  
     8  	"strings"
     9  )
    10  
    11  // AttachAliasFlags attaches the alias flags to the given flag parser.
    12  // It returns true if any modifications were made.
    13  func (config *Configuration) AttachAliasFlags(parser *flags.Parser) bool {
    14  	for name, alias := range config.AllAliases() {
    15  		cmd := parser.Command
    16  		fields := strings.Fields(name)
    17  		for i, namePart := range fields {
    18  			cmd = addSubcommand(cmd, namePart, alias.Desc, alias.PositionalLabels && len(alias.Subcommand) == 0 && i == len(fields)-1)
    19  			for _, subcommand := range alias.Subcommand {
    20  				addSubcommands(cmd, strings.Fields(subcommand), alias.PositionalLabels)
    21  			}
    22  			for _, flag := range alias.Flag {
    23  				// This is unavailable during bootstrap due to being a local modification.
    24  				cmd.AddOption(getOption(flag))
    25  			}
    26  		}
    27  	}
    28  	return len(config.Aliases) > 0 || len(config.Alias) > 0
    29  }
    30  
    31  // addSubcommands attaches a series of subcommands to the given command.
    32  func addSubcommands(cmd *flags.Command, subcommands []string, positionalLabels bool) {
    33  	if len(subcommands) > 0 && cmd != nil {
    34  		addSubcommands(addSubcommand(cmd, subcommands[0], "", positionalLabels), subcommands[1:], positionalLabels)
    35  	}
    36  }
    37  
    38  // addSubcommand adds a single subcommand to the given command.
    39  // If one by that name already exists, it is returned.
    40  func addSubcommand(cmd *flags.Command, subcommand, desc string, positionalLabels bool) *flags.Command {
    41  	if existing := cmd.Find(subcommand); existing != nil {
    42  		return existing
    43  	}
    44  	var data interface{} = &struct{}{}
    45  	if positionalLabels {
    46  		data = &struct {
    47  			Args struct {
    48  				Target []BuildLabel `positional-arg-name:"target" description:"Build targets"`
    49  			} `positional-args:"true"`
    50  		}{}
    51  	}
    52  	newCmd, _ := cmd.AddCommand(subcommand, desc, desc, data)
    53  	return newCmd
    54  }
    55  
    56  // getOption creates a new flags.Option.
    57  // This is a fiddle since it doesn't really expose a direct way of doing this programmatically.
    58  func getOption(name string) *flags.Option {
    59  	data := struct {
    60  		Opt string `long:"option"`
    61  	}{}
    62  	p := flags.NewParser(&data, 0)
    63  	opt := p.FindOptionByLongName("option")
    64  	opt.LongName = strings.TrimLeft(name, "-")
    65  	if len(name) == 2 && name[0] == '-' {
    66  		opt.ShortName = rune(name[1])
    67  	}
    68  	return opt
    69  }