File: struct.go

package info (click to toggle)
golang-github-spdx-tools-golang 0.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 3,252 kB
  • sloc: xml: 428; makefile: 22; ansic: 5; python: 2
file content (50 lines) | stat: -rw-r--r-- 1,122 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later

package convert

import (
	"fmt"
	"reflect"

	"github.com/spdx/tools-golang/spdx/common"
)

// FromPtr accepts a document or a document pointer and returns the direct struct reference
func FromPtr(doc common.AnyDocument) common.AnyDocument {
	value := reflect.ValueOf(doc)
	for value.Type().Kind() == reflect.Ptr {
		value = value.Elem()
	}
	return value.Interface()
}

func IsPtr(obj common.AnyDocument) bool {
	t := reflect.TypeOf(obj)
	if t.Kind() == reflect.Interface {
		t = t.Elem()
	}
	return t.Kind() == reflect.Ptr
}

func Describe(o interface{}) string {
	value := reflect.ValueOf(o)
	typ := value.Type()
	prefix := ""
	for typ.Kind() == reflect.Ptr {
		prefix += "*"
		value = value.Elem()
		typ = value.Type()
	}
	str := limit(fmt.Sprintf("%+v", value.Interface()), 300)
	name := fmt.Sprintf("%s.%s%s", typ.PkgPath(), prefix, typ.Name())
	return fmt.Sprintf("%s: %s", name, str)
}

func limit(text string, length int) string {
	if length <= 0 || len(text) <= length+3 {
		return text
	}
	r := []rune(text)
	r = r[:length]
	return string(r) + "..."
}