github.com/wtfutil/wtf@v0.43.0/utils/help_parser.go (about)

     1  package utils
     2  
     3  import (
     4  	"reflect"
     5  	"regexp"
     6  	"strconv"
     7  	"unicode"
     8  	"unicode/utf8"
     9  
    10  	"github.com/wtfutil/wtf/cfg"
    11  )
    12  
    13  /* -------------------- Exported Functions -------------------- */
    14  
    15  func HelpFromInterface(item interface{}) string {
    16  	result := ""
    17  	t := reflect.TypeOf(item)
    18  
    19  	for i := 0; i < t.NumField(); i++ {
    20  		field := t.Field(i)
    21  
    22  		kind := field.Type.Kind()
    23  		if field.Type.Kind() == reflect.Ptr {
    24  			kind = field.Type.Elem().Kind()
    25  		}
    26  
    27  		if field.Name == "common" {
    28  			result += HelpFromInterface(cfg.Common{})
    29  		}
    30  
    31  		switch kind {
    32  		case reflect.Interface:
    33  			result += HelpFromInterface(field.Type.Elem())
    34  		default:
    35  			result += helpFromValue(field)
    36  		}
    37  	}
    38  
    39  	return result
    40  }
    41  
    42  // StripColorTags removes tcell color tags from a given string
    43  func StripColorTags(input string) string {
    44  	openColorRegex := regexp.MustCompile(`\[.*?\]`)
    45  	return openColorRegex.ReplaceAllString(input, "")
    46  }
    47  
    48  /* -------------------- Unexported Functions -------------------- */
    49  
    50  func helpFromValue(field reflect.StructField) string {
    51  	result := ""
    52  
    53  	optional, err := strconv.ParseBool(field.Tag.Get("optional"))
    54  	if err != nil {
    55  		optional = false
    56  	}
    57  
    58  	help := field.Tag.Get("help")
    59  	if optional {
    60  		help = "Optional " + help
    61  	}
    62  
    63  	values := field.Tag.Get("values")
    64  	if help != "" {
    65  		result += "\n\n " + lowercaseTitle(field.Name)
    66  		result += "\n " + help
    67  
    68  		if values != "" {
    69  			result += "\n Values: " + values
    70  		}
    71  	}
    72  
    73  	return result
    74  }
    75  
    76  func lowercaseTitle(title string) string {
    77  	if title == "" {
    78  		return ""
    79  	}
    80  	r, n := utf8.DecodeRuneInString(title)
    81  	return string(unicode.ToLower(r)) + title[n:]
    82  }