Skip to content

Instantly share code, notes, and snippets.

@tonglil
Last active August 29, 2023 00:56
Show Gist options
  • Save tonglil/cce8dac158111add1487ad652b7570d0 to your computer and use it in GitHub Desktop.
Save tonglil/cce8dac158111add1487ad652b7570d0 to your computer and use it in GitHub Desktop.
merging and sorting hcl files
package main
import (
"os"
"sort"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
)
func main() {
// read files
f1, err := os.ReadFile("f1.tf")
check(err)
f2, err := os.ReadFile("f2.tf")
check(err)
// parse files
h1, d := hclwrite.ParseConfig(f1, "filename", hcl.InitialPos)
if d.HasErrors() {
panic(d.Error())
}
h2, d := hclwrite.ParseConfig(f2, "filename", hcl.InitialPos)
if d.HasErrors() {
panic(d.Error())
}
// merge all blocks together
blocks := h1.Body().Blocks()
blocks = append(blocks, h2.Body().Blocks()...)
// sort blocks
sort.Slice(blocks, func(i, j int) bool {
return comparer(blocks[i]) < comparer(blocks[j])
})
// write out file
out := hclwrite.NewFile()
for _, b := range blocks {
out.Body().AppendBlock(b)
out.Body().AppendNewline()
}
fout, err := os.Create("out.tf")
check(err)
defer fout.Close()
out.WriteTo(fout)
}
func check(err error) {
if err != nil {
panic(err)
}
}
func comparer(block *hclwrite.Block) string {
return block.Type() + strings.Join(block.Labels(), ".")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment