From 9c29a827885ba2025ad7fc1641b6a197b36ac6e7 Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Sat, 3 Oct 2015 02:18:04 +0300 Subject: [PATCH] hclfmt: only parse hcl files --- hclfmt.go | 37 ++++++++++++++++++++++++++++++------- testdata/complex.hcl | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 7 deletions(-) create mode 100644 testdata/complex.hcl diff --git a/hclfmt.go b/hclfmt.go index 5b3a2e2..707fa4b 100644 --- a/hclfmt.go +++ b/hclfmt.go @@ -6,10 +6,13 @@ import ( "fmt" "go/scanner" "io" + "io/ioutil" "os" "path/filepath" "runtime/pprof" "strings" + + "github.com/hashicorp/hcl" ) func main() { @@ -71,22 +74,22 @@ func usage() { os.Exit(2) } -func isGoFile(f os.FileInfo) bool { - // ignore non-Go files - name := f.Name() - return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") -} - func report(err error) { scanner.PrintError(os.Stderr, err) } +func isHclFile(f os.FileInfo) bool { + // ignore non-hcl files + name := f.Name() + return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".hcl") +} + func walkDir(path string) { filepath.Walk(path, visitFile) } func visitFile(path string, f os.FileInfo, err error) error { - if err == nil && isGoFile(f) { + if err == nil && isHclFile(f) { err = processFile(path, nil, os.Stdout, false) } if err != nil { @@ -97,5 +100,25 @@ func visitFile(path string, f os.FileInfo, err error) error { // If in == nil, the source is the contents of the file with the given filename. func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error { + if in == nil { + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + in = f + } + + src, err := ioutil.ReadAll(in) + if err != nil { + return err + } + + obj, err := hcl.Parse(string(src)) + if err != nil { + return err + } + + fmt.Printf("obj = %+v\n", obj) return errors.New("not imlemented yet") } diff --git a/testdata/complex.hcl b/testdata/complex.hcl new file mode 100644 index 0000000..cccb5b0 --- /dev/null +++ b/testdata/complex.hcl @@ -0,0 +1,42 @@ +// This comes from Terraform, as a test +variable "foo" { + default = "bar" + description = "bar" +} + +provider "aws" { + access_key = "foo" + secret_key = "bar" +} + +provider "do" { + api_key = "${var.foo}" +} + +resource "aws_security_group" "firewall" { + count = 5 +} + +resource aws_instance "web" { + ami = "${var.foo}" + security_groups = [ + "foo", + "${aws_security_group.firewall.foo}" + ] + + network_interface { + device_index = 0 + description = "Main network interface" + } +} + +resource "aws_instance" "db" { + security_groups = "${aws_security_group.firewall.*.id}" + VPC = "foo" + + depends_on = ["aws_instance.web"] +} + +output "web_ip" { + value = "${aws_instance.web.private_ip}" +}