fmt: initial working version of hclfmt

This commit is contained in:
Fatih Arslan 2015-10-25 18:45:54 +03:00
parent 94c0e1e8d4
commit 69f125c80f
2 changed files with 38 additions and 11 deletions

View File

@ -12,7 +12,14 @@ import (
"runtime/pprof" "runtime/pprof"
"strings" "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() { func main() {
@ -23,12 +30,6 @@ func main() {
} }
func realMain() error { 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.Usage = usage
flag.Parse() flag.Parse()
@ -114,11 +115,18 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error
return err return err
} }
obj, err := hcl.Parse(string(src)) res, err := printer.Format(src)
if err != nil { if err != nil {
return err return err
} }
fmt.Printf("obj = %+v\n", obj) if *write {
return errors.New("not imlemented yet") err = ioutil.WriteFile(filename, res, 0644)
if err != nil {
return err
}
}
_, err = out.Write(res)
return err
} }

View File

@ -2,12 +2,16 @@
package printer package printer
import ( import (
"bytes"
"io" "io"
"text/tabwriter" "text/tabwriter"
"github.com/fatih/hcl/ast" "github.com/fatih/hcl/ast"
"github.com/fatih/hcl/parser"
) )
var DefaultConfig = Config{}
type printer struct { type printer struct {
cfg Config 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 // Fprint "pretty-prints" an HCL node to output
// It calls Config.Fprint with default settings. // It calls Config.Fprint with default settings.
func Fprint(output io.Writer, node ast.Node) error { 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
} }