forked from mitchellh/golicense
/
parse.go
90 lines (74 loc) · 1.81 KB
/
parse.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
package config
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/hashicorp/hcl2/gohcl"
"github.com/hashicorp/hcl2/hcl"
"github.com/hashicorp/hcl2/hcl/hclsyntax"
"github.com/hashicorp/hcl2/hcl/json"
)
// ParseFile parses the given file for a configuration. The syntax of the
// file is determined based on the filename extension: "hcl" for HCL,
// "json" for JSON, other is an error.
func ParseFile(filename string) (*Config, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
ext := filepath.Ext(filename)
if len(ext) > 0 {
ext = ext[1:]
}
return Parse(f, filename, ext)
}
// Parse parses the configuration from the given reader. The reader will be
// read to completion (EOF) before returning so ensure that the reader
// does not block forever.
//
// format is either "hcl" or "json"
func Parse(r io.Reader, filename, format string) (*Config, error) {
switch format {
case "hcl":
return parseHCL(r, filename)
case "json":
return parseJSON(r, filename)
default:
return nil, fmt.Errorf("Format must be either 'hcl' or 'json'")
}
}
func parseHCL(r io.Reader, filename string) (*Config, error) {
src, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
f, diag := hclsyntax.ParseConfig(src, filename, hcl.Pos{})
if diag.HasErrors() {
return nil, diag
}
var config Config
diag = gohcl.DecodeBody(f.Body, nil, &config)
if diag.HasErrors() {
return nil, diag
}
return &config, nil
}
func parseJSON(r io.Reader, filename string) (*Config, error) {
src, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
f, diag := json.Parse(src, filename)
if diag.HasErrors() {
return nil, diag
}
var config Config
diag = gohcl.DecodeBody(f.Body, nil, &config)
if diag.HasErrors() {
return nil, diag
}
return &config, nil
}