77c0b55a59
The original prototype of hclwrite tried to track both the tokens and the AST as two parallel data structures. This quickly exploded in complexity, leading to lots of messy code to manage keeping those two structures in sync. This new approach melds the two structures together, creating first a physical token tree (made of "node" objects, and hidden from the caller) and then attaching the AST nodes to that token tree as additional sidecar data. The result is much easier to work with, leading to less code in the parser and considerably less complex data structures in the parser's tests. This commit is enough to reach feature parity with the previous prototype, but it remains a prototype. With a more usable foundation, we'll evolve this into a more complete implementation in subsequent commits.
45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package hclwrite
|
|
|
|
import (
|
|
"bytes"
|
|
|
|
"github.com/hashicorp/hcl2/hcl"
|
|
)
|
|
|
|
// NewFile creates a new file object that is empty and ready to have constructs
|
|
// added t it.
|
|
func NewFile() *File {
|
|
body := &Body{
|
|
inTree: newInTree(),
|
|
indentLevel: 0,
|
|
}
|
|
file := &File{
|
|
inTree: newInTree(),
|
|
}
|
|
file.body = file.inTree.children.Append(body)
|
|
return file
|
|
}
|
|
|
|
// ParseConfig interprets the given source bytes into a *hclwrite.File. The
|
|
// resulting AST can be used to perform surgical edits on the source code
|
|
// before turning it back into bytes again.
|
|
func ParseConfig(src []byte, filename string, start hcl.Pos) (*File, hcl.Diagnostics) {
|
|
return parse(src, filename, start)
|
|
}
|
|
|
|
// Format takes source code and performs simple whitespace changes to transform
|
|
// it to a canonical layout style.
|
|
//
|
|
// Format skips constructing an AST and works directly with tokens, so it
|
|
// is less expensive than formatting via the AST for situations where no other
|
|
// changes will be made. It also ignores syntax errors and can thus be applied
|
|
// to partial source code, although the result in that case may not be
|
|
// desirable.
|
|
func Format(src []byte) []byte {
|
|
tokens := lexConfig(src)
|
|
format(tokens)
|
|
buf := &bytes.Buffer{}
|
|
tokens.WriteTo(buf)
|
|
return buf.Bytes()
|
|
}
|