File: file_node.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 (96 lines) | stat: -rw-r--r-- 1,999 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
package file

import (
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"strings"

	"github.com/BurntSushi/toml"
	"github.com/traefik/paerser/parser"
	"gopkg.in/yaml.v3"
)

// decodeFileToNode decodes the configuration in filePath in a tree of untyped nodes.
// If filters is not empty, it skips any configuration element whose name is not among filters.
func decodeFileToNode(filePath string, filters ...string) (*parser.Node, error) {
	content, err := os.ReadFile(filepath.Clean(filePath))
	if err != nil {
		return nil, err
	}

	data := make(map[string]interface{})

	switch strings.ToLower(filepath.Ext(filePath)) {
	case ".toml":
		err = toml.Unmarshal(content, &data)
		if err != nil {
			return nil, err
		}

	case ".yml", ".yaml", ".json":
		err = yaml.Unmarshal(content, data)
		if err != nil {
			return nil, err
		}

	default:
		return nil, fmt.Errorf("unsupported file extension: %s", filePath)
	}

	if len(data) == 0 {
		return nil, fmt.Errorf("no configuration found in file: %s", filePath)
	}

	node, err := decodeRawToNode(data, filters...)
	if err != nil {
		return nil, err
	}

	if len(node.Children) == 0 {
		return nil, fmt.Errorf("no valid configuration found in file: %s", filePath)
	}

	return node, nil
}

func getRootFieldNames(element interface{}) []string {
	if element == nil {
		return nil
	}

	rootType := reflect.TypeOf(element)

	return getFieldNames(rootType)
}

func getFieldNames(rootType reflect.Type) []string {
	var names []string

	if rootType.Kind() == reflect.Pointer {
		rootType = rootType.Elem()
	}

	if rootType.Kind() != reflect.Struct {
		return nil
	}

	for i := 0; i < rootType.NumField(); i++ {
		field := rootType.Field(i)

		if !parser.IsExported(field) {
			continue
		}

		if field.Anonymous &&
			(field.Type.Kind() == reflect.Pointer && field.Type.Elem().Kind() == reflect.Struct || field.Type.Kind() == reflect.Struct) {
			names = append(names, getFieldNames(field.Type)...)
			continue
		}

		names = append(names, field.Name)
	}

	return names
}