/
config.go
115 lines (94 loc) · 2.04 KB
/
config.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package config
import (
"bytes"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"github.com/hashicorp/go-multierror"
"gopkg.in/yaml.v2"
)
// Error definitions
var (
ErrFilePathInvalid = errors.New("File Path invalid")
ErrFileTypeInvalid = errors.New("File Type invalid")
ErrDataInvalid = errors.New("Data invalid")
)
// License ...
type License struct {
Path string `yaml:"path" json:"path"`
Content string `yaml:"content" json:"content"`
}
// FileType ...
type FileType struct {
Match string `yaml:"match" json:"match"`
Comment string `yaml:"comment" json:"comment"`
}
// Config ...
type Config struct {
License License `yaml:"license" json:"license"`
Files []FileType `yaml:"files" json:"files"`
Excludes []string `yaml:"excludes" json:"excludes"`
}
var types = [3]string{".json", ".yml", ".yaml"}
func isSupported(ext string) bool {
for _, t := range types {
if t == ext {
return true
}
}
return false
}
// ReadFile ...
func ReadFile(path string) (c *Config, rerr error) {
if path == "" {
return nil, ErrFilePathInvalid
}
if !isSupported(filepath.Ext(path)) {
return nil, ErrFileTypeInvalid
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() {
err = file.Close()
if err != nil {
rerr = multierror.Append(rerr, err)
}
}()
var config *Config
switch filepath.Ext(path) {
case ".json":
config, err = ReadIOJSON(file)
case ".yml":
fallthrough
case ".yaml":
config, err = ReadIOYAML(file)
}
if err != nil {
return nil, err
}
return config, nil
}
// ReadString ...
func ReadString(data string) (*Config, error) {
if data == "" {
return nil, ErrDataInvalid
}
buffer := bytes.NewBufferString(data)
return ReadIOJSON(buffer)
}
// ReadIOYAML ...
func ReadIOYAML(reader io.Reader) (*Config, error) {
config := new(Config)
err := yaml.NewDecoder(reader).Decode(config)
return config, err
}
// ReadIOJSON ...
func ReadIOJSON(reader io.Reader) (*Config, error) {
config := new(Config)
err := json.NewDecoder(reader).Decode(config)
return config, err
}