Files
threshold/internal/cmd/base/format.go
T

107 lines
2.3 KiB
Go
Raw Normal View History

2020-02-12 13:53:27 -05:00
package base
import (
"encoding/json"
"fmt"
"os"
2020-08-28 01:28:26 -04:00
"sort"
2020-02-12 13:53:27 -05:00
"strings"
"unicode"
"unicode/utf8"
2020-02-12 13:53:27 -05:00
"github.com/mitchellh/cli"
"github.com/mitchellh/go-wordwrap"
2020-02-12 13:53:27 -05:00
)
// This is adapted from the code in the strings package for TrimSpace
var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
func trimSpaceRight(in string) string {
for stop := len(in); stop > 0; stop-- {
c := in[stop-1]
if c >= utf8.RuneSelf {
return strings.TrimFunc(in[:stop], unicode.IsSpace)
}
if asciiSpace[c] == 0 {
return in[0:stop]
}
}
return ""
}
func WrapForHelpText(lines []string) string {
var ret []string
for _, line := range lines {
line = trimSpaceRight(line)
trimmed := strings.TrimSpace(line)
diff := uint(len(line) - len(trimmed))
wrapped := wordwrap.WrapString(trimmed, TermWidth-diff)
splitWrapped := strings.Split(wrapped, "\n")
for i := range splitWrapped {
splitWrapped[i] = fmt.Sprintf("%s%s", strings.Repeat(" ", int(diff)), strings.TrimSpace(splitWrapped[i]))
}
ret = append(ret, strings.Join(splitWrapped, "\n"))
}
return strings.Join(ret, "\n")
}
2020-08-28 01:28:26 -04:00
func WrapSlice(prefixSpaces int, input []string) string {
var ret []string
for _, v := range input {
ret = append(ret, fmt.Sprintf("%s%s",
strings.Repeat(" ", prefixSpaces),
fmt.Sprintf("%s: ", v),
))
}
return strings.Join(ret, "\n")
}
2020-08-18 17:46:34 -04:00
func WrapMap(prefixSpaces, maxLengthOverride int, input map[string]interface{}) string {
maxKeyLength := maxLengthOverride
2020-08-28 01:28:26 -04:00
var sortedKeys []string
2020-08-18 17:46:34 -04:00
if maxKeyLength == 0 {
for k := range input {
2020-08-28 01:28:26 -04:00
sortedKeys = append(sortedKeys, k)
2020-08-18 17:46:34 -04:00
if len(k) > maxKeyLength {
maxKeyLength = len(k)
}
}
}
2020-08-28 01:28:26 -04:00
sort.Strings(sortedKeys)
2020-08-18 17:46:34 -04:00
var ret []string
2020-08-28 01:28:26 -04:00
for _, k := range sortedKeys {
v := input[k]
2020-08-18 17:46:34 -04:00
spaces := maxKeyLength - len(k)
ret = append(ret, fmt.Sprintf("%s%s%s%s",
strings.Repeat(" ", prefixSpaces),
fmt.Sprintf("%s: ", k),
strings.Repeat(" ", spaces),
2020-08-28 01:28:26 -04:00
fmt.Sprintf("%v", v),
))
2020-08-18 17:46:34 -04:00
}
return strings.Join(ret, "\n")
}
2020-02-12 13:53:27 -05:00
// An output formatter for json output of an object
type JsonFormatter struct{}
func (j JsonFormatter) Format(data interface{}) ([]byte, error) {
return json.Marshal(data)
2020-02-12 13:53:27 -05:00
}
func Format(ui cli.Ui) string {
2020-08-07 13:50:39 -04:00
switch t := ui.(type) {
2020-08-10 17:15:02 -04:00
case *BoundaryUI:
2020-08-07 13:50:39 -04:00
return t.Format
}
2020-08-10 17:15:02 -04:00
format := os.Getenv(EnvBoundaryCLIFormat)
if format == "" {
format = "table"
}
return format
}