-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathread.go
59 lines (48 loc) · 1.14 KB
/
read.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
package hcledit
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
)
// New constructs a new HCL file with no content which is ready to be mutated.
func New() (*HCLEditor, error) {
return &HCLEditor{
writeFile: hclwrite.NewEmptyFile(),
}, nil
}
// ReadFile reads HCL file in the given path and returns operation interface for it.
func ReadFile(path string) (*HCLEditor, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
editor, err := Read(f, filepath.Base(path))
if err != nil {
return nil, err
}
editor.path = path
return editor, err
}
// Read reads HCL file from the given io.Reader and returns operation interface for it.
func Read(r io.Reader, filename string) (*HCLEditor, error) {
buf, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
writeFile, diags := hclwrite.ParseConfig(buf, filename, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, diags
}
return &HCLEditor{
filename: filename,
writeFile: writeFile,
}, nil
}