84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/hashicorp/hcl/v2"
|
|
"github.com/hashicorp/hcl/v2/gohcl"
|
|
"github.com/hashicorp/hcl/v2/hclsyntax"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// Load the configuration file.
|
|
func Load(name string) (*Config, error) {
|
|
log := logrus.WithField("path", name)
|
|
log.Debug("loading configuration")
|
|
|
|
source, err := os.ReadFile(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var (
|
|
config = new(Config)
|
|
ctx *hcl.EvalContext
|
|
file *hcl.File
|
|
diag hcl.Diagnostics
|
|
)
|
|
|
|
start := hcl.Pos{Line: 1, Column: 1}
|
|
if file, diag = hclsyntax.ParseConfig(source, name, start); diag.HasErrors() {
|
|
return nil, diag
|
|
}
|
|
|
|
if diag = gohcl.DecodeBody(file.Body, ctx, config); diag.HasErrors() {
|
|
return nil, diag
|
|
}
|
|
|
|
return config, nil
|
|
}
|
|
|
|
func ExplainError(name string, err error) bool {
|
|
fmt.Printf("error type %T\n", err)
|
|
if diags, ok := err.(hcl.Diagnostics); ok {
|
|
for _, diag := range diags {
|
|
if diag.Subject != nil {
|
|
return explainSubject(diag)
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func explainSubject(diag *hcl.Diagnostic) bool {
|
|
if diag.Subject == nil || diag.Subject.Filename == "" {
|
|
return false
|
|
}
|
|
|
|
source, err := os.ReadFile(diag.Subject.Filename)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
fmt.Printf("Fatal error parsing %s:\n", diag.Subject)
|
|
lines := strings.Split(string(source), "\n")
|
|
start := diag.Subject.Start.Line - 3
|
|
if start < 0 {
|
|
start = 0
|
|
}
|
|
for line := start; line < diag.Subject.Start.Line; line++ {
|
|
fmt.Printf("%4d| %s\n", line+1, lines[line])
|
|
}
|
|
fmt.Print(" ...|")
|
|
if diag.Subject.Start.Column > 1 {
|
|
fmt.Print(strings.Repeat(" ", diag.Subject.Start.Column))
|
|
}
|
|
fmt.Print("^- ")
|
|
fmt.Println(diag.Summary + "\n")
|
|
fmt.Println(diag.Detail)
|
|
|
|
return true
|
|
}
|