goweb/cli/format/table/prop.go

66 lines
1.2 KiB
Go
Raw Permalink Normal View History

2023-12-15 20:01:37 +01:00
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 ""
}
if fieldValue.Kind() == reflect.Pointer && !fieldValue.IsNil() {
fieldValue = fieldValue.Elem()
}
2023-12-15 20:01:37 +01:00
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)
}
}