goweb/cli/format/table/prop.go

62 lines
1.1 KiB
Go

package table
import (
"encoding/json"
"fmt"
"reflect"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cli/format"
)
const (
hintCompactModeMaxColumnWidth format.PropHintName = "compactModeMaxColumnWidth"
)
func WithCompactModeMaxColumnWidth(max int) format.PropHintFunc {
return format.WithPropHint(hintCompactModeMaxColumnWidth, max)
}
func getProps(d any) []format.Prop {
props := make([]format.Prop, 0)
v := reflect.Indirect(reflect.ValueOf(d))
typeOf := v.Type()
for i := 0; i < v.NumField(); i++ {
name := typeOf.Field(i).Name
props = append(props, format.NewProp(name, name))
}
return props
}
func getFieldValue(obj any, name string) string {
v := reflect.Indirect(reflect.ValueOf(obj))
fieldValue := v.FieldByName(name)
if !fieldValue.IsValid() {
return ""
}
switch fieldValue.Kind() {
case reflect.Map:
fallthrough
case reflect.Struct:
fallthrough
case reflect.Slice:
fallthrough
case reflect.Interface:
json, err := json.Marshal(fieldValue.Interface())
if err != nil {
panic(errors.WithStack(err))
}
return string(json)
default:
return fmt.Sprintf("%v", fieldValue)
}
}