github.com/WindomZ/go-commander@v1.2.2/format.go (about)

     1  package commander
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  )
     7  
     8  var Format Formatter = newDefaultFormat()
     9  
    10  type Formatter interface {
    11  	Description(title, desc string) string
    12  }
    13  
    14  type _Format struct {
    15  	MinSpace int
    16  	MaxSpace int
    17  	Line     bool
    18  }
    19  
    20  func newFormat(minSpace, maxSpace int, line bool) *_Format {
    21  	return &_Format{
    22  		MinSpace: minSpace,
    23  		MaxSpace: maxSpace,
    24  		Line:     line,
    25  	}
    26  }
    27  
    28  func newDefaultFormat() *_Format {
    29  	return newFormat(2, 14, true)
    30  }
    31  
    32  // Description format a line description to symmetric string
    33  // title and desc are shown the content by default format.
    34  func (f _Format) Description(title, desc string) string {
    35  	return formatDescription(title, desc, 2, 14, true)
    36  }
    37  
    38  // formatDescription format a line description to symmetric string
    39  // title and desc are shown the content,
    40  // minSpace and maxSpace are indentation range numbers.
    41  func formatDescription(title, desc string, minSpace, maxSpace int, line bool) string {
    42  	if minSpace < 0 {
    43  		minSpace = 0
    44  	}
    45  	if maxSpace < minSpace {
    46  		maxSpace = minSpace
    47  	}
    48  	var pattern string
    49  	if len(title) > (maxSpace - minSpace) {
    50  		if line {
    51  			pattern = "%s\n%" + strconv.Itoa(len(desc)+maxSpace) + "s"
    52  		} else {
    53  			pattern = "%s%" + strconv.Itoa(len(desc)+minSpace) + "s"
    54  		}
    55  	} else {
    56  		pattern = "%-" + strconv.Itoa(maxSpace) + "s%s"
    57  	}
    58  	return fmt.Sprintf(pattern, title, desc)
    59  }