summaryrefslogtreecommitdiff
path: root/hclwrite/public.go
blob: 8003a71ddf91b94c1ffe2668d7c4d76f27c86054 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package hclwrite

import (
	"bytes"

	"github.com/hashicorp/hcl/v2"
)

// NewFile creates a new file object that is empty and ready to have constructs
// added t it.
func NewFile() *File {
	body := &Body{
		inTree: newInTree(),
		items:  newNodeSet(),
	}
	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()
}