1
0
Fork 0
mirror of https://github.com/Luzifer/cloudkeys-go.git synced 2024-11-14 00:42:44 +00:00
cloudkeys-go/vendor/github.com/flosch/pongo2/error.go

92 lines
2 KiB
Go
Raw Normal View History

2015-07-30 15:43:22 +00:00
package pongo2
import (
"bufio"
"fmt"
"os"
)
2017-12-28 01:56:23 +00:00
// The Error type is being used to address an error during lexing, parsing or
2015-07-30 15:43:22 +00:00
// execution. If you want to return an error object (for example in your own
// tag or filter) fill this object with as much information as you have.
// Make sure "Sender" is always given (if you're returning an error within
// a filter, make Sender equals 'filter:yourfilter'; same goes for tags: 'tag:mytag').
// It's okay if you only fill in ErrorMsg if you don't have any other details at hand.
type Error struct {
2017-12-28 01:56:23 +00:00
Template *Template
Filename string
Line int
Column int
Token *Token
Sender string
OrigError error
2015-07-30 15:43:22 +00:00
}
func (e *Error) updateFromTokenIfNeeded(template *Template, t *Token) *Error {
if e.Template == nil {
e.Template = template
}
if e.Token == nil {
e.Token = t
if e.Line <= 0 {
e.Line = t.Line
e.Column = t.Col
}
}
return e
}
// Returns a nice formatted error string.
func (e *Error) Error() string {
s := "[Error"
if e.Sender != "" {
s += " (where: " + e.Sender + ")"
}
if e.Filename != "" {
s += " in " + e.Filename
}
if e.Line > 0 {
s += fmt.Sprintf(" | Line %d Col %d", e.Line, e.Column)
if e.Token != nil {
s += fmt.Sprintf(" near '%s'", e.Token.Val)
}
}
s += "] "
2017-12-28 01:56:23 +00:00
s += e.OrigError.Error()
2015-07-30 15:43:22 +00:00
return s
}
2017-12-28 01:56:23 +00:00
// RawLine returns the affected line from the original template, if available.
func (e *Error) RawLine() (line string, available bool, outErr error) {
2015-07-30 15:43:22 +00:00
if e.Line <= 0 || e.Filename == "<string>" {
2017-12-28 01:56:23 +00:00
return "", false, nil
2015-07-30 15:43:22 +00:00
}
filename := e.Filename
if e.Template != nil {
filename = e.Template.set.resolveFilename(e.Template, e.Filename)
}
file, err := os.Open(filename)
if err != nil {
2017-12-28 01:56:23 +00:00
return "", false, err
2015-07-30 15:43:22 +00:00
}
2017-12-28 01:56:23 +00:00
defer func() {
err := file.Close()
if err != nil && outErr == nil {
outErr = err
}
}()
2015-07-30 15:43:22 +00:00
scanner := bufio.NewScanner(file)
l := 0
for scanner.Scan() {
l++
if l == e.Line {
2017-12-28 01:56:23 +00:00
return scanner.Text(), true, nil
2015-07-30 15:43:22 +00:00
}
}
2017-12-28 01:56:23 +00:00
return "", false, nil
2015-07-30 15:43:22 +00:00
}