Skip to content

Commit

Permalink
goutil: Ad RelImpPath.
Browse files Browse the repository at this point in the history
  • Loading branch information
mewmew committed Feb 13, 2017
1 parent ac6027b commit 34f4d97
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions goutil/gotuil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
package goutil

import (
"fmt"
"go/build"
"os"
"path/filepath"
"strings"

"github.com/pkg/errors"
)

// SrcDir tries to locate dir in GOPATH/src/ or GOROOT/src/pkg/ and returns its
Expand All @@ -19,7 +20,7 @@ func SrcDir(dir string) (absDir string, err error) {
return absDir, nil
}
}
return "", fmt.Errorf("goutil.SrcDir: unable to locate directory (%q) in GOPATH/src/ (%q) or GOROOT/src/pkg/ (%q)", dir, os.Getenv("GOPATH"), os.Getenv("GOROOT"))
return "", errors.Errorf("unable to locate directory (%q) in GOPATH/src/ (%q) or GOROOT/src/pkg/ (%q)", dir, os.Getenv("GOPATH"), os.Getenv("GOROOT"))
}

// AbsImpPath tries to locate the absolute import path based on the provided
Expand All @@ -30,7 +31,7 @@ func AbsImpPath(relImpPath string) (absImpPath string, err error) {
}
absPath, err := filepath.Abs(relImpPath)
if err != nil {
return "", fmt.Errorf("goutil.AbsImpPath: %v", err)
return "", errors.WithStack(err)
}
for _, srcDir := range build.Default.SrcDirs() {
if strings.HasPrefix(absPath, srcDir) {
Expand All @@ -41,5 +42,22 @@ func AbsImpPath(relImpPath string) (absImpPath string, err error) {
return absImpPath, nil
}
}
return "", fmt.Errorf("goutil.AbsImpPath: unable to locate absolute import path for %q", relImpPath)
return "", errors.Errorf("unable to locate absolute import path for %q", relImpPath)
}

// RelImpPath tries to locate the relative import path of the provided path. A
// pre-condition is that the given path resides within GOPATH.
func RelImpPath(path string) (relImpPath string, err error) {
if !filepath.IsAbs(path) {
path, err = filepath.Abs(path)
if err != nil {
return "", errors.WithStack(err)
}
}
for _, srcDir := range build.Default.SrcDirs() {
if filepath.HasPrefix(path, srcDir) {
return path[len(srcDir)+1:], nil
}
}
return "", errors.Errorf("unable to locate path (%q) in GOPATH/src/ (%q) or GOROOT/src/pkg/ (%q)", path, os.Getenv("GOPATH"), os.Getenv("GOROOT"))
}

0 comments on commit 34f4d97

Please sign in to comment.