File: flat_encode.go

package info (click to toggle)
golang-github-traefik-paerser 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 612 kB
  • sloc: makefile: 14
file content (167 lines) | stat: -rw-r--r-- 4,196 bytes parent folder | download
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package parser

import (
	"fmt"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/traefik/paerser/types"
)

const defaultPtrValue = "false"

// FlatOpts holds options used when encoding to Flat.
type FlatOpts struct {
	Case      string // "lower" or "upper", defaults to "lower".
	Separator string
	SkipRoot  bool
	TagName   string
}

// Flat is a configuration item representation.
type Flat struct {
	Name        string
	Description string
	Default     string
}

// EncodeToFlat encodes a node to a Flat representation.
// Even though the given node argument should have already been augmented with metadata such as kind,
// the element (and its type information) is still needed to treat remaining edge cases.
func EncodeToFlat(element interface{}, node *Node, opts FlatOpts) ([]Flat, error) {
	if element == nil || node == nil {
		return nil, nil
	}

	if node.Kind == 0 {
		return nil, fmt.Errorf("missing node type: %s", node.Name)
	}

	elem := reflect.ValueOf(element)
	if elem.Kind() == reflect.Struct {
		return nil, fmt.Errorf("structs are not supported, use pointer instead")
	}

	encoder := encoderToFlat{FlatOpts: opts}

	var entries []Flat
	if encoder.SkipRoot {
		for _, child := range node.Children {
			field := encoder.getField(elem.Elem(), child)
			entries = append(entries, encoder.createFlat(field, child.Name, child)...)
		}
	} else {
		entries = encoder.createFlat(elem, strings.ToLower(node.Name), node)
	}

	sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })

	return entries, nil
}

type encoderToFlat struct {
	FlatOpts
}

func (e encoderToFlat) createFlat(field reflect.Value, name string, node *Node) []Flat {
	var entries []Flat
	if node.Kind != reflect.Map && node.Description != "-" {
		if !(node.Kind == reflect.Pointer && len(node.Children) > 0) ||
			(node.Kind == reflect.Pointer && node.Tag.Get(e.TagName) == TagLabelAllowEmpty) {
			if node.Name[0] != '[' {
				entries = append(entries, Flat{
					Name:        e.getName(name),
					Description: node.Description,
					Default:     e.getNodeValue(e.getField(field, node), node),
				})
			}
		}
	}

	for _, child := range node.Children {
		if node.Kind == reflect.Map {
			fChild := e.getField(field, child)

			var v string
			if child.Kind == reflect.Struct {
				v = defaultPtrValue
			} else {
				v = e.getNodeValue(fChild, child)
			}

			if node.Description != "-" {
				entries = append(entries, Flat{
					Name:        e.getName(name, child.Name),
					Description: node.Description,
					Default:     v,
				})
			}

			if child.Kind == reflect.Struct || child.Kind == reflect.Pointer {
				for _, ch := range child.Children {
					f := e.getField(fChild, ch)
					n := e.getName(name, child.Name, ch.Name)
					entries = append(entries, e.createFlat(f, n, ch)...)
				}
			}
		} else {
			f := e.getField(field, child)
			n := e.getName(name, child.Name)
			entries = append(entries, e.createFlat(f, n, child)...)
		}
	}

	return entries
}

func (e encoderToFlat) getField(field reflect.Value, node *Node) reflect.Value {
	switch field.Kind() {
	case reflect.Struct:
		return field.FieldByName(node.FieldName)
	case reflect.Pointer:
		if field.Elem().Kind() == reflect.Struct {
			return field.Elem().FieldByName(node.FieldName)
		}
		return field.Elem()
	case reflect.Map:
		return field.MapIndex(reflect.ValueOf(node.FieldName))
	default:
		return field
	}
}

func (e encoderToFlat) getNodeValue(field reflect.Value, node *Node) string {
	if node.Kind == reflect.Pointer && len(node.Children) > 0 {
		return defaultPtrValue
	}

	if field.Kind() == reflect.Int64 {
		i, _ := strconv.ParseInt(node.Value, 10, 64)

		switch field.Type() {
		case reflect.TypeOf(types.Duration(time.Second)):
			return strconv.Itoa(int(i) / int(time.Second))
		case reflect.TypeOf(time.Second):
			return time.Duration(i).String()
		}
	}

	return node.Value
}

func (e encoderToFlat) getName(names ...string) string {
	var name string
	if names[len(names)-1][0] == '[' {
		name = strings.Join(names, "")
	} else {
		name = strings.Join(names, e.Separator)
	}

	if strings.EqualFold(e.Case, "upper") {
		return strings.ToUpper(name)
	}
	return strings.ToLower(name)
}