github.com/hashicorp/hcl/v2@v2.20.0/hclwrite/public.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package hclwrite
     5  
     6  import (
     7  	"bytes"
     8  
     9  	"github.com/hashicorp/hcl/v2"
    10  )
    11  
    12  // NewFile creates a new file object that is empty and ready to have constructs
    13  // added t it.
    14  func NewFile() *File {
    15  	body := &Body{
    16  		inTree: newInTree(),
    17  		items:  newNodeSet(),
    18  	}
    19  	file := &File{
    20  		inTree: newInTree(),
    21  	}
    22  	file.body = file.inTree.children.Append(body)
    23  	return file
    24  }
    25  
    26  // ParseConfig interprets the given source bytes into a *hclwrite.File. The
    27  // resulting AST can be used to perform surgical edits on the source code
    28  // before turning it back into bytes again.
    29  func ParseConfig(src []byte, filename string, start hcl.Pos) (*File, hcl.Diagnostics) {
    30  	return parse(src, filename, start)
    31  }
    32  
    33  // Format takes source code and performs simple whitespace changes to transform
    34  // it to a canonical layout style.
    35  //
    36  // Format skips constructing an AST and works directly with tokens, so it
    37  // is less expensive than formatting via the AST for situations where no other
    38  // changes will be made. It also ignores syntax errors and can thus be applied
    39  // to partial source code, although the result in that case may not be
    40  // desirable.
    41  func Format(src []byte) []byte {
    42  	tokens := lexConfig(src)
    43  	format(tokens)
    44  	buf := &bytes.Buffer{}
    45  	tokens.WriteTo(buf)
    46  	return buf.Bytes()
    47  }