-
Notifications
You must be signed in to change notification settings - Fork 70
/
tomlx.go
83 lines (68 loc) · 2.53 KB
/
tomlx.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
// Copyright (c) 2023, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tomlx
import (
"fmt"
"io"
"io/fs"
"cogentcore.org/core/base/dirs"
"cogentcore.org/core/base/iox"
"github.com/pelletier/go-toml/v2"
)
// NewDecoder returns a new [iox.Decoder]
func NewDecoder(r io.Reader) iox.Decoder { return toml.NewDecoder(r) }
// Open reads the given object from the given filename using TOML encoding
func Open(v any, filename string) error {
return iox.Open(v, filename, NewDecoder)
}
// OpenFiles reads the given object from the given filenames using TOML encoding
func OpenFiles(v any, filenames []string) error {
return iox.OpenFiles(v, filenames, NewDecoder)
}
// OpenFS reads the given object from the given filename using TOML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFS(v any, fsys fs.FS, filename string) error {
return iox.OpenFS(v, fsys, filename, NewDecoder)
}
// OpenFilesFS reads the given object from the given filenames using TOML encoding,
// using the given [fs.FS] filesystem (e.g., for embed files)
func OpenFilesFS(v any, fsys fs.FS, filenames []string) error {
return iox.OpenFilesFS(v, fsys, filenames, NewDecoder)
}
// Read reads the given object from the given reader,
// using TOML encoding
func Read(v any, reader io.Reader) error {
return iox.Read(v, reader, NewDecoder)
}
// ReadBytes reads the given object from the given bytes,
// using TOML encoding
func ReadBytes(v any, data []byte) error {
return iox.ReadBytes(v, data, NewDecoder)
}
// NewEncoder returns a new [iox.Encoder]
func NewEncoder(w io.Writer) iox.Encoder {
return toml.NewEncoder(w).SetIndentTables(true).SetArraysMultiline(true)
}
// Save writes the given object to the given filename using TOML encoding
func Save(v any, filename string) error {
return iox.Save(v, filename, NewEncoder)
}
// Write writes the given object using TOML encoding
func Write(v any, writer io.Writer) error {
return iox.Write(v, writer, NewEncoder)
}
// WriteBytes writes the given object, returning bytes of the encoding,
// using TOML encoding
func WriteBytes(v any) ([]byte, error) {
return iox.WriteBytes(v, NewEncoder)
}
// OpenFromPaths reads the given object from the given TOML file,
// looking on paths for the file.
func OpenFromPaths(v any, file string, paths []string) error {
filenames := dirs.FindFilesOnPaths(paths, file)
if len(filenames) == 0 {
return fmt.Errorf("OpenFromPaths: no files found")
}
return Open(v, filenames[0])
}