github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/flags/flags_usage.go (about)

     1  package flags
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"strings"
     7  )
     8  
     9  func (c *flagContext) ShowUsage(leadingSpace int) string {
    10  	displayFlags := flags{}
    11  
    12  	for _, f := range c.cmdFlags {
    13  		if !f.Visible() {
    14  			continue
    15  		}
    16  
    17  		d := flagPresenter{
    18  			flagSet: f,
    19  		}
    20  
    21  		displayFlags = append(displayFlags, d)
    22  	}
    23  
    24  	return displayFlags.toString(strings.Repeat(" ", leadingSpace))
    25  }
    26  
    27  type flagPresenter struct {
    28  	flagSet FlagSet
    29  }
    30  
    31  func (p *flagPresenter) line(l int) string {
    32  	flagList := p.flagList()
    33  	usage := p.usage()
    34  	spaces := strings.Repeat(" ", 6+(l-len(flagList)))
    35  
    36  	return strings.TrimRight(fmt.Sprintf("%s%s%s", flagList, spaces, usage), " ")
    37  }
    38  
    39  func (p *flagPresenter) flagList() string {
    40  	f := p.flagSet
    41  	var parts []string
    42  
    43  	if f.GetName() != "" {
    44  		parts = append(parts, fmt.Sprintf("--%s", f.GetName()))
    45  	}
    46  
    47  	if f.GetShortName() != "" {
    48  		parts = append(parts, fmt.Sprintf("-%s", f.GetShortName()))
    49  	}
    50  
    51  	return strings.Join(parts, ", ")
    52  }
    53  
    54  func (p *flagPresenter) usage() string {
    55  	return p.flagSet.String()
    56  }
    57  
    58  func (p *flagPresenter) comparableString() string {
    59  	if p.flagSet.GetName() != "" {
    60  		return p.flagSet.GetName()
    61  	}
    62  
    63  	return p.flagSet.GetShortName()
    64  }
    65  
    66  type flags []flagPresenter
    67  
    68  func (f flags) Len() int {
    69  	return len(f)
    70  }
    71  
    72  func (f flags) Less(i, j int) bool {
    73  	return (f[i].comparableString() < f[j].comparableString())
    74  }
    75  
    76  func (f flags) Swap(i, j int) {
    77  	f[i], f[j] = f[j], f[i]
    78  }
    79  
    80  func (f flags) toString(prefix string) string {
    81  	sort.Sort(f)
    82  
    83  	lines := make([]string, f.Len())
    84  	maxLength := f.maxLineLength()
    85  
    86  	for i, l := range f {
    87  		lines[i] = fmt.Sprintf("%s%s", prefix, l.line(maxLength))
    88  	}
    89  
    90  	return strings.Join(lines, "\n")
    91  }
    92  
    93  func (f flags) maxLineLength() int {
    94  	var l int
    95  
    96  	for _, x := range f {
    97  
    98  		lPrime := len(x.flagList())
    99  
   100  		if lPrime > l {
   101  			l = lPrime
   102  		}
   103  	}
   104  
   105  	return l
   106  }