Skip to content

Instantly share code, notes, and snippets.

@dbanck
Last active August 29, 2022 09:19
Show Gist options
  • Save dbanck/83e0e7936556eab2184d5d89e9d1feac to your computer and use it in GitHub Desktop.
Save dbanck/83e0e7936556eab2184d5d89e9d1feac to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
)
func main() {
err := checkFile("main.tf")
if err != nil {
fmt.Println(err)
}
err = checkFile("main2.tf")
if err != nil {
fmt.Println(err)
}
}
func checkFile(filename string) error {
fmt.Printf("Checking file: %s\n", filename)
pos := hcl.InitialPos
fullPath, err := filepath.Abs(filename)
if err != nil {
return err
}
src, err := os.ReadFile(fullPath)
if err != nil {
return err
}
f, _ := hclsyntax.ParseConfig(src, filename, pos)
body, isHcl := f.Body.(*hclsyntax.Body)
if !isHcl {
return fmt.Errorf("ERR: no hcl content in file: %s", filename)
}
fmt.Println(body.Range())
if !body.Range().ContainsPos(pos) {
return fmt.Errorf("ERR: %s: position %s is out of range %s", filename, stringPos(pos), body.Range())
}
return nil
}
func stringPos(pos hcl.Pos) string {
return fmt.Sprintf("%d,%d", pos.Line, pos.Column)
}
/********************************
Some comment
********************************/
data "google_project" "project" {
project_id = var.project_id
}
/********************************
More content
********************************/
# some
# content
data "google_project" "project" {
project_id = var.project_id
}
# more
# content
$ go run main.go
Checking file: main.tf
main.tf:3,34-11,34
ERR: main.tf: position 1,1 is out of range main.tf:3,34-11,34
Checking file: main2.tf
main2.tf:1,1-9,10

When the file starts with a multiline comment, the SrcRange of the hclsyntax.Body starts at line 3 instead of line 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment