summaryrefslogtreecommitdiff
path: root/vendor/github.com/ecordell/optgen/helpers/helpers.go
blob: dbfd4eb3db98024b9e3f797e21c4b528bffc84aa (plain)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package helpers

import (
	"fmt"
	"reflect"
)

type withDebugMap interface {
	DebugMap() map[string]any
}

// DebugValue returns the debug value for the given raw Go value. If the value
// is a primitive, it is directly returned. If the value is itself a generated
// Config with a DebugMap function, the DebugMap is invoked. Otherwise, "(value)"
// is returned, unless fmtValue is specified, in which case it is returned as the
// result of fmt.Sprintf.
func DebugValue(value any, fmtValue bool) any {
	if value == nil {
		return "nil"
	}

	if value == "" {
		return "(empty)"
	}

	if wdm, ok := value.(withDebugMap); ok {
		return wdm.DebugMap()
	}

	switch reflect.TypeOf(value).Kind() {
	case reflect.Map:
		if fmtValue {
			return fmt.Sprintf("%v", value)
		}

		return fmt.Sprintf("(map of size %d)", reflect.ValueOf(value).Len())

	case reflect.Slice:
		slce, ok := value.([]any)
		if !ok {
			if fmtValue {
				return fmt.Sprintf("%v", value)
			}

			return fmt.Sprintf("(slice of size %d)", reflect.ValueOf(value).Len())
		}

		updated := make([]any, 0, len(slce))
		for _, vle := range slce {
			updated = append(updated, DebugValue(vle, fmtValue))
		}
		return updated

	case reflect.String:
		fallthrough

	case reflect.Int:
		fallthrough

	case reflect.Int8:
		fallthrough

	case reflect.Int16:
		fallthrough

	case reflect.Int32:
		fallthrough

	case reflect.Int64:
		fallthrough

	case reflect.Uint:
		fallthrough

	case reflect.Uint8:
		fallthrough

	case reflect.Uint16:
		fallthrough

	case reflect.Uint32:
		fallthrough

	case reflect.Uint64:
		fallthrough

	case reflect.Bool:
		fallthrough

	case reflect.Float32:
		fallthrough

	case reflect.Float64:
		return value

	default:
		if fmtValue {
			return fmt.Sprintf("%v", value)
		}
		return "(value)"
	}
}

// SensitiveDebugValue returns the string "nil" if the value is nil, "(empty)"
// if empty and otherwise returns "(sensitive)".
func SensitiveDebugValue(value any) any {
	if value == nil {
		return "nil"
	}

	if value == "" {
		return "(empty)"
	}

	return "(sensitive)"
}

func Flatten(debugMap map[string]any) map[string]any {
	flattened := make(map[string]any, len(debugMap))
	for key, value := range debugMap {
		childMap, ok := value.(map[string]any)
		if ok {
			for fk, fv := range Flatten(childMap) {
				flattened[key+"."+fk] = fv
			}
			continue
		}

		flattened[key] = value
	}
	return flattened
}