2015-10-25 15:14:16 +00:00
|
|
|
// Package printer implements printing of AST nodes to HCL format.
|
2015-10-16 20:22:28 +00:00
|
|
|
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"
|
|
|
|
|
2015-10-24 21:04:31 +00:00
|
|
|
"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 {
|
2015-10-25 15:10:34 +00:00
|
|
|
cfg Config
|
2015-10-03 00:30:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// A Config node controls the output of Fprint.
|
|
|
|
type Config struct {
|
2015-10-25 15:10:34 +00:00
|
|
|
SpacesWidth int // if set, it will use spaces instead of tabs for alignment
|
2015-10-03 00:30:57 +00:00
|
|
|
}
|
|
|
|
|
2015-10-25 15:10:34 +00:00
|
|
|
func (c *Config) Fprint(output io.Writer, node ast.Node) error {
|
2015-10-03 00:30:57 +00:00
|
|
|
p := &printer{
|
2015-10-25 15:10:34 +00:00
|
|
|
cfg: *c,
|
2015-10-03 00:30:57 +00:00
|
|
|
}
|
|
|
|
|
2015-10-25 15:10:34 +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
|
|
|
|
}
|
|
|
|
|
2015-10-24 21:04:31 +00:00
|
|
|
// Fprint "pretty-prints" an HCL node to output
|
2015-10-03 00:30:57 +00:00
|
|
|
// It calls Config.Fprint with default settings.
|
2015-10-24 21:04:31 +00:00
|
|
|
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
|
|
|
}
|