struct.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  2. package convert
  3. import (
  4. "fmt"
  5. "reflect"
  6. "github.com/spdx/tools-golang/spdx/common"
  7. )
  8. // FromPtr accepts a document or a document pointer and returns the direct struct reference
  9. func FromPtr(doc common.AnyDocument) common.AnyDocument {
  10. value := reflect.ValueOf(doc)
  11. for value.Type().Kind() == reflect.Ptr {
  12. value = value.Elem()
  13. }
  14. return value.Interface()
  15. }
  16. func IsPtr(obj common.AnyDocument) bool {
  17. t := reflect.TypeOf(obj)
  18. if t.Kind() == reflect.Interface {
  19. t = t.Elem()
  20. }
  21. return t.Kind() == reflect.Ptr
  22. }
  23. func Describe(o interface{}) string {
  24. value := reflect.ValueOf(o)
  25. typ := value.Type()
  26. prefix := ""
  27. for typ.Kind() == reflect.Ptr {
  28. prefix += "*"
  29. value = value.Elem()
  30. typ = value.Type()
  31. }
  32. str := limit(fmt.Sprintf("%+v", value.Interface()), 300)
  33. name := fmt.Sprintf("%s.%s%s", typ.PkgPath(), prefix, typ.Name())
  34. return fmt.Sprintf("%s: %s", name, str)
  35. }
  36. func limit(text string, length int) string {
  37. if length <= 0 || len(text) <= length+3 {
  38. return text
  39. }
  40. r := []rune(text)
  41. r = r[:length]
  42. return string(r) + "..."
  43. }