-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground.go
54 lines (40 loc) · 1.26 KB
/
playground.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
package main
import (
"log"
"strings"
"syscall/js"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclwrite"
)
func main() {
log.Println("starting playground")
document := js.Global().Get("document")
codeInput := document.Call("getElementById", "code")
formattedOutput := document.Call("getElementById", "formatted")
errorsOutput := document.Call("getElementById", "errors")
validateButton := document.Call("getElementById", "validate")
buttonClicks := make(chan struct{})
validateButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) any {
log.Println("button clicked")
buttonClicks <- struct{}{}
return nil
}))
for range buttonClicks {
log.Println("validating")
hclInput := []byte(codeInput.Get("value").String())
p := hclparse.NewParser()
_, diags := p.ParseHCL(hclInput, "playground")
log.Println("parsed code, checking errors")
errMsgs := make([]string, len(diags))
for i, diag := range diags {
errMsgs[i] = diag.Error()
}
errorsOutput.Set("value", strings.Join(errMsgs, "\n"))
if diags.HasErrors() {
continue
}
log.Println("no errors found, formatting code")
formattedCode := hclwrite.Format(hclInput)
formattedOutput.Set("value", string(formattedCode))
}
}