Skip to content

Commit

Permalink
Add line number to JSON syntax error.
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelsauter committed Mar 5, 2014
1 parent 6822466 commit 92f2bec
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions containers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
Expand All @@ -26,10 +27,32 @@ func readCranefile(filename string) Containers {
return unmarshal(file)
}

// Thanks to https://github.com/markpeek/packer/commit/5bf33a0e91b2318a40c42e9bf855dcc8dd4cdec5
func displaySyntaxError(js []byte, syntaxError error) (err error) {
syntax, ok := syntaxError.(*json.SyntaxError)
if !ok {
err = syntaxError
return
}
newline := []byte{'\x0a'}
space := []byte{' '}

start, end := bytes.LastIndex(js[:syntax.Offset], newline)+1, len(js)
if idx := bytes.Index(js[start:], newline); idx >= 0 {
end = start + idx
}

line, pos := bytes.Count(js[:start], newline)+1, int(syntax.Offset)-start-1

err = fmt.Errorf("\nError in line %d: %s \n%s\n%s^", line, syntaxError, js[start:end], bytes.Repeat(space, pos))
return
}

func unmarshal(data []byte) Containers {
var containers Containers
err := json.Unmarshal(data, &containers)
if err != nil {
err = displaySyntaxError(data, err)
panic(err)
}
return containers
Expand Down

0 comments on commit 92f2bec

Please sign in to comment.