/
input.go
94 lines (72 loc) · 1.66 KB
/
input.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
package config
import (
"errors"
"io"
"io/ioutil"
"os"
"path/filepath"
hcl2 "github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
hcl2syntax "github.com/hashicorp/hcl/v2/hclsyntax"
hcl2json "github.com/hashicorp/hcl/v2/json"
)
var (
ErrorExtension = errors.New("extension must be either 'hcl' or 'json'")
)
//ParseFile gets the io.Reader and the extension of the file
func ParseFile(filename string) (*Root, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
// check extension hcl or json
extension := filepath.Ext(filename)
if len(extension) > 0 {
extension = extension[1:]
}
return Parse(f, filename, extension)
}
//Parse parses the configuration from hcl or json
func Parse(r io.Reader, filename, extension string) (*Root, error) {
switch extension {
case "hcl":
return parseHCL(r, filename)
case "json":
return parseJSON(r, filename)
default:
return nil, ErrorExtension
}
}
func parseHCL(r io.Reader, filename string) (*Root, error) {
src, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
f, diag := hcl2syntax.ParseConfig(src, filename, hcl2.Pos{})
if diag.HasErrors() {
return nil, diag
}
var config Root
diag = gohcl.DecodeBody(f.Body, nil, &config)
if diag.HasErrors() {
return nil, diag
}
return &config, nil
}
func parseJSON(r io.Reader, filename string) (*Root, error) {
src, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
f, diag := hcl2json.Parse(src, filename)
if diag.HasErrors() {
return nil, diag
}
var config Root
diag = gohcl.DecodeBody(f.Body, nil, &config)
if diag.HasErrors() {
return nil, diag
}
return &config, nil
}