-
Notifications
You must be signed in to change notification settings - Fork 6
/
pygohcl.go
49 lines (42 loc) · 1.16 KB
/
pygohcl.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
package main
// typedef struct {
// char *json;
// char *err;
// } parseResponse;
import "C"
import (
"encoding/json"
"fmt"
"strings"
"github.com/hashicorp/hcl/v2/hclparse"
)
//export Parse
func Parse(a *C.char) (resp C.parseResponse) {
defer func() {
if err := recover(); err != nil {
retValue := fmt.Sprintf("panic HCL: %v", err)
resp = C.parseResponse{nil, C.CString(retValue)}
}
}()
input := C.GoString(a)
hclFile, diags := hclparse.NewParser().ParseHCL([]byte(input), "tmp.hcl")
if diags.HasErrors() {
errors := make([]string, 0, len(diags))
for _, diag := range diags {
errors = append(errors, diag.Error())
}
return C.parseResponse{nil, C.CString(fmt.Sprintf("invalid HCL: %s", strings.Join(errors, ", ")))}
}
hclMap, err := convertFile(hclFile)
if err != nil {
return C.parseResponse{nil, C.CString(fmt.Sprintf("cannot convert HCL to Go map representation: %s", err))}
}
hclInJson, err := json.Marshal(hclMap)
if err != nil {
return C.parseResponse{nil, C.CString(fmt.Sprintf("cannot Go map representation to JSON: %s", err))}
}
resp = C.parseResponse{C.CString(string(hclInJson)), nil}
return
}
func main() {
}