From ab5efb805c51ad07d02df797e7437266cee362c0 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Thu, 5 Oct 2017 11:38:21 -0700 Subject: [PATCH] tfdiags: SourceRange.StartString This helper provides a concise string showing the filename, start line and start column for a range, for easy inclusion in error messages. --- tfdiags/source_range.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tfdiags/source_range.go b/tfdiags/source_range.go index 47a8b1610..3031168d6 100644 --- a/tfdiags/source_range.go +++ b/tfdiags/source_range.go @@ -1,5 +1,11 @@ package tfdiags +import ( + "fmt" + "os" + "path/filepath" +) + type SourceRange struct { Filename string Start, End SourcePos @@ -8,3 +14,22 @@ type SourceRange struct { type SourcePos struct { Line, Column, Byte int } + +// StartString returns a string representation of the start of the range, +// including the filename and the line and column numbers. +func (r SourceRange) StartString() string { + filename := r.Filename + + // We'll try to relative-ize our filename here so it's less verbose + // in the common case of being in the current working directory. If not, + // we'll just show the full path. + wd, err := os.Getwd() + if err == nil { + relFn, err := filepath.Rel(wd, filename) + if err == nil { + filename = relFn + } + } + + return fmt.Sprintf("%s:%d,%d", filename, r.Start.Line, r.Start.Column) +}