hcl/printer/printer.go

62 lines
1.2 KiB
Go
Raw Normal View History

2015-10-25 15:14:16 +00:00
// Package printer implements printing of AST nodes to HCL format.
package printer
2015-10-03 00:30:57 +00:00
import (
2015-10-25 15:45:54 +00:00
"bytes"
2015-10-03 00:30:57 +00:00
"io"
"text/tabwriter"
"github.com/fatih/hcl/ast"
2015-10-25 15:45:54 +00:00
"github.com/fatih/hcl/parser"
2015-10-03 00:30:57 +00:00
)
2015-10-25 15:45:54 +00:00
var DefaultConfig = Config{}
2015-10-03 00:30:57 +00:00
type printer struct {
cfg Config
2015-10-03 00:30:57 +00:00
}
// A Config node controls the output of Fprint.
type Config struct {
SpacesWidth int // if set, it will use spaces instead of tabs for alignment
2015-10-03 00:30:57 +00:00
}
func (c *Config) Fprint(output io.Writer, node ast.Node) error {
2015-10-03 00:30:57 +00:00
p := &printer{
cfg: *c,
2015-10-03 00:30:57 +00:00
}
if _, err := output.Write(p.output(node)); err != nil {
2015-10-03 00:30:57 +00:00
return err
}
// flush tabwriter, if any
var err error
if tw, _ := output.(*tabwriter.Writer); tw != nil {
err = tw.Flush()
}
return err
}
// Fprint "pretty-prints" an HCL node to output
2015-10-03 00:30:57 +00:00
// It calls Config.Fprint with default settings.
func Fprint(output io.Writer, node ast.Node) error {
2015-10-25 15:45:54 +00:00
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
2015-10-03 00:30:57 +00:00
}