forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.go
87 lines (68 loc) · 1.79 KB
/
parser.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
package parser
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
)
type File interface {
io.ReadWriter
Name() string
}
// Decode decodes a file into data.
// The choice of the decoder is based on the file extension.
func Decode(file File, data any) error {
ext := filepath.Ext(file.Name())
switch strings.ToLower(ext) {
case ".yaml", ".yml", ".json":
err := yaml.NewDecoder(file).Decode(data)
if err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("YAML decode file %s: %w", file.Name(), err)
}
case ".toml":
err := toml.NewDecoder(file).Decode(&data)
if err != nil {
return fmt.Errorf("TOML decode file %s: %w", file.Name(), err)
}
default:
return fmt.Errorf("unsupported file type: %s", ext)
}
return nil
}
// Encode encodes data into a file.
// The choice of the encoder is based on the file extension.
func Encode(data any, dstFile File) error {
ext := filepath.Ext(dstFile.Name())
switch strings.ToLower(ext) {
case ".yml", ".yaml":
encoder := yaml.NewEncoder(dstFile)
encoder.SetIndent(2)
return encoder.Encode(data)
case ".toml":
encoder := toml.NewEncoder(dstFile)
return encoder.Encode(data)
case ".json":
// The JSON encoder converts empty struct to `{}` instead of nothing (even with omitempty JSON struct tags).
// So we need to use the YAML encoder as bridge to create JSON file.
var buf bytes.Buffer
err := yaml.NewEncoder(&buf).Encode(data)
if err != nil {
return err
}
raw := map[string]any{}
err = yaml.NewDecoder(&buf).Decode(raw)
if err != nil {
return err
}
encoder := json.NewEncoder(dstFile)
encoder.SetIndent("", " ")
return encoder.Encode(raw)
default:
return fmt.Errorf("unsupported file type: %s", ext)
}
}