-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
97 lines (83 loc) · 2.23 KB
/
decoder.go
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
// SPDX-FileCopyrightText: 2022 Weston Schmidt <[email protected]>
// SPDX-License-Identifier: Apache-2.0
// properties package is a goschtalt decoder package.
//
// The properties package automatically registers the decoder as a default decoder
// with the goschtalt package so the usage is as simple as possible ... simply
// import the package and it should just work.
//
// Import the package like you do for pprof - like this:
//
// import (
// "fmt"
// "os"
// ...
//
// "github.com/goschtalt/goschtalt"
// _ "github.com/goschtalt/properties-decoder"
// )
//
// See the example for how to use this extension package.
package properties
import (
"strings"
"github.com/goschtalt/goschtalt"
"github.com/goschtalt/goschtalt/pkg/decoder"
"github.com/goschtalt/goschtalt/pkg/meta"
"github.com/magiconair/properties"
)
var _ decoder.Decoder = (*Decoder)(nil)
// Use init to automatically wire this encoder as one available for goschtalt
// simply by including this package.
func init() {
var d Decoder
goschtalt.DefaultOptions = append(goschtalt.DefaultOptions, goschtalt.WithDecoder(d))
}
// Decoder is a class for the property decoder.
type Decoder struct{}
// Extensions returns the supported extensions.
func (d Decoder) Extensions() []string {
return []string{"properties"}
}
// Decode decodes a byte arreay into the meta.Object tree.
func (d Decoder) Decode(ctx decoder.Context, b []byte, m *meta.Object) error {
props, err := properties.Load(b, properties.UTF8)
if err != nil {
return err
}
lines := strings.Split(string(b), "\n")
keys := props.Keys()
if len(keys) == 0 {
return nil
}
tree := meta.Object{
Origins: []meta.Origin{{
File: ctx.Filename,
Line: 1,
Col: 1,
}},
Map: make(map[string]meta.Object),
}
for _, key := range keys {
origin := meta.Origin{
File: ctx.Filename,
Col: 1,
}
for i, line := range lines {
for _, c := range []string{"=", ":", " ", "\t", "\f"} {
k := key + c
if strings.HasPrefix(strings.TrimSpace(line), k) {
origin.Line = i + 1
break
}
}
}
val, _ := props.Get(key)
tree, err = tree.Add(ctx.Delimiter, key, meta.StringToBestType(val), origin)
if err != nil {
return err
}
}
*m = tree.ConvertMapsToArrays()
return nil
}