Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion alpha/declcfg/load.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package declcfg

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -135,7 +136,7 @@ func LoadReader(r io.Reader) (*DeclarativeConfig, error) {

var in Meta
if err := json.Unmarshal(doc, &in); err != nil {
return nil, err
return nil, fmt.Errorf("unmarshal error: %s", resolveUnmarshalErr(doc, err))
}

switch in.Schema {
Expand Down Expand Up @@ -186,3 +187,47 @@ func LoadFile(root fs.FS, path string) (*DeclarativeConfig, error) {

return cfg, nil
}

func resolveUnmarshalErr(data []byte, err error) string {
var te *json.UnmarshalTypeError
if errors.As(err, &te) {
return formatUnmarshallErrorString(data, te.Error(), te.Offset)
}
var se *json.SyntaxError
if errors.As(err, &se) {
return formatUnmarshallErrorString(data, se.Error(), se.Offset)
}
return err.Error()
}

func formatUnmarshallErrorString(data []byte, errmsg string, offset int64) string {
sb := new(strings.Builder)
_, _ = sb.WriteString(fmt.Sprintf("%s at offset %d (indicated by <==)\n ", errmsg, offset))
// attempt to present the erroneous JSON in indented, human-readable format
// errors result in presenting the original, unformatted output
var pretty bytes.Buffer
err := json.Indent(&pretty, data, "", " ")
if err == nil {
pString := pretty.String()
// calc the prettified string offset which correlates to the original string offset
var pOffset, origOffset int64
origOffset = 0
for origOffset = 0; origOffset < offset; {
pOffset++
if pString[pOffset] != '\n' && pString[pOffset] != ' ' {
origOffset++
}
}
_, _ = sb.WriteString(pString[:pOffset])
_, _ = sb.WriteString(" <== ")
_, _ = sb.WriteString(pString[pOffset:])
} else {
for i := int64(0); i < offset; i++ {
_ = sb.WriteByte(data[i])
}
_, _ = sb.WriteString(" <== ")
_, _ = sb.Write(data[offset:])
}

return sb.String()
}