| 1 |
// Package nestedtext implements a koanf Parser that parses NestedText bytes as conf maps. |
| 2 |
package nestedtext |
| 3 |
|
| 4 |
import ( |
| 5 |
"bytes" |
| 6 |
"errors" |
| 7 |
|
| 8 |
"github.com/npillmayer/nestext" |
| 9 |
"github.com/npillmayer/nestext/ntenc" |
| 10 |
) |
| 11 |
|
| 12 |
// NT implements a NestedText parser. |
| 13 |
type NT struct{} |
| 14 |
|
| 15 |
// Parser returns a NestedText Parser. |
| 16 |
func Parser() *NT { |
| 17 |
return &NT{} |
| 18 |
} |
| 19 |
|
| 20 |
// Unmarshal parses the given NestedText bytes. |
| 21 |
// |
| 22 |
// If the NT content does not reflect a dict (NT allows for top-level lists or strings as well), |
| 23 |
// the content will be wrapped into a dict with a single key named "nestedtext". |
| 24 |
func (p *NT) Unmarshal(b []byte) (map[string]any, error) { |
| 25 |
r := bytes.NewReader(b) |
| 26 |
result, err := nestext.Parse(r, nestext.TopLevel("dict")) |
| 27 |
if err != nil { |
| 28 |
return nil, err |
| 29 |
} |
| 30 |
// Given option-parameter TopLevel, nestext.Parse is guaranteed to wrap the return value |
| 31 |
// in an appropriate type (dict = map[string]any in this case), if necessary. |
| 32 |
// However, guard against type conversion failure anyway. |
| 33 |
rmap, ok := result.(map[string]any) |
| 34 |
if !ok { |
| 35 |
return nil, errors.New("NestedText configuration expected to be a dict at top-level") |
| 36 |
} |
| 37 |
return rmap, nil |
| 38 |
} |
| 39 |
|
| 40 |
// Marshal marshals the given config map to NestedText bytes. |
| 41 |
func (p *NT) Marshal(m map[string]any) ([]byte, error) { |
| 42 |
var buf bytes.Buffer |
| 43 |
_, err := ntenc.Encode(m, &buf) |
| 44 |
if err != nil { |
| 45 |
return nil, err |
| 46 |
} |
| 47 |
return buf.Bytes(), nil |
| 48 |
} |