build: include position information in errors

Updates #5
This commit is contained in:
Michael McLoughlin
2019-01-04 15:01:29 -08:00
parent 80c427d051
commit 05cfa809f2
3 changed files with 65 additions and 2 deletions

View File

@@ -1,6 +1,11 @@
package src
import "strconv"
import (
"os"
"path/filepath"
"runtime"
"strconv"
)
// Position represents a position in a source file.
type Position struct {
@@ -8,6 +13,13 @@ type Position struct {
Line int // 1-up
}
func FramePosition(f runtime.Frame) Position {
return Position{
Filename: f.File,
Line: f.Line,
}
}
// IsValid reports whether the position is valid: Line must be positive, but
// Filename may be empty.
func (p Position) IsValid() bool {
@@ -26,3 +38,23 @@ func (p Position) String() string {
s += strconv.Itoa(p.Line)
return s
}
// Rel returns Position relative to basepath. If the given filename cannot be
// expressed relative to basepath the position will be returned unchanged.
func (p Position) Rel(basepath string) Position {
q := p
if rel, err := filepath.Rel(basepath, q.Filename); err == nil {
q.Filename = rel
}
return q
}
// Relwd returns Position relative to the current working directory. Returns p
// unchanged if the working directory cannot be determined, or the filename
// cannot be expressed relative to the working directory.
func (p Position) Relwd() Position {
if wd, err := os.Getwd(); err == nil {
return p.Rel(wd)
}
return p
}