-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
stacktrace_cleanpath.go
42 lines (37 loc) · 1.32 KB
/
stacktrace_cleanpath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package oops
///
/// Stolen from palantir/stacktrace repo
/// -> https://github.com/palantir/stacktrace/blob/master/cleanpath/gopath.go
/// -> Apache 2.0 LICENSE
///
import (
"os"
"path/filepath"
"sort"
"strings"
)
/*
RemoveGoPath makes a path relative to one of the src directories in the $GOPATH
environment variable. If $GOPATH is empty or the input path is not contained
within any of the src directories in $GOPATH, the original path is returned. If
the input path is contained within multiple of the src directories in $GOPATH,
it is made relative to the longest one of them.
*/
func removeGoPath(path string) string {
dirs := filepath.SplitList(os.Getenv("GOPATH"))
// Sort in decreasing order by length so the longest matching prefix is removed
sort.Stable(longestFirst(dirs))
for _, dir := range dirs {
srcdir := filepath.Join(dir, "src")
rel, err := filepath.Rel(srcdir, path)
// filepath.Rel can traverse parent directories, don't want those
if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return rel
}
}
return path
}
type longestFirst []string
func (strs longestFirst) Len() int { return len(strs) }
func (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }
func (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }