-
Notifications
You must be signed in to change notification settings - Fork 100
/
main.go
79 lines (64 loc) · 1.41 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/hashicorp/hcl"
"github.com/hashicorp/hcl/hcl/printer"
jsonParser "github.com/hashicorp/hcl/json/parser"
)
// VERSION is what is returned by the `-v` flag
var Version = "development"
func main() {
version := flag.Bool("version", false, "Prints current app version")
reverse := flag.Bool("reverse", false, "Input HCL, output JSON")
flag.Parse()
if *version {
fmt.Println(Version)
return
}
var err error
if *reverse {
err = toJSON()
} else {
err = toHCL()
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func toJSON() error {
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("unable to read from stdin: %s", err)
}
var v interface{}
err = hcl.Unmarshal(input, &v)
if err != nil {
return fmt.Errorf("unable to parse HCL: %s", err)
}
json, err := json.MarshalIndent(v, "", " ")
if err != nil {
return fmt.Errorf("unable to marshal json: %s", err)
}
fmt.Println(string(json))
return nil
}
func toHCL() error {
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("unable to read from stdin: %s", err)
}
ast, err := jsonParser.Parse([]byte(input))
if err != nil {
return fmt.Errorf("unable to parse JSON: %s", err)
}
err = printer.Fprint(os.Stdout, ast)
if err != nil {
return fmt.Errorf("unable to print HCL: %s", err)
}
return nil
}