| 1 | // Package src provides types for working with source files. |
| 2 | package src |
| 3 | |
| 4 | import ( |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "runtime" |
| 8 | "strconv" |
| 9 | ) |
| 10 | |
| 11 | // Position represents a position in a source file. |
| 12 | type Position struct { |
| 13 | Filename string |
| 14 | Line int // 1-up |
| 15 | } |
| 16 | |
| 17 | // FramePosition returns the Position of the given stack frame. |
| 18 | func FramePosition(f runtime.Frame) Position { |
| 19 | return Position{ |
| 20 | Filename: f.File, |
| 21 | Line: f.Line, |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | // IsValid reports whether the position is valid: Line must be positive, but |
| 26 | // Filename may be empty. |
| 27 | func (p Position) IsValid() bool { |
| 28 | return p.Line > 0 |
| 29 | } |
| 30 | |
| 31 | // String represents Position as a string. |
| 32 | func (p Position) String() string { |
| 33 | if !p.IsValid() { |
| 34 | return "-" |
| 35 | } |
| 36 | var s string |
| 37 | if p.Filename != "" { |
| 38 | s += p.Filename + ":" |
| 39 | } |
| 40 | s += strconv.Itoa(p.Line) |
| 41 | return s |
| 42 | } |
| 43 | |
| 44 | // Rel returns Position relative to basepath. If the given filename cannot be |
| 45 | // expressed relative to basepath the position will be returned unchanged. |
| 46 | func (p Position) Rel(basepath string) Position { |
| 47 | q := p |
| 48 | if rel, err := filepath.Rel(basepath, q.Filename); err == nil { |
| 49 | q.Filename = rel |
| 50 | } |
| 51 | return q |
| 52 | } |
| 53 | |
| 54 | // Relwd returns Position relative to the current working directory. Returns p |
| 55 | // unchanged if the working directory cannot be determined, or the filename |
| 56 | // cannot be expressed relative to the working directory. |
| 57 | func (p Position) Relwd() Position { |
| 58 | if wd, err := os.Getwd(); err == nil { |
| 59 | return p.Rel(wd) |
| 60 | } |
| 61 | return p |
| 62 | } |