diff --git a/fmt/fmt.go b/cmd/hclfmt/fmt.go similarity index 83% rename from fmt/fmt.go rename to cmd/hclfmt/fmt.go index 707fa4b..987f34c 100644 --- a/fmt/fmt.go +++ b/cmd/hclfmt/fmt.go @@ -12,7 +12,14 @@ import ( "runtime/pprof" "strings" - "github.com/hashicorp/hcl" + "github.com/fatih/hcl/printer" +) + +var ( + write = flag.Bool("w", false, "write result to (source) file instead of stdout") + + // debugging + cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file") ) func main() { @@ -23,12 +30,6 @@ func main() { } func realMain() error { - var ( - write = flag.Bool("w", false, "write result to (source) file instead of stdout") - - // debugging - cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file") - ) flag.Usage = usage flag.Parse() @@ -114,11 +115,18 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error return err } - obj, err := hcl.Parse(string(src)) + res, err := printer.Format(src) if err != nil { return err } - fmt.Printf("obj = %+v\n", obj) - return errors.New("not imlemented yet") + if *write { + err = ioutil.WriteFile(filename, res, 0644) + if err != nil { + return err + } + } + + _, err = out.Write(res) + return err } diff --git a/printer/printer.go b/printer/printer.go index a34d160..a9a0d78 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -2,12 +2,16 @@ package printer import ( + "bytes" "io" "text/tabwriter" "github.com/fatih/hcl/ast" + "github.com/fatih/hcl/parser" ) +var DefaultConfig = Config{} + type printer struct { cfg Config } @@ -38,5 +42,20 @@ func (c *Config) Fprint(output io.Writer, node ast.Node) error { // Fprint "pretty-prints" an HCL node to output // It calls Config.Fprint with default settings. func Fprint(output io.Writer, node ast.Node) error { - return (&Config{}).Fprint(output, node) + return DefaultConfig.Fprint(output, node) +} + +// Format formats src HCL and returns the result. +func Format(src []byte) ([]byte, error) { + node, err := parser.Parse(src) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + if err := DefaultConfig.Fprint(&buf, node); err != nil { + return nil, err + } + + return buf.Bytes(), nil }