~alazarte/cfgreader

ref: 52a1f1900e8a800e610e70c24f4e70d683d47578 cfgreader/unmarshaler.go -rw-r--r-- 1.4 KiB
52a1f190 — Alejandro Lazarte Initial commit 7 months ago
                                                                                
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
package cfgreader

import (
	"bufio"
	"io"
	"os"
	"reflect"
	"regexp"
)

type unmarshalError string

func (e unmarshalError) Error() string {
	return string(e)
}

func unmarshalKeyValue(m map[string]interface{}, v *reflect.Value) {
	for key, ival := range m {
		if reflect.ValueOf(ival).Kind() == reflect.Map {
			v2 := v.FieldByName(key)
			unmarshalKeyValue(ival.(map[string]interface{}), &v2)
		}
		switch v.FieldByName(key).Type().Kind() {
		case reflect.String:
			v.FieldByName(key).SetString(ival.(string))
		}
	}
}

func unmarshalCfg(m map[string]interface{}, v interface{}) error {
	vt := reflect.ValueOf(v).Elem()
	if !vt.CanSet() {
		return unmarshalError("cannot set interface")
	}
	unmarshalKeyValue(m, &vt)
	return nil
}

func FromFile(filepath string, v interface{}) error {
	f, err := os.Open(filepath)
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	group := regexp.MustCompile(`(?:([A-Z][a-z]+)\.)?([A-Z][a-z]+)=([A-Za-z0-9\./]+)\n`)
	m := make(map[string]interface{})
	for {
		l, err := buf.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			continue
		}
		ss := group.FindAllStringSubmatch(l, -1)
		if len(ss) == 0 {
			continue
		}
		if ss[0][1] == "" {
			// "" "Key" "Value"
			m[ss[0][2]] = ss[0][3]
			continue
		}
		if m[ss[0][1]] == nil {
			m[ss[0][1]] = make(map[string]interface{})
		}
		// "Group" "Key" "Value"
		m[ss[0][1]].(map[string]interface{})[ss[0][2]] = ss[0][3]
	}
	return unmarshalCfg(m, v)
}